blob: 8277804d27c0eceff30192f23e60a140730b407b [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();
Zequan Wu84fffa62020-08-17 15:25:08 -070047 if (Tok.getKind() != clang::tok::eod)
48 CoverageInfo->updateNextTokLoc(Tok.getLocation());
Zequan Wub46176b2020-07-22 19:04:59 -070049 });
50 return CoverageInfo;
51}
52
Vedant Kumar3919a502017-09-11 20:47:42 +000053void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Zequan Wub46176b2020-07-22 19:04:59 -070054 SkippedRanges.push_back({Range});
55}
56
57bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
58 SkippedRanges.push_back({Range, PrevTokLoc});
59 AfterComment = true;
60 return false;
61}
62
63void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
64 if (AfterComment) {
65 SkippedRanges.back().NextTokLoc = Loc;
66 AfterComment = false;
67 }
Alex Lorenzee024992014-08-04 18:41:51 +000068}
69
70namespace {
71
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000072/// A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000073class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000074 Counter Count;
75
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000076 /// The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000077 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000078
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000079 /// The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000080 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000081
Vedant Kumar747b0e22017-09-08 18:44:56 +000082 /// Whether this region should be emitted after its parent is emitted.
83 bool DeferRegion;
84
Vedant Kumara1c4deb2017-09-18 23:37:30 +000085 /// Whether this region is a gap region. The count from a gap region is set
86 /// as the line execution count if there are no other regions on the line.
87 bool GapRegion;
88
Justin Bogner09c71792014-10-01 03:33:49 +000089public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000090 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000091 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
92 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000093 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000094 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000095
Justin Bogner09c71792014-10-01 03:33:49 +000096 const Counter &getCounter() const { return Count; }
97
Justin Bognerbf42cfd2015-02-18 21:24:51 +000098 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000099
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000100 bool hasStartLoc() const { return LocStart.hasValue(); }
101
102 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
103
Stephen Kelly3cffc4c2018-08-09 20:05:18 +0000104 SourceLocation getBeginLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000105 assert(LocStart && "Region has no start location");
106 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +0000107 }
108
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000109 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +0000110
Vedant Kumara14a1f92018-01-17 18:53:51 +0000111 void setEndLoc(SourceLocation Loc) {
112 assert(Loc.isValid() && "Setting an invalid end location");
113 LocEnd = Loc;
114 }
Alex Lorenzee024992014-08-04 18:41:51 +0000115
Craig Topper462c77b2015-09-26 05:10:14 +0000116 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000117 assert(LocEnd && "Region has no end location");
118 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +0000119 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000120
121 bool isDeferred() const { return DeferRegion; }
122
123 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000124
125 bool isGap() const { return GapRegion; }
126
127 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +0000128};
129
Vedant Kumard7369642017-07-27 02:20:25 +0000130/// Spelling locations for the start and end of a source region.
131struct SpellingRegion {
132 /// The line where the region starts.
133 unsigned LineStart;
134
135 /// The column where the region starts.
136 unsigned ColumnStart;
137
138 /// The line where the region ends.
139 unsigned LineEnd;
140
141 /// The column where the region ends.
142 unsigned ColumnEnd;
143
144 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
145 SourceLocation LocEnd) {
146 LineStart = SM.getSpellingLineNumber(LocStart);
147 ColumnStart = SM.getSpellingColumnNumber(LocStart);
148 LineEnd = SM.getSpellingLineNumber(LocEnd);
149 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
150 }
151
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000152 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
Stephen Kellya6e43582018-08-09 21:05:56 +0000153 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000154
Vedant Kumard7369642017-07-27 02:20:25 +0000155 /// Check if the start and end locations appear in source order, i.e
156 /// top->bottom, left->right.
157 bool isInSourceOrder() const {
158 return (LineStart < LineEnd) ||
159 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
160 }
161};
162
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000163/// Provides the common functionality for the different
Alex Lorenzee024992014-08-04 18:41:51 +0000164/// coverage mapping region builders.
165class CoverageMappingBuilder {
166public:
167 CoverageMappingModuleGen &CVM;
168 SourceManager &SM;
169 const LangOptions &LangOpts;
170
171private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000172 /// Map of clang's FileIDs to IDs used for coverage mapping.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000173 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
174 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000175
176public:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// The coverage mapping regions for this function
Alex Lorenzee024992014-08-04 18:41:51 +0000178 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000179 /// The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000180 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000181
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000182 /// A set of regions which can be used as a filter.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000183 ///
184 /// It is produced by emitExpansionRegions() and is used in
185 /// emitSourceRegions() to suppress producing code regions if
186 /// the same area is covered by expansion regions.
187 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
188 SourceRegionFilter;
189
Alex Lorenzee024992014-08-04 18:41:51 +0000190 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
191 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000192 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000193
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000194 /// Return the precise end location for the given token.
Alex Lorenzee024992014-08-04 18:41:51 +0000195 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000196 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
197 // macro locations, which we just treat as expanded files.
198 unsigned TokLen =
199 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
200 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000201 }
202
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000203 /// Return the start location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000204 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
205 if (Loc.isMacroID())
206 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
207 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000208 }
209
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000210 /// Return the end location of an included file or expanded macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000211 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
212 if (Loc.isMacroID())
213 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000214 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000215 return SM.getLocForEndOfFile(SM.getFileID(Loc));
216 }
217
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000218 /// Find out where the current file is included or macro is expanded.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000219 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
Richard Smithb5f81712018-04-30 05:25:48 +0000220 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000221 : SM.getIncludeLoc(SM.getFileID(Loc));
222 }
223
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000224 /// Return true if \c Loc is a location in a built-in macro.
Justin Bogner682bfbf2015-05-14 22:14:10 +0000225 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000226 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000227 }
228
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000229 /// Check whether \c Loc is included or expanded from \c Parent.
Igor Kudrind9e1a612016-06-07 10:07:51 +0000230 bool isNestedIn(SourceLocation Loc, FileID Parent) {
231 do {
232 Loc = getIncludeOrExpansionLoc(Loc);
233 if (Loc.isInvalid())
234 return false;
235 } while (!SM.isInFileID(Loc, Parent));
236 return true;
237 }
238
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000239 /// Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000240 SourceLocation getStart(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000241 SourceLocation Loc = S->getBeginLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000242 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000243 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000244 return Loc;
245 }
246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247 /// Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000248 SourceLocation getEnd(const Stmt *S) {
Stephen Kelly1c301dc2018-08-09 21:09:38 +0000249 SourceLocation Loc = S->getEndLoc();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000250 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Richard Smithb5f81712018-04-30 05:25:48 +0000251 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
Justin Bognerf14b2072015-03-25 04:13:49 +0000252 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000253 }
254
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000255 /// Find the set of files we have regions for and assign IDs
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000256 ///
257 /// Fills \c Mapping with the virtual file mapping needed to write out
258 /// coverage and collects the necessary file information to emit source and
259 /// expansion regions.
260 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
261 FileIDMapping.clear();
262
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000263 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000264 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
265 for (const auto &Region : SourceRegions) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000266 SourceLocation Loc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000267 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000268 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000269 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000270
Vedant Kumar93205af2016-07-11 22:57:46 +0000271 // Do not map FileID's associated with system headers.
272 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
273 continue;
274
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000275 unsigned Depth = 0;
276 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000277 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000278 ++Depth;
279 FileLocs.push_back(std::make_pair(Loc, Depth));
280 }
Fangrui Song899d1392019-04-24 14:43:05 +0000281 llvm::stable_sort(FileLocs, llvm::less_second());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000282
283 for (const auto &FL : FileLocs) {
284 SourceLocation Loc = FL.first;
285 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
286 auto Entry = SM.getFileEntryForID(SpellingFile);
287 if (!Entry)
288 continue;
289
290 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
291 Mapping.push_back(CVM.getFileID(Entry));
292 }
293 }
294
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000295 /// Get the coverage mapping file ID for \c Loc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000296 ///
297 /// If such file id doesn't exist, return None.
298 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
299 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000300 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000301 return Mapping->second.first;
302 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000303 }
304
Zequan Wub46176b2020-07-22 19:04:59 -0700305 /// This shrinks the skipped range if it spans a line that contains a
306 /// non-comment token. If shrinking the skipped range would make it empty,
307 /// this returns None.
308 Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
Zequan Wu84fffa62020-08-17 15:25:08 -0700309 SourceLocation LocStart,
310 SourceLocation LocEnd,
Zequan Wub46176b2020-07-22 19:04:59 -0700311 SourceLocation PrevTokLoc,
312 SourceLocation NextTokLoc) {
Zequan Wu84fffa62020-08-17 15:25:08 -0700313 SpellingRegion SR{SM, LocStart, LocEnd};
Zequan Wub46176b2020-07-22 19:04:59 -0700314 // If Range begin location is invalid, it's not a comment region.
315 if (PrevTokLoc.isInvalid())
316 return SR;
317 unsigned PrevTokLine = SM.getSpellingLineNumber(PrevTokLoc);
318 unsigned NextTokLine = SM.getSpellingLineNumber(NextTokLoc);
319 SpellingRegion newSR(SR);
Zequan Wu84fffa62020-08-17 15:25:08 -0700320 if (SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
321 SR.LineStart == PrevTokLine) {
Zequan Wub46176b2020-07-22 19:04:59 -0700322 newSR.LineStart = SR.LineStart + 1;
323 newSR.ColumnStart = 1;
324 }
Zequan Wu84fffa62020-08-17 15:25:08 -0700325 if (SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
326 SR.LineEnd == NextTokLine) {
Zequan Wub46176b2020-07-22 19:04:59 -0700327 newSR.LineEnd = SR.LineEnd - 1;
328 newSR.ColumnEnd = SR.ColumnStart + 1;
329 }
330 if (newSR.isInSourceOrder())
331 return newSR;
332 return None;
333 }
334
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000335 /// Gather all the regions that were skipped by the preprocessor
Zequan Wub46176b2020-07-22 19:04:59 -0700336 /// using the constructs like #if or comments.
Alex Lorenzee024992014-08-04 18:41:51 +0000337 void gatherSkippedRegions() {
338 /// An array of the minimum lineStarts and the maximum lineEnds
339 /// for mapping regions from the appropriate source files.
340 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
341 FileLineRanges.resize(
342 FileIDMapping.size(),
343 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
344 for (const auto &R : MappingRegions) {
345 FileLineRanges[R.FileID].first =
346 std::min(FileLineRanges[R.FileID].first, R.LineStart);
347 FileLineRanges[R.FileID].second =
348 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
349 }
350
351 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
Zequan Wub46176b2020-07-22 19:04:59 -0700352 for (auto &I : SkippedRanges) {
353 SourceRange Range = I.Range;
354 auto LocStart = Range.getBegin();
355 auto LocEnd = Range.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000356 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
357 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000358
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000359 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000360 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000361 continue;
Zequan Wu84fffa62020-08-17 15:25:08 -0700362 Optional<SpellingRegion> SR =
363 adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc);
364 if (!SR.hasValue())
Zequan Wub46176b2020-07-22 19:04:59 -0700365 continue;
Justin Bognerfd34280b2015-02-03 23:59:48 +0000366 auto Region = CounterMappingRegion::makeSkipped(
Zequan Wu84fffa62020-08-17 15:25:08 -0700367 *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
368 SR->ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000369 // Make sure that we only collect the regions that are inside
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000370 // the source code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000371 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
372 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000373 MappingRegions.push_back(Region);
374 }
375 }
376
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000377 /// Generate the coverage counter mapping regions from collected
Alex Lorenzee024992014-08-04 18:41:51 +0000378 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000379 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000380 for (const auto &Region : SourceRegions) {
381 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000382
Stephen Kellya6e43582018-08-09 21:05:56 +0000383 SourceLocation LocStart = Region.getBeginLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000384 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000385
Vedant Kumar93205af2016-07-11 22:57:46 +0000386 // Ignore regions from system headers.
387 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
388 continue;
389
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000390 auto CovFileID = getCoverageFileID(LocStart);
391 // Ignore regions that don't have a file, such as builtin macros.
392 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000393 continue;
394
Justin Bognerf14b2072015-03-25 04:13:49 +0000395 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000396 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
397 "region spans multiple files");
398
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000399 // Don't add code regions for the area covered by expansion regions.
400 // This not only suppresses redundant regions, but sometimes prevents
401 // creating regions with wrong counters if, for example, a statement's
402 // body ends at the end of a nested macro.
403 if (Filter.count(std::make_pair(LocStart, LocEnd)))
404 continue;
405
Vedant Kumard7369642017-07-27 02:20:25 +0000406 // Find the spelling locations for the mapping region.
407 SpellingRegion SR{SM, LocStart, LocEnd};
408 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000409
410 if (Region.isGap()) {
411 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
412 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
413 SR.LineEnd, SR.ColumnEnd));
414 } else {
415 MappingRegions.push_back(CounterMappingRegion::makeRegion(
416 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
417 SR.LineEnd, SR.ColumnEnd));
418 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000419 }
420 }
421
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000422 /// Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000423 SourceRegionFilter emitExpansionRegions() {
424 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000425 for (const auto &FM : FileIDMapping) {
426 SourceLocation ExpandedLoc = FM.second.second;
427 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
428 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000429 continue;
430
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000431 auto ParentFileID = getCoverageFileID(ParentLoc);
432 if (!ParentFileID)
433 continue;
434 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
435 assert(ExpandedFileID && "expansion in uncovered file");
436
437 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
438 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
439 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000440 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000441
Vedant Kumard7369642017-07-27 02:20:25 +0000442 SpellingRegion SR{SM, ParentLoc, LocEnd};
443 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000444 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000445 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
446 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000447 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000448 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000449 }
450};
451
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000452/// Creates unreachable coverage regions for the functions that
Alex Lorenzee024992014-08-04 18:41:51 +0000453/// are not emitted.
454struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
455 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
456 const LangOptions &LangOpts)
457 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
458
459 void VisitDecl(const Decl *D) {
460 if (!D->hasBody())
461 return;
462 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000463 SourceLocation Start = getStart(Body);
464 SourceLocation End = getEnd(Body);
465 if (!SM.isWrittenInSameFile(Start, End)) {
466 // Walk up to find the common ancestor.
467 // Correct the locations accordingly.
468 FileID StartFileID = SM.getFileID(Start);
469 FileID EndFileID = SM.getFileID(End);
470 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
471 Start = getIncludeOrExpansionLoc(Start);
472 assert(Start.isValid() &&
473 "Declaration start location not nested within a known region");
474 StartFileID = SM.getFileID(Start);
475 }
476 while (StartFileID != EndFileID) {
477 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
478 assert(End.isValid() &&
479 "Declaration end location not nested within a known region");
480 EndFileID = SM.getFileID(End);
481 }
482 }
483 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000484 }
485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000487 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000488 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000489 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000490 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000491
Vedant Kumarefd319a2016-07-26 00:24:59 +0000492 if (MappingRegions.empty())
493 return;
494
Craig Topper5fc8fc22014-08-27 06:28:36 +0000495 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000496 Writer.write(OS);
497 }
498};
499
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000500/// A StmtVisitor that creates coverage mapping regions which map
Alex Lorenzee024992014-08-04 18:41:51 +0000501/// from the source code locations to the PGO counters.
502struct CounterCoverageMappingBuilder
503 : public CoverageMappingBuilder,
504 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000505 /// The map of statements to count values.
Alex Lorenzee024992014-08-04 18:41:51 +0000506 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// A stack of currently live regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000509 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000510
Vedant Kumar747b0e22017-09-08 18:44:56 +0000511 /// The currently deferred region: its end location and count can be set once
512 /// its parent has been popped from the region stack.
513 Optional<SourceMappingRegion> DeferredRegion;
514
Alex Lorenzee024992014-08-04 18:41:51 +0000515 CounterExpressionBuilder Builder;
516
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000517 /// A location in the most recently visited file or macro.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000518 ///
519 /// This is used to adjust the active source regions appropriately when
520 /// expressions cross file or macro boundaries.
521 SourceLocation MostRecentLocation;
522
Vedant Kumar8046d222017-11-09 02:33:39 +0000523 /// Location of the last terminated region.
524 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
525
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000526 /// Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000527 Counter subtractCounters(Counter LHS, Counter RHS) {
528 return Builder.subtract(LHS, RHS);
529 }
530
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000531 /// Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000532 Counter addCounters(Counter LHS, Counter RHS) {
533 return Builder.add(LHS, RHS);
534 }
535
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000536 Counter addCounters(Counter C1, Counter C2, Counter C3) {
537 return addCounters(addCounters(C1, C2), C3);
538 }
539
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000540 /// Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000541 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000542 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000543 Counter getRegionCounter(const Stmt *S) {
544 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000545 }
546
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000547 /// Push a region onto the stack.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000548 ///
549 /// Returns the index on the stack where the region was pushed. This can be
550 /// used with popRegions to exit a "scope", ending the region that was pushed.
551 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
552 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000553 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000554 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000555 completeDeferred(Count, MostRecentLocation);
556 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000557 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000558
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000559 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000560 }
561
Vedant Kumar747b0e22017-09-08 18:44:56 +0000562 /// Complete any pending deferred region by setting its end location and
563 /// count, and then pushing it onto the region stack.
564 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
565 size_t Index = RegionStack.size();
566 if (!DeferredRegion)
567 return Index;
568
569 // Consume the pending region.
570 SourceMappingRegion DR = DeferredRegion.getValue();
571 DeferredRegion = None;
572
573 // If the region ends in an expansion, find the expansion site.
Stephen Kellya6e43582018-08-09 21:05:56 +0000574 FileID StartFile = SM.getFileID(DR.getBeginLoc());
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000575 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000576 if (isNestedIn(DeferredEndLoc, StartFile)) {
577 do {
578 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
579 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000580 } else {
581 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000582 }
583 }
584
585 // The parent of this deferred region ends where the containing decl ends,
586 // so the region isn't useful.
Stephen Kellya6e43582018-08-09 21:05:56 +0000587 if (DR.getBeginLoc() == DeferredEndLoc)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000588 return Index;
589
590 // If we're visiting statements in non-source order (e.g switch cases or
591 // a loop condition) we can't construct a sensible deferred region.
Stephen Kellya6e43582018-08-09 21:05:56 +0000592 if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000593 return Index;
594
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000595 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000596 DR.setCounter(Count);
597 DR.setEndLoc(DeferredEndLoc);
598 handleFileExit(DeferredEndLoc);
599 RegionStack.push_back(DR);
600 return Index;
601 }
602
Vedant Kumar8046d222017-11-09 02:33:39 +0000603 /// Complete a deferred region created after a terminated region at the
604 /// top-level.
605 void completeTopLevelDeferredRegion(Counter Count,
606 SourceLocation DeferredEndLoc) {
607 if (DeferredRegion || !LastTerminatedRegion)
608 return;
609
610 if (LastTerminatedRegion->second != RegionStack.size())
611 return;
612
613 SourceLocation Start = LastTerminatedRegion->first;
614 if (SM.getFileID(Start) != SM.getMainFileID())
615 return;
616
617 SourceMappingRegion DR = RegionStack.back();
618 DR.setStartLoc(Start);
619 DR.setDeferred(false);
620 DeferredRegion = DR;
621 completeDeferred(Count, DeferredEndLoc);
622 }
623
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000624 size_t locationDepth(SourceLocation Loc) {
625 size_t Depth = 0;
626 while (Loc.isValid()) {
627 Loc = getIncludeOrExpansionLoc(Loc);
628 Depth++;
629 }
630 return Depth;
631 }
632
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000633 /// Pop regions from the stack into the function's list of regions.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000634 ///
635 /// Adds all regions from \c ParentIndex to the top of the stack to the
636 /// function's \c SourceRegions.
637 void popRegions(size_t ParentIndex) {
638 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000639 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000640 while (RegionStack.size() > ParentIndex) {
641 SourceMappingRegion &Region = RegionStack.back();
642 if (Region.hasStartLoc()) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000643 SourceLocation StartLoc = Region.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000644 SourceLocation EndLoc = Region.hasEndLoc()
645 ? Region.getEndLoc()
646 : RegionStack[ParentIndex].getEndLoc();
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000647 size_t StartDepth = locationDepth(StartLoc);
648 size_t EndDepth = locationDepth(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000649 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000650 bool UnnestStart = StartDepth >= EndDepth;
651 bool UnnestEnd = EndDepth >= StartDepth;
652 if (UnnestEnd) {
653 // The region ends in a nested file or macro expansion. Create a
654 // separate region for each expansion.
655 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
656 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000657
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000658 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
659 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000660
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000661 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
662 if (EndLoc.isInvalid())
663 llvm::report_fatal_error("File exit not handled before popRegions");
664 EndDepth--;
665 }
666 if (UnnestStart) {
667 // The region begins in a nested file or macro expansion. Create a
668 // separate region for each expansion.
669 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
670 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
671
672 if (!isRegionAlreadyAdded(StartLoc, NestedLoc))
673 SourceRegions.emplace_back(Region.getCounter(), StartLoc, NestedLoc);
674
675 StartLoc = getIncludeOrExpansionLoc(StartLoc);
676 if (StartLoc.isInvalid())
677 llvm::report_fatal_error("File exit not handled before popRegions");
678 StartDepth--;
679 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000680 }
Vedant Kumar0c3e3112018-11-19 20:10:22 +0000681 Region.setStartLoc(StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000682 Region.setEndLoc(EndLoc);
683
684 MostRecentLocation = EndLoc;
685 // If this region happens to span an entire expansion, we need to make
686 // sure we don't overlap the parent region with it.
687 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
688 EndLoc == getEndOfFileOrMacro(EndLoc))
689 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
690
Stephen Kellya6e43582018-08-09 21:05:56 +0000691 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000692 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000693 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000694
695 if (ParentOfDeferredRegion) {
696 ParentOfDeferredRegion = false;
697
698 // If there's an existing deferred region, keep the old one, because
699 // it means there are two consecutive returns (or a similar pattern).
700 if (!DeferredRegion.hasValue() &&
701 // File IDs aren't gathered within macro expansions, so it isn't
702 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000703 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000704 DeferredRegion =
705 SourceMappingRegion(Counter::getZero(), EndLoc, None);
706 }
707 } else if (Region.isDeferred()) {
708 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
709 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000710 }
711 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000712
713 // If the zero region pushed after the last terminated region no longer
714 // exists, clear its cached information.
715 if (LastTerminatedRegion &&
716 RegionStack.size() < LastTerminatedRegion->second)
717 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000718 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000719 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000720 }
721
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000722 /// Return the currently active region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000723 SourceMappingRegion &getRegion() {
724 assert(!RegionStack.empty() && "statement has no region");
725 return RegionStack.back();
726 }
Alex Lorenzee024992014-08-04 18:41:51 +0000727
Vedant Kumar7225a262018-11-28 20:48:07 +0000728 /// Propagate counts through the children of \p S if \p VisitChildren is true.
729 /// Otherwise, only emit a count for \p S itself.
730 Counter propagateCounts(Counter TopCount, const Stmt *S,
731 bool VisitChildren = true) {
Vedant Kumar78386962017-07-27 02:20:20 +0000732 SourceLocation StartLoc = getStart(S);
733 SourceLocation EndLoc = getEnd(S);
734 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Vedant Kumar7225a262018-11-28 20:48:07 +0000735 if (VisitChildren)
736 Visit(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000737 Counter ExitCount = getRegion().getCounter();
738 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000739
740 // The statement may be spanned by an expansion. Make sure we handle a file
741 // exit out of this expansion before moving to the next statement.
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000742 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
Vedant Kumar78386962017-07-27 02:20:20 +0000743 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000744
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000745 return ExitCount;
746 }
Alex Lorenzee024992014-08-04 18:41:51 +0000747
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000748 /// Check whether a region with bounds \c StartLoc and \c EndLoc
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000749 /// is already added to \c SourceRegions.
750 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
751 return SourceRegions.rend() !=
752 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
753 [&](const SourceMappingRegion &Region) {
Stephen Kellya6e43582018-08-09 21:05:56 +0000754 return Region.getBeginLoc() == StartLoc &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000755 Region.getEndLoc() == EndLoc;
756 });
757 }
758
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000759 /// Adjust the most recently visited location to \c EndLoc.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000760 ///
761 /// This should be used after visiting any statements in non-source order.
762 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
763 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000764 // The code region for a whole macro is created in handleFileExit() when
765 // it detects exiting of the virtual file of that macro. If we visited
766 // statements in non-source order, we might already have such a region
767 // added, for example, if a body of a loop is divided among multiple
768 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000769 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000770 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
771 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
772 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000773 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
774 }
Alex Lorenzee024992014-08-04 18:41:51 +0000775
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000776 /// Adjust regions and state when \c NewLoc exits a file.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000777 ///
778 /// If moving from our most recently tracked location to \c NewLoc exits any
779 /// files, this adjusts our current region stack and creates the file regions
780 /// for the exited file.
781 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000782 if (NewLoc.isInvalid() ||
783 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000784 return;
785
786 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
787 // find the common ancestor.
788 SourceLocation LCA = NewLoc;
789 FileID ParentFile = SM.getFileID(LCA);
790 while (!isNestedIn(MostRecentLocation, ParentFile)) {
791 LCA = getIncludeOrExpansionLoc(LCA);
792 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
793 // Since there isn't a common ancestor, no file was exited. We just need
794 // to adjust our location to the new file.
795 MostRecentLocation = NewLoc;
796 return;
797 }
798 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000799 }
800
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000801 llvm::SmallSet<SourceLocation, 8> StartLocs;
802 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000803 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
804 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000805 continue;
Stephen Kellya6e43582018-08-09 21:05:56 +0000806 SourceLocation Loc = I.getBeginLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000807 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000808 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000809 break;
810 }
Alex Lorenzee024992014-08-04 18:41:51 +0000811
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000812 while (!SM.isInFileID(Loc, ParentFile)) {
813 // The most nested region for each start location is the one with the
814 // correct count. We avoid creating redundant regions by stopping once
815 // we've seen this region.
816 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000817 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000818 getEndOfFileOrMacro(Loc));
819 Loc = getIncludeOrExpansionLoc(Loc);
820 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000821 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000822 }
823
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000824 if (ParentCounter) {
825 // If the file is contained completely by another region and doesn't
826 // immediately start its own region, the whole file gets a region
827 // corresponding to the parent.
828 SourceLocation Loc = MostRecentLocation;
829 while (isNestedIn(Loc, ParentFile)) {
830 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000831 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000832 SourceRegions.emplace_back(*ParentCounter, FileStart,
833 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000834 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
835 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000836 Loc = getIncludeOrExpansionLoc(Loc);
837 }
Alex Lorenzee024992014-08-04 18:41:51 +0000838 }
839
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000840 MostRecentLocation = NewLoc;
841 }
Alex Lorenzee024992014-08-04 18:41:51 +0000842
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000843 /// Ensure that \c S is included in the current region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000844 void extendRegion(const Stmt *S) {
845 SourceMappingRegion &Region = getRegion();
846 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000847
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000848 handleFileExit(StartLoc);
849 if (!Region.hasStartLoc())
850 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000851
852 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000853 }
854
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000855 /// Mark \c S as a terminator, starting a zero region.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000856 void terminateRegion(const Stmt *S) {
857 extendRegion(S);
858 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000859 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000860 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000861 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000862 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000863 auto &ZeroRegion = getRegion();
864 ZeroRegion.setDeferred(true);
865 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000866 }
Alex Lorenzee024992014-08-04 18:41:51 +0000867
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000868 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
869 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
870 SourceLocation BeforeLoc) {
Zequan Wua31c89c2020-08-11 12:39:25 -0700871 AfterLoc = SM.getExpansionLoc(AfterLoc);
872 BeforeLoc = SM.getExpansionLoc(BeforeLoc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000873 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
874 return None;
875 return {{AfterLoc, BeforeLoc}};
876 }
877
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000878 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
879 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
880 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000881 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000882 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000883 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000884 handleFileExit(StartLoc);
885 size_t Index = pushRegion(Count, StartLoc, EndLoc);
886 getRegion().setGap(true);
887 handleFileExit(EndLoc);
888 popRegions(Index);
889 }
890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000891 /// Keep counts of breaks and continues inside loops.
Alex Lorenzee024992014-08-04 18:41:51 +0000892 struct BreakContinue {
893 Counter BreakCount;
894 Counter ContinueCount;
895 };
896 SmallVector<BreakContinue, 8> BreakContinueStack;
897
898 CounterCoverageMappingBuilder(
899 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000900 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000901 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000902 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
903 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000904
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000905 /// Write the mapping data to the output stream
Alex Lorenzee024992014-08-04 18:41:51 +0000906 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000907 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000908 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000909 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000910 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000911 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000912 gatherSkippedRegions();
913
Vedant Kumarefd319a2016-07-26 00:24:59 +0000914 if (MappingRegions.empty())
915 return;
916
Justin Bogner4da909b2015-02-03 21:35:49 +0000917 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
918 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000919 Writer.write(OS);
920 }
921
Alex Lorenzee024992014-08-04 18:41:51 +0000922 void VisitStmt(const Stmt *S) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +0000923 if (S->getBeginLoc().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000924 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000925 for (const Stmt *Child : S->children())
926 if (Child)
927 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000928 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000929 }
930
Alex Lorenzee024992014-08-04 18:41:51 +0000931 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000932 assert(!DeferredRegion && "Deferred region never completed");
933
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000934 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000935
936 // Do not propagate region counts into system headers.
937 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
938 return;
939
Vedant Kumar7225a262018-11-28 20:48:07 +0000940 // Do not visit the artificial children nodes of defaulted methods. The
941 // lexer may not be able to report back precise token end locations for
942 // these children nodes (llvm.org/PR39822), and moreover users will not be
943 // able to see coverage for them.
944 bool Defaulted = false;
945 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
946 Defaulted = Method->isDefaulted();
947
948 propagateCounts(getRegionCounter(Body), Body,
949 /*VisitChildren=*/!Defaulted);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000950 assert(RegionStack.empty() && "Regions entered but never exited");
951
Vedant Kumar61763b62018-05-30 23:35:44 +0000952 // Discard the last uncompleted deferred region in a decl, if one exists.
953 // This prevents lines at the end of a function containing only whitespace
954 // or closing braces from being marked as uncovered.
955 DeferredRegion = None;
Alex Lorenzee024992014-08-04 18:41:51 +0000956 }
957
958 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000959 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000960 if (S->getRetValue())
961 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000962 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000963 }
964
Xun Li565e37c2020-06-30 17:07:45 -0700965 void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
966 extendRegion(S);
967 Visit(S->getBody());
968 }
969
970 void VisitCoreturnStmt(const CoreturnStmt *S) {
971 extendRegion(S);
972 if (S->getOperand())
973 Visit(S->getOperand());
974 terminateRegion(S);
975 }
976
Justin Bognerf959feb2015-04-28 06:31:55 +0000977 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
978 extendRegion(E);
979 if (E->getSubExpr())
980 Visit(E->getSubExpr());
981 terminateRegion(E);
982 }
983
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000984 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000985
986 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000987 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000988 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000989 completeTopLevelDeferredRegion(LabelCount, Start);
Vedant Kumard781d972018-06-01 00:37:13 +0000990 completeDeferred(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000991 // We can't extendRegion here or we risk overlapping with our new region.
992 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000993 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000994 Visit(S->getSubStmt());
995 }
996
997 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000998 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
999 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001000 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001001 // FIXME: a break in a switch should terminate regions for all preceding
1002 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001003 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001004 }
1005
1006 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +00001007 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1008 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001009 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1010 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001011 }
1012
Eli Friedman181dfe42017-08-08 20:10:14 +00001013 void VisitCallExpr(const CallExpr *E) {
1014 VisitStmt(E);
1015
1016 // Terminate the region when we hit a noreturn function.
1017 // (This is helpful dealing with switch statements.)
1018 QualType CalleeType = E->getCallee()->getType();
1019 if (getFunctionExtInfo(*CalleeType).getNoReturn())
1020 terminateRegion(E);
1021 }
1022
Alex Lorenzee024992014-08-04 18:41:51 +00001023 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001024 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001025
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001026 Counter ParentCount = getRegion().getCounter();
1027 Counter BodyCount = getRegionCounter(S);
1028
1029 // Handle the body first so that we can get the backedge count.
1030 BreakContinueStack.push_back(BreakContinue());
1031 extendRegion(S->getBody());
1032 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001033 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001034
1035 // Go back to handle the condition.
1036 Counter CondCount =
1037 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1038 propagateCounts(CondCount, S->getCond());
1039 adjustForOutOfOrderTraversal(getEnd(S));
1040
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001041 // The body count applies to the area immediately after the increment.
Zequan Wua31c89c2020-08-11 12:39:25 -07001042 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1043 getStart(S->getBody()));
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001044 if (Gap)
1045 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1046
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001047 Counter OutCount =
1048 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1049 if (OutCount != ParentCount)
1050 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001051 }
1052
1053 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001054 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001055
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001056 Counter ParentCount = getRegion().getCounter();
1057 Counter BodyCount = getRegionCounter(S);
1058
1059 BreakContinueStack.push_back(BreakContinue());
1060 extendRegion(S->getBody());
1061 Counter BackedgeCount =
1062 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001063 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001064
1065 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1066 propagateCounts(CondCount, S->getCond());
1067
1068 Counter OutCount =
1069 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1070 if (OutCount != ParentCount)
1071 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001072 }
1073
1074 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001075 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001076 if (S->getInit())
1077 Visit(S->getInit());
1078
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001079 Counter ParentCount = getRegion().getCounter();
1080 Counter BodyCount = getRegionCounter(S);
1081
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001082 // The loop increment may contain a break or continue.
1083 if (S->getInc())
1084 BreakContinueStack.emplace_back();
1085
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001086 // Handle the body first so that we can get the backedge count.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001087 BreakContinueStack.emplace_back();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001088 extendRegion(S->getBody());
1089 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001090 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +00001091
1092 // The increment is essentially part of the body but it needs to include
1093 // the count for all the continue statements.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001094 BreakContinue IncrementBC;
1095 if (const Stmt *Inc = S->getInc()) {
1096 propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1097 IncrementBC = BreakContinueStack.pop_back_val();
1098 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001099
1100 // Go back to handle the condition.
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001101 Counter CondCount = addCounters(
1102 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1103 IncrementBC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001104 if (const Expr *Cond = S->getCond()) {
1105 propagateCounts(CondCount, Cond);
1106 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +00001107 }
1108
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001109 // The body count applies to the area immediately after the increment.
1110 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1111 getStart(S->getBody()));
1112 if (Gap)
1113 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1114
Vedant Kumar3e2ae492018-02-16 07:59:43 +00001115 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1116 subtractCounters(CondCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001117 if (OutCount != ParentCount)
1118 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001119 }
1120
1121 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001122 extendRegion(S);
Richard Smith8baa5002018-09-28 18:44:09 +00001123 if (S->getInit())
1124 Visit(S->getInit());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001125 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001126 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001127
1128 Counter ParentCount = getRegion().getCounter();
1129 Counter BodyCount = getRegionCounter(S);
1130
Alex Lorenzee024992014-08-04 18:41:51 +00001131 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001132 extendRegion(S->getBody());
1133 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001134 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001135
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001136 // The body count applies to the area immediately after the range.
1137 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1138 getStart(S->getBody()));
1139 if (Gap)
1140 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1141
Justin Bogner15874322015-04-30 21:31:02 +00001142 Counter LoopCount =
1143 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1144 Counter OutCount =
1145 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001146 if (OutCount != ParentCount)
1147 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001148 }
1149
1150 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001151 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001152 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001153
1154 Counter ParentCount = getRegion().getCounter();
1155 Counter BodyCount = getRegionCounter(S);
1156
Alex Lorenzee024992014-08-04 18:41:51 +00001157 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001158 extendRegion(S->getBody());
1159 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001160 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001161
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001162 // The body count applies to the area immediately after the collection.
1163 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1164 getStart(S->getBody()));
1165 if (Gap)
1166 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1167
Justin Bogner15874322015-04-30 21:31:02 +00001168 Counter LoopCount =
1169 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1170 Counter OutCount =
1171 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001172 if (OutCount != ParentCount)
1173 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001174 }
1175
1176 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001177 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001178 if (S->getInit())
1179 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001180 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001181
Alex Lorenzee024992014-08-04 18:41:51 +00001182 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001183
1184 const Stmt *Body = S->getBody();
1185 extendRegion(Body);
1186 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1187 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001188 // Make a region for the body of the switch. If the body starts with
1189 // a case, that case will reuse this region; otherwise, this covers
1190 // the unreachable code at the beginning of the switch body.
Vedant Kumar859bf4d2019-11-21 14:17:04 -08001191 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1192 getRegion().setGap(true);
Richard Trieub5841332015-04-15 01:21:42 +00001193 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001194 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001195
1196 // Set the end for the body of the switch, if it isn't already set.
1197 for (size_t i = RegionStack.size(); i != Index; --i) {
1198 if (!RegionStack[i - 1].hasEndLoc())
1199 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1200 }
1201
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001202 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001203 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001204 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001205 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001206 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001207
Alex Lorenzee024992014-08-04 18:41:51 +00001208 if (!BreakContinueStack.empty())
1209 BreakContinueStack.back().ContinueCount = addCounters(
1210 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001211
1212 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001213 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001214 pushRegion(ExitCount);
1215
1216 // Ensure that handleFileExit recognizes when the end location is located
1217 // in a different file.
1218 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001219 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001220 }
1221
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001222 void VisitSwitchCase(const SwitchCase *S) {
1223 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001224
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001225 SourceMappingRegion &Parent = getRegion();
1226
1227 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1228 // Reuse the existing region if it starts at our label. This is typical of
1229 // the first case in a switch.
Stephen Kellya6e43582018-08-09 21:05:56 +00001230 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001231 Parent.setCounter(Count);
1232 else
1233 pushRegion(Count, getStart(S));
1234
Sanjay Patel376c06c2015-12-24 21:11:29 +00001235 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001236 Visit(CS->getLHS());
1237 if (const Expr *RHS = CS->getRHS())
1238 Visit(RHS);
1239 }
Alex Lorenzee024992014-08-04 18:41:51 +00001240 Visit(S->getSubStmt());
1241 }
1242
1243 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001244 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001245 if (S->getInit())
1246 Visit(S->getInit());
1247
Justin Bogner055ebc32015-06-16 06:24:15 +00001248 // Extend into the condition before we propagate through it below - this is
1249 // needed to handle macros that generate the "if" but not the condition.
1250 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001251
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001252 Counter ParentCount = getRegion().getCounter();
1253 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001254
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001255 // Emitting a counter for the condition makes it easier to interpret the
1256 // counter for the body when looking at the coverage.
1257 propagateCounts(ParentCount, S->getCond());
1258
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001259 // The 'then' count applies to the area immediately after the condition.
Zequan Wua31c89c2020-08-11 12:39:25 -07001260 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1261 getStart(S->getThen()));
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001262 if (Gap)
1263 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001264
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001265 extendRegion(S->getThen());
1266 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1267
1268 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1269 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001270 // The 'else' count applies to the area immediately after the 'then'.
Zequan Wua31c89c2020-08-11 12:39:25 -07001271 Gap = findGapAreaBetween(getPreciseTokenLocEnd(getEnd(S->getThen())),
1272 getStart(Else));
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001273 if (Gap)
1274 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001275 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001276 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1277 } else
1278 OutCount = addCounters(OutCount, ElseCount);
1279
1280 if (OutCount != ParentCount)
1281 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001282 }
1283
1284 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001285 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001286 // Handle macros that generate the "try" but not the rest.
1287 extendRegion(S->getTryBlock());
1288
1289 Counter ParentCount = getRegion().getCounter();
1290 propagateCounts(ParentCount, S->getTryBlock());
1291
Alex Lorenzee024992014-08-04 18:41:51 +00001292 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1293 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001294
1295 Counter ExitCount = getRegionCounter(S);
1296 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001297 }
1298
1299 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001300 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001301 }
1302
1303 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001304 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001305
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001306 Counter ParentCount = getRegion().getCounter();
1307 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001308
Justin Bognere3654ce2015-04-24 23:37:57 +00001309 Visit(E->getCond());
1310
1311 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001312 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001313 auto Gap =
1314 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1315 if (Gap)
1316 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001317
Justin Bognere3654ce2015-04-24 23:37:57 +00001318 extendRegion(E->getTrueExpr());
1319 propagateCounts(TrueCount, E->getTrueExpr());
1320 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001321
Justin Bognere3654ce2015-04-24 23:37:57 +00001322 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001323 propagateCounts(subtractCounters(ParentCount, TrueCount),
1324 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001325 }
1326
1327 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001328 extendRegion(E->getLHS());
1329 propagateCounts(getRegion().getCounter(), E->getLHS());
1330 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001331
1332 extendRegion(E->getRHS());
1333 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001334 }
1335
1336 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001337 extendRegion(E->getLHS());
1338 propagateCounts(getRegion().getCounter(), E->getLHS());
1339 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001340
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001341 extendRegion(E->getRHS());
1342 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001343 }
Justin Bognerc1091022015-02-24 04:13:56 +00001344
1345 void VisitLambdaExpr(const LambdaExpr *LE) {
1346 // Lambdas are treated as their own functions for now, so we shouldn't
1347 // propagate counts into them.
1348 }
Alex Lorenzee024992014-08-04 18:41:51 +00001349};
Alex Lorenzee024992014-08-04 18:41:51 +00001350
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001351std::string normalizeFilename(StringRef Filename) {
1352 llvm::SmallString<256> Path(Filename);
1353 llvm::sys::fs::make_absolute(Path);
1354 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
Jonas Devlieghere509e21a2020-01-29 21:27:46 -08001355 return std::string(Path);
Reid Kleckner7cd595d2019-10-28 14:40:17 -07001356}
1357
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001358} // end anonymous namespace
1359
Justin Bognera432d172015-02-03 00:20:24 +00001360static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1361 ArrayRef<CounterExpression> Expressions,
1362 ArrayRef<CounterMappingRegion> Regions) {
1363 OS << FunctionName << ":\n";
1364 CounterMappingContext Ctx(Expressions);
1365 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001366 OS.indent(2);
1367 switch (R.Kind) {
1368 case CounterMappingRegion::CodeRegion:
1369 break;
1370 case CounterMappingRegion::ExpansionRegion:
1371 OS << "Expansion,";
1372 break;
1373 case CounterMappingRegion::SkippedRegion:
1374 OS << "Skipped,";
1375 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001376 case CounterMappingRegion::GapRegion:
1377 OS << "Gap,";
1378 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001379 }
1380
Justin Bogner4da909b2015-02-03 21:35:49 +00001381 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1382 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001383 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001384 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001385 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1386 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001387 }
1388}
1389
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001390static std::string getInstrProfSection(const CodeGenModule &CGM,
1391 llvm::InstrProfSectKind SK) {
1392 return llvm::getInstrProfSectionName(
1393 SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1394}
1395
1396void CoverageMappingModuleGen::emitFunctionMappingRecord(
1397 const FunctionInfo &Info, uint64_t FilenamesRef) {
1398 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1399
1400 // Assign a name to the function record. This is used to merge duplicates.
1401 std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1402
1403 // A dummy description for a function included-but-not-used in a TU can be
1404 // replaced by full description provided by a different TU. The two kinds of
1405 // descriptions play distinct roles: therefore, assign them different names
1406 // to prevent `linkonce_odr` merging.
1407 if (Info.IsUsed)
1408 FuncRecordName += "u";
1409
1410 // Create the function record type.
1411 const uint64_t NameHash = Info.NameHash;
1412 const uint64_t FuncHash = Info.FuncHash;
1413 const std::string &CoverageMapping = Info.CoverageMapping;
1414#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1415 llvm::Type *FunctionRecordTypes[] = {
1416#include "llvm/ProfileData/InstrProfData.inc"
1417 };
1418 auto *FunctionRecordTy =
1419 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1420 /*isPacked=*/true);
1421
1422 // Create the function record constant.
1423#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1424 llvm::Constant *FunctionRecordVals[] = {
1425 #include "llvm/ProfileData/InstrProfData.inc"
1426 };
1427 auto *FuncRecordConstant = llvm::ConstantStruct::get(
1428 FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1429
1430 // Create the function record global.
1431 auto *FuncRecord = new llvm::GlobalVariable(
1432 CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1433 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1434 FuncRecordName);
1435 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1436 FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1437 FuncRecord->setAlignment(llvm::Align(8));
1438 if (CGM.supportsCOMDAT())
1439 FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1440
1441 // Make sure the data doesn't get deleted.
1442 CGM.addUsedGlobal(FuncRecord);
1443}
1444
Alex Lorenzee024992014-08-04 18:41:51 +00001445void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001446 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001447 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001448 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001449 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1450 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
Alex Lorenzee024992014-08-04 18:41:51 +00001451
Xinliang David Li848da132016-01-19 00:49:06 +00001452 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001453 FunctionNames.push_back(
1454 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001455
1456 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1457 // Dump the coverage mapping data for this function by decoding the
1458 // encoded data. This allows us to dump the mapping regions which were
1459 // also processed by the CoverageMappingWriter which performs
1460 // additional minimization operations such as reducing the number of
1461 // expressions.
1462 std::vector<StringRef> Filenames;
1463 std::vector<CounterExpression> Expressions;
1464 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001465 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001466 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001467 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001468 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001469 for (const auto &Entry : FileEntries) {
1470 auto I = Entry.second;
1471 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1472 FilenameRefs[I] = FilenameStrs[I];
1473 }
Justin Bognera432d172015-02-03 00:20:24 +00001474 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1475 Expressions, Regions);
1476 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001477 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001478 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001479 }
Alex Lorenzee024992014-08-04 18:41:51 +00001480}
1481
1482void CoverageMappingModuleGen::emit() {
1483 if (FunctionRecords.empty())
1484 return;
1485 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1486 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1487
1488 // Create the filenames and merge them with coverage mappings
1489 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001490 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001491 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001492 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001493 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001494 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001495 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001496 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001497 }
1498
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001499 std::string Filenames;
1500 {
1501 llvm::raw_string_ostream OS(Filenames);
1502 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001503 }
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001504 auto *FilenamesVal =
1505 llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1506 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
Serge Guelton4cd07db2019-06-05 06:35:10 +00001507
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001508 // Emit the function records.
1509 for (const FunctionInfo &Info : FunctionRecords)
1510 emitFunctionMappingRecord(Info, FilenamesRef);
Alex Lorenzee024992014-08-04 18:41:51 +00001511
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001512 const unsigned NRecords = 0;
1513 const size_t FilenamesSize = Filenames.size();
1514 const unsigned CoverageMappingSize = 0;
Xinliang David Li20b188c2016-01-03 19:25:54 +00001515 llvm::Type *CovDataHeaderTypes[] = {
1516#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1517#include "llvm/ProfileData/InstrProfData.inc"
1518 };
1519 auto CovDataHeaderTy =
1520 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1521 llvm::Constant *CovDataHeaderVals[] = {
1522#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1523#include "llvm/ProfileData/InstrProfData.inc"
1524 };
1525 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1526 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1527
Alex Lorenzee024992014-08-04 18:41:51 +00001528 // Create the coverage data record
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001529 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001530 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001531 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001532 auto CovDataVal =
1533 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001534 auto CovData = new llvm::GlobalVariable(
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001535 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
Xinliang David Li20b188c2016-01-03 19:25:54 +00001536 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001537
Vedant Kumardd1ea9d2019-10-21 11:48:38 -07001538 CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
Guillaume Chateletc79099e2019-10-03 13:00:29 +00001539 CovData->setAlignment(llvm::Align(8));
Alex Lorenzee024992014-08-04 18:41:51 +00001540
1541 // Make sure the data doesn't get deleted.
1542 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001543 // Create the deferred function records array
1544 if (!FunctionNames.empty()) {
1545 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1546 FunctionNames.size());
1547 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1548 // This variable will *NOT* be emitted to the object file. It is used
1549 // to pass the list of names referenced to codegen.
1550 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1551 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001552 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001553 }
Alex Lorenzee024992014-08-04 18:41:51 +00001554}
1555
1556unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1557 auto It = FileEntries.find(File);
1558 if (It != FileEntries.end())
1559 return It->second;
1560 unsigned FileID = FileEntries.size();
1561 FileEntries.insert(std::make_pair(File, FileID));
1562 return FileID;
1563}
1564
1565void CoverageMappingGen::emitCounterMapping(const Decl *D,
1566 llvm::raw_ostream &OS) {
1567 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001568 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001569 Walker.VisitDecl(D);
1570 Walker.write(OS);
1571}
1572
1573void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1574 llvm::raw_ostream &OS) {
1575 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1576 Walker.VisitDecl(D);
1577 Walker.write(OS);
1578}