blob: b56cd077c8b4acc477dd85844bb69170117c6db3 [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"
26
27using namespace clang;
28using namespace CodeGen;
29using namespace llvm::coverage;
30
31void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
32 SkippedRanges.push_back(Range);
33}
34
35namespace {
36
37/// \brief A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000038class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000039 Counter Count;
40
Alex Lorenzee024992014-08-04 18:41:51 +000041 /// \brief The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000042 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000043
44 /// \brief The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000045 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000046
Justin Bogner09c71792014-10-01 03:33:49 +000047public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000048 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
49 Optional<SourceLocation> LocEnd)
50 : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
Alex Lorenzee024992014-08-04 18:41:51 +000051
Justin Bogner09c71792014-10-01 03:33:49 +000052 const Counter &getCounter() const { return Count; }
53
Justin Bognerbf42cfd2015-02-18 21:24:51 +000054 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000055
Justin Bognerbf42cfd2015-02-18 21:24:51 +000056 bool hasStartLoc() const { return LocStart.hasValue(); }
57
58 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
59
Craig Topper462c77b2015-09-26 05:10:14 +000060 SourceLocation getStartLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000061 assert(LocStart && "Region has no start location");
62 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000063 }
64
Justin Bognerbf42cfd2015-02-18 21:24:51 +000065 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000066
Justin Bognerbf42cfd2015-02-18 21:24:51 +000067 void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
Alex Lorenzee024992014-08-04 18:41:51 +000068
Craig Topper462c77b2015-09-26 05:10:14 +000069 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000070 assert(LocEnd && "Region has no end location");
71 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000072 }
73};
74
Alex Lorenzee024992014-08-04 18:41:51 +000075/// \brief Provides the common functionality for the different
76/// coverage mapping region builders.
77class CoverageMappingBuilder {
78public:
79 CoverageMappingModuleGen &CVM;
80 SourceManager &SM;
81 const LangOptions &LangOpts;
82
83private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000084 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
85 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
86 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +000087
88public:
Alex Lorenzee024992014-08-04 18:41:51 +000089 /// \brief The coverage mapping regions for this function
90 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
91 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +000092 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +000093
94 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
95 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +000096 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +000097
98 /// \brief Return the precise end location for the given token.
99 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000100 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
101 // macro locations, which we just treat as expanded files.
102 unsigned TokLen =
103 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
104 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000105 }
106
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000107 /// \brief Return the start location of an included file or expanded macro.
108 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
109 if (Loc.isMacroID())
110 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
111 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000112 }
113
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000114 /// \brief Return the end location of an included file or expanded macro.
115 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
116 if (Loc.isMacroID())
117 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000118 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000119 return SM.getLocForEndOfFile(SM.getFileID(Loc));
120 }
121
122 /// \brief Find out where the current file is included or macro is expanded.
123 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
124 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
125 : SM.getIncludeLoc(SM.getFileID(Loc));
126 }
127
Justin Bogner682bfbf2015-05-14 22:14:10 +0000128 /// \brief Return true if \c Loc is a location in a built-in macro.
129 bool isInBuiltin(SourceLocation Loc) {
130 return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0;
131 }
132
Igor Kudrind9e1a612016-06-07 10:07:51 +0000133 /// \brief Check whether \c Loc is included or expanded from \c Parent.
134 bool isNestedIn(SourceLocation Loc, FileID Parent) {
135 do {
136 Loc = getIncludeOrExpansionLoc(Loc);
137 if (Loc.isInvalid())
138 return false;
139 } while (!SM.isInFileID(Loc, Parent));
140 return true;
141 }
142
Justin Bogner682bfbf2015-05-14 22:14:10 +0000143 /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000144 SourceLocation getStart(const Stmt *S) {
145 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000146 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000147 Loc = SM.getImmediateExpansionRange(Loc).first;
148 return Loc;
149 }
150
Justin Bogner682bfbf2015-05-14 22:14:10 +0000151 /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000152 SourceLocation getEnd(const Stmt *S) {
153 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000154 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000155 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000156 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000157 }
158
159 /// \brief Find the set of files we have regions for and assign IDs
160 ///
161 /// Fills \c Mapping with the virtual file mapping needed to write out
162 /// coverage and collects the necessary file information to emit source and
163 /// expansion regions.
164 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
165 FileIDMapping.clear();
166
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000167 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000168 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
169 for (const auto &Region : SourceRegions) {
170 SourceLocation Loc = Region.getStartLoc();
171 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000172 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000173 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000174
175 unsigned Depth = 0;
176 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000177 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000178 ++Depth;
179 FileLocs.push_back(std::make_pair(Loc, Depth));
180 }
181 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
182
183 for (const auto &FL : FileLocs) {
184 SourceLocation Loc = FL.first;
185 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
186 auto Entry = SM.getFileEntryForID(SpellingFile);
187 if (!Entry)
188 continue;
189
190 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
191 Mapping.push_back(CVM.getFileID(Entry));
192 }
193 }
194
195 /// \brief Get the coverage mapping file ID for \c Loc.
196 ///
197 /// If such file id doesn't exist, return None.
198 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
199 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000200 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000201 return Mapping->second.first;
202 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000203 }
204
205 /// \brief Return true if the given clang's file id has a corresponding
206 /// coverage file id.
207 bool hasExistingCoverageFileID(FileID File) const {
208 return FileIDMapping.count(File);
209 }
210
211 /// \brief Gather all the regions that were skipped by the preprocessor
212 /// using the constructs like #if.
213 void gatherSkippedRegions() {
214 /// An array of the minimum lineStarts and the maximum lineEnds
215 /// for mapping regions from the appropriate source files.
216 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
217 FileLineRanges.resize(
218 FileIDMapping.size(),
219 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
220 for (const auto &R : MappingRegions) {
221 FileLineRanges[R.FileID].first =
222 std::min(FileLineRanges[R.FileID].first, R.LineStart);
223 FileLineRanges[R.FileID].second =
224 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
225 }
226
227 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
228 for (const auto &I : SkippedRanges) {
229 auto LocStart = I.getBegin();
230 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000231 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
232 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000233
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000234 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000235 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000236 continue;
237 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
238 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
239 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
240 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
Justin Bognerfd34280b2015-02-03 23:59:48 +0000241 auto Region = CounterMappingRegion::makeSkipped(
242 *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000243 // Make sure that we only collect the regions that are inside
244 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000245 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
246 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000247 MappingRegions.push_back(Region);
248 }
249 }
250
Alex Lorenzee024992014-08-04 18:41:51 +0000251 /// \brief Generate the coverage counter mapping regions from collected
252 /// source regions.
253 void emitSourceRegions() {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000254 for (const auto &Region : SourceRegions) {
255 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000256
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000257 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000258 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000259
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000260 auto CovFileID = getCoverageFileID(LocStart);
261 // Ignore regions that don't have a file, such as builtin macros.
262 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000263 continue;
264
Justin Bognerf14b2072015-03-25 04:13:49 +0000265 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000266 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
267 "region spans multiple files");
268
Justin Bognerf59329b2014-10-01 03:33:52 +0000269 // Find the spilling locations for the mapping region.
Alex Lorenzee024992014-08-04 18:41:51 +0000270 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
271 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
272 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
273 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
274
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000275 assert(LineStart <= LineEnd && "region start and end out of order");
276 MappingRegions.push_back(CounterMappingRegion::makeRegion(
277 Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
278 ColumnEnd));
279 }
280 }
281
282 /// \brief Generate expansion regions for each virtual file we've seen.
283 void emitExpansionRegions() {
284 for (const auto &FM : FileIDMapping) {
285 SourceLocation ExpandedLoc = FM.second.second;
286 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
287 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000288 continue;
289
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000290 auto ParentFileID = getCoverageFileID(ParentLoc);
291 if (!ParentFileID)
292 continue;
293 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
294 assert(ExpandedFileID && "expansion in uncovered file");
295
296 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
297 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
298 "region spans multiple files");
299
300 unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
301 unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
302 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
303 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
304
305 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
306 *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
Justin Bognerfd34280b2015-02-03 23:59:48 +0000307 ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000308 }
309 }
310};
311
312/// \brief Creates unreachable coverage regions for the functions that
313/// are not emitted.
314struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
315 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
316 const LangOptions &LangOpts)
317 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
318
319 void VisitDecl(const Decl *D) {
320 if (!D->hasBody())
321 return;
322 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000323 SourceLocation Start = getStart(Body);
324 SourceLocation End = getEnd(Body);
325 if (!SM.isWrittenInSameFile(Start, End)) {
326 // Walk up to find the common ancestor.
327 // Correct the locations accordingly.
328 FileID StartFileID = SM.getFileID(Start);
329 FileID EndFileID = SM.getFileID(End);
330 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
331 Start = getIncludeOrExpansionLoc(Start);
332 assert(Start.isValid() &&
333 "Declaration start location not nested within a known region");
334 StartFileID = SM.getFileID(Start);
335 }
336 while (StartFileID != EndFileID) {
337 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
338 assert(End.isValid() &&
339 "Declaration end location not nested within a known region");
340 EndFileID = SM.getFileID(End);
341 }
342 }
343 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000344 }
345
346 /// \brief Write the mapping data to the output stream
347 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000348 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000349 gatherFileIDs(FileIDMapping);
350 emitSourceRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000351
Craig Topper5fc8fc22014-08-27 06:28:36 +0000352 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000353 Writer.write(OS);
354 }
355};
356
357/// \brief A StmtVisitor that creates coverage mapping regions which map
358/// from the source code locations to the PGO counters.
359struct CounterCoverageMappingBuilder
360 : public CoverageMappingBuilder,
361 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
362 /// \brief The map of statements to count values.
363 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
364
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000365 /// \brief A stack of currently live regions.
366 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000367
368 CounterExpressionBuilder Builder;
369
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000370 /// \brief A location in the most recently visited file or macro.
371 ///
372 /// This is used to adjust the active source regions appropriately when
373 /// expressions cross file or macro boundaries.
374 SourceLocation MostRecentLocation;
375
376 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000377 Counter subtractCounters(Counter LHS, Counter RHS) {
378 return Builder.subtract(LHS, RHS);
379 }
380
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000381 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000382 Counter addCounters(Counter LHS, Counter RHS) {
383 return Builder.add(LHS, RHS);
384 }
385
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000386 Counter addCounters(Counter C1, Counter C2, Counter C3) {
387 return addCounters(addCounters(C1, C2), C3);
388 }
389
390 Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) {
391 return addCounters(addCounters(C1, C2, C3), C4);
392 }
393
Alex Lorenzee024992014-08-04 18:41:51 +0000394 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000395 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000396 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000397 Counter getRegionCounter(const Stmt *S) {
398 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000399 }
400
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000401 /// \brief Push a region onto the stack.
402 ///
403 /// Returns the index on the stack where the region was pushed. This can be
404 /// used with popRegions to exit a "scope", ending the region that was pushed.
405 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
406 Optional<SourceLocation> EndLoc = None) {
407 if (StartLoc)
408 MostRecentLocation = *StartLoc;
409 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000410
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000411 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000412 }
413
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000414 /// \brief Pop regions from the stack into the function's list of regions.
415 ///
416 /// Adds all regions from \c ParentIndex to the top of the stack to the
417 /// function's \c SourceRegions.
418 void popRegions(size_t ParentIndex) {
419 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
420 while (RegionStack.size() > ParentIndex) {
421 SourceMappingRegion &Region = RegionStack.back();
422 if (Region.hasStartLoc()) {
423 SourceLocation StartLoc = Region.getStartLoc();
424 SourceLocation EndLoc = Region.hasEndLoc()
425 ? Region.getEndLoc()
426 : RegionStack[ParentIndex].getEndLoc();
427 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
428 // The region ends in a nested file or macro expansion. Create a
429 // separate region for each expansion.
430 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
431 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
432
433 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
434
Justin Bognerf14b2072015-03-25 04:13:49 +0000435 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000436 if (EndLoc.isInvalid())
437 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000438 }
439 Region.setEndLoc(EndLoc);
440
441 MostRecentLocation = EndLoc;
442 // If this region happens to span an entire expansion, we need to make
443 // sure we don't overlap the parent region with it.
444 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
445 EndLoc == getEndOfFileOrMacro(EndLoc))
446 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
447
448 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Craig Topperf36a5c42015-09-26 05:10:16 +0000449 SourceRegions.push_back(Region);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000450 }
451 RegionStack.pop_back();
452 }
Alex Lorenzee024992014-08-04 18:41:51 +0000453 }
454
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000455 /// \brief Return the currently active region.
456 SourceMappingRegion &getRegion() {
457 assert(!RegionStack.empty() && "statement has no region");
458 return RegionStack.back();
459 }
Alex Lorenzee024992014-08-04 18:41:51 +0000460
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000461 /// \brief Propagate counts through the children of \c S.
462 Counter propagateCounts(Counter TopCount, const Stmt *S) {
463 size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
464 Visit(S);
465 Counter ExitCount = getRegion().getCounter();
466 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000467
468 // The statement may be spanned by an expansion. Make sure we handle a file
469 // exit out of this expansion before moving to the next statement.
470 if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart()))
471 MostRecentLocation = getEnd(S);
472
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000473 return ExitCount;
474 }
Alex Lorenzee024992014-08-04 18:41:51 +0000475
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000476 /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
477 /// is already added to \c SourceRegions.
478 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
479 return SourceRegions.rend() !=
480 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
481 [&](const SourceMappingRegion &Region) {
482 return Region.getStartLoc() == StartLoc &&
483 Region.getEndLoc() == EndLoc;
484 });
485 }
486
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000487 /// \brief Adjust the most recently visited location to \c EndLoc.
488 ///
489 /// This should be used after visiting any statements in non-source order.
490 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
491 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000492 // The code region for a whole macro is created in handleFileExit() when
493 // it detects exiting of the virtual file of that macro. If we visited
494 // statements in non-source order, we might already have such a region
495 // added, for example, if a body of a loop is divided among multiple
496 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000497 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000498 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
499 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
500 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000501 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
502 }
Alex Lorenzee024992014-08-04 18:41:51 +0000503
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000504 /// \brief Adjust regions and state when \c NewLoc exits a file.
505 ///
506 /// If moving from our most recently tracked location to \c NewLoc exits any
507 /// files, this adjusts our current region stack and creates the file regions
508 /// for the exited file.
509 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000510 if (NewLoc.isInvalid() ||
511 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000512 return;
513
514 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
515 // find the common ancestor.
516 SourceLocation LCA = NewLoc;
517 FileID ParentFile = SM.getFileID(LCA);
518 while (!isNestedIn(MostRecentLocation, ParentFile)) {
519 LCA = getIncludeOrExpansionLoc(LCA);
520 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
521 // Since there isn't a common ancestor, no file was exited. We just need
522 // to adjust our location to the new file.
523 MostRecentLocation = NewLoc;
524 return;
525 }
526 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000527 }
528
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000529 llvm::SmallSet<SourceLocation, 8> StartLocs;
530 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000531 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
532 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000533 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000534 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000535 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000536 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000537 break;
538 }
Alex Lorenzee024992014-08-04 18:41:51 +0000539
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000540 while (!SM.isInFileID(Loc, ParentFile)) {
541 // The most nested region for each start location is the one with the
542 // correct count. We avoid creating redundant regions by stopping once
543 // we've seen this region.
544 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000545 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000546 getEndOfFileOrMacro(Loc));
547 Loc = getIncludeOrExpansionLoc(Loc);
548 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000549 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000550 }
551
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000552 if (ParentCounter) {
553 // If the file is contained completely by another region and doesn't
554 // immediately start its own region, the whole file gets a region
555 // corresponding to the parent.
556 SourceLocation Loc = MostRecentLocation;
557 while (isNestedIn(Loc, ParentFile)) {
558 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
559 if (StartLocs.insert(FileStart).second)
560 SourceRegions.emplace_back(*ParentCounter, FileStart,
561 getEndOfFileOrMacro(Loc));
562 Loc = getIncludeOrExpansionLoc(Loc);
563 }
Alex Lorenzee024992014-08-04 18:41:51 +0000564 }
565
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000566 MostRecentLocation = NewLoc;
567 }
Alex Lorenzee024992014-08-04 18:41:51 +0000568
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000569 /// \brief Ensure that \c S is included in the current region.
570 void extendRegion(const Stmt *S) {
571 SourceMappingRegion &Region = getRegion();
572 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000573
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000574 handleFileExit(StartLoc);
575 if (!Region.hasStartLoc())
576 Region.setStartLoc(StartLoc);
577 }
578
579 /// \brief Mark \c S as a terminator, starting a zero region.
580 void terminateRegion(const Stmt *S) {
581 extendRegion(S);
582 SourceMappingRegion &Region = getRegion();
583 if (!Region.hasEndLoc())
584 Region.setEndLoc(getEnd(S));
585 pushRegion(Counter::getZero());
586 }
Alex Lorenzee024992014-08-04 18:41:51 +0000587
588 /// \brief Keep counts of breaks and continues inside loops.
589 struct BreakContinue {
590 Counter BreakCount;
591 Counter ContinueCount;
592 };
593 SmallVector<BreakContinue, 8> BreakContinueStack;
594
595 CounterCoverageMappingBuilder(
596 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000597 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000598 const LangOptions &LangOpts)
Justin Bognere5ee6c52014-10-02 16:44:01 +0000599 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000600
601 /// \brief Write the mapping data to the output stream
602 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000603 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000604 gatherFileIDs(VirtualFileMapping);
605 emitSourceRegions();
606 emitExpansionRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000607 gatherSkippedRegions();
608
Justin Bogner4da909b2015-02-03 21:35:49 +0000609 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
610 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000611 Writer.write(OS);
612 }
613
Alex Lorenzee024992014-08-04 18:41:51 +0000614 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000615 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000616 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000617 for (const Stmt *Child : S->children())
618 if (Child)
619 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000620 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000621 }
622
Alex Lorenzee024992014-08-04 18:41:51 +0000623 void VisitDecl(const Decl *D) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000624 Stmt *Body = D->getBody();
625 propagateCounts(getRegionCounter(Body), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000626 }
627
628 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000629 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000630 if (S->getRetValue())
631 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000632 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000633 }
634
Justin Bognerf959feb2015-04-28 06:31:55 +0000635 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
636 extendRegion(E);
637 if (E->getSubExpr())
638 Visit(E->getSubExpr());
639 terminateRegion(E);
640 }
641
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000642 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000643
644 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000645 SourceLocation Start = getStart(S);
646 // We can't extendRegion here or we risk overlapping with our new region.
647 handleFileExit(Start);
648 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000649 Visit(S->getSubStmt());
650 }
651
652 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000653 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
654 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000655 BreakContinueStack.back().BreakCount, getRegion().getCounter());
656 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000657 }
658
659 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000660 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
661 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000662 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
663 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000664 }
665
666 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000667 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000668
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000669 Counter ParentCount = getRegion().getCounter();
670 Counter BodyCount = getRegionCounter(S);
671
672 // Handle the body first so that we can get the backedge count.
673 BreakContinueStack.push_back(BreakContinue());
674 extendRegion(S->getBody());
675 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000676 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000677
678 // Go back to handle the condition.
679 Counter CondCount =
680 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
681 propagateCounts(CondCount, S->getCond());
682 adjustForOutOfOrderTraversal(getEnd(S));
683
684 Counter OutCount =
685 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
686 if (OutCount != ParentCount)
687 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000688 }
689
690 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000691 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000692
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000693 Counter ParentCount = getRegion().getCounter();
694 Counter BodyCount = getRegionCounter(S);
695
696 BreakContinueStack.push_back(BreakContinue());
697 extendRegion(S->getBody());
698 Counter BackedgeCount =
699 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000700 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000701
702 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
703 propagateCounts(CondCount, S->getCond());
704
705 Counter OutCount =
706 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
707 if (OutCount != ParentCount)
708 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000709 }
710
711 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000712 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000713 if (S->getInit())
714 Visit(S->getInit());
715
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000716 Counter ParentCount = getRegion().getCounter();
717 Counter BodyCount = getRegionCounter(S);
718
719 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000720 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000721 extendRegion(S->getBody());
722 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
723 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000724
725 // The increment is essentially part of the body but it needs to include
726 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000727 if (const Stmt *Inc = S->getInc())
728 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
729
730 // Go back to handle the condition.
731 Counter CondCount =
732 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
733 if (const Expr *Cond = S->getCond()) {
734 propagateCounts(CondCount, Cond);
735 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000736 }
737
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000738 Counter OutCount =
739 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
740 if (OutCount != ParentCount)
741 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000742 }
743
744 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000745 extendRegion(S);
746 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000747 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000748
749 Counter ParentCount = getRegion().getCounter();
750 Counter BodyCount = getRegionCounter(S);
751
Alex Lorenzee024992014-08-04 18:41:51 +0000752 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000753 extendRegion(S->getBody());
754 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000755 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000756
Justin Bogner15874322015-04-30 21:31:02 +0000757 Counter LoopCount =
758 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
759 Counter OutCount =
760 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000761 if (OutCount != ParentCount)
762 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000763 }
764
765 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000766 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000767 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000768
769 Counter ParentCount = getRegion().getCounter();
770 Counter BodyCount = getRegionCounter(S);
771
Alex Lorenzee024992014-08-04 18:41:51 +0000772 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000773 extendRegion(S->getBody());
774 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000775 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000776
Justin Bogner15874322015-04-30 21:31:02 +0000777 Counter LoopCount =
778 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
779 Counter OutCount =
780 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000781 if (OutCount != ParentCount)
782 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000783 }
784
785 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000786 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000787 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000788
Alex Lorenzee024992014-08-04 18:41:51 +0000789 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000790
791 const Stmt *Body = S->getBody();
792 extendRegion(Body);
793 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
794 if (!CS->body_empty()) {
795 // The body of the switch needs a zero region so that fallthrough counts
796 // behave correctly, but it would be misleading to include the braces of
797 // the compound statement in the zeroed area, so we need to handle this
798 // specially.
799 size_t Index =
800 pushRegion(Counter::getZero(), getStart(CS->body_front()),
801 getEnd(CS->body_back()));
Richard Trieub5841332015-04-15 01:21:42 +0000802 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000803 Visit(Child);
804 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +0000805 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +0000806 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000807 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000808 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000809
Alex Lorenzee024992014-08-04 18:41:51 +0000810 if (!BreakContinueStack.empty())
811 BreakContinueStack.back().ContinueCount = addCounters(
812 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000813
814 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +0000815 SourceLocation ExitLoc = getEnd(S);
816 pushRegion(ExitCount, getStart(S), ExitLoc);
817 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000818 }
819
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000820 void VisitSwitchCase(const SwitchCase *S) {
821 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000822
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000823 SourceMappingRegion &Parent = getRegion();
824
825 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
826 // Reuse the existing region if it starts at our label. This is typical of
827 // the first case in a switch.
828 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
829 Parent.setCounter(Count);
830 else
831 pushRegion(Count, getStart(S));
832
Sanjay Patel376c06c2015-12-24 21:11:29 +0000833 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000834 Visit(CS->getLHS());
835 if (const Expr *RHS = CS->getRHS())
836 Visit(RHS);
837 }
Alex Lorenzee024992014-08-04 18:41:51 +0000838 Visit(S->getSubStmt());
839 }
840
841 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000842 extendRegion(S);
Justin Bogner055ebc32015-06-16 06:24:15 +0000843 // Extend into the condition before we propagate through it below - this is
844 // needed to handle macros that generate the "if" but not the condition.
845 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +0000846
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000847 Counter ParentCount = getRegion().getCounter();
848 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000849
Justin Bogner91f2e3c2015-02-19 03:10:30 +0000850 // Emitting a counter for the condition makes it easier to interpret the
851 // counter for the body when looking at the coverage.
852 propagateCounts(ParentCount, S->getCond());
853
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000854 extendRegion(S->getThen());
855 Counter OutCount = propagateCounts(ThenCount, S->getThen());
856
857 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
858 if (const Stmt *Else = S->getElse()) {
859 extendRegion(S->getElse());
860 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
861 } else
862 OutCount = addCounters(OutCount, ElseCount);
863
864 if (OutCount != ParentCount)
865 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000866 }
867
868 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000869 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +0000870 // Handle macros that generate the "try" but not the rest.
871 extendRegion(S->getTryBlock());
872
873 Counter ParentCount = getRegion().getCounter();
874 propagateCounts(ParentCount, S->getTryBlock());
875
Alex Lorenzee024992014-08-04 18:41:51 +0000876 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
877 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000878
879 Counter ExitCount = getRegionCounter(S);
880 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000881 }
882
883 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000884 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +0000885 }
886
887 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000888 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000889
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000890 Counter ParentCount = getRegion().getCounter();
891 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000892
Justin Bognere3654ce2015-04-24 23:37:57 +0000893 Visit(E->getCond());
894
895 if (!isa<BinaryConditionalOperator>(E)) {
896 extendRegion(E->getTrueExpr());
897 propagateCounts(TrueCount, E->getTrueExpr());
898 }
899 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000900 propagateCounts(subtractCounters(ParentCount, TrueCount),
901 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +0000902 }
903
904 void VisitBinLAnd(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000905 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000906 Visit(E->getLHS());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000907
908 extendRegion(E->getRHS());
909 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000910 }
911
912 void VisitBinLOr(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000913 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000914 Visit(E->getLHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000915
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000916 extendRegion(E->getRHS());
917 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +0000918 }
Justin Bognerc1091022015-02-24 04:13:56 +0000919
920 void VisitLambdaExpr(const LambdaExpr *LE) {
921 // Lambdas are treated as their own functions for now, so we shouldn't
922 // propagate counts into them.
923 }
Alex Lorenzee024992014-08-04 18:41:51 +0000924};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000925}
Alex Lorenzee024992014-08-04 18:41:51 +0000926
927static bool isMachO(const CodeGenModule &CGM) {
928 return CGM.getTarget().getTriple().isOSBinFormatMachO();
929}
930
931static StringRef getCoverageSection(const CodeGenModule &CGM) {
Xinliang David Li03711cb2015-10-22 22:25:11 +0000932 return llvm::getInstrProfCoverageSectionName(isMachO(CGM));
Alex Lorenzee024992014-08-04 18:41:51 +0000933}
934
Justin Bognera432d172015-02-03 00:20:24 +0000935static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
936 ArrayRef<CounterExpression> Expressions,
937 ArrayRef<CounterMappingRegion> Regions) {
938 OS << FunctionName << ":\n";
939 CounterMappingContext Ctx(Expressions);
940 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000941 OS.indent(2);
942 switch (R.Kind) {
943 case CounterMappingRegion::CodeRegion:
944 break;
945 case CounterMappingRegion::ExpansionRegion:
946 OS << "Expansion,";
947 break;
948 case CounterMappingRegion::SkippedRegion:
949 OS << "Skipped,";
950 break;
951 }
952
Justin Bogner4da909b2015-02-03 21:35:49 +0000953 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
954 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +0000955 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000956 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +0000957 OS << " (Expanded file = " << R.ExpandedFileID << ")";
958 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000959 }
960}
961
Alex Lorenzee024992014-08-04 18:41:51 +0000962void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000963 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +0000964 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +0000965 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +0000966 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +0000967#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +0000968 llvm::Type *FunctionRecordTypes[] = {
969 #include "llvm/ProfileData/InstrProfData.inc"
970 };
Alex Lorenzee024992014-08-04 18:41:51 +0000971 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +0000972 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
973 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +0000974 }
975
Xinliang David Lia026a432015-11-05 05:46:39 +0000976 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +0000977 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +0000978 #include "llvm/ProfileData/InstrProfData.inc"
979 };
Alex Lorenzee024992014-08-04 18:41:51 +0000980 FunctionRecords.push_back(llvm::ConstantStruct::get(
981 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +0000982 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +0000983 FunctionNames.push_back(
984 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +0000985 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000986
987 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
988 // Dump the coverage mapping data for this function by decoding the
989 // encoded data. This allows us to dump the mapping regions which were
990 // also processed by the CoverageMappingWriter which performs
991 // additional minimization operations such as reducing the number of
992 // expressions.
993 std::vector<StringRef> Filenames;
994 std::vector<CounterExpression> Expressions;
995 std::vector<CounterMappingRegion> Regions;
996 llvm::SmallVector<StringRef, 16> FilenameRefs;
997 FilenameRefs.resize(FileEntries.size());
998 for (const auto &Entry : FileEntries)
999 FilenameRefs[Entry.second] = Entry.first->getName();
Justin Bognera432d172015-02-03 00:20:24 +00001000 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1001 Expressions, Regions);
1002 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001003 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001004 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001005 }
Alex Lorenzee024992014-08-04 18:41:51 +00001006}
1007
1008void CoverageMappingModuleGen::emit() {
1009 if (FunctionRecords.empty())
1010 return;
1011 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1012 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1013
1014 // Create the filenames and merge them with coverage mappings
1015 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzee024992014-08-04 18:41:51 +00001016 FilenameStrs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001017 for (const auto &Entry : FileEntries) {
1018 llvm::SmallString<256> Path(Entry.first->getName());
1019 llvm::sys::fs::make_absolute(Path);
1020
1021 auto I = Entry.second;
Richard Trieud1ffdda2015-04-30 23:13:52 +00001022 FilenameStrs[I] = std::string(Path.begin(), Path.end());
Alex Lorenzee024992014-08-04 18:41:51 +00001023 }
1024
Vedant Kumaraecc0262016-06-17 21:53:55 +00001025 size_t FilenamesSize;
1026 size_t CoverageMappingSize;
1027 llvm::Expected<std::string> CoverageDataOrErr = encodeFilenamesAndRawMappings(
1028 FilenameStrs, CoverageMappings, FilenamesSize, CoverageMappingSize);
1029 if (llvm::Error E = CoverageDataOrErr.takeError()) {
1030 llvm::handleAllErrors(std::move(E), [](llvm::ErrorInfoBase &EI) {
1031 llvm::report_fatal_error(EI.message());
1032 });
Alex Lorenzee024992014-08-04 18:41:51 +00001033 }
Vedant Kumaraecc0262016-06-17 21:53:55 +00001034 std::string CoverageData = std::move(CoverageDataOrErr.get());
Alex Lorenzee024992014-08-04 18:41:51 +00001035 auto *FilenamesAndMappingsVal =
Vedant Kumaraecc0262016-06-17 21:53:55 +00001036 llvm::ConstantDataArray::getString(Ctx, CoverageData, false);
Alex Lorenzee024992014-08-04 18:41:51 +00001037
1038 // Create the deferred function records array
1039 auto RecordsTy =
1040 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1041 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1042
Xinliang David Li20b188c2016-01-03 19:25:54 +00001043 llvm::Type *CovDataHeaderTypes[] = {
1044#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1045#include "llvm/ProfileData/InstrProfData.inc"
1046 };
1047 auto CovDataHeaderTy =
1048 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1049 llvm::Constant *CovDataHeaderVals[] = {
1050#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1051#include "llvm/ProfileData/InstrProfData.inc"
1052 };
1053 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1054 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1055
Alex Lorenzee024992014-08-04 18:41:51 +00001056 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001057 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1058 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001059 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001060 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1061 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001062 auto CovDataVal =
1063 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001064 auto CovData = new llvm::GlobalVariable(
1065 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1066 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001067
1068 CovData->setSection(getCoverageSection(CGM));
1069 CovData->setAlignment(8);
1070
1071 // Make sure the data doesn't get deleted.
1072 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001073 // Create the deferred function records array
1074 if (!FunctionNames.empty()) {
1075 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1076 FunctionNames.size());
1077 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1078 // This variable will *NOT* be emitted to the object file. It is used
1079 // to pass the list of names referenced to codegen.
1080 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1081 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001082 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001083 }
Alex Lorenzee024992014-08-04 18:41:51 +00001084}
1085
1086unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1087 auto It = FileEntries.find(File);
1088 if (It != FileEntries.end())
1089 return It->second;
1090 unsigned FileID = FileEntries.size();
1091 FileEntries.insert(std::make_pair(File, FileID));
1092 return FileID;
1093}
1094
1095void CoverageMappingGen::emitCounterMapping(const Decl *D,
1096 llvm::raw_ostream &OS) {
1097 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001098 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001099 Walker.VisitDecl(D);
1100 Walker.write(OS);
1101}
1102
1103void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1104 llvm::raw_ostream &OS) {
1105 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1106 Walker.VisitDecl(D);
1107 Walker.write(OS);
1108}