blob: 89a30dc7040c836683aae5cb5b79903366e1210a [file] [log] [blame]
Alex Lorenzee024992014-08-04 18:41:51 +00001//===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based code coverage mapping generator
11//
12//===----------------------------------------------------------------------===//
13
14#include "CoverageMappingGen.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Lex/Lexer.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000018#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000019#include "llvm/ADT/StringExtras.h"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000020#include "llvm/ADT/Optional.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000021#include "llvm/ProfileData/Coverage/CoverageMapping.h"
22#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000025#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000026#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000027
28using namespace clang;
29using namespace CodeGen;
30using namespace llvm::coverage;
31
Vedant Kumar3919a502017-09-11 20:47:42 +000032void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Alex Lorenzee024992014-08-04 18:41:51 +000033 SkippedRanges.push_back(Range);
34}
35
36namespace {
37
38/// \brief A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000039class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000040 Counter Count;
41
Alex Lorenzee024992014-08-04 18:41:51 +000042 /// \brief The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000043 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000044
45 /// \brief The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000046 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000047
Vedant Kumar747b0e22017-09-08 18:44:56 +000048 /// Whether this region should be emitted after its parent is emitted.
49 bool DeferRegion;
50
Vedant Kumara1c4deb2017-09-18 23:37:30 +000051 /// Whether this region is a gap region. The count from a gap region is set
52 /// as the line execution count if there are no other regions on the line.
53 bool GapRegion;
54
Justin Bogner09c71792014-10-01 03:33:49 +000055public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000056 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumara1c4deb2017-09-18 23:37:30 +000057 Optional<SourceLocation> LocEnd, bool DeferRegion = false,
58 bool GapRegion = false)
Vedant Kumar747b0e22017-09-08 18:44:56 +000059 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
Vedant Kumara1c4deb2017-09-18 23:37:30 +000060 DeferRegion(DeferRegion), GapRegion(GapRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000061
Justin Bogner09c71792014-10-01 03:33:49 +000062 const Counter &getCounter() const { return Count; }
63
Justin Bognerbf42cfd2015-02-18 21:24:51 +000064 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000065
Justin Bognerbf42cfd2015-02-18 21:24:51 +000066 bool hasStartLoc() const { return LocStart.hasValue(); }
67
68 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
69
Craig Topper462c77b2015-09-26 05:10:14 +000070 SourceLocation getStartLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000071 assert(LocStart && "Region has no start location");
72 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000073 }
74
Justin Bognerbf42cfd2015-02-18 21:24:51 +000075 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000076
Justin Bognerbf42cfd2015-02-18 21:24:51 +000077 void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
Alex Lorenzee024992014-08-04 18:41:51 +000078
Craig Topper462c77b2015-09-26 05:10:14 +000079 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000080 assert(LocEnd && "Region has no end location");
81 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000082 }
Vedant Kumar747b0e22017-09-08 18:44:56 +000083
84 bool isDeferred() const { return DeferRegion; }
85
86 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Vedant Kumara1c4deb2017-09-18 23:37:30 +000087
88 bool isGap() const { return GapRegion; }
89
90 void setGap(bool Gap) { GapRegion = Gap; }
Alex Lorenzee024992014-08-04 18:41:51 +000091};
92
Vedant Kumard7369642017-07-27 02:20:25 +000093/// Spelling locations for the start and end of a source region.
94struct SpellingRegion {
95 /// The line where the region starts.
96 unsigned LineStart;
97
98 /// The column where the region starts.
99 unsigned ColumnStart;
100
101 /// The line where the region ends.
102 unsigned LineEnd;
103
104 /// The column where the region ends.
105 unsigned ColumnEnd;
106
107 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
108 SourceLocation LocEnd) {
109 LineStart = SM.getSpellingLineNumber(LocStart);
110 ColumnStart = SM.getSpellingColumnNumber(LocStart);
111 LineEnd = SM.getSpellingLineNumber(LocEnd);
112 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
113 }
114
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000115 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
116 : SpellingRegion(SM, R.getStartLoc(), R.getEndLoc()) {}
117
Vedant Kumard7369642017-07-27 02:20:25 +0000118 /// Check if the start and end locations appear in source order, i.e
119 /// top->bottom, left->right.
120 bool isInSourceOrder() const {
121 return (LineStart < LineEnd) ||
122 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
123 }
124};
125
Alex Lorenzee024992014-08-04 18:41:51 +0000126/// \brief Provides the common functionality for the different
127/// coverage mapping region builders.
128class CoverageMappingBuilder {
129public:
130 CoverageMappingModuleGen &CVM;
131 SourceManager &SM;
132 const LangOptions &LangOpts;
133
134private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000135 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
136 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
137 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000138
139public:
Alex Lorenzee024992014-08-04 18:41:51 +0000140 /// \brief The coverage mapping regions for this function
141 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
142 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000143 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000144
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000145 /// \brief A set of regions which can be used as a filter.
146 ///
147 /// It is produced by emitExpansionRegions() and is used in
148 /// emitSourceRegions() to suppress producing code regions if
149 /// the same area is covered by expansion regions.
150 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
151 SourceRegionFilter;
152
Alex Lorenzee024992014-08-04 18:41:51 +0000153 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
154 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000155 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000156
157 /// \brief Return the precise end location for the given token.
158 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000159 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
160 // macro locations, which we just treat as expanded files.
161 unsigned TokLen =
162 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
163 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000164 }
165
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000166 /// \brief Return the start location of an included file or expanded macro.
167 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
168 if (Loc.isMacroID())
169 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
170 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000171 }
172
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000173 /// \brief Return the end location of an included file or expanded macro.
174 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
175 if (Loc.isMacroID())
176 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000177 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000178 return SM.getLocForEndOfFile(SM.getFileID(Loc));
179 }
180
181 /// \brief Find out where the current file is included or macro is expanded.
182 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
183 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
184 : SM.getIncludeLoc(SM.getFileID(Loc));
185 }
186
Justin Bogner682bfbf2015-05-14 22:14:10 +0000187 /// \brief Return true if \c Loc is a location in a built-in macro.
188 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000189 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000190 }
191
Igor Kudrind9e1a612016-06-07 10:07:51 +0000192 /// \brief Check whether \c Loc is included or expanded from \c Parent.
193 bool isNestedIn(SourceLocation Loc, FileID Parent) {
194 do {
195 Loc = getIncludeOrExpansionLoc(Loc);
196 if (Loc.isInvalid())
197 return false;
198 } while (!SM.isInFileID(Loc, Parent));
199 return true;
200 }
201
Justin Bogner682bfbf2015-05-14 22:14:10 +0000202 /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000203 SourceLocation getStart(const Stmt *S) {
204 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000205 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000206 Loc = SM.getImmediateExpansionRange(Loc).first;
207 return Loc;
208 }
209
Justin Bogner682bfbf2015-05-14 22:14:10 +0000210 /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000211 SourceLocation getEnd(const Stmt *S) {
212 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000213 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000214 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000215 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000216 }
217
218 /// \brief Find the set of files we have regions for and assign IDs
219 ///
220 /// Fills \c Mapping with the virtual file mapping needed to write out
221 /// coverage and collects the necessary file information to emit source and
222 /// expansion regions.
223 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
224 FileIDMapping.clear();
225
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000226 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000227 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
228 for (const auto &Region : SourceRegions) {
229 SourceLocation Loc = Region.getStartLoc();
230 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000231 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000232 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000233
Vedant Kumar93205af2016-07-11 22:57:46 +0000234 // Do not map FileID's associated with system headers.
235 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
236 continue;
237
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000238 unsigned Depth = 0;
239 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000240 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000241 ++Depth;
242 FileLocs.push_back(std::make_pair(Loc, Depth));
243 }
244 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
245
246 for (const auto &FL : FileLocs) {
247 SourceLocation Loc = FL.first;
248 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
249 auto Entry = SM.getFileEntryForID(SpellingFile);
250 if (!Entry)
251 continue;
252
253 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
254 Mapping.push_back(CVM.getFileID(Entry));
255 }
256 }
257
258 /// \brief Get the coverage mapping file ID for \c Loc.
259 ///
260 /// If such file id doesn't exist, return None.
261 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
262 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000263 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000264 return Mapping->second.first;
265 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000266 }
267
Alex Lorenzee024992014-08-04 18:41:51 +0000268 /// \brief Gather all the regions that were skipped by the preprocessor
269 /// using the constructs like #if.
270 void gatherSkippedRegions() {
271 /// An array of the minimum lineStarts and the maximum lineEnds
272 /// for mapping regions from the appropriate source files.
273 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
274 FileLineRanges.resize(
275 FileIDMapping.size(),
276 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
277 for (const auto &R : MappingRegions) {
278 FileLineRanges[R.FileID].first =
279 std::min(FileLineRanges[R.FileID].first, R.LineStart);
280 FileLineRanges[R.FileID].second =
281 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
282 }
283
284 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
285 for (const auto &I : SkippedRanges) {
286 auto LocStart = I.getBegin();
287 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000288 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
289 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000290
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000291 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000292 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000293 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000294 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000295 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000296 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000297 // Make sure that we only collect the regions that are inside
298 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000299 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
300 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000301 MappingRegions.push_back(Region);
302 }
303 }
304
Alex Lorenzee024992014-08-04 18:41:51 +0000305 /// \brief Generate the coverage counter mapping regions from collected
306 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000307 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000308 for (const auto &Region : SourceRegions) {
309 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000310
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000311 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000312 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000313
Vedant Kumar93205af2016-07-11 22:57:46 +0000314 // Ignore regions from system headers.
315 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
316 continue;
317
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000318 auto CovFileID = getCoverageFileID(LocStart);
319 // Ignore regions that don't have a file, such as builtin macros.
320 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000321 continue;
322
Justin Bognerf14b2072015-03-25 04:13:49 +0000323 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000324 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
325 "region spans multiple files");
326
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000327 // Don't add code regions for the area covered by expansion regions.
328 // This not only suppresses redundant regions, but sometimes prevents
329 // creating regions with wrong counters if, for example, a statement's
330 // body ends at the end of a nested macro.
331 if (Filter.count(std::make_pair(LocStart, LocEnd)))
332 continue;
333
Vedant Kumard7369642017-07-27 02:20:25 +0000334 // Find the spelling locations for the mapping region.
335 SpellingRegion SR{SM, LocStart, LocEnd};
336 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000337
338 if (Region.isGap()) {
339 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
340 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
341 SR.LineEnd, SR.ColumnEnd));
342 } else {
343 MappingRegions.push_back(CounterMappingRegion::makeRegion(
344 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
345 SR.LineEnd, SR.ColumnEnd));
346 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000347 }
348 }
349
350 /// \brief Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000351 SourceRegionFilter emitExpansionRegions() {
352 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000353 for (const auto &FM : FileIDMapping) {
354 SourceLocation ExpandedLoc = FM.second.second;
355 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
356 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000357 continue;
358
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000359 auto ParentFileID = getCoverageFileID(ParentLoc);
360 if (!ParentFileID)
361 continue;
362 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
363 assert(ExpandedFileID && "expansion in uncovered file");
364
365 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
366 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
367 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000368 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000369
Vedant Kumard7369642017-07-27 02:20:25 +0000370 SpellingRegion SR{SM, ParentLoc, LocEnd};
371 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000372 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000373 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
374 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000375 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000376 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000377 }
378};
379
380/// \brief Creates unreachable coverage regions for the functions that
381/// are not emitted.
382struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
383 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
384 const LangOptions &LangOpts)
385 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
386
387 void VisitDecl(const Decl *D) {
388 if (!D->hasBody())
389 return;
390 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000391 SourceLocation Start = getStart(Body);
392 SourceLocation End = getEnd(Body);
393 if (!SM.isWrittenInSameFile(Start, End)) {
394 // Walk up to find the common ancestor.
395 // Correct the locations accordingly.
396 FileID StartFileID = SM.getFileID(Start);
397 FileID EndFileID = SM.getFileID(End);
398 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
399 Start = getIncludeOrExpansionLoc(Start);
400 assert(Start.isValid() &&
401 "Declaration start location not nested within a known region");
402 StartFileID = SM.getFileID(Start);
403 }
404 while (StartFileID != EndFileID) {
405 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
406 assert(End.isValid() &&
407 "Declaration end location not nested within a known region");
408 EndFileID = SM.getFileID(End);
409 }
410 }
411 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000412 }
413
414 /// \brief Write the mapping data to the output stream
415 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000416 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000417 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000418 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000419
Vedant Kumarefd319a2016-07-26 00:24:59 +0000420 if (MappingRegions.empty())
421 return;
422
Craig Topper5fc8fc22014-08-27 06:28:36 +0000423 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000424 Writer.write(OS);
425 }
426};
427
428/// \brief A StmtVisitor that creates coverage mapping regions which map
429/// from the source code locations to the PGO counters.
430struct CounterCoverageMappingBuilder
431 : public CoverageMappingBuilder,
432 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
433 /// \brief The map of statements to count values.
434 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
435
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000436 /// \brief A stack of currently live regions.
437 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000438
Vedant Kumar747b0e22017-09-08 18:44:56 +0000439 /// The currently deferred region: its end location and count can be set once
440 /// its parent has been popped from the region stack.
441 Optional<SourceMappingRegion> DeferredRegion;
442
Alex Lorenzee024992014-08-04 18:41:51 +0000443 CounterExpressionBuilder Builder;
444
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000445 /// \brief A location in the most recently visited file or macro.
446 ///
447 /// This is used to adjust the active source regions appropriately when
448 /// expressions cross file or macro boundaries.
449 SourceLocation MostRecentLocation;
450
Vedant Kumar8046d222017-11-09 02:33:39 +0000451 /// Location of the last terminated region.
452 Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
453
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000454 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000455 Counter subtractCounters(Counter LHS, Counter RHS) {
456 return Builder.subtract(LHS, RHS);
457 }
458
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000459 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000460 Counter addCounters(Counter LHS, Counter RHS) {
461 return Builder.add(LHS, RHS);
462 }
463
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000464 Counter addCounters(Counter C1, Counter C2, Counter C3) {
465 return addCounters(addCounters(C1, C2), C3);
466 }
467
Alex Lorenzee024992014-08-04 18:41:51 +0000468 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000469 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000470 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000471 Counter getRegionCounter(const Stmt *S) {
472 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000473 }
474
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000475 /// \brief Push a region onto the stack.
476 ///
477 /// Returns the index on the stack where the region was pushed. This can be
478 /// used with popRegions to exit a "scope", ending the region that was pushed.
479 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
480 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000481 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000482 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000483 completeDeferred(Count, MostRecentLocation);
484 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000485 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000486
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000487 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000488 }
489
Vedant Kumar747b0e22017-09-08 18:44:56 +0000490 /// Complete any pending deferred region by setting its end location and
491 /// count, and then pushing it onto the region stack.
492 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
493 size_t Index = RegionStack.size();
494 if (!DeferredRegion)
495 return Index;
496
497 // Consume the pending region.
498 SourceMappingRegion DR = DeferredRegion.getValue();
499 DeferredRegion = None;
500
501 // If the region ends in an expansion, find the expansion site.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000502 FileID StartFile = SM.getFileID(DR.getStartLoc());
503 if (SM.getFileID(DeferredEndLoc) != StartFile) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000504 if (isNestedIn(DeferredEndLoc, StartFile)) {
505 do {
506 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
507 } while (StartFile != SM.getFileID(DeferredEndLoc));
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000508 } else {
509 return Index;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000510 }
511 }
512
513 // The parent of this deferred region ends where the containing decl ends,
514 // so the region isn't useful.
515 if (DR.getStartLoc() == DeferredEndLoc)
516 return Index;
517
518 // If we're visiting statements in non-source order (e.g switch cases or
519 // a loop condition) we can't construct a sensible deferred region.
520 if (!SpellingRegion(SM, DR.getStartLoc(), DeferredEndLoc).isInSourceOrder())
521 return Index;
522
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000523 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000524 DR.setCounter(Count);
525 DR.setEndLoc(DeferredEndLoc);
526 handleFileExit(DeferredEndLoc);
527 RegionStack.push_back(DR);
528 return Index;
529 }
530
Vedant Kumar8046d222017-11-09 02:33:39 +0000531 /// Complete a deferred region created after a terminated region at the
532 /// top-level.
533 void completeTopLevelDeferredRegion(Counter Count,
534 SourceLocation DeferredEndLoc) {
535 if (DeferredRegion || !LastTerminatedRegion)
536 return;
537
538 if (LastTerminatedRegion->second != RegionStack.size())
539 return;
540
541 SourceLocation Start = LastTerminatedRegion->first;
542 if (SM.getFileID(Start) != SM.getMainFileID())
543 return;
544
545 SourceMappingRegion DR = RegionStack.back();
546 DR.setStartLoc(Start);
547 DR.setDeferred(false);
548 DeferredRegion = DR;
549 completeDeferred(Count, DeferredEndLoc);
550 }
551
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000552 /// \brief Pop regions from the stack into the function's list of regions.
553 ///
554 /// Adds all regions from \c ParentIndex to the top of the stack to the
555 /// function's \c SourceRegions.
556 void popRegions(size_t ParentIndex) {
557 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000558 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000559 while (RegionStack.size() > ParentIndex) {
560 SourceMappingRegion &Region = RegionStack.back();
561 if (Region.hasStartLoc()) {
562 SourceLocation StartLoc = Region.getStartLoc();
563 SourceLocation EndLoc = Region.hasEndLoc()
564 ? Region.getEndLoc()
565 : RegionStack[ParentIndex].getEndLoc();
566 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
567 // The region ends in a nested file or macro expansion. Create a
568 // separate region for each expansion.
569 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
570 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
571
Igor Kudrin8545dae2016-08-29 11:48:50 +0000572 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
573 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000574
Justin Bognerf14b2072015-03-25 04:13:49 +0000575 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000576 if (EndLoc.isInvalid())
577 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000578 }
579 Region.setEndLoc(EndLoc);
580
581 MostRecentLocation = EndLoc;
582 // If this region happens to span an entire expansion, we need to make
583 // sure we don't overlap the parent region with it.
584 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
585 EndLoc == getEndOfFileOrMacro(EndLoc))
586 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
587
588 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000589 assert(SpellingRegion(SM, Region).isInSourceOrder());
Craig Topperf36a5c42015-09-26 05:10:16 +0000590 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000591
592 if (ParentOfDeferredRegion) {
593 ParentOfDeferredRegion = false;
594
595 // If there's an existing deferred region, keep the old one, because
596 // it means there are two consecutive returns (or a similar pattern).
597 if (!DeferredRegion.hasValue() &&
598 // File IDs aren't gathered within macro expansions, so it isn't
599 // useful to try and create a deferred region inside of one.
Vedant Kumarf9a0d442017-11-09 02:33:40 +0000600 !EndLoc.isMacroID())
Vedant Kumar747b0e22017-09-08 18:44:56 +0000601 DeferredRegion =
602 SourceMappingRegion(Counter::getZero(), EndLoc, None);
603 }
604 } else if (Region.isDeferred()) {
605 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
606 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000607 }
608 RegionStack.pop_back();
Vedant Kumar8046d222017-11-09 02:33:39 +0000609
610 // If the zero region pushed after the last terminated region no longer
611 // exists, clear its cached information.
612 if (LastTerminatedRegion &&
613 RegionStack.size() < LastTerminatedRegion->second)
614 LastTerminatedRegion = None;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000615 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000616 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000617 }
618
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000619 /// \brief Return the currently active region.
620 SourceMappingRegion &getRegion() {
621 assert(!RegionStack.empty() && "statement has no region");
622 return RegionStack.back();
623 }
Alex Lorenzee024992014-08-04 18:41:51 +0000624
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000625 /// \brief Propagate counts through the children of \c S.
626 Counter propagateCounts(Counter TopCount, const Stmt *S) {
Vedant Kumar78386962017-07-27 02:20:20 +0000627 SourceLocation StartLoc = getStart(S);
628 SourceLocation EndLoc = getEnd(S);
629 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000630 Visit(S);
631 Counter ExitCount = getRegion().getCounter();
632 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000633
634 // The statement may be spanned by an expansion. Make sure we handle a file
635 // exit out of this expansion before moving to the next statement.
Vedant Kumar78386962017-07-27 02:20:20 +0000636 if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
637 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000638
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000639 return ExitCount;
640 }
Alex Lorenzee024992014-08-04 18:41:51 +0000641
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000642 /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
643 /// is already added to \c SourceRegions.
644 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
645 return SourceRegions.rend() !=
646 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
647 [&](const SourceMappingRegion &Region) {
648 return Region.getStartLoc() == StartLoc &&
649 Region.getEndLoc() == EndLoc;
650 });
651 }
652
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000653 /// \brief Adjust the most recently visited location to \c EndLoc.
654 ///
655 /// This should be used after visiting any statements in non-source order.
656 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
657 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000658 // The code region for a whole macro is created in handleFileExit() when
659 // it detects exiting of the virtual file of that macro. If we visited
660 // statements in non-source order, we might already have such a region
661 // added, for example, if a body of a loop is divided among multiple
662 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000663 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000664 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
665 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
666 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000667 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
668 }
Alex Lorenzee024992014-08-04 18:41:51 +0000669
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000670 /// \brief Adjust regions and state when \c NewLoc exits a file.
671 ///
672 /// If moving from our most recently tracked location to \c NewLoc exits any
673 /// files, this adjusts our current region stack and creates the file regions
674 /// for the exited file.
675 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000676 if (NewLoc.isInvalid() ||
677 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000678 return;
679
680 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
681 // find the common ancestor.
682 SourceLocation LCA = NewLoc;
683 FileID ParentFile = SM.getFileID(LCA);
684 while (!isNestedIn(MostRecentLocation, ParentFile)) {
685 LCA = getIncludeOrExpansionLoc(LCA);
686 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
687 // Since there isn't a common ancestor, no file was exited. We just need
688 // to adjust our location to the new file.
689 MostRecentLocation = NewLoc;
690 return;
691 }
692 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000693 }
694
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000695 llvm::SmallSet<SourceLocation, 8> StartLocs;
696 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000697 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
698 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000699 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000700 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000701 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000702 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000703 break;
704 }
Alex Lorenzee024992014-08-04 18:41:51 +0000705
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000706 while (!SM.isInFileID(Loc, ParentFile)) {
707 // The most nested region for each start location is the one with the
708 // correct count. We avoid creating redundant regions by stopping once
709 // we've seen this region.
710 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000711 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000712 getEndOfFileOrMacro(Loc));
713 Loc = getIncludeOrExpansionLoc(Loc);
714 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000715 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000716 }
717
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000718 if (ParentCounter) {
719 // If the file is contained completely by another region and doesn't
720 // immediately start its own region, the whole file gets a region
721 // corresponding to the parent.
722 SourceLocation Loc = MostRecentLocation;
723 while (isNestedIn(Loc, ParentFile)) {
724 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000725 if (StartLocs.insert(FileStart).second) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000726 SourceRegions.emplace_back(*ParentCounter, FileStart,
727 getEndOfFileOrMacro(Loc));
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000728 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
729 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000730 Loc = getIncludeOrExpansionLoc(Loc);
731 }
Alex Lorenzee024992014-08-04 18:41:51 +0000732 }
733
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000734 MostRecentLocation = NewLoc;
735 }
Alex Lorenzee024992014-08-04 18:41:51 +0000736
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000737 /// \brief Ensure that \c S is included in the current region.
738 void extendRegion(const Stmt *S) {
739 SourceMappingRegion &Region = getRegion();
740 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000741
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000742 handleFileExit(StartLoc);
743 if (!Region.hasStartLoc())
744 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000745
746 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000747 }
748
749 /// \brief Mark \c S as a terminator, starting a zero region.
750 void terminateRegion(const Stmt *S) {
751 extendRegion(S);
752 SourceMappingRegion &Region = getRegion();
Vedant Kumar8046d222017-11-09 02:33:39 +0000753 SourceLocation EndLoc = getEnd(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000754 if (!Region.hasEndLoc())
Vedant Kumar8046d222017-11-09 02:33:39 +0000755 Region.setEndLoc(EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000756 pushRegion(Counter::getZero());
Vedant Kumar8046d222017-11-09 02:33:39 +0000757 auto &ZeroRegion = getRegion();
758 ZeroRegion.setDeferred(true);
759 LastTerminatedRegion = {EndLoc, RegionStack.size()};
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000760 }
Alex Lorenzee024992014-08-04 18:41:51 +0000761
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000762 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
763 Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
764 SourceLocation BeforeLoc) {
765 // If the start and end locations of the gap are both within the same macro
766 // file, the range may not be in source order.
767 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
768 return None;
769 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
770 return None;
771 return {{AfterLoc, BeforeLoc}};
772 }
773
774 /// Find the source range after \p AfterStmt and before \p BeforeStmt.
775 Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
776 const Stmt *BeforeStmt) {
777 return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
778 getStart(BeforeStmt));
779 }
780
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000781 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
782 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
783 Counter Count) {
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000784 if (StartLoc == EndLoc)
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000785 return;
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000786 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000787 handleFileExit(StartLoc);
788 size_t Index = pushRegion(Count, StartLoc, EndLoc);
789 getRegion().setGap(true);
790 handleFileExit(EndLoc);
791 popRegions(Index);
792 }
793
Alex Lorenzee024992014-08-04 18:41:51 +0000794 /// \brief Keep counts of breaks and continues inside loops.
795 struct BreakContinue {
796 Counter BreakCount;
797 Counter ContinueCount;
798 };
799 SmallVector<BreakContinue, 8> BreakContinueStack;
800
801 CounterCoverageMappingBuilder(
802 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000803 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000804 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000805 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
806 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000807
808 /// \brief Write the mapping data to the output stream
809 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000810 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000811 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000812 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000813 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000814 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000815 gatherSkippedRegions();
816
Vedant Kumarefd319a2016-07-26 00:24:59 +0000817 if (MappingRegions.empty())
818 return;
819
Justin Bogner4da909b2015-02-03 21:35:49 +0000820 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
821 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000822 Writer.write(OS);
823 }
824
Alex Lorenzee024992014-08-04 18:41:51 +0000825 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000826 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000827 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000828 for (const Stmt *Child : S->children())
829 if (Child)
830 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000831 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000832 }
833
Vedant Kumar341bf422017-10-17 07:47:39 +0000834 /// Determine whether the final deferred region emitted in \p Body should be
835 /// discarded.
836 static bool discardFinalDeferredRegionInDecl(Stmt *Body) {
837 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
838 Stmt *LastStmt = CS->body_back();
839 if (auto *IfElse = dyn_cast<IfStmt>(LastStmt)) {
840 if (auto *Else = dyn_cast_or_null<CompoundStmt>(IfElse->getElse()))
841 LastStmt = Else->body_back();
842 else
843 LastStmt = IfElse->getElse();
844 }
845 return dyn_cast_or_null<ReturnStmt>(LastStmt);
846 }
847 return false;
848 }
849
Alex Lorenzee024992014-08-04 18:41:51 +0000850 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000851 assert(!DeferredRegion && "Deferred region never completed");
852
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000853 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000854
855 // Do not propagate region counts into system headers.
856 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
857 return;
858
Vedant Kumar747b0e22017-09-08 18:44:56 +0000859 Counter ExitCount = propagateCounts(getRegionCounter(Body), Body);
860 assert(RegionStack.empty() && "Regions entered but never exited");
861
Vedant Kumar341bf422017-10-17 07:47:39 +0000862 if (DeferredRegion) {
863 // Complete (or discard) any deferred regions introduced by the last
864 // statement.
865 if (discardFinalDeferredRegionInDecl(Body))
Vedant Kumaref8e05f2017-09-19 00:29:46 +0000866 DeferredRegion = None;
Vedant Kumar341bf422017-10-17 07:47:39 +0000867 else
868 popRegions(completeDeferred(ExitCount, getEnd(Body)));
869 }
Alex Lorenzee024992014-08-04 18:41:51 +0000870 }
871
872 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000873 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000874 if (S->getRetValue())
875 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000876 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000877 }
878
Justin Bognerf959feb2015-04-28 06:31:55 +0000879 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
880 extendRegion(E);
881 if (E->getSubExpr())
882 Visit(E->getSubExpr());
883 terminateRegion(E);
884 }
885
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000886 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000887
888 void VisitLabelStmt(const LabelStmt *S) {
Vedant Kumar8046d222017-11-09 02:33:39 +0000889 Counter LabelCount = getRegionCounter(S);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000890 SourceLocation Start = getStart(S);
Vedant Kumar8046d222017-11-09 02:33:39 +0000891 completeTopLevelDeferredRegion(LabelCount, Start);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000892 // We can't extendRegion here or we risk overlapping with our new region.
893 handleFileExit(Start);
Vedant Kumar8046d222017-11-09 02:33:39 +0000894 pushRegion(LabelCount, Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000895 Visit(S->getSubStmt());
896 }
897
898 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000899 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
900 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000901 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000902 // FIXME: a break in a switch should terminate regions for all preceding
903 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000904 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000905 }
906
907 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000908 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
909 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000910 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
911 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000912 }
913
Eli Friedman181dfe42017-08-08 20:10:14 +0000914 void VisitCallExpr(const CallExpr *E) {
915 VisitStmt(E);
916
917 // Terminate the region when we hit a noreturn function.
918 // (This is helpful dealing with switch statements.)
919 QualType CalleeType = E->getCallee()->getType();
920 if (getFunctionExtInfo(*CalleeType).getNoReturn())
921 terminateRegion(E);
922 }
923
Alex Lorenzee024992014-08-04 18:41:51 +0000924 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000925 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000926
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000927 Counter ParentCount = getRegion().getCounter();
928 Counter BodyCount = getRegionCounter(S);
929
930 // Handle the body first so that we can get the backedge count.
931 BreakContinueStack.push_back(BreakContinue());
932 extendRegion(S->getBody());
933 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000934 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000935
936 // Go back to handle the condition.
937 Counter CondCount =
938 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
939 propagateCounts(CondCount, S->getCond());
940 adjustForOutOfOrderTraversal(getEnd(S));
941
Vedant Kumarfa8fa042017-11-29 22:25:14 +0000942 // The body count applies to the area immediately after the increment.
943 auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
944 if (Gap)
945 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
946
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000947 Counter OutCount =
948 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
949 if (OutCount != ParentCount)
950 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000951 }
952
953 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000954 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000955
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000956 Counter ParentCount = getRegion().getCounter();
957 Counter BodyCount = getRegionCounter(S);
958
959 BreakContinueStack.push_back(BreakContinue());
960 extendRegion(S->getBody());
961 Counter BackedgeCount =
962 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000963 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000964
965 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
966 propagateCounts(CondCount, S->getCond());
967
968 Counter OutCount =
969 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
970 if (OutCount != ParentCount)
971 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000972 }
973
974 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000975 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000976 if (S->getInit())
977 Visit(S->getInit());
978
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000979 Counter ParentCount = getRegion().getCounter();
980 Counter BodyCount = getRegionCounter(S);
981
982 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000983 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000984 extendRegion(S->getBody());
985 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
986 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000987
988 // The increment is essentially part of the body but it needs to include
989 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000990 if (const Stmt *Inc = S->getInc())
991 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
992
993 // Go back to handle the condition.
994 Counter CondCount =
995 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
996 if (const Expr *Cond = S->getCond()) {
997 propagateCounts(CondCount, Cond);
998 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000999 }
1000
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001001 // The body count applies to the area immediately after the increment.
1002 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1003 getStart(S->getBody()));
1004 if (Gap)
1005 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1006
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001007 Counter OutCount =
1008 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1009 if (OutCount != ParentCount)
1010 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001011 }
1012
1013 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001014 extendRegion(S);
1015 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +00001016 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001017
1018 Counter ParentCount = getRegion().getCounter();
1019 Counter BodyCount = getRegionCounter(S);
1020
Alex Lorenzee024992014-08-04 18:41:51 +00001021 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001022 extendRegion(S->getBody());
1023 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001024 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001025
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001026 // The body count applies to the area immediately after the range.
1027 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1028 getStart(S->getBody()));
1029 if (Gap)
1030 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1031
Justin Bogner15874322015-04-30 21:31:02 +00001032 Counter LoopCount =
1033 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1034 Counter OutCount =
1035 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001036 if (OutCount != ParentCount)
1037 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001038 }
1039
1040 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001041 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001042 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001043
1044 Counter ParentCount = getRegion().getCounter();
1045 Counter BodyCount = getRegionCounter(S);
1046
Alex Lorenzee024992014-08-04 18:41:51 +00001047 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001048 extendRegion(S->getBody());
1049 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +00001050 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001051
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001052 // The body count applies to the area immediately after the collection.
1053 auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1054 getStart(S->getBody()));
1055 if (Gap)
1056 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1057
Justin Bogner15874322015-04-30 21:31:02 +00001058 Counter LoopCount =
1059 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1060 Counter OutCount =
1061 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001062 if (OutCount != ParentCount)
1063 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001064 }
1065
1066 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001067 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +00001068 if (S->getInit())
1069 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +00001070 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001071
Alex Lorenzee024992014-08-04 18:41:51 +00001072 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001073
1074 const Stmt *Body = S->getBody();
1075 extendRegion(Body);
1076 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1077 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001078 // Make a region for the body of the switch. If the body starts with
1079 // a case, that case will reuse this region; otherwise, this covers
1080 // the unreachable code at the beginning of the switch body.
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001081 size_t Index =
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001082 pushRegion(Counter::getZero(), getStart(CS->body_front()));
Richard Trieub5841332015-04-15 01:21:42 +00001083 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001084 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001085
1086 // Set the end for the body of the switch, if it isn't already set.
1087 for (size_t i = RegionStack.size(); i != Index; --i) {
1088 if (!RegionStack[i - 1].hasEndLoc())
1089 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1090 }
1091
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001092 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001093 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001094 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001095 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001096 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001097
Alex Lorenzee024992014-08-04 18:41:51 +00001098 if (!BreakContinueStack.empty())
1099 BreakContinueStack.back().ContinueCount = addCounters(
1100 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001101
1102 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001103 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001104 pushRegion(ExitCount);
1105
1106 // Ensure that handleFileExit recognizes when the end location is located
1107 // in a different file.
1108 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001109 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001110 }
1111
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001112 void VisitSwitchCase(const SwitchCase *S) {
1113 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001114
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001115 SourceMappingRegion &Parent = getRegion();
1116
1117 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1118 // Reuse the existing region if it starts at our label. This is typical of
1119 // the first case in a switch.
1120 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
1121 Parent.setCounter(Count);
1122 else
1123 pushRegion(Count, getStart(S));
1124
Sanjay Patel376c06c2015-12-24 21:11:29 +00001125 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001126 Visit(CS->getLHS());
1127 if (const Expr *RHS = CS->getRHS())
1128 Visit(RHS);
1129 }
Alex Lorenzee024992014-08-04 18:41:51 +00001130 Visit(S->getSubStmt());
1131 }
1132
1133 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001134 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001135 if (S->getInit())
1136 Visit(S->getInit());
1137
Justin Bogner055ebc32015-06-16 06:24:15 +00001138 // Extend into the condition before we propagate through it below - this is
1139 // needed to handle macros that generate the "if" but not the condition.
1140 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001141
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001142 Counter ParentCount = getRegion().getCounter();
1143 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001144
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001145 // Emitting a counter for the condition makes it easier to interpret the
1146 // counter for the body when looking at the coverage.
1147 propagateCounts(ParentCount, S->getCond());
1148
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001149 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001150 auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1151 if (Gap)
1152 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001153
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001154 extendRegion(S->getThen());
1155 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1156
1157 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1158 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001159 // The 'else' count applies to the area immediately after the 'then'.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001160 Gap = findGapAreaBetween(S->getThen(), Else);
1161 if (Gap)
1162 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001163 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001164 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1165 } else
1166 OutCount = addCounters(OutCount, ElseCount);
1167
1168 if (OutCount != ParentCount)
1169 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001170 }
1171
1172 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001173 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001174 // Handle macros that generate the "try" but not the rest.
1175 extendRegion(S->getTryBlock());
1176
1177 Counter ParentCount = getRegion().getCounter();
1178 propagateCounts(ParentCount, S->getTryBlock());
1179
Alex Lorenzee024992014-08-04 18:41:51 +00001180 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1181 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001182
1183 Counter ExitCount = getRegionCounter(S);
1184 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001185 }
1186
1187 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001188 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001189 }
1190
1191 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001192 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001193
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001194 Counter ParentCount = getRegion().getCounter();
1195 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001196
Justin Bognere3654ce2015-04-24 23:37:57 +00001197 Visit(E->getCond());
1198
1199 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001200 // The 'then' count applies to the area immediately after the condition.
Vedant Kumarfa8fa042017-11-29 22:25:14 +00001201 auto Gap =
1202 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1203 if (Gap)
1204 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001205
Justin Bognere3654ce2015-04-24 23:37:57 +00001206 extendRegion(E->getTrueExpr());
1207 propagateCounts(TrueCount, E->getTrueExpr());
1208 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001209
Justin Bognere3654ce2015-04-24 23:37:57 +00001210 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001211 propagateCounts(subtractCounters(ParentCount, TrueCount),
1212 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001213 }
1214
1215 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001216 extendRegion(E->getLHS());
1217 propagateCounts(getRegion().getCounter(), E->getLHS());
1218 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001219
1220 extendRegion(E->getRHS());
1221 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001222 }
1223
1224 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001225 extendRegion(E->getLHS());
1226 propagateCounts(getRegion().getCounter(), E->getLHS());
1227 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001228
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001229 extendRegion(E->getRHS());
1230 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001231 }
Justin Bognerc1091022015-02-24 04:13:56 +00001232
1233 void VisitLambdaExpr(const LambdaExpr *LE) {
1234 // Lambdas are treated as their own functions for now, so we shouldn't
1235 // propagate counts into them.
1236 }
Alex Lorenzee024992014-08-04 18:41:51 +00001237};
Alex Lorenzee024992014-08-04 18:41:51 +00001238
Xinliang David Li1f39fcf2017-04-14 04:14:29 +00001239std::string getCoverageSection(const CodeGenModule &CGM) {
Vedant Kumar8a767a42017-04-15 00:10:05 +00001240 return llvm::getInstrProfSectionName(
1241 llvm::IPSK_covmap,
1242 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
Alex Lorenzee024992014-08-04 18:41:51 +00001243}
1244
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001245std::string normalizeFilename(StringRef Filename) {
1246 llvm::SmallString<256> Path(Filename);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001247 llvm::sys::fs::make_absolute(Path);
Vedant Kumard04929d2016-07-18 22:32:02 +00001248 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001249 return Path.str().str();
1250}
1251
1252} // end anonymous namespace
1253
Justin Bognera432d172015-02-03 00:20:24 +00001254static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1255 ArrayRef<CounterExpression> Expressions,
1256 ArrayRef<CounterMappingRegion> Regions) {
1257 OS << FunctionName << ":\n";
1258 CounterMappingContext Ctx(Expressions);
1259 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001260 OS.indent(2);
1261 switch (R.Kind) {
1262 case CounterMappingRegion::CodeRegion:
1263 break;
1264 case CounterMappingRegion::ExpansionRegion:
1265 OS << "Expansion,";
1266 break;
1267 case CounterMappingRegion::SkippedRegion:
1268 OS << "Skipped,";
1269 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001270 case CounterMappingRegion::GapRegion:
1271 OS << "Gap,";
1272 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001273 }
1274
Justin Bogner4da909b2015-02-03 21:35:49 +00001275 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1276 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001277 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001278 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001279 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1280 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001281 }
1282}
1283
Alex Lorenzee024992014-08-04 18:41:51 +00001284void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001285 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001286 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001287 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +00001288 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +00001289#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +00001290 llvm::Type *FunctionRecordTypes[] = {
1291 #include "llvm/ProfileData/InstrProfData.inc"
1292 };
Alex Lorenzee024992014-08-04 18:41:51 +00001293 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +00001294 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1295 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +00001296 }
1297
Xinliang David Lia026a432015-11-05 05:46:39 +00001298 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +00001299 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +00001300 #include "llvm/ProfileData/InstrProfData.inc"
1301 };
Alex Lorenzee024992014-08-04 18:41:51 +00001302 FunctionRecords.push_back(llvm::ConstantStruct::get(
1303 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +00001304 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001305 FunctionNames.push_back(
1306 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +00001307 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001308
1309 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1310 // Dump the coverage mapping data for this function by decoding the
1311 // encoded data. This allows us to dump the mapping regions which were
1312 // also processed by the CoverageMappingWriter which performs
1313 // additional minimization operations such as reducing the number of
1314 // expressions.
1315 std::vector<StringRef> Filenames;
1316 std::vector<CounterExpression> Expressions;
1317 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001318 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001319 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001320 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001321 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001322 for (const auto &Entry : FileEntries) {
1323 auto I = Entry.second;
1324 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1325 FilenameRefs[I] = FilenameStrs[I];
1326 }
Justin Bognera432d172015-02-03 00:20:24 +00001327 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1328 Expressions, Regions);
1329 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001330 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001331 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001332 }
Alex Lorenzee024992014-08-04 18:41:51 +00001333}
1334
1335void CoverageMappingModuleGen::emit() {
1336 if (FunctionRecords.empty())
1337 return;
1338 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1339 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1340
1341 // Create the filenames and merge them with coverage mappings
1342 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001343 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001344 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001345 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001346 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001347 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001348 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001349 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001350 }
1351
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001352 std::string FilenamesAndCoverageMappings;
1353 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1354 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1355 std::string RawCoverageMappings =
1356 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1357 OS << RawCoverageMappings;
1358 size_t CoverageMappingSize = RawCoverageMappings.size();
1359 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1360 // Append extra zeroes if necessary to ensure that the size of the filenames
1361 // and coverage mappings is a multiple of 8.
1362 if (size_t Rem = OS.str().size() % 8) {
1363 CoverageMappingSize += 8 - Rem;
1364 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
1365 OS << '\0';
Alex Lorenzee024992014-08-04 18:41:51 +00001366 }
1367 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001368 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001369
1370 // Create the deferred function records array
1371 auto RecordsTy =
1372 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1373 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1374
Xinliang David Li20b188c2016-01-03 19:25:54 +00001375 llvm::Type *CovDataHeaderTypes[] = {
1376#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1377#include "llvm/ProfileData/InstrProfData.inc"
1378 };
1379 auto CovDataHeaderTy =
1380 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1381 llvm::Constant *CovDataHeaderVals[] = {
1382#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1383#include "llvm/ProfileData/InstrProfData.inc"
1384 };
1385 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1386 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1387
Alex Lorenzee024992014-08-04 18:41:51 +00001388 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001389 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1390 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001391 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001392 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1393 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001394 auto CovDataVal =
1395 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001396 auto CovData = new llvm::GlobalVariable(
1397 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1398 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001399
1400 CovData->setSection(getCoverageSection(CGM));
1401 CovData->setAlignment(8);
1402
1403 // Make sure the data doesn't get deleted.
1404 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001405 // Create the deferred function records array
1406 if (!FunctionNames.empty()) {
1407 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1408 FunctionNames.size());
1409 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1410 // This variable will *NOT* be emitted to the object file. It is used
1411 // to pass the list of names referenced to codegen.
1412 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1413 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001414 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001415 }
Alex Lorenzee024992014-08-04 18:41:51 +00001416}
1417
1418unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1419 auto It = FileEntries.find(File);
1420 if (It != FileEntries.end())
1421 return It->second;
1422 unsigned FileID = FileEntries.size();
1423 FileEntries.insert(std::make_pair(File, FileID));
1424 return FileID;
1425}
1426
1427void CoverageMappingGen::emitCounterMapping(const Decl *D,
1428 llvm::raw_ostream &OS) {
1429 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001430 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001431 Walker.VisitDecl(D);
1432 Walker.write(OS);
1433}
1434
1435void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1436 llvm::raw_ostream &OS) {
1437 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1438 Walker.VisitDecl(D);
1439 Walker.write(OS);
1440}