blob: e6e1b2111935910351242e3437189574651ac15d [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"
Vedant Kumardd1ea9d2019-10-21 11:48:38 -070016#include "clang/Basic/Diagnostic.h"
Reid Klecknere08464f2020-02-29 09:10:42 -080017#include "clang/Basic/FileManager.h"
Vedant Kumardd1ea9d2019-10-21 11:48:38 -070018#include "clang/Frontend/FrontendDiagnostic.h"
Alex Lorenzee024992014-08-04 18:41:51 +000019#include "clang/Lex/Lexer.h"
Reid Klecknere08464f2020-02-29 09:10:42 -080020#include "llvm/ADT/Optional.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000021#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000022#include "llvm/ADT/StringExtras.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000023#include "llvm/ProfileData/Coverage/CoverageMapping.h"
24#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000026#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000027#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000028#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000029
Vedant Kumardd1ea9d2019-10-21 11:48:38 -070030// This selects the coverage mapping format defined when `InstrProfData.inc`
31// is textually included.
32#define COVMAP_V3
33
Alex Lorenzee024992014-08-04 18:41:51 +000034using namespace clang;
35using namespace CodeGen;
36using namespace llvm::coverage;
37
Zequan Wub46176b2020-07-22 19:04:59 -070038CoverageSourceInfo *
39CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
40 CoverageSourceInfo *CoverageInfo = new CoverageSourceInfo();
41 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
42 PP.addCommentHandler(CoverageInfo);
43 PP.setPreprocessToken(true);
44 PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
45 // Update previous token location.
46 CoverageInfo->PrevTokLoc = Tok.getLocation();
47 CoverageInfo->updateNextTokLoc(Tok.getLocation());
48 });
49 return CoverageInfo;
50}
51
Vedant Kumar3919a502017-09-11 20:47:42 +000052void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Zequan Wub46176b2020-07-22 19:04:59 -070053 SkippedRanges.push_back({Range});
54}
55
56bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
57 SkippedRanges.push_back({Range, PrevTokLoc});
58 AfterComment = true;
59 return false;
60}
61
62void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
63 if (AfterComment) {
64 SkippedRanges.back().NextTokLoc = Loc;
65 AfterComment = false;
66 }
Alex Lorenzee024992014-08-04 18:41:51 +000067}
68
69namespace {
70
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000071/// A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000072class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000073 Counter Count;
74
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000075 /// The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000076 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000077
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000078 /// The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000079 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000080
Vedant Kumar747b0e22017-09-08 18:44:56 +000081 /// Whether this region should be emitted after its parent is emitted.
82 bool DeferRegion;
83
Vedant Kumara1c4deb2017-09-18 23:37:30 +000084 /// Whether this region is a gap region. The count from a gap region is set
85 /// as the line execution count if there are no other regions on the line.
86 bool GapRegion;
87
Justin Bogner09c71792014-10-01 03:33:49 +000088public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000089 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000090 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
91 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000092 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000093 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000094
Justin Bogner09c71792014-10-01 03:33:49 +000095 const Counter &getCounter() const { return Count; }
96
Justin Bognerbf42cfd2015-02-18 21:24:51 +000097 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000098
Justin Bognerbf42cfd2015-02-18 21:24:51 +000099 bool hasStartLoc() const { return LocStart.hasValue(); }
100
101 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
102
Stephen Kelly3cffc4c2018-08-09 20:05:18 +0000103 SourceLocation getBeginLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000104 assert(LocStart && "Region has no start location");
105 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +0000106 }
107
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000108 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +0000109
Vedant Kumara14a1f92018-01-17 18:53:51 +0000110 void setEndLoc(SourceLocation Loc) {
111 assert(Loc.isValid() && "Setting an invalid end location");
112 LocEnd = Loc;
113 }
Alex Lorenzee024992014-08-04 18:41:51 +0000114
Craig Topper462c77b2015-09-26 05:10:14 +0000115 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000116 assert(LocEnd && "Region has no end location");
117 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +0000118 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000119
120 bool isDeferred() const { return DeferRegion; }
121
122 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000123
124 bool isGap() const { return GapRegion; }
125
126 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +0000127};
128
Vedant Kumard7369642017-07-27 02:20:25 +0000129/// Spelling locations for the start and end of a source region.
130struct SpellingRegion {
131 /// The line where the region starts.
132 unsigned LineStart;
133
134 /// The column where the region starts.
135 unsigned ColumnStart;
136
137 /// The line where the region ends.
138 unsigned LineEnd;
139
140 /// The column where the region ends.
141 unsigned ColumnEnd;
142
143 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
144 SourceLocation LocEnd) {
145 LineStart = SM.getSpellingLineNumber(LocStart);
146 ColumnStart = SM.getSpellingColumnNumber(LocStart);
147 LineEnd = SM.getSpellingLineNumber(LocEnd);
148 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
149 }
150
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000151 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
Stephen Kellya6e43582018-08-09 21:05:56 +0000152 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000153
Vedant Kumard7369642017-07-27 02:20:25 +0000154 /// Check if the start and end locations appear in source order, i.e
155 /// top->bottom, left->right.
156 bool isInSourceOrder() const {
157 return (LineStart < LineEnd) ||
158 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
159 }
160};
161
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000162/// Provides the common functionality for the different
Alex Lorenzee024992014-08-04 18:41:51 +0000163/// coverage mapping region builders.
164class CoverageMappingBuilder {
165public:
166 CoverageMappingModuleGen &CVM;
167 SourceManager &SM;
168 const LangOptions &LangOpts;
169
170private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000171 /// Map of clang's FileIDs to IDs used for coverage mapping.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000172 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
173 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000174
175public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000176 /// The coverage mapping regions for this function
Alex Lorenzee024992014-08-04 18:41:51 +0000177 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000178 /// The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000179 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000181 /// A set of regions which can be used as a filter.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000182 ///
183 /// It is produced by emitExpansionRegions() and is used in
184 /// emitSourceRegions() to suppress producing code regions if
185 /// the same area is covered by expansion regions.
186 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
187 SourceRegionFilter;
188
Alex Lorenzee024992014-08-04 18:41:51 +0000189 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
190 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000191 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000192
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000193 /// Return the precise end location for the given token.
Alex Lorenzee024992014-08-04 18:41:51 +0000194 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000195 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
196 // macro locations, which we just treat as expanded files.
197 unsigned TokLen =
198 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
199 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000200 }
201
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000202 /// Return the start location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000203 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
204 if (Loc.isMacroID())
205 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
206 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000207 }
208
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000209 /// Return the end location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000210 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
211 if (Loc.isMacroID())
212 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000213 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000214 return SM.getLocForEndOfFile(SM.getFileID(Loc));
215 }
216
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000217 /// Find out where the current file is included or macro is expanded.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000218 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
Richard Smithb5f81712018-04-30 05:25:48 +0000219 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000220 : SM.getIncludeLoc(SM.getFileID(Loc));
221 }
222
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000223 /// Return true if \c Loc is a location in a built-in macro.
Justin Bogner682bfbf2015-05-14 22:14:10 +0000224 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000225 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000226 }
227
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000228 /// Check whether \c Loc is included or expanded from \c Parent.
Igor Kudrind9e1a612016-06-07 10:07:51 +0000229 bool isNestedIn(SourceLocation Loc, FileID Parent) {
230 do {
231 Loc = getIncludeOrExpansionLoc(Loc);
232 if (Loc.isInvalid())
233 return false;
234 } while (!SM.isInFileID(Loc, Parent));
235 return true;
236 }
237
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000238 /// Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000239 SourceLocation getStart(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000240 SourceLocation Loc = S->getBeginLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000241 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000242 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000243 return Loc;
244 }
245
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000246 /// Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000247 SourceLocation getEnd(const Stmt *S) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000248 SourceLocation Loc = S->getEndLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000249 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000250 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerf14b2072015-03-25 04:13:49 +0000251 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000252 }
253
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000254 /// Find the set of files we have regions for and assign IDs
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000255 ///
256 /// Fills \c Mapping with the virtual file mapping needed to write out
257 /// coverage and collects the necessary file information to emit source and
258 /// expansion regions.
259 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
260 FileIDMapping.clear();
261
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000262 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000263 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
264 for (const auto &Region : SourceRegions) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000265 SourceLocation Loc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000266 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000267 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000268 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000269
Vedant Kumar93205af2016-07-11 22:57:46 +0000270 // Do not map FileID's associated with system headers.
271 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
272 continue;
273
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000274 unsigned Depth = 0;
275 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000276 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000277 ++Depth;
278 FileLocs.push_back(std::make_pair(Loc, Depth));
279 }
Fangrui Song899d1392019-04-24 14:43:05 +0000280 llvm::stable_sort(FileLocs, llvm::less_second());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000281
282 for (const auto &FL : FileLocs) {
283 SourceLocation Loc = FL.first;
284 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
285 auto Entry = SM.getFileEntryForID(SpellingFile);
286 if (!Entry)
287 continue;
288
289 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
290 Mapping.push_back(CVM.getFileID(Entry));
291 }
292 }
293
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000294 /// Get the coverage mapping file ID for \c Loc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000295 ///
296 /// If such file id doesn't exist, return None.
297 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
298 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000299 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000300 return Mapping->second.first;
301 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000302 }
303
Zequan Wub46176b2020-07-22 19:04:59 -0700304 /// This shrinks the skipped range if it spans a line that contains a
305 /// non-comment token. If shrinking the skipped range would make it empty,
306 /// this returns None.
307 Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
308 SpellingRegion SR,
309 SourceLocation PrevTokLoc,
310 SourceLocation NextTokLoc) {
311 // If Range begin location is invalid, it's not a comment region.
312 if (PrevTokLoc.isInvalid())
313 return SR;
314 unsigned PrevTokLine = SM.getSpellingLineNumber(PrevTokLoc);
315 unsigned NextTokLine = SM.getSpellingLineNumber(NextTokLoc);
316 SpellingRegion newSR(SR);
317 if (SR.LineStart == PrevTokLine) {
318 newSR.LineStart = SR.LineStart + 1;
319 newSR.ColumnStart = 1;
320 }
321 if (SR.LineEnd == NextTokLine) {
322 newSR.LineEnd = SR.LineEnd - 1;
323 newSR.ColumnEnd = SR.ColumnStart + 1;
324 }
325 if (newSR.isInSourceOrder())
326 return newSR;
327 return None;
328 }
329
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000330 /// Gather all the regions that were skipped by the preprocessor
Zequan Wub46176b2020-07-22 19:04:59 -0700331 /// using the constructs like #if or comments.
Alex Lorenzee024992014-08-04 18:41:51 +0000332 void gatherSkippedRegions() {
333 /// An array of the minimum lineStarts and the maximum lineEnds
334 /// for mapping regions from the appropriate source files.
335 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
336 FileLineRanges.resize(
337 FileIDMapping.size(),
338 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
339 for (const auto &R : MappingRegions) {
340 FileLineRanges[R.FileID].first =
341 std::min(FileLineRanges[R.FileID].first, R.LineStart);
342 FileLineRanges[R.FileID].second =
343 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
344 }
345
346 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
Zequan Wub46176b2020-07-22 19:04:59 -0700347 for (auto &I : SkippedRanges) {
348 SourceRange Range = I.Range;
349 auto LocStart = Range.getBegin();
350 auto LocEnd = Range.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000351 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
352 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000353
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000354 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000355 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000356 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000357 SpellingRegion SR{SM, LocStart, LocEnd};
Zequan Wub46176b2020-07-22 19:04:59 -0700358 if (Optional<SpellingRegion> res =
359 adjustSkippedRange(SM, SR, I.PrevTokLoc, I.NextTokLoc))
360 SR = res.getValue();
361 else
362 continue;
Justin Bognerfd34280b2015-02-03 23:59:48 +0000363 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000364 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000365 // Make sure that we only collect the regions that are inside
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000366 // the source code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000367 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
368 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000369 MappingRegions.push_back(Region);
370 }
371 }
372
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000373 /// Generate the coverage counter mapping regions from collected
Alex Lorenzee024992014-08-04 18:41:51 +0000374 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000375 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000376 for (const auto &Region : SourceRegions) {
377 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000378
Stephen Kellya6e43582018-08-09 21:05:56 +0000379 SourceLocation LocStart = Region.getBeginLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000380 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000381
Vedant Kumar93205af2016-07-11 22:57:46 +0000382 // Ignore regions from system headers.
383 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
384 continue;
385
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000386 auto CovFileID = getCoverageFileID(LocStart);
387 // Ignore regions that don't have a file, such as builtin macros.
388 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000389 continue;
390
Justin Bognerf14b2072015-03-25 04:13:49 +0000391 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000392 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
393 "region spans multiple files");
394
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000395 // Don't add code regions for the area covered by expansion regions.
396 // This not only suppresses redundant regions, but sometimes prevents
397 // creating regions with wrong counters if, for example, a statement's
398 // body ends at the end of a nested macro.
399 if (Filter.count(std::make_pair(LocStart, LocEnd)))
400 continue;
401
Vedant Kumard7369642017-07-27 02:20:25 +0000402 // Find the spelling locations for the mapping region.
403 SpellingRegion SR{SM, LocStart, LocEnd};
404 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000405
406 if (Region.isGap()) {
407 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
408 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
409 SR.LineEnd, SR.ColumnEnd));
410 } else {
411 MappingRegions.push_back(CounterMappingRegion::makeRegion(
412 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
413 SR.LineEnd, SR.ColumnEnd));
414 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000415 }
416 }
417
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000418 /// Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000419 SourceRegionFilter emitExpansionRegions() {
420 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000421 for (const auto &FM : FileIDMapping) {
422 SourceLocation ExpandedLoc = FM.second.second;
423 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
424 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000425 continue;
426
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000427 auto ParentFileID = getCoverageFileID(ParentLoc);
428 if (!ParentFileID)
429 continue;
430 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
431 assert(ExpandedFileID && "expansion in uncovered file");
432
433 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
434 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
435 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000436 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000437
Vedant Kumard7369642017-07-27 02:20:25 +0000438 SpellingRegion SR{SM, ParentLoc, LocEnd};
439 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000440 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000441 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
442 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000443 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000444 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000445 }
446};
447
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000448/// Creates unreachable coverage regions for the functions that
Alex Lorenzee024992014-08-04 18:41:51 +0000449/// are not emitted.
450struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
451 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
452 const LangOptions &LangOpts)
453 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
454
455 void VisitDecl(const Decl *D) {
456 if (!D->hasBody())
457 return;
458 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000459 SourceLocation Start = getStart(Body);
460 SourceLocation End = getEnd(Body);
461 if (!SM.isWrittenInSameFile(Start, End)) {
462 // Walk up to find the common ancestor.
463 // Correct the locations accordingly.
464 FileID StartFileID = SM.getFileID(Start);
465 FileID EndFileID = SM.getFileID(End);
466 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
467 Start = getIncludeOrExpansionLoc(Start);
468 assert(Start.isValid() &&
469 "Declaration start location not nested within a known region");
470 StartFileID = SM.getFileID(Start);
471 }
472 while (StartFileID != EndFileID) {
473 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
474 assert(End.isValid() &&
475 "Declaration end location not nested within a known region");
476 EndFileID = SM.getFileID(End);
477 }
478 }
479 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000480 }
481
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000482 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000483 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000484 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000485 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000486 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000487
Vedant Kumarefd319a2016-07-26 00:24:59 +0000488 if (MappingRegions.empty())
489 return;
490
Craig Topper5fc8fc22014-08-27 06:28:36 +0000491 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000492 Writer.write(OS);
493 }
494};
495
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000496/// A StmtVisitor that creates coverage mapping regions which map
Alex Lorenzee024992014-08-04 18:41:51 +0000497/// from the source code locations to the PGO counters.
498struct CounterCoverageMappingBuilder
499 : public CoverageMappingBuilder,
500 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000501 /// The map of statements to count values.
Alex Lorenzee024992014-08-04 18:41:51 +0000502 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
503
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000504 /// A stack of currently live regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000505 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000506
Vedant Kumar747b0e22017-09-08 18:44:56 +0000507 /// The currently deferred region: its end location and count can be set once
508 /// its parent has been popped from the region stack.
509 Optional<SourceMappingRegion> DeferredRegion;
510
Alex Lorenzee024992014-08-04 18:41:51 +0000511 CounterExpressionBuilder Builder;
512
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000513 /// A location in the most recently visited file or macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000514 ///
515 /// This is used to adjust the active source regions appropriately when
516 /// expressions cross file or macro boundaries.
517 SourceLocation MostRecentLocation;
518
Vedant Kumar8046d222017-11-09 02:33:39 +0000519 /// Location of the last terminated region.
520 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
521
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000522 /// Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000523 Counter subtractCounters(Counter LHS, Counter RHS) {
524 return Builder.subtract(LHS, RHS);
525 }
526
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000527 /// Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000528 Counter addCounters(Counter LHS, Counter RHS) {
529 return Builder.add(LHS, RHS);
530 }
531
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000532 Counter addCounters(Counter C1, Counter C2, Counter C3) {
533 return addCounters(addCounters(C1, C2), C3);
534 }
535
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000536 /// Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000537 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000538 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000539 Counter getRegionCounter(const Stmt *S) {
540 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000541 }
542
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000543 /// Push a region onto the stack.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000544 ///
545 /// Returns the index on the stack where the region was pushed. This can be
546 /// used with popRegions to exit a "scope", ending the region that was pushed.
547 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
548 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000549 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000550 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000551 completeDeferred(Count, MostRecentLocation);
552 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000553 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000554
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000555 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000556 }
557
Vedant Kumar747b0e22017-09-08 18:44:56 +0000558 /// Complete any pending deferred region by setting its end location and
559 /// count, and then pushing it onto the region stack.
560 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
561 size_t Index = RegionStack.size();
562 if (!DeferredRegion)
563 return Index;
564
565 // Consume the pending region.
566 SourceMappingRegion DR = DeferredRegion.getValue();
567 DeferredRegion = None;
568
569 // If the region ends in an expansion, find the expansion site.
Stephen Kellya6e43582018-08-09 21:05:56 +0000570 FileID StartFile = SM.getFileID(DR.getBeginLoc());
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000571 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000572 if (isNestedIn(DeferredEndLoc, StartFile)) {
573 do {
574 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
575 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000576 } else {
577 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000578 }
579 }
580
581 // The parent of this deferred region ends where the containing decl ends,
582 // so the region isn't useful.
Stephen Kellya6e43582018-08-09 21:05:56 +0000583 if (DR.getBeginLoc() == DeferredEndLoc)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000584 return Index;
585
586 // If we're visiting statements in non-source order (e.g switch cases or
587 // a loop condition) we can't construct a sensible deferred region.
Stephen Kellya6e43582018-08-09 21:05:56 +0000588 if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000589 return Index;
590
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000591 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000592 DR.setCounter(Count);
593 DR.setEndLoc(DeferredEndLoc);
594 handleFileExit(DeferredEndLoc);
595 RegionStack.push_back(DR);
596 return Index;
597 }
598
Vedant Kumar8046d222017-11-09 02:33:39 +0000599 /// Complete a deferred region created after a terminated region at the
600 /// top-level.
601 void completeTopLevelDeferredRegion(Counter Count,
602 SourceLocation DeferredEndLoc) {
603 if (DeferredRegion || !LastTerminatedRegion)
604 return;
605
606 if (LastTerminatedRegion->second != RegionStack.size())
607 return;
608
609 SourceLocation Start = LastTerminatedRegion->first;
610 if (SM.getFileID(Start) != SM.getMainFileID())
611 return;
612
613 SourceMappingRegion DR = RegionStack.back();
614 DR.setStartLoc(Start);
615 DR.setDeferred(false);
616 DeferredRegion = DR;
617 completeDeferred(Count, DeferredEndLoc);
618 }
619
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000620 size_t locationDepth(SourceLocation Loc) {
621 size_t Depth = 0;
622 while (Loc.isValid()) {
623 Loc = getIncludeOrExpansionLoc(Loc);
624 Depth++;
625 }
626 return Depth;
627 }
628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000629 /// Pop regions from the stack into the function's list of regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000630 ///
631 /// Adds all regions from \c ParentIndex to the top of the stack to the
632 /// function's \c SourceRegions.
633 void popRegions(size_t ParentIndex) {
634 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000635 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000636 while (RegionStack.size() > ParentIndex) {
637 SourceMappingRegion &Region = RegionStack.back();
638 if (Region.hasStartLoc()) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000639 SourceLocation StartLoc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000640 SourceLocation EndLoc = Region.hasEndLoc()
641 ? Region.getEndLoc()
642 : RegionStack[ParentIndex].getEndLoc();
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000643 size_t StartDepth = locationDepth(StartLoc);
644 size_t EndDepth = locationDepth(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000645 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000646 bool UnnestStart = StartDepth >= EndDepth;
647 bool UnnestEnd = EndDepth >= StartDepth;
648 if (UnnestEnd) {
649 // The region ends in a nested file or macro expansion. Create a
650 // separate region for each expansion.
651 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
652 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000653
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000654 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
655 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000656
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000657 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
658 if (EndLoc.isInvalid())
659 llvm::report_fatal_error("File exit not handled before popRegions");
660 EndDepth--;
661 }
662 if (UnnestStart) {
663 // The region begins in a nested file or macro expansion. Create a
664 // separate region for each expansion.
665 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
666 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
667
668 if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
669 SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
670
671 StartLoc = getIncludeOrExpansionLoc(StartLoc);
672 if (StartLoc.isInvalid())
673 llvm::report_fatal_error("File exit not handled before popRegions");
674 StartDepth--;
675 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000676 }
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000677 Region.setStartLoc(StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000678 Region.setEndLoc(EndLoc);
679
680 MostRecentLocation = EndLoc;
681 // If this region happens to span an entire expansion, we need to make
682 // sure we don't overlap the parent region with it.
683 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
684 EndLoc == getEndOfFileOrMacro(EndLoc))
685 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
686
Stephen Kellya6e43582018-08-09 21:05:56 +0000687 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000688 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000689 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000690
691 if (ParentOfDeferredRegion) {
692 ParentOfDeferredRegion = false;
693
694 // If there's an existing deferred region, keep the old one, because
695 // it means there are two consecutive returns (or a similar pattern).
696 if (!DeferredRegion.hasValue() &&
697 // File IDs aren't gathered within macro expansions, so it isn't
698 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000699 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000700 DeferredRegion =
701 SourceMappingRegion(Counter::getZero(), EndLoc, None);
702 }
703 } else if (Region.isDeferred()) {
704 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
705 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000706 }
707 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000708
709 // If the zero region pushed after the last terminated region no longer
710 // exists, clear its cached information.
711 if (LastTerminatedRegion &&
712 RegionStack.size() < LastTerminatedRegion->second)
713 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000714 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000715 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000716 }
717
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000718 /// Return the currently active region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000719 SourceMappingRegion &getRegion() {
720 assert(!RegionStack.empty() && "statement has no region");
721 return RegionStack.back();
722 }
Alex Lorenzee024992014-08-04 18:41:51 +0000723
Vedant Kumar7225a262018-11-28 20:48:07 +0000724 /// Propagate counts through the children of \p S if \p VisitChildren is true.
725 /// Otherwise, only emit a count for \p S itself.
726 Counter propagateCounts(Counter TopCount, const Stmt *S,
727 bool VisitChildren = true) {
Vedant Kumar78386962017-07-27 02:20:20 +0000728 SourceLocation StartLoc = getStart(S);
729 SourceLocation EndLoc = getEnd(S);
730 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Vedant Kumar7225a262018-11-28 20:48:07 +0000731 if (VisitChildren)
732 Visit(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000733 Counter ExitCount = getRegion().getCounter();
734 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000735
736 // The statement may be spanned by an expansion. Make sure we handle a file
737 // exit out of this expansion before moving to the next statement.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000738 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
Vedant Kumar78386962017-07-27 02:20:20 +0000739 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000740
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000741 return ExitCount;
742 }
Alex Lorenzee024992014-08-04 18:41:51 +0000743
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000744 /// Check whether a region with bounds \c StartLoc and \c EndLoc
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000745 /// is already added to \c SourceRegions.
746 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
747 return SourceRegions.rend() !=
748 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
749 [&](const SourceMappingRegion &Region) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000750 return Region.getBeginLoc() == StartLoc &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000751 Region.getEndLoc() == EndLoc;
752 });
753 }
754
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000755 /// Adjust the most recently visited location to \c EndLoc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000756 ///
757 /// This should be used after visiting any statements in non-source order.
758 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
759 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000760 // The code region for a whole macro is created in handleFileExit() when
761 // it detects exiting of the virtual file of that macro. If we visited
762 // statements in non-source order, we might already have such a region
763 // added, for example, if a body of a loop is divided among multiple
764 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000765 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000766 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
767 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
768 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000769 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
770 }
Alex Lorenzee024992014-08-04 18:41:51 +0000771
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000772 /// Adjust regions and state when \c NewLoc exits a file.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000773 ///
774 /// If moving from our most recently tracked location to \c NewLoc exits any
775 /// files, this adjusts our current region stack and creates the file regions
776 /// for the exited file.
777 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000778 if (NewLoc.isInvalid() ||
779 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000780 return;
781
782 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
783 // find the common ancestor.
784 SourceLocation LCA = NewLoc;
785 FileID ParentFile = SM.getFileID(LCA);
786 while (!isNestedIn(MostRecentLocation, ParentFile)) {
787 LCA = getIncludeOrExpansionLoc(LCA);
788 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
789 // Since there isn't a common ancestor, no file was exited. We just need
790 // to adjust our location to the new file.
791 MostRecentLocation = NewLoc;
792 return;
793 }
794 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000795 }
796
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000797 llvm::SmallSet<SourceLocation, 8> StartLocs;
798 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000799 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
800 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000801 continue;
Stephen Kellya6e43582018-08-09 21:05:56 +0000802 SourceLocation Loc = I.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000803 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000804 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000805 break;
806 }
Alex Lorenzee024992014-08-04 18:41:51 +0000807
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000808 while (!SM.isInFileID(Loc, ParentFile)) {
809 // The most nested region for each start location is the one with the
810 // correct count. We avoid creating redundant regions by stopping once
811 // we've seen this region.
812 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000813 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000814 getEndOfFileOrMacro(Loc));
815 Loc = getIncludeOrExpansionLoc(Loc);
816 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000817 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000818 }
819
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000820 if (ParentCounter) {
821 // If the file is contained completely by another region and doesn't
822 // immediately start its own region, the whole file gets a region
823 // corresponding to the parent.
824 SourceLocation Loc = MostRecentLocation;
825 while (isNestedIn(Loc, ParentFile)) {
826 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000827 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000828 SourceRegions.emplace_back(*ParentCounter, FileStart,
829 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000830 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
831 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000832 Loc = getIncludeOrExpansionLoc(Loc);
833 }
Alex Lorenzee024992014-08-04 18:41:51 +0000834 }
835
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000836 MostRecentLocation = NewLoc;
837 }
Alex Lorenzee024992014-08-04 18:41:51 +0000838
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000839 /// Ensure that \c S is included in the current region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000840 void extendRegion(const Stmt *S) {
841 SourceMappingRegion &Region = getRegion();
842 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000843
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000844 handleFileExit(StartLoc);
845 if (!Region.hasStartLoc())
846 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000847
848 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000849 }
850
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000851 /// Mark \c S as a terminator, starting a zero region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000852 void terminateRegion(const Stmt *S) {
853 extendRegion(S);
854 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000855 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000856 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000857 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000858 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000859 auto &ZeroRegion = getRegion();
860 ZeroRegion.setDeferred(true);
861 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000862 }
Alex Lorenzee024992014-08-04 18:41:51 +0000863
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000864 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
865 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
866 SourceLocation BeforeLoc) {
Zequan Wua31c89c2020-08-11 12:39:25 -0700867 AfterLoc = SM.getExpansionLoc(AfterLoc);
868 BeforeLoc = SM.getExpansionLoc(BeforeLoc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000869 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
870 return None;
871 return {{AfterLoc, BeforeLoc}};
872 }
873
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000874 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
875 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
876 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000877 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000878 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000879 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000880 handleFileExit(StartLoc);
881 size_t Index = pushRegion(Count, StartLoc, EndLoc);
882 getRegion().setGap(true);
883 handleFileExit(EndLoc);
884 popRegions(Index);
885 }
886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000887 /// Keep counts of breaks and continues inside loops.
Alex Lorenzee024992014-08-04 18:41:51 +0000888 struct BreakContinue {
889 Counter BreakCount;
890 Counter ContinueCount;
891 };
892 SmallVector<BreakContinue, 8> BreakContinueStack;
893
894 CounterCoverageMappingBuilder(
895 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000896 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000897 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000898 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
899 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000900
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000901 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000902 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000903 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000904 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000905 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000906 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000907 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000908 gatherSkippedRegions();
909
Vedant Kumarefd319a2016-07-26 00:24:59 +0000910 if (MappingRegions.empty())
911 return;
912
Justin Bogner4da909b2015-02-03 21:35:49 +0000913 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
914 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000915 Writer.write(OS);
916 }
917
Alex Lorenzee024992014-08-04 18:41:51 +0000918 void VisitStmt(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000919 if (S->getBeginLoc().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000920 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000921 for (const Stmt *Child : S->children())
922 if (Child)
923 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000924 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000925 }
926
Alex Lorenzee024992014-08-04 18:41:51 +0000927 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000928 assert(!DeferredRegion && "Deferred region never completed");
929
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000930 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000931
932 // Do not propagate region counts into system headers.
933 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
934 return;
935
Vedant Kumar7225a262018-11-28 20:48:07 +0000936 // Do not visit the artificial children nodes of defaulted methods. The
937 // lexer may not be able to report back precise token end locations for
938 // these children nodes (llvm.org/PR39822), and moreover users will not be
939 // able to see coverage for them.
940 bool Defaulted = false;
941 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
942 Defaulted = Method->isDefaulted();
943
944 propagateCounts(getRegionCounter(Body), Body,
945 /*VisitChildren=*/!Defaulted);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000946 assert(RegionStack.empty() && "Regions entered but never exited");
947
Vedant Kumar61763b62018-05-30 23:35:44 +0000948 // Discard the last uncompleted deferred region in a decl, if one exists.
949 // This prevents lines at the end of a function containing only whitespace
950 // or closing braces from being marked as uncovered.
951 DeferredRegion = None;
Alex Lorenzee024992014-08-04 18:41:51 +0000952 }
953
954 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000955 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000956 if (S->getRetValue())
957 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000958 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000959 }
960
Xun Li565e37c2020-06-30 17:07:45 -0700961 void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
962 extendRegion(S);
963 Visit(S->getBody());
964 }
965
966 void VisitCoreturnStmt(const CoreturnStmt *S) {
967 extendRegion(S);
968 if (S->getOperand())
969 Visit(S->getOperand());
970 terminateRegion(S);
971 }
972
Justin Bognerf959feb2015-04-28 06:31:55 +0000973 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
974 extendRegion(E);
975 if (E->getSubExpr())
976 Visit(E->getSubExpr());
977 terminateRegion(E);
978 }
979
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000980 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000981
982 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000983 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000984 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000985 completeTopLevelDeferredRegion(LabelCount, Start);
Vedant Kumard781d972018-06-01 00:37:13 +0000986 completeDeferred(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000987 // We can't extendRegion here or we risk overlapping with our new region.
988 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000989 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000990 Visit(S->getSubStmt());
991 }
992
993 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000994 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
995 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000996 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000997 // FIXME: a break in a switch should terminate regions for all preceding
998 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000999 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001000 }
1001
1002 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +00001003 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1004 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001005 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1006 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001007 }
1008
Eli Friedman181dfe42017-08-08 20:10:14 +00001009 void VisitCallExpr(const CallExpr *E) {
1010 VisitStmt(E);
1011
1012 // Terminate the region when we hit a noreturn function.
1013 // (This is helpful dealing with switch statements.)
1014 QualType CalleeType = E->getCallee()->getType();
1015 if (getFunctionExtInfo(*CalleeType).getNoReturn())
1016 terminateRegion(E);
1017 }
1018
Alex Lorenzee024992014-08-04 18:41:51 +00001019 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001020 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001021
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001022 Counter ParentCount = getRegion().getCounter();
1023 Counter BodyCount = getRegionCounter(S);
1024
1025 // Handle the body first so that we can get the backedge count.
1026 BreakContinueStack.push_back(BreakContinue());
1027 extendRegion(S->getBody());
1028 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001029 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001030
1031 // Go back to handle the condition.
1032 Counter CondCount =
1033 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1034 propagateCounts(CondCount, S->getCond());
1035 adjustForOutOfOrderTraversal(getEnd(S));
1036
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001037 // The body count applies to the area immediately after the increment.
Zequan Wua31c89c2020-08-11 12:39:25 -07001038 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1039 getStart(S->getBody()));
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001040 if (Gap)
1041 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1042
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001043 Counter OutCount =
1044 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1045 if (OutCount != ParentCount)
1046 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001047 }
1048
1049 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001050 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001051
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001052 Counter ParentCount = getRegion().getCounter();
1053 Counter BodyCount = getRegionCounter(S);
1054
1055 BreakContinueStack.push_back(BreakContinue());
1056 extendRegion(S->getBody());
1057 Counter BackedgeCount =
1058 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001059 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001060
1061 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1062 propagateCounts(CondCount, S->getCond());
1063
1064 Counter OutCount =
1065 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1066 if (OutCount != ParentCount)
1067 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001068 }
1069
1070 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001071 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001072 if (S->getInit())
1073 Visit(S->getInit());
1074
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001075 Counter ParentCount = getRegion().getCounter();
1076 Counter BodyCount = getRegionCounter(S);
1077
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001078 // The loop increment may contain a break or continue.
1079 if (S->getInc())
1080 BreakContinueStack.emplace_back();
1081
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001082 // Handle the body first so that we can get the backedge count.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001083 BreakContinueStack.emplace_back();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001084 extendRegion(S->getBody());
1085 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001086 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +00001087
1088 // The increment is essentially part of the body but it needs to include
1089 // the count for all the continue statements.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001090 BreakContinue IncrementBC;
1091 if (const Stmt *Inc = S->getInc()) {
1092 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1093 IncrementBC = BreakContinueStack.pop_back_val();
1094 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001095
1096 // Go back to handle the condition.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001097 Counter CondCount = addCounters(
1098 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1099 IncrementBC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001100 if (const Expr *Cond = S->getCond()) {
1101 propagateCounts(CondCount, Cond);
1102 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +00001103 }
1104
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001105 // The body count applies to the area immediately after the increment.
1106 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1107 getStart(S->getBody()));
1108 if (Gap)
1109 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1110
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001111 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1112 subtractCounters(CondCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001113 if (OutCount != ParentCount)
1114 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001115 }
1116
1117 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001118 extendRegion(S);
Richard Smith8baa5002018-09-28 18:44:09 +00001119 if (S->getInit())
1120 Visit(S->getInit());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001121 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001122 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001123
1124 Counter ParentCount = getRegion().getCounter();
1125 Counter BodyCount = getRegionCounter(S);
1126
Alex Lorenzee024992014-08-04 18:41:51 +00001127 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001128 extendRegion(S->getBody());
1129 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001130 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001131
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001132 // The body count applies to the area immediately after the range.
1133 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1134 getStart(S->getBody()));
1135 if (Gap)
1136 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1137
Justin Bogner15874322015-04-30 21:31:02 +00001138 Counter LoopCount =
1139 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1140 Counter OutCount =
1141 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001142 if (OutCount != ParentCount)
1143 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001144 }
1145
1146 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001147 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001148 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001149
1150 Counter ParentCount = getRegion().getCounter();
1151 Counter BodyCount = getRegionCounter(S);
1152
Alex Lorenzee024992014-08-04 18:41:51 +00001153 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001154 extendRegion(S->getBody());
1155 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001156 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001157
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001158 // The body count applies to the area immediately after the collection.
1159 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1160 getStart(S->getBody()));
1161 if (Gap)
1162 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1163
Justin Bogner15874322015-04-30 21:31:02 +00001164 Counter LoopCount =
1165 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1166 Counter OutCount =
1167 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001168 if (OutCount != ParentCount)
1169 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001170 }
1171
1172 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001173 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001174 if (S->getInit())
1175 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001176 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001177
Alex Lorenzee024992014-08-04 18:41:51 +00001178 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001179
1180 const Stmt *Body = S->getBody();
1181 extendRegion(Body);
1182 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1183 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001184 // Make a region for the body of the switch. If the body starts with
1185 // a case, that case will reuse this region; otherwise, this covers
1186 // the unreachable code at the beginning of the switch body.
Vedant Kumar859bf4d2019-11-21 14:17:04 -08001187 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1188 getRegion().setGap(true);
Richard Trieub5841332015-04-15 01:21:42 +00001189 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001190 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001191
1192 // Set the end for the body of the switch, if it isn't already set.
1193 for (size_t i = RegionStack.size(); i != Index; --i) {
1194 if (!RegionStack[i - 1].hasEndLoc())
1195 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1196 }
1197
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001198 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001199 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001200 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001201 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001202 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001203
Alex Lorenzee024992014-08-04 18:41:51 +00001204 if (!BreakContinueStack.empty())
1205 BreakContinueStack.back().ContinueCount = addCounters(
1206 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001207
1208 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001209 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001210 pushRegion(ExitCount);
1211
1212 // Ensure that handleFileExit recognizes when the end location is located
1213 // in a different file.
1214 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001215 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001216 }
1217
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001218 void VisitSwitchCase(const SwitchCase *S) {
1219 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001220
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001221 SourceMappingRegion &Parent = getRegion();
1222
1223 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1224 // Reuse the existing region if it starts at our label. This is typical of
1225 // the first case in a switch.
Stephen Kellya6e43582018-08-09 21:05:56 +00001226 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001227 Parent.setCounter(Count);
1228 else
1229 pushRegion(Count, getStart(S));
1230
Sanjay Patel376c06c2015-12-24 21:11:29 +00001231 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001232 Visit(CS->getLHS());
1233 if (const Expr *RHS = CS->getRHS())
1234 Visit(RHS);
1235 }
Alex Lorenzee024992014-08-04 18:41:51 +00001236 Visit(S->getSubStmt());
1237 }
1238
1239 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001240 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001241 if (S->getInit())
1242 Visit(S->getInit());
1243
Justin Bogner055ebc32015-06-16 06:24:15 +00001244 // Extend into the condition before we propagate through it below - this is
1245 // needed to handle macros that generate the "if" but not the condition.
1246 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001247
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001248 Counter ParentCount = getRegion().getCounter();
1249 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001250
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001251 // Emitting a counter for the condition makes it easier to interpret the
1252 // counter for the body when looking at the coverage.
1253 propagateCounts(ParentCount, S->getCond());
1254
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001255 // The 'then' count applies to the area immediately after the condition.
Zequan Wua31c89c2020-08-11 12:39:25 -07001256 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1257 getStart(S->getThen()));
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001258 if (Gap)
1259 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001260
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001261 extendRegion(S->getThen());
1262 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1263
1264 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1265 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001266 // The 'else' count applies to the area immediately after the 'then'.
Zequan Wua31c89c2020-08-11 12:39:25 -07001267 Gap = findGapAreaBetween(getPreciseTokenLocEnd(getEnd(S->getThen())),
1268 getStart(Else));
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001269 if (Gap)
1270 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001271 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001272 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1273 } else
1274 OutCount = addCounters(OutCount, ElseCount);
1275
1276 if (OutCount != ParentCount)
1277 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001278 }
1279
1280 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001281 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001282 // Handle macros that generate the "try" but not the rest.
1283 extendRegion(S->getTryBlock());
1284
1285 Counter ParentCount = getRegion().getCounter();
1286 propagateCounts(ParentCount, S->getTryBlock());
1287
Alex Lorenzee024992014-08-04 18:41:51 +00001288 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1289 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001290
1291 Counter ExitCount = getRegionCounter(S);
1292 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001293 }
1294
1295 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001296 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001297 }
1298
1299 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001300 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001301
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001302 Counter ParentCount = getRegion().getCounter();
1303 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001304
Justin Bognere3654ce2015-04-24 23:37:57 +00001305 Visit(E->getCond());
1306
1307 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001308 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001309 auto Gap =
1310 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1311 if (Gap)
1312 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001313
Justin Bognere3654ce2015-04-24 23:37:57 +00001314 extendRegion(E->getTrueExpr());
1315 propagateCounts(TrueCount, E->getTrueExpr());
1316 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001317
Justin Bognere3654ce2015-04-24 23:37:57 +00001318 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001319 propagateCounts(subtractCounters(ParentCount, TrueCount),
1320 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001321 }
1322
1323 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001324 extendRegion(E->getLHS());
1325 propagateCounts(getRegion().getCounter(), E->getLHS());
1326 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001327
1328 extendRegion(E->getRHS());
1329 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001330 }
1331
1332 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001333 extendRegion(E->getLHS());
1334 propagateCounts(getRegion().getCounter(), E->getLHS());
1335 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001336
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001337 extendRegion(E->getRHS());
1338 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001339 }
Justin Bognerc1091022015-02-24 04:13:56 +00001340
1341 void VisitLambdaExpr(const LambdaExpr *LE) {
1342 // Lambdas are treated as their own functions for now, so we shouldn't
1343 // propagate counts into them.
1344 }
Alex Lorenzee024992014-08-04 18:41:51 +00001345};
Alex Lorenzee024992014-08-04 18:41:51 +00001346
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001347std::string normalizeFilename(StringRef Filename) {
1348 llvm::SmallString<256> Path(Filename);
1349 llvm::sys::fs::make_absolute(Path);
1350 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Jonas Devlieghere509e21a2020-01-29 21:27:46 -08001351 return std::string(Path);
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001352}
1353
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001354} // end anonymous namespace
1355
Justin Bognera432d172015-02-03 00:20:24 +00001356static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1357 ArrayRef<CounterExpression> Expressions,
1358 ArrayRef<CounterMappingRegion> Regions) {
1359 OS << FunctionName << ":\n";
1360 CounterMappingContext Ctx(Expressions);
1361 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001362 OS.indent(2);
1363 switch (R.Kind) {
1364 case CounterMappingRegion::CodeRegion:
1365 break;
1366 case CounterMappingRegion::ExpansionRegion:
1367 OS << "Expansion,";
1368 break;
1369 case CounterMappingRegion::SkippedRegion:
1370 OS << "Skipped,";
1371 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001372 case CounterMappingRegion::GapRegion:
1373 OS << "Gap,";
1374 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001375 }
1376
Justin Bogner4da909b2015-02-03 21:35:49 +00001377 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1378 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001379 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001380 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001381 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1382 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001383 }
1384}
1385
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001386static std::string getInstrProfSection(const CodeGenModule &CGM,
1387 llvm::InstrProfSectKind SK) {
1388 return llvm::getInstrProfSectionName(
1389 SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1390}
1391
1392void CoverageMappingModuleGen::emitFunctionMappingRecord(
1393 const FunctionInfo &Info, uint64_t FilenamesRef) {
1394 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1395
1396 // Assign a name to the function record. This is used to merge duplicates.
1397 std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1398
1399 // A dummy description for a function included-but-not-used in a TU can be
1400 // replaced by full description provided by a different TU. The two kinds of
1401 // descriptions play distinct roles: therefore, assign them different names
1402 // to prevent `linkonce_odr` merging.
1403 if (Info.IsUsed)
1404 FuncRecordName += "u";
1405
1406 // Create the function record type.
1407 const uint64_t NameHash = Info.NameHash;
1408 const uint64_t FuncHash = Info.FuncHash;
1409 const std::string &CoverageMapping = Info.CoverageMapping;
1410#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1411 llvm::Type *FunctionRecordTypes[] = {
1412#include "llvm/ProfileData/InstrProfData.inc"
1413 };
1414 auto *FunctionRecordTy =
1415 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1416 /*isPacked=*/true);
1417
1418 // Create the function record constant.
1419#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1420 llvm::Constant *FunctionRecordVals[] = {
1421 #include "llvm/ProfileData/InstrProfData.inc"
1422 };
1423 auto *FuncRecordConstant = llvm::ConstantStruct::get(
1424 FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1425
1426 // Create the function record global.
1427 auto *FuncRecord = new llvm::GlobalVariable(
1428 CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1429 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1430 FuncRecordName);
1431 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1432 FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1433 FuncRecord->setAlignment(llvm::Align(8));
1434 if (CGM.supportsCOMDAT())
1435 FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1436
1437 // Make sure the data doesn't get deleted.
1438 CGM.addUsedGlobal(FuncRecord);
1439}
1440
Alex Lorenzee024992014-08-04 18:41:51 +00001441void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001442 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001443 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001444 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001445 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1446 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
Alex Lorenzee024992014-08-04 18:41:51 +00001447
Xinliang David Li848da132016-01-19 00:49:06 +00001448 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001449 FunctionNames.push_back(
1450 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001451
1452 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1453 // Dump the coverage mapping data for this function by decoding the
1454 // encoded data. This allows us to dump the mapping regions which were
1455 // also processed by the CoverageMappingWriter which performs
1456 // additional minimization operations such as reducing the number of
1457 // expressions.
1458 std::vector<StringRef> Filenames;
1459 std::vector<CounterExpression> Expressions;
1460 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001461 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001462 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001463 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001464 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001465 for (const auto &Entry : FileEntries) {
1466 auto I = Entry.second;
1467 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1468 FilenameRefs[I] = FilenameStrs[I];
1469 }
Justin Bognera432d172015-02-03 00:20:24 +00001470 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1471 Expressions, Regions);
1472 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001473 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001474 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001475 }
Alex Lorenzee024992014-08-04 18:41:51 +00001476}
1477
1478void CoverageMappingModuleGen::emit() {
1479 if (FunctionRecords.empty())
1480 return;
1481 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1482 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1483
1484 // Create the filenames and merge them with coverage mappings
1485 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001486 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001487 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001488 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001489 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001490 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001491 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001492 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001493 }
1494
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001495 std::string Filenames;
1496 {
1497 llvm::raw_string_ostream OS(Filenames);
1498 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001499 }
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001500 auto *FilenamesVal =
1501 llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1502 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001503
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001504 // Emit the function records.
1505 for (const FunctionInfo &Info : FunctionRecords)
1506 emitFunctionMappingRecord(Info, FilenamesRef);
Alex Lorenzee024992014-08-04 18:41:51 +00001507
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001508 const unsigned NRecords = 0;
1509 const size_t FilenamesSize = Filenames.size();
1510 const unsigned CoverageMappingSize = 0;
Xinliang David Li20b188c2016-01-03 19:25:54 +00001511 llvm::Type *CovDataHeaderTypes[] = {
1512#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1513#include "llvm/ProfileData/InstrProfData.inc"
1514 };
1515 auto CovDataHeaderTy =
1516 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1517 llvm::Constant *CovDataHeaderVals[] = {
1518#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1519#include "llvm/ProfileData/InstrProfData.inc"
1520 };
1521 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1522 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1523
Alex Lorenzee024992014-08-04 18:41:51 +00001524 // Create the coverage data record
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001525 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001526 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001527 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001528 auto CovDataVal =
1529 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001530 auto CovData = new llvm::GlobalVariable(
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001531 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
Xinliang David Li20b188c2016-01-03 19:25:54 +00001532 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001533
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001534 CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001535 CovData->setAlignment(llvm::Align(8));
Alex Lorenzee024992014-08-04 18:41:51 +00001536
1537 // Make sure the data doesn't get deleted.
1538 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001539 // Create the deferred function records array
1540 if (!FunctionNames.empty()) {
1541 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1542 FunctionNames.size());
1543 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1544 // This variable will *NOT* be emitted to the object file. It is used
1545 // to pass the list of names referenced to codegen.
1546 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1547 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001548 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001549 }
Alex Lorenzee024992014-08-04 18:41:51 +00001550}
1551
1552unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1553 auto It = FileEntries.find(File);
1554 if (It != FileEntries.end())
1555 return It->second;
1556 unsigned FileID = FileEntries.size();
1557 FileEntries.insert(std::make_pair(File, FileID));
1558 return FileID;
1559}
1560
1561void CoverageMappingGen::emitCounterMapping(const Decl *D,
1562 llvm::raw_ostream &OS) {
1563 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001564 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001565 Walker.VisitDecl(D);
1566 Walker.write(OS);
1567}
1568
1569void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1570 llvm::raw_ostream &OS) {
1571 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1572 Walker.VisitDecl(D);
1573 Walker.write(OS);
1574}