blob: 2b6e6deb5549decc7f6f3d8b4711c4a40a02655a [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
115 /// Check if the start and end locations appear in source order, i.e
116 /// top->bottom, left->right.
117 bool isInSourceOrder() const {
118 return (LineStart < LineEnd) ||
119 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
120 }
121};
122
Alex Lorenzee024992014-08-04 18:41:51 +0000123/// \brief Provides the common functionality for the different
124/// coverage mapping region builders.
125class CoverageMappingBuilder {
126public:
127 CoverageMappingModuleGen &CVM;
128 SourceManager &SM;
129 const LangOptions &LangOpts;
130
131private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000132 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
133 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
134 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000135
136public:
Alex Lorenzee024992014-08-04 18:41:51 +0000137 /// \brief The coverage mapping regions for this function
138 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
139 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000140 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000141
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000142 /// \brief A set of regions which can be used as a filter.
143 ///
144 /// It is produced by emitExpansionRegions() and is used in
145 /// emitSourceRegions() to suppress producing code regions if
146 /// the same area is covered by expansion regions.
147 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
148 SourceRegionFilter;
149
Alex Lorenzee024992014-08-04 18:41:51 +0000150 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
151 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000152 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000153
154 /// \brief Return the precise end location for the given token.
155 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000156 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
157 // macro locations, which we just treat as expanded files.
158 unsigned TokLen =
159 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
160 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000161 }
162
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000163 /// \brief Return the start location of an included file or expanded macro.
164 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
165 if (Loc.isMacroID())
166 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
167 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000168 }
169
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000170 /// \brief Return the end location of an included file or expanded macro.
171 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
172 if (Loc.isMacroID())
173 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000174 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000175 return SM.getLocForEndOfFile(SM.getFileID(Loc));
176 }
177
178 /// \brief Find out where the current file is included or macro is expanded.
179 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
180 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
181 : SM.getIncludeLoc(SM.getFileID(Loc));
182 }
183
Justin Bogner682bfbf2015-05-14 22:14:10 +0000184 /// \brief Return true if \c Loc is a location in a built-in macro.
185 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000186 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000187 }
188
Igor Kudrind9e1a612016-06-07 10:07:51 +0000189 /// \brief Check whether \c Loc is included or expanded from \c Parent.
190 bool isNestedIn(SourceLocation Loc, FileID Parent) {
191 do {
192 Loc = getIncludeOrExpansionLoc(Loc);
193 if (Loc.isInvalid())
194 return false;
195 } while (!SM.isInFileID(Loc, Parent));
196 return true;
197 }
198
Justin Bogner682bfbf2015-05-14 22:14:10 +0000199 /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000200 SourceLocation getStart(const Stmt *S) {
201 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000202 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000203 Loc = SM.getImmediateExpansionRange(Loc).first;
204 return Loc;
205 }
206
Justin Bogner682bfbf2015-05-14 22:14:10 +0000207 /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000208 SourceLocation getEnd(const Stmt *S) {
209 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000210 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000211 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000212 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000213 }
214
215 /// \brief Find the set of files we have regions for and assign IDs
216 ///
217 /// Fills \c Mapping with the virtual file mapping needed to write out
218 /// coverage and collects the necessary file information to emit source and
219 /// expansion regions.
220 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
221 FileIDMapping.clear();
222
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000223 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000224 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
225 for (const auto &Region : SourceRegions) {
226 SourceLocation Loc = Region.getStartLoc();
227 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000228 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000229 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000230
Vedant Kumar93205af2016-07-11 22:57:46 +0000231 // Do not map FileID's associated with system headers.
232 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
233 continue;
234
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000235 unsigned Depth = 0;
236 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000237 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000238 ++Depth;
239 FileLocs.push_back(std::make_pair(Loc, Depth));
240 }
241 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
242
243 for (const auto &FL : FileLocs) {
244 SourceLocation Loc = FL.first;
245 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
246 auto Entry = SM.getFileEntryForID(SpellingFile);
247 if (!Entry)
248 continue;
249
250 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
251 Mapping.push_back(CVM.getFileID(Entry));
252 }
253 }
254
255 /// \brief Get the coverage mapping file ID for \c Loc.
256 ///
257 /// If such file id doesn't exist, return None.
258 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
259 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000260 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000261 return Mapping->second.first;
262 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000263 }
264
Alex Lorenzee024992014-08-04 18:41:51 +0000265 /// \brief Gather all the regions that were skipped by the preprocessor
266 /// using the constructs like #if.
267 void gatherSkippedRegions() {
268 /// An array of the minimum lineStarts and the maximum lineEnds
269 /// for mapping regions from the appropriate source files.
270 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
271 FileLineRanges.resize(
272 FileIDMapping.size(),
273 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
274 for (const auto &R : MappingRegions) {
275 FileLineRanges[R.FileID].first =
276 std::min(FileLineRanges[R.FileID].first, R.LineStart);
277 FileLineRanges[R.FileID].second =
278 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
279 }
280
281 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
282 for (const auto &I : SkippedRanges) {
283 auto LocStart = I.getBegin();
284 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000285 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
286 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000287
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000288 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000289 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000290 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000291 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000292 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000293 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000294 // Make sure that we only collect the regions that are inside
295 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000296 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
297 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000298 MappingRegions.push_back(Region);
299 }
300 }
301
Alex Lorenzee024992014-08-04 18:41:51 +0000302 /// \brief Generate the coverage counter mapping regions from collected
303 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000304 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000305 for (const auto &Region : SourceRegions) {
306 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000307
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000308 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000309 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000310
Vedant Kumar93205af2016-07-11 22:57:46 +0000311 // Ignore regions from system headers.
312 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
313 continue;
314
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000315 auto CovFileID = getCoverageFileID(LocStart);
316 // Ignore regions that don't have a file, such as builtin macros.
317 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000318 continue;
319
Justin Bognerf14b2072015-03-25 04:13:49 +0000320 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000321 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
322 "region spans multiple files");
323
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000324 // Don't add code regions for the area covered by expansion regions.
325 // This not only suppresses redundant regions, but sometimes prevents
326 // creating regions with wrong counters if, for example, a statement's
327 // body ends at the end of a nested macro.
328 if (Filter.count(std::make_pair(LocStart, LocEnd)))
329 continue;
330
Vedant Kumard7369642017-07-27 02:20:25 +0000331 // Find the spelling locations for the mapping region.
332 SpellingRegion SR{SM, LocStart, LocEnd};
333 assert(SR.isInSourceOrder() && "region start and end out of order");
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000334
335 if (Region.isGap()) {
336 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
337 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
338 SR.LineEnd, SR.ColumnEnd));
339 } else {
340 MappingRegions.push_back(CounterMappingRegion::makeRegion(
341 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
342 SR.LineEnd, SR.ColumnEnd));
343 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000344 }
345 }
346
347 /// \brief Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000348 SourceRegionFilter emitExpansionRegions() {
349 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000350 for (const auto &FM : FileIDMapping) {
351 SourceLocation ExpandedLoc = FM.second.second;
352 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
353 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000354 continue;
355
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000356 auto ParentFileID = getCoverageFileID(ParentLoc);
357 if (!ParentFileID)
358 continue;
359 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
360 assert(ExpandedFileID && "expansion in uncovered file");
361
362 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
363 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
364 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000365 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000366
Vedant Kumard7369642017-07-27 02:20:25 +0000367 SpellingRegion SR{SM, ParentLoc, LocEnd};
368 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000369 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000370 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
371 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000372 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000373 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000374 }
375};
376
377/// \brief Creates unreachable coverage regions for the functions that
378/// are not emitted.
379struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
380 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
381 const LangOptions &LangOpts)
382 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
383
384 void VisitDecl(const Decl *D) {
385 if (!D->hasBody())
386 return;
387 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000388 SourceLocation Start = getStart(Body);
389 SourceLocation End = getEnd(Body);
390 if (!SM.isWrittenInSameFile(Start, End)) {
391 // Walk up to find the common ancestor.
392 // Correct the locations accordingly.
393 FileID StartFileID = SM.getFileID(Start);
394 FileID EndFileID = SM.getFileID(End);
395 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
396 Start = getIncludeOrExpansionLoc(Start);
397 assert(Start.isValid() &&
398 "Declaration start location not nested within a known region");
399 StartFileID = SM.getFileID(Start);
400 }
401 while (StartFileID != EndFileID) {
402 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
403 assert(End.isValid() &&
404 "Declaration end location not nested within a known region");
405 EndFileID = SM.getFileID(End);
406 }
407 }
408 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000409 }
410
411 /// \brief Write the mapping data to the output stream
412 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000413 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000414 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000415 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000416
Vedant Kumarefd319a2016-07-26 00:24:59 +0000417 if (MappingRegions.empty())
418 return;
419
Craig Topper5fc8fc22014-08-27 06:28:36 +0000420 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000421 Writer.write(OS);
422 }
423};
424
425/// \brief A StmtVisitor that creates coverage mapping regions which map
426/// from the source code locations to the PGO counters.
427struct CounterCoverageMappingBuilder
428 : public CoverageMappingBuilder,
429 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
430 /// \brief The map of statements to count values.
431 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
432
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000433 /// \brief A stack of currently live regions.
434 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000435
Vedant Kumar747b0e22017-09-08 18:44:56 +0000436 /// The currently deferred region: its end location and count can be set once
437 /// its parent has been popped from the region stack.
438 Optional<SourceMappingRegion> DeferredRegion;
439
Alex Lorenzee024992014-08-04 18:41:51 +0000440 CounterExpressionBuilder Builder;
441
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000442 /// \brief A location in the most recently visited file or macro.
443 ///
444 /// This is used to adjust the active source regions appropriately when
445 /// expressions cross file or macro boundaries.
446 SourceLocation MostRecentLocation;
447
448 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000449 Counter subtractCounters(Counter LHS, Counter RHS) {
450 return Builder.subtract(LHS, RHS);
451 }
452
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000453 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000454 Counter addCounters(Counter LHS, Counter RHS) {
455 return Builder.add(LHS, RHS);
456 }
457
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000458 Counter addCounters(Counter C1, Counter C2, Counter C3) {
459 return addCounters(addCounters(C1, C2), C3);
460 }
461
Alex Lorenzee024992014-08-04 18:41:51 +0000462 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000463 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000464 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000465 Counter getRegionCounter(const Stmt *S) {
466 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000467 }
468
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000469 /// \brief Push a region onto the stack.
470 ///
471 /// Returns the index on the stack where the region was pushed. This can be
472 /// used with popRegions to exit a "scope", ending the region that was pushed.
473 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
474 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000475 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000476 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000477 completeDeferred(Count, MostRecentLocation);
478 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000479 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000480
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000481 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000482 }
483
Vedant Kumar747b0e22017-09-08 18:44:56 +0000484 /// Complete any pending deferred region by setting its end location and
485 /// count, and then pushing it onto the region stack.
486 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
487 size_t Index = RegionStack.size();
488 if (!DeferredRegion)
489 return Index;
490
491 // Consume the pending region.
492 SourceMappingRegion DR = DeferredRegion.getValue();
493 DeferredRegion = None;
494
495 // If the region ends in an expansion, find the expansion site.
496 if (SM.getFileID(DeferredEndLoc) != SM.getMainFileID()) {
497 FileID StartFile = SM.getFileID(DR.getStartLoc());
498 if (isNestedIn(DeferredEndLoc, StartFile)) {
499 do {
500 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
501 } while (StartFile != SM.getFileID(DeferredEndLoc));
502 }
503 }
504
505 // The parent of this deferred region ends where the containing decl ends,
506 // so the region isn't useful.
507 if (DR.getStartLoc() == DeferredEndLoc)
508 return Index;
509
510 // If we're visiting statements in non-source order (e.g switch cases or
511 // a loop condition) we can't construct a sensible deferred region.
512 if (!SpellingRegion(SM, DR.getStartLoc(), DeferredEndLoc).isInSourceOrder())
513 return Index;
514
Vedant Kumara1c4deb2017-09-18 23:37:30 +0000515 DR.setGap(true);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000516 DR.setCounter(Count);
517 DR.setEndLoc(DeferredEndLoc);
518 handleFileExit(DeferredEndLoc);
519 RegionStack.push_back(DR);
520 return Index;
521 }
522
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000523 /// \brief Pop regions from the stack into the function's list of regions.
524 ///
525 /// Adds all regions from \c ParentIndex to the top of the stack to the
526 /// function's \c SourceRegions.
527 void popRegions(size_t ParentIndex) {
528 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000529 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000530 while (RegionStack.size() > ParentIndex) {
531 SourceMappingRegion &Region = RegionStack.back();
532 if (Region.hasStartLoc()) {
533 SourceLocation StartLoc = Region.getStartLoc();
534 SourceLocation EndLoc = Region.hasEndLoc()
535 ? Region.getEndLoc()
536 : RegionStack[ParentIndex].getEndLoc();
537 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
538 // The region ends in a nested file or macro expansion. Create a
539 // separate region for each expansion.
540 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
541 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
542
Igor Kudrin8545dae2016-08-29 11:48:50 +0000543 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
544 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000545
Justin Bognerf14b2072015-03-25 04:13:49 +0000546 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000547 if (EndLoc.isInvalid())
548 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000549 }
550 Region.setEndLoc(EndLoc);
551
552 MostRecentLocation = EndLoc;
553 // If this region happens to span an entire expansion, we need to make
554 // sure we don't overlap the parent region with it.
555 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
556 EndLoc == getEndOfFileOrMacro(EndLoc))
557 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
558
559 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Craig Topperf36a5c42015-09-26 05:10:16 +0000560 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000561
562 if (ParentOfDeferredRegion) {
563 ParentOfDeferredRegion = false;
564
565 // If there's an existing deferred region, keep the old one, because
566 // it means there are two consecutive returns (or a similar pattern).
567 if (!DeferredRegion.hasValue() &&
568 // File IDs aren't gathered within macro expansions, so it isn't
569 // useful to try and create a deferred region inside of one.
570 (SM.getFileID(EndLoc) == SM.getMainFileID()))
571 DeferredRegion =
572 SourceMappingRegion(Counter::getZero(), EndLoc, None);
573 }
574 } else if (Region.isDeferred()) {
575 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
576 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000577 }
578 RegionStack.pop_back();
579 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000580 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000581 }
582
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000583 /// \brief Return the currently active region.
584 SourceMappingRegion &getRegion() {
585 assert(!RegionStack.empty() && "statement has no region");
586 return RegionStack.back();
587 }
Alex Lorenzee024992014-08-04 18:41:51 +0000588
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000589 /// \brief Propagate counts through the children of \c S.
590 Counter propagateCounts(Counter TopCount, const Stmt *S) {
Vedant Kumar78386962017-07-27 02:20:20 +0000591 SourceLocation StartLoc = getStart(S);
592 SourceLocation EndLoc = getEnd(S);
593 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000594 Visit(S);
595 Counter ExitCount = getRegion().getCounter();
596 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000597
598 // The statement may be spanned by an expansion. Make sure we handle a file
599 // exit out of this expansion before moving to the next statement.
Vedant Kumar78386962017-07-27 02:20:20 +0000600 if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
601 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000602
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000603 return ExitCount;
604 }
Alex Lorenzee024992014-08-04 18:41:51 +0000605
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000606 /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
607 /// is already added to \c SourceRegions.
608 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
609 return SourceRegions.rend() !=
610 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
611 [&](const SourceMappingRegion &Region) {
612 return Region.getStartLoc() == StartLoc &&
613 Region.getEndLoc() == EndLoc;
614 });
615 }
616
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000617 /// \brief Adjust the most recently visited location to \c EndLoc.
618 ///
619 /// This should be used after visiting any statements in non-source order.
620 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
621 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000622 // The code region for a whole macro is created in handleFileExit() when
623 // it detects exiting of the virtual file of that macro. If we visited
624 // statements in non-source order, we might already have such a region
625 // added, for example, if a body of a loop is divided among multiple
626 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000627 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000628 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
629 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
630 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000631 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
632 }
Alex Lorenzee024992014-08-04 18:41:51 +0000633
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000634 /// \brief Adjust regions and state when \c NewLoc exits a file.
635 ///
636 /// If moving from our most recently tracked location to \c NewLoc exits any
637 /// files, this adjusts our current region stack and creates the file regions
638 /// for the exited file.
639 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000640 if (NewLoc.isInvalid() ||
641 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000642 return;
643
644 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
645 // find the common ancestor.
646 SourceLocation LCA = NewLoc;
647 FileID ParentFile = SM.getFileID(LCA);
648 while (!isNestedIn(MostRecentLocation, ParentFile)) {
649 LCA = getIncludeOrExpansionLoc(LCA);
650 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
651 // Since there isn't a common ancestor, no file was exited. We just need
652 // to adjust our location to the new file.
653 MostRecentLocation = NewLoc;
654 return;
655 }
656 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000657 }
658
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000659 llvm::SmallSet<SourceLocation, 8> StartLocs;
660 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000661 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
662 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000663 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000664 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000665 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000666 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000667 break;
668 }
Alex Lorenzee024992014-08-04 18:41:51 +0000669
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000670 while (!SM.isInFileID(Loc, ParentFile)) {
671 // The most nested region for each start location is the one with the
672 // correct count. We avoid creating redundant regions by stopping once
673 // we've seen this region.
674 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000675 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000676 getEndOfFileOrMacro(Loc));
677 Loc = getIncludeOrExpansionLoc(Loc);
678 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000679 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000680 }
681
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000682 if (ParentCounter) {
683 // If the file is contained completely by another region and doesn't
684 // immediately start its own region, the whole file gets a region
685 // corresponding to the parent.
686 SourceLocation Loc = MostRecentLocation;
687 while (isNestedIn(Loc, ParentFile)) {
688 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
689 if (StartLocs.insert(FileStart).second)
690 SourceRegions.emplace_back(*ParentCounter, FileStart,
691 getEndOfFileOrMacro(Loc));
692 Loc = getIncludeOrExpansionLoc(Loc);
693 }
Alex Lorenzee024992014-08-04 18:41:51 +0000694 }
695
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000696 MostRecentLocation = NewLoc;
697 }
Alex Lorenzee024992014-08-04 18:41:51 +0000698
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000699 /// \brief Ensure that \c S is included in the current region.
700 void extendRegion(const Stmt *S) {
701 SourceMappingRegion &Region = getRegion();
702 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000703
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000704 handleFileExit(StartLoc);
705 if (!Region.hasStartLoc())
706 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000707
708 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000709 }
710
711 /// \brief Mark \c S as a terminator, starting a zero region.
712 void terminateRegion(const Stmt *S) {
713 extendRegion(S);
714 SourceMappingRegion &Region = getRegion();
715 if (!Region.hasEndLoc())
716 Region.setEndLoc(getEnd(S));
717 pushRegion(Counter::getZero());
Vedant Kumar747b0e22017-09-08 18:44:56 +0000718 getRegion().setDeferred(true);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000719 }
Alex Lorenzee024992014-08-04 18:41:51 +0000720
Vedant Kumar2e8c8752017-11-09 02:33:38 +0000721 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
722 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
723 Counter Count) {
724 if (StartLoc == EndLoc || StartLoc.isMacroID() || EndLoc.isMacroID() ||
725 !SM.isWrittenInSameFile(StartLoc, EndLoc))
726 return;
727 handleFileExit(StartLoc);
728 size_t Index = pushRegion(Count, StartLoc, EndLoc);
729 getRegion().setGap(true);
730 handleFileExit(EndLoc);
731 popRegions(Index);
732 }
733
Alex Lorenzee024992014-08-04 18:41:51 +0000734 /// \brief Keep counts of breaks and continues inside loops.
735 struct BreakContinue {
736 Counter BreakCount;
737 Counter ContinueCount;
738 };
739 SmallVector<BreakContinue, 8> BreakContinueStack;
740
741 CounterCoverageMappingBuilder(
742 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000743 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000744 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000745 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
746 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000747
748 /// \brief Write the mapping data to the output stream
749 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000750 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000751 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000752 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000753 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000754 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000755 gatherSkippedRegions();
756
Vedant Kumarefd319a2016-07-26 00:24:59 +0000757 if (MappingRegions.empty())
758 return;
759
Justin Bogner4da909b2015-02-03 21:35:49 +0000760 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
761 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000762 Writer.write(OS);
763 }
764
Alex Lorenzee024992014-08-04 18:41:51 +0000765 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000766 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000767 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000768 for (const Stmt *Child : S->children())
769 if (Child)
770 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000771 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000772 }
773
Vedant Kumar341bf422017-10-17 07:47:39 +0000774 /// Determine whether the final deferred region emitted in \p Body should be
775 /// discarded.
776 static bool discardFinalDeferredRegionInDecl(Stmt *Body) {
777 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
778 Stmt *LastStmt = CS->body_back();
779 if (auto *IfElse = dyn_cast<IfStmt>(LastStmt)) {
780 if (auto *Else = dyn_cast_or_null<CompoundStmt>(IfElse->getElse()))
781 LastStmt = Else->body_back();
782 else
783 LastStmt = IfElse->getElse();
784 }
785 return dyn_cast_or_null<ReturnStmt>(LastStmt);
786 }
787 return false;
788 }
789
Alex Lorenzee024992014-08-04 18:41:51 +0000790 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000791 assert(!DeferredRegion && "Deferred region never completed");
792
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000793 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000794
795 // Do not propagate region counts into system headers.
796 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
797 return;
798
Vedant Kumar747b0e22017-09-08 18:44:56 +0000799 Counter ExitCount = propagateCounts(getRegionCounter(Body), Body);
800 assert(RegionStack.empty() && "Regions entered but never exited");
801
Vedant Kumar341bf422017-10-17 07:47:39 +0000802 if (DeferredRegion) {
803 // Complete (or discard) any deferred regions introduced by the last
804 // statement.
805 if (discardFinalDeferredRegionInDecl(Body))
Vedant Kumaref8e05f2017-09-19 00:29:46 +0000806 DeferredRegion = None;
Vedant Kumar341bf422017-10-17 07:47:39 +0000807 else
808 popRegions(completeDeferred(ExitCount, getEnd(Body)));
809 }
Alex Lorenzee024992014-08-04 18:41:51 +0000810 }
811
812 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000813 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000814 if (S->getRetValue())
815 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000816 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000817 }
818
Justin Bognerf959feb2015-04-28 06:31:55 +0000819 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
820 extendRegion(E);
821 if (E->getSubExpr())
822 Visit(E->getSubExpr());
823 terminateRegion(E);
824 }
825
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000826 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000827
828 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000829 SourceLocation Start = getStart(S);
830 // We can't extendRegion here or we risk overlapping with our new region.
831 handleFileExit(Start);
832 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000833 Visit(S->getSubStmt());
834 }
835
836 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000837 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
838 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000839 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000840 // FIXME: a break in a switch should terminate regions for all preceding
841 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000842 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000843 }
844
845 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000846 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
847 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000848 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
849 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000850 }
851
Eli Friedman181dfe42017-08-08 20:10:14 +0000852 void VisitCallExpr(const CallExpr *E) {
853 VisitStmt(E);
854
855 // Terminate the region when we hit a noreturn function.
856 // (This is helpful dealing with switch statements.)
857 QualType CalleeType = E->getCallee()->getType();
858 if (getFunctionExtInfo(*CalleeType).getNoReturn())
859 terminateRegion(E);
860 }
861
Alex Lorenzee024992014-08-04 18:41:51 +0000862 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000863 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000864
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000865 Counter ParentCount = getRegion().getCounter();
866 Counter BodyCount = getRegionCounter(S);
867
868 // Handle the body first so that we can get the backedge count.
869 BreakContinueStack.push_back(BreakContinue());
870 extendRegion(S->getBody());
871 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000872 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000873
874 // Go back to handle the condition.
875 Counter CondCount =
876 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
877 propagateCounts(CondCount, S->getCond());
878 adjustForOutOfOrderTraversal(getEnd(S));
879
880 Counter OutCount =
881 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
882 if (OutCount != ParentCount)
883 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000884 }
885
886 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000887 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000888
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000889 Counter ParentCount = getRegion().getCounter();
890 Counter BodyCount = getRegionCounter(S);
891
892 BreakContinueStack.push_back(BreakContinue());
893 extendRegion(S->getBody());
894 Counter BackedgeCount =
895 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000896 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000897
898 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
899 propagateCounts(CondCount, S->getCond());
900
901 Counter OutCount =
902 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
903 if (OutCount != ParentCount)
904 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000905 }
906
907 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000908 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000909 if (S->getInit())
910 Visit(S->getInit());
911
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000912 Counter ParentCount = getRegion().getCounter();
913 Counter BodyCount = getRegionCounter(S);
914
915 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000916 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000917 extendRegion(S->getBody());
918 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
919 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000920
921 // The increment is essentially part of the body but it needs to include
922 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000923 if (const Stmt *Inc = S->getInc())
924 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
925
926 // Go back to handle the condition.
927 Counter CondCount =
928 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
929 if (const Expr *Cond = S->getCond()) {
930 propagateCounts(CondCount, Cond);
931 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000932 }
933
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000934 Counter OutCount =
935 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
936 if (OutCount != ParentCount)
937 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000938 }
939
940 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000941 extendRegion(S);
942 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000943 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000944
945 Counter ParentCount = getRegion().getCounter();
946 Counter BodyCount = getRegionCounter(S);
947
Alex Lorenzee024992014-08-04 18:41:51 +0000948 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000949 extendRegion(S->getBody());
950 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000951 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000952
Justin Bogner15874322015-04-30 21:31:02 +0000953 Counter LoopCount =
954 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
955 Counter OutCount =
956 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000957 if (OutCount != ParentCount)
958 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000959 }
960
961 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000962 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000963 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000964
965 Counter ParentCount = getRegion().getCounter();
966 Counter BodyCount = getRegionCounter(S);
967
Alex Lorenzee024992014-08-04 18:41:51 +0000968 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000969 extendRegion(S->getBody());
970 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000971 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000972
Justin Bogner15874322015-04-30 21:31:02 +0000973 Counter LoopCount =
974 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
975 Counter OutCount =
976 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000977 if (OutCount != ParentCount)
978 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000979 }
980
981 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000982 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +0000983 if (S->getInit())
984 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +0000985 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000986
Alex Lorenzee024992014-08-04 18:41:51 +0000987 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000988
989 const Stmt *Body = S->getBody();
990 extendRegion(Body);
991 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
992 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000993 // Make a region for the body of the switch. If the body starts with
994 // a case, that case will reuse this region; otherwise, this covers
995 // the unreachable code at the beginning of the switch body.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000996 size_t Index =
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000997 pushRegion(Counter::getZero(), getStart(CS->body_front()));
Richard Trieub5841332015-04-15 01:21:42 +0000998 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000999 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +00001000
1001 // Set the end for the body of the switch, if it isn't already set.
1002 for (size_t i = RegionStack.size(); i != Index; --i) {
1003 if (!RegionStack[i - 1].hasEndLoc())
1004 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1005 }
1006
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001007 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +00001008 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +00001009 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001010 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +00001011 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001012
Alex Lorenzee024992014-08-04 18:41:51 +00001013 if (!BreakContinueStack.empty())
1014 BreakContinueStack.back().ContinueCount = addCounters(
1015 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001016
1017 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001018 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +00001019 pushRegion(ExitCount);
1020
1021 // Ensure that handleFileExit recognizes when the end location is located
1022 // in a different file.
1023 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +00001024 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +00001025 }
1026
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001027 void VisitSwitchCase(const SwitchCase *S) {
1028 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001029
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001030 SourceMappingRegion &Parent = getRegion();
1031
1032 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1033 // Reuse the existing region if it starts at our label. This is typical of
1034 // the first case in a switch.
1035 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
1036 Parent.setCounter(Count);
1037 else
1038 pushRegion(Count, getStart(S));
1039
Sanjay Patel376c06c2015-12-24 21:11:29 +00001040 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001041 Visit(CS->getLHS());
1042 if (const Expr *RHS = CS->getRHS())
1043 Visit(RHS);
1044 }
Alex Lorenzee024992014-08-04 18:41:51 +00001045 Visit(S->getSubStmt());
1046 }
1047
1048 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001049 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +00001050 if (S->getInit())
1051 Visit(S->getInit());
1052
Justin Bogner055ebc32015-06-16 06:24:15 +00001053 // Extend into the condition before we propagate through it below - this is
1054 // needed to handle macros that generate the "if" but not the condition.
1055 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001056
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001057 Counter ParentCount = getRegion().getCounter();
1058 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001059
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001060 // Emitting a counter for the condition makes it easier to interpret the
1061 // counter for the body when looking at the coverage.
1062 propagateCounts(ParentCount, S->getCond());
1063
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001064 // The 'then' count applies to the area immediately after the condition.
1065 fillGapAreaWithCount(getPreciseTokenLocEnd(getEnd(S->getCond())),
1066 getStart(S->getThen()), ThenCount);
1067
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001068 extendRegion(S->getThen());
1069 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1070
1071 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1072 if (const Stmt *Else = S->getElse()) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001073 // The 'else' count applies to the area immediately after the 'then'.
1074 fillGapAreaWithCount(getPreciseTokenLocEnd(getEnd(S->getThen())),
1075 getStart(Else), ElseCount);
1076 extendRegion(Else);
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001077 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1078 } else
1079 OutCount = addCounters(OutCount, ElseCount);
1080
1081 if (OutCount != ParentCount)
1082 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001083 }
1084
1085 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001086 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001087 // Handle macros that generate the "try" but not the rest.
1088 extendRegion(S->getTryBlock());
1089
1090 Counter ParentCount = getRegion().getCounter();
1091 propagateCounts(ParentCount, S->getTryBlock());
1092
Alex Lorenzee024992014-08-04 18:41:51 +00001093 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1094 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001095
1096 Counter ExitCount = getRegionCounter(S);
1097 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001098 }
1099
1100 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001101 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001102 }
1103
1104 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001105 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001106
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001107 Counter ParentCount = getRegion().getCounter();
1108 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001109
Justin Bognere3654ce2015-04-24 23:37:57 +00001110 Visit(E->getCond());
1111
1112 if (!isa<BinaryConditionalOperator>(E)) {
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001113 // The 'then' count applies to the area immediately after the condition.
1114 fillGapAreaWithCount(E->getQuestionLoc(), getStart(E->getTrueExpr()),
1115 TrueCount);
1116
Justin Bognere3654ce2015-04-24 23:37:57 +00001117 extendRegion(E->getTrueExpr());
1118 propagateCounts(TrueCount, E->getTrueExpr());
1119 }
Vedant Kumar2e8c8752017-11-09 02:33:38 +00001120
Justin Bognere3654ce2015-04-24 23:37:57 +00001121 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001122 propagateCounts(subtractCounters(ParentCount, TrueCount),
1123 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001124 }
1125
1126 void VisitBinLAnd(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001127 extendRegion(E->getLHS());
1128 propagateCounts(getRegion().getCounter(), E->getLHS());
1129 handleFileExit(getEnd(E->getLHS()));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001130
1131 extendRegion(E->getRHS());
1132 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001133 }
1134
1135 void VisitBinLOr(const BinaryOperator *E) {
Vedant Kumare5f06a82017-10-17 06:51:54 +00001136 extendRegion(E->getLHS());
1137 propagateCounts(getRegion().getCounter(), E->getLHS());
1138 handleFileExit(getEnd(E->getLHS()));
Alex Lorenzee024992014-08-04 18:41:51 +00001139
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001140 extendRegion(E->getRHS());
1141 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001142 }
Justin Bognerc1091022015-02-24 04:13:56 +00001143
1144 void VisitLambdaExpr(const LambdaExpr *LE) {
1145 // Lambdas are treated as their own functions for now, so we shouldn't
1146 // propagate counts into them.
1147 }
Alex Lorenzee024992014-08-04 18:41:51 +00001148};
Alex Lorenzee024992014-08-04 18:41:51 +00001149
Xinliang David Li1f39fcf2017-04-14 04:14:29 +00001150std::string getCoverageSection(const CodeGenModule &CGM) {
Vedant Kumar8a767a42017-04-15 00:10:05 +00001151 return llvm::getInstrProfSectionName(
1152 llvm::IPSK_covmap,
1153 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
Alex Lorenzee024992014-08-04 18:41:51 +00001154}
1155
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001156std::string normalizeFilename(StringRef Filename) {
1157 llvm::SmallString<256> Path(Filename);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001158 llvm::sys::fs::make_absolute(Path);
Vedant Kumard04929d2016-07-18 22:32:02 +00001159 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001160 return Path.str().str();
1161}
1162
1163} // end anonymous namespace
1164
Justin Bognera432d172015-02-03 00:20:24 +00001165static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1166 ArrayRef<CounterExpression> Expressions,
1167 ArrayRef<CounterMappingRegion> Regions) {
1168 OS << FunctionName << ":\n";
1169 CounterMappingContext Ctx(Expressions);
1170 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001171 OS.indent(2);
1172 switch (R.Kind) {
1173 case CounterMappingRegion::CodeRegion:
1174 break;
1175 case CounterMappingRegion::ExpansionRegion:
1176 OS << "Expansion,";
1177 break;
1178 case CounterMappingRegion::SkippedRegion:
1179 OS << "Skipped,";
1180 break;
Vedant Kumara1c4deb2017-09-18 23:37:30 +00001181 case CounterMappingRegion::GapRegion:
1182 OS << "Gap,";
1183 break;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001184 }
1185
Justin Bogner4da909b2015-02-03 21:35:49 +00001186 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1187 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001188 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001189 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001190 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1191 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001192 }
1193}
1194
Alex Lorenzee024992014-08-04 18:41:51 +00001195void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001196 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001197 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001198 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +00001199 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +00001200#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +00001201 llvm::Type *FunctionRecordTypes[] = {
1202 #include "llvm/ProfileData/InstrProfData.inc"
1203 };
Alex Lorenzee024992014-08-04 18:41:51 +00001204 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +00001205 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1206 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +00001207 }
1208
Xinliang David Lia026a432015-11-05 05:46:39 +00001209 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +00001210 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +00001211 #include "llvm/ProfileData/InstrProfData.inc"
1212 };
Alex Lorenzee024992014-08-04 18:41:51 +00001213 FunctionRecords.push_back(llvm::ConstantStruct::get(
1214 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +00001215 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001216 FunctionNames.push_back(
1217 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +00001218 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001219
1220 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1221 // Dump the coverage mapping data for this function by decoding the
1222 // encoded data. This allows us to dump the mapping regions which were
1223 // also processed by the CoverageMappingWriter which performs
1224 // additional minimization operations such as reducing the number of
1225 // expressions.
1226 std::vector<StringRef> Filenames;
1227 std::vector<CounterExpression> Expressions;
1228 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001229 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001230 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001231 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001232 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001233 for (const auto &Entry : FileEntries) {
1234 auto I = Entry.second;
1235 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1236 FilenameRefs[I] = FilenameStrs[I];
1237 }
Justin Bognera432d172015-02-03 00:20:24 +00001238 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1239 Expressions, Regions);
1240 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001241 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001242 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001243 }
Alex Lorenzee024992014-08-04 18:41:51 +00001244}
1245
1246void CoverageMappingModuleGen::emit() {
1247 if (FunctionRecords.empty())
1248 return;
1249 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1250 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1251
1252 // Create the filenames and merge them with coverage mappings
1253 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001254 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001255 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001256 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001257 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001258 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001259 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001260 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001261 }
1262
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001263 std::string FilenamesAndCoverageMappings;
1264 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1265 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1266 std::string RawCoverageMappings =
1267 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1268 OS << RawCoverageMappings;
1269 size_t CoverageMappingSize = RawCoverageMappings.size();
1270 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1271 // Append extra zeroes if necessary to ensure that the size of the filenames
1272 // and coverage mappings is a multiple of 8.
1273 if (size_t Rem = OS.str().size() % 8) {
1274 CoverageMappingSize += 8 - Rem;
1275 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
1276 OS << '\0';
Alex Lorenzee024992014-08-04 18:41:51 +00001277 }
1278 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001279 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001280
1281 // Create the deferred function records array
1282 auto RecordsTy =
1283 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1284 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1285
Xinliang David Li20b188c2016-01-03 19:25:54 +00001286 llvm::Type *CovDataHeaderTypes[] = {
1287#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1288#include "llvm/ProfileData/InstrProfData.inc"
1289 };
1290 auto CovDataHeaderTy =
1291 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1292 llvm::Constant *CovDataHeaderVals[] = {
1293#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1294#include "llvm/ProfileData/InstrProfData.inc"
1295 };
1296 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1297 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1298
Alex Lorenzee024992014-08-04 18:41:51 +00001299 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001300 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1301 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001302 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001303 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1304 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001305 auto CovDataVal =
1306 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001307 auto CovData = new llvm::GlobalVariable(
1308 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1309 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001310
1311 CovData->setSection(getCoverageSection(CGM));
1312 CovData->setAlignment(8);
1313
1314 // Make sure the data doesn't get deleted.
1315 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001316 // Create the deferred function records array
1317 if (!FunctionNames.empty()) {
1318 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1319 FunctionNames.size());
1320 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1321 // This variable will *NOT* be emitted to the object file. It is used
1322 // to pass the list of names referenced to codegen.
1323 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1324 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001325 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001326 }
Alex Lorenzee024992014-08-04 18:41:51 +00001327}
1328
1329unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1330 auto It = FileEntries.find(File);
1331 if (It != FileEntries.end())
1332 return It->second;
1333 unsigned FileID = FileEntries.size();
1334 FileEntries.insert(std::make_pair(File, FileID));
1335 return FileID;
1336}
1337
1338void CoverageMappingGen::emitCounterMapping(const Decl *D,
1339 llvm::raw_ostream &OS) {
1340 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001341 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001342 Walker.VisitDecl(D);
1343 Walker.write(OS);
1344}
1345
1346void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1347 llvm::raw_ostream &OS) {
1348 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1349 Walker.VisitDecl(D);
1350 Walker.write(OS);
1351}