blob: 03e22cd398aa056944ae3732614bdcbb5dbacf81 [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"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000018#include "llvm/ADT/Optional.h"
Alex Lorenzee024992014-08-04 18:41:51 +000019#include "llvm/ProfileData/CoverageMapping.h"
Alex Lorenzf2cf38e2014-08-08 23:41:24 +000020#include "llvm/ProfileData/CoverageMappingReader.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000021#include "llvm/ProfileData/CoverageMappingWriter.h"
22#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000023#include "llvm/Support/FileSystem.h"
24
25using namespace clang;
26using namespace CodeGen;
27using namespace llvm::coverage;
28
29void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
30 SkippedRanges.push_back(Range);
31}
32
33namespace {
34
35/// \brief A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000036class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000037 Counter Count;
38
Alex Lorenzee024992014-08-04 18:41:51 +000039 /// \brief The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000040 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000041
42 /// \brief The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000043 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000044
Justin Bogner09c71792014-10-01 03:33:49 +000045public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000046 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
47 Optional<SourceLocation> LocEnd)
48 : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
Alex Lorenzee024992014-08-04 18:41:51 +000049
Justin Bogner09c71792014-10-01 03:33:49 +000050 const Counter &getCounter() const { return Count; }
51
Justin Bognerbf42cfd2015-02-18 21:24:51 +000052 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000053
Justin Bognerbf42cfd2015-02-18 21:24:51 +000054 bool hasStartLoc() const { return LocStart.hasValue(); }
55
56 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
57
Craig Topper462c77b2015-09-26 05:10:14 +000058 SourceLocation getStartLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000059 assert(LocStart && "Region has no start location");
60 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000061 }
62
Justin Bognerbf42cfd2015-02-18 21:24:51 +000063 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000064
Justin Bognerbf42cfd2015-02-18 21:24:51 +000065 void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
Alex Lorenzee024992014-08-04 18:41:51 +000066
Craig Topper462c77b2015-09-26 05:10:14 +000067 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000068 assert(LocEnd && "Region has no end location");
69 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000070 }
71};
72
Alex Lorenzee024992014-08-04 18:41:51 +000073/// \brief Provides the common functionality for the different
74/// coverage mapping region builders.
75class CoverageMappingBuilder {
76public:
77 CoverageMappingModuleGen &CVM;
78 SourceManager &SM;
79 const LangOptions &LangOpts;
80
81private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000082 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
83 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
84 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +000085
86public:
Alex Lorenzee024992014-08-04 18:41:51 +000087 /// \brief The coverage mapping regions for this function
88 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
89 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +000090 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +000091
92 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
93 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +000094 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +000095
96 /// \brief Return the precise end location for the given token.
97 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000098 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
99 // macro locations, which we just treat as expanded files.
100 unsigned TokLen =
101 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
102 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000103 }
104
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000105 /// \brief Return the start location of an included file or expanded macro.
106 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
107 if (Loc.isMacroID())
108 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
109 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000110 }
111
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000112 /// \brief Return the end location of an included file or expanded macro.
113 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
114 if (Loc.isMacroID())
115 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000116 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000117 return SM.getLocForEndOfFile(SM.getFileID(Loc));
118 }
119
120 /// \brief Find out where the current file is included or macro is expanded.
121 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
122 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
123 : SM.getIncludeLoc(SM.getFileID(Loc));
124 }
125
Justin Bogner682bfbf2015-05-14 22:14:10 +0000126 /// \brief Return true if \c Loc is a location in a built-in macro.
127 bool isInBuiltin(SourceLocation Loc) {
128 return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0;
129 }
130
131 /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000132 SourceLocation getStart(const Stmt *S) {
133 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000134 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000135 Loc = SM.getImmediateExpansionRange(Loc).first;
136 return Loc;
137 }
138
Justin Bogner682bfbf2015-05-14 22:14:10 +0000139 /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000140 SourceLocation getEnd(const Stmt *S) {
141 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000142 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000143 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000144 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000145 }
146
147 /// \brief Find the set of files we have regions for and assign IDs
148 ///
149 /// Fills \c Mapping with the virtual file mapping needed to write out
150 /// coverage and collects the necessary file information to emit source and
151 /// expansion regions.
152 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
153 FileIDMapping.clear();
154
155 SmallVector<FileID, 8> Visited;
156 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
157 for (const auto &Region : SourceRegions) {
158 SourceLocation Loc = Region.getStartLoc();
159 FileID File = SM.getFileID(Loc);
160 if (std::find(Visited.begin(), Visited.end(), File) != Visited.end())
161 continue;
162 Visited.push_back(File);
163
164 unsigned Depth = 0;
165 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000166 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000167 ++Depth;
168 FileLocs.push_back(std::make_pair(Loc, Depth));
169 }
170 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
171
172 for (const auto &FL : FileLocs) {
173 SourceLocation Loc = FL.first;
174 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
175 auto Entry = SM.getFileEntryForID(SpellingFile);
176 if (!Entry)
177 continue;
178
179 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
180 Mapping.push_back(CVM.getFileID(Entry));
181 }
182 }
183
184 /// \brief Get the coverage mapping file ID for \c Loc.
185 ///
186 /// If such file id doesn't exist, return None.
187 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
188 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000189 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000190 return Mapping->second.first;
191 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000192 }
193
194 /// \brief Return true if the given clang's file id has a corresponding
195 /// coverage file id.
196 bool hasExistingCoverageFileID(FileID File) const {
197 return FileIDMapping.count(File);
198 }
199
200 /// \brief Gather all the regions that were skipped by the preprocessor
201 /// using the constructs like #if.
202 void gatherSkippedRegions() {
203 /// An array of the minimum lineStarts and the maximum lineEnds
204 /// for mapping regions from the appropriate source files.
205 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
206 FileLineRanges.resize(
207 FileIDMapping.size(),
208 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
209 for (const auto &R : MappingRegions) {
210 FileLineRanges[R.FileID].first =
211 std::min(FileLineRanges[R.FileID].first, R.LineStart);
212 FileLineRanges[R.FileID].second =
213 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
214 }
215
216 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
217 for (const auto &I : SkippedRanges) {
218 auto LocStart = I.getBegin();
219 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000220 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
221 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000222
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000223 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000224 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000225 continue;
226 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
227 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
228 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
229 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
Justin Bognerfd34280b2015-02-03 23:59:48 +0000230 auto Region = CounterMappingRegion::makeSkipped(
231 *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000232 // Make sure that we only collect the regions that are inside
233 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000234 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
235 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000236 MappingRegions.push_back(Region);
237 }
238 }
239
Alex Lorenzee024992014-08-04 18:41:51 +0000240 /// \brief Generate the coverage counter mapping regions from collected
241 /// source regions.
242 void emitSourceRegions() {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000243 for (const auto &Region : SourceRegions) {
244 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000245
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000246 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000247 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000248
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000249 auto CovFileID = getCoverageFileID(LocStart);
250 // Ignore regions that don't have a file, such as builtin macros.
251 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000252 continue;
253
Justin Bognerf14b2072015-03-25 04:13:49 +0000254 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000255 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
256 "region spans multiple files");
257
Justin Bognerf59329b2014-10-01 03:33:52 +0000258 // Find the spilling locations for the mapping region.
Alex Lorenzee024992014-08-04 18:41:51 +0000259 unsigned LineStart = SM.getSpellingLineNumber(LocStart);
260 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
261 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
262 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
263
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000264 assert(LineStart <= LineEnd && "region start and end out of order");
265 MappingRegions.push_back(CounterMappingRegion::makeRegion(
266 Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
267 ColumnEnd));
268 }
269 }
270
271 /// \brief Generate expansion regions for each virtual file we've seen.
272 void emitExpansionRegions() {
273 for (const auto &FM : FileIDMapping) {
274 SourceLocation ExpandedLoc = FM.second.second;
275 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
276 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000277 continue;
278
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000279 auto ParentFileID = getCoverageFileID(ParentLoc);
280 if (!ParentFileID)
281 continue;
282 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
283 assert(ExpandedFileID && "expansion in uncovered file");
284
285 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
286 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
287 "region spans multiple files");
288
289 unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
290 unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
291 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
292 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
293
294 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
295 *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
Justin Bognerfd34280b2015-02-03 23:59:48 +0000296 ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000297 }
298 }
299};
300
301/// \brief Creates unreachable coverage regions for the functions that
302/// are not emitted.
303struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
304 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
305 const LangOptions &LangOpts)
306 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
307
308 void VisitDecl(const Decl *D) {
309 if (!D->hasBody())
310 return;
311 auto Body = D->getBody();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000312 SourceRegions.emplace_back(Counter(), getStart(Body), getEnd(Body));
Alex Lorenzee024992014-08-04 18:41:51 +0000313 }
314
315 /// \brief Write the mapping data to the output stream
316 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000317 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000318 gatherFileIDs(FileIDMapping);
319 emitSourceRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000320
Craig Topper5fc8fc22014-08-27 06:28:36 +0000321 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000322 Writer.write(OS);
323 }
324};
325
326/// \brief A StmtVisitor that creates coverage mapping regions which map
327/// from the source code locations to the PGO counters.
328struct CounterCoverageMappingBuilder
329 : public CoverageMappingBuilder,
330 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
331 /// \brief The map of statements to count values.
332 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
333
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000334 /// \brief A stack of currently live regions.
335 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000336
337 CounterExpressionBuilder Builder;
338
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000339 /// \brief A location in the most recently visited file or macro.
340 ///
341 /// This is used to adjust the active source regions appropriately when
342 /// expressions cross file or macro boundaries.
343 SourceLocation MostRecentLocation;
344
345 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000346 Counter subtractCounters(Counter LHS, Counter RHS) {
347 return Builder.subtract(LHS, RHS);
348 }
349
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000350 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000351 Counter addCounters(Counter LHS, Counter RHS) {
352 return Builder.add(LHS, RHS);
353 }
354
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000355 Counter addCounters(Counter C1, Counter C2, Counter C3) {
356 return addCounters(addCounters(C1, C2), C3);
357 }
358
359 Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) {
360 return addCounters(addCounters(C1, C2, C3), C4);
361 }
362
Alex Lorenzee024992014-08-04 18:41:51 +0000363 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000364 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000365 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000366 Counter getRegionCounter(const Stmt *S) {
367 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000368 }
369
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000370 /// \brief Push a region onto the stack.
371 ///
372 /// Returns the index on the stack where the region was pushed. This can be
373 /// used with popRegions to exit a "scope", ending the region that was pushed.
374 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
375 Optional<SourceLocation> EndLoc = None) {
376 if (StartLoc)
377 MostRecentLocation = *StartLoc;
378 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000379
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000380 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000381 }
382
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000383 /// \brief Pop regions from the stack into the function's list of regions.
384 ///
385 /// Adds all regions from \c ParentIndex to the top of the stack to the
386 /// function's \c SourceRegions.
387 void popRegions(size_t ParentIndex) {
388 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
389 while (RegionStack.size() > ParentIndex) {
390 SourceMappingRegion &Region = RegionStack.back();
391 if (Region.hasStartLoc()) {
392 SourceLocation StartLoc = Region.getStartLoc();
393 SourceLocation EndLoc = Region.hasEndLoc()
394 ? Region.getEndLoc()
395 : RegionStack[ParentIndex].getEndLoc();
396 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
397 // The region ends in a nested file or macro expansion. Create a
398 // separate region for each expansion.
399 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
400 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
401
402 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
403
Justin Bognerf14b2072015-03-25 04:13:49 +0000404 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000405 if (EndLoc.isInvalid())
406 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000407 }
408 Region.setEndLoc(EndLoc);
409
410 MostRecentLocation = EndLoc;
411 // If this region happens to span an entire expansion, we need to make
412 // sure we don't overlap the parent region with it.
413 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
414 EndLoc == getEndOfFileOrMacro(EndLoc))
415 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
416
417 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Craig Topperf36a5c42015-09-26 05:10:16 +0000418 SourceRegions.push_back(Region);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000419 }
420 RegionStack.pop_back();
421 }
Alex Lorenzee024992014-08-04 18:41:51 +0000422 }
423
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000424 /// \brief Return the currently active region.
425 SourceMappingRegion &getRegion() {
426 assert(!RegionStack.empty() && "statement has no region");
427 return RegionStack.back();
428 }
Alex Lorenzee024992014-08-04 18:41:51 +0000429
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000430 /// \brief Propagate counts through the children of \c S.
431 Counter propagateCounts(Counter TopCount, const Stmt *S) {
432 size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
433 Visit(S);
434 Counter ExitCount = getRegion().getCounter();
435 popRegions(Index);
436 return ExitCount;
437 }
Alex Lorenzee024992014-08-04 18:41:51 +0000438
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000439 /// \brief Adjust the most recently visited location to \c EndLoc.
440 ///
441 /// This should be used after visiting any statements in non-source order.
442 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
443 MostRecentLocation = EndLoc;
Justin Bogner96ae73f2015-05-01 19:23:34 +0000444 // Avoid adding duplicate regions if we have a completed region on the top
445 // of the stack and are adjusting to the end of a virtual file.
446 if (getRegion().hasEndLoc() &&
447 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000448 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
449 }
Alex Lorenzee024992014-08-04 18:41:51 +0000450
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000451 /// \brief Check whether \c Loc is included or expanded from \c Parent.
452 bool isNestedIn(SourceLocation Loc, FileID Parent) {
453 do {
454 Loc = getIncludeOrExpansionLoc(Loc);
455 if (Loc.isInvalid())
456 return false;
457 } while (!SM.isInFileID(Loc, Parent));
458 return true;
459 }
460
461 /// \brief Adjust regions and state when \c NewLoc exits a file.
462 ///
463 /// If moving from our most recently tracked location to \c NewLoc exits any
464 /// files, this adjusts our current region stack and creates the file regions
465 /// for the exited file.
466 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000467 if (NewLoc.isInvalid() ||
468 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000469 return;
470
471 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
472 // find the common ancestor.
473 SourceLocation LCA = NewLoc;
474 FileID ParentFile = SM.getFileID(LCA);
475 while (!isNestedIn(MostRecentLocation, ParentFile)) {
476 LCA = getIncludeOrExpansionLoc(LCA);
477 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
478 // Since there isn't a common ancestor, no file was exited. We just need
479 // to adjust our location to the new file.
480 MostRecentLocation = NewLoc;
481 return;
482 }
483 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000484 }
485
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000486 llvm::SmallSet<SourceLocation, 8> StartLocs;
487 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000488 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
489 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000490 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000491 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000492 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000493 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000494 break;
495 }
Alex Lorenzee024992014-08-04 18:41:51 +0000496
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000497 while (!SM.isInFileID(Loc, ParentFile)) {
498 // The most nested region for each start location is the one with the
499 // correct count. We avoid creating redundant regions by stopping once
500 // we've seen this region.
501 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000502 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000503 getEndOfFileOrMacro(Loc));
504 Loc = getIncludeOrExpansionLoc(Loc);
505 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000506 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000507 }
508
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000509 if (ParentCounter) {
510 // If the file is contained completely by another region and doesn't
511 // immediately start its own region, the whole file gets a region
512 // corresponding to the parent.
513 SourceLocation Loc = MostRecentLocation;
514 while (isNestedIn(Loc, ParentFile)) {
515 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
516 if (StartLocs.insert(FileStart).second)
517 SourceRegions.emplace_back(*ParentCounter, FileStart,
518 getEndOfFileOrMacro(Loc));
519 Loc = getIncludeOrExpansionLoc(Loc);
520 }
Alex Lorenzee024992014-08-04 18:41:51 +0000521 }
522
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000523 MostRecentLocation = NewLoc;
524 }
Alex Lorenzee024992014-08-04 18:41:51 +0000525
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000526 /// \brief Ensure that \c S is included in the current region.
527 void extendRegion(const Stmt *S) {
528 SourceMappingRegion &Region = getRegion();
529 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000530
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000531 handleFileExit(StartLoc);
532 if (!Region.hasStartLoc())
533 Region.setStartLoc(StartLoc);
534 }
535
536 /// \brief Mark \c S as a terminator, starting a zero region.
537 void terminateRegion(const Stmt *S) {
538 extendRegion(S);
539 SourceMappingRegion &Region = getRegion();
540 if (!Region.hasEndLoc())
541 Region.setEndLoc(getEnd(S));
542 pushRegion(Counter::getZero());
543 }
Alex Lorenzee024992014-08-04 18:41:51 +0000544
545 /// \brief Keep counts of breaks and continues inside loops.
546 struct BreakContinue {
547 Counter BreakCount;
548 Counter ContinueCount;
549 };
550 SmallVector<BreakContinue, 8> BreakContinueStack;
551
552 CounterCoverageMappingBuilder(
553 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000554 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000555 const LangOptions &LangOpts)
Justin Bognere5ee6c52014-10-02 16:44:01 +0000556 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000557
558 /// \brief Write the mapping data to the output stream
559 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000560 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000561 gatherFileIDs(VirtualFileMapping);
562 emitSourceRegions();
563 emitExpansionRegions();
Alex Lorenzee024992014-08-04 18:41:51 +0000564 gatherSkippedRegions();
565
Justin Bogner4da909b2015-02-03 21:35:49 +0000566 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
567 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000568 Writer.write(OS);
569 }
570
Alex Lorenzee024992014-08-04 18:41:51 +0000571 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000572 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000573 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000574 for (const Stmt *Child : S->children())
575 if (Child)
576 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000577 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000578 }
579
Alex Lorenzee024992014-08-04 18:41:51 +0000580 void VisitDecl(const Decl *D) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000581 Stmt *Body = D->getBody();
582 propagateCounts(getRegionCounter(Body), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000583 }
584
585 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000586 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000587 if (S->getRetValue())
588 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000589 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000590 }
591
Justin Bognerf959feb2015-04-28 06:31:55 +0000592 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
593 extendRegion(E);
594 if (E->getSubExpr())
595 Visit(E->getSubExpr());
596 terminateRegion(E);
597 }
598
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000599 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000600
601 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000602 SourceLocation Start = getStart(S);
603 // We can't extendRegion here or we risk overlapping with our new region.
604 handleFileExit(Start);
605 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000606 Visit(S->getSubStmt());
607 }
608
609 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000610 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
611 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000612 BreakContinueStack.back().BreakCount, getRegion().getCounter());
613 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000614 }
615
616 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000617 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
618 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000619 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
620 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000621 }
622
623 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000624 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000625
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000626 Counter ParentCount = getRegion().getCounter();
627 Counter BodyCount = getRegionCounter(S);
628
629 // Handle the body first so that we can get the backedge count.
630 BreakContinueStack.push_back(BreakContinue());
631 extendRegion(S->getBody());
632 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000633 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000634
635 // Go back to handle the condition.
636 Counter CondCount =
637 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
638 propagateCounts(CondCount, S->getCond());
639 adjustForOutOfOrderTraversal(getEnd(S));
640
641 Counter OutCount =
642 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
643 if (OutCount != ParentCount)
644 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000645 }
646
647 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000648 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000649
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000650 Counter ParentCount = getRegion().getCounter();
651 Counter BodyCount = getRegionCounter(S);
652
653 BreakContinueStack.push_back(BreakContinue());
654 extendRegion(S->getBody());
655 Counter BackedgeCount =
656 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000657 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000658
659 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
660 propagateCounts(CondCount, S->getCond());
661
662 Counter OutCount =
663 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
664 if (OutCount != ParentCount)
665 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000666 }
667
668 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000669 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000670 if (S->getInit())
671 Visit(S->getInit());
672
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000673 Counter ParentCount = getRegion().getCounter();
674 Counter BodyCount = getRegionCounter(S);
675
676 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000677 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000678 extendRegion(S->getBody());
679 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
680 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000681
682 // The increment is essentially part of the body but it needs to include
683 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000684 if (const Stmt *Inc = S->getInc())
685 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
686
687 // Go back to handle the condition.
688 Counter CondCount =
689 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
690 if (const Expr *Cond = S->getCond()) {
691 propagateCounts(CondCount, Cond);
692 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000693 }
694
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000695 Counter OutCount =
696 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
697 if (OutCount != ParentCount)
698 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000699 }
700
701 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000702 extendRegion(S);
703 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000704 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000705
706 Counter ParentCount = getRegion().getCounter();
707 Counter BodyCount = getRegionCounter(S);
708
Alex Lorenzee024992014-08-04 18:41:51 +0000709 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000710 extendRegion(S->getBody());
711 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000712 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000713
Justin Bogner15874322015-04-30 21:31:02 +0000714 Counter LoopCount =
715 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
716 Counter OutCount =
717 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000718 if (OutCount != ParentCount)
719 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000720 }
721
722 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000723 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000724 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000725
726 Counter ParentCount = getRegion().getCounter();
727 Counter BodyCount = getRegionCounter(S);
728
Alex Lorenzee024992014-08-04 18:41:51 +0000729 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000730 extendRegion(S->getBody());
731 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000732 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000733
Justin Bogner15874322015-04-30 21:31:02 +0000734 Counter LoopCount =
735 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
736 Counter OutCount =
737 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000738 if (OutCount != ParentCount)
739 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000740 }
741
742 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000743 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000744 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000745
Alex Lorenzee024992014-08-04 18:41:51 +0000746 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000747
748 const Stmt *Body = S->getBody();
749 extendRegion(Body);
750 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
751 if (!CS->body_empty()) {
752 // The body of the switch needs a zero region so that fallthrough counts
753 // behave correctly, but it would be misleading to include the braces of
754 // the compound statement in the zeroed area, so we need to handle this
755 // specially.
756 size_t Index =
757 pushRegion(Counter::getZero(), getStart(CS->body_front()),
758 getEnd(CS->body_back()));
Richard Trieub5841332015-04-15 01:21:42 +0000759 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000760 Visit(Child);
761 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +0000762 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000763 } else
764 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000765 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000766
Alex Lorenzee024992014-08-04 18:41:51 +0000767 if (!BreakContinueStack.empty())
768 BreakContinueStack.back().ContinueCount = addCounters(
769 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000770
771 Counter ExitCount = getRegionCounter(S);
772 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000773 }
774
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000775 void VisitSwitchCase(const SwitchCase *S) {
776 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000777
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000778 SourceMappingRegion &Parent = getRegion();
779
780 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
781 // Reuse the existing region if it starts at our label. This is typical of
782 // the first case in a switch.
783 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
784 Parent.setCounter(Count);
785 else
786 pushRegion(Count, getStart(S));
787
Sanjay Patel376c06c2015-12-24 21:11:29 +0000788 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000789 Visit(CS->getLHS());
790 if (const Expr *RHS = CS->getRHS())
791 Visit(RHS);
792 }
Alex Lorenzee024992014-08-04 18:41:51 +0000793 Visit(S->getSubStmt());
794 }
795
796 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000797 extendRegion(S);
Justin Bogner055ebc32015-06-16 06:24:15 +0000798 // Extend into the condition before we propagate through it below - this is
799 // needed to handle macros that generate the "if" but not the condition.
800 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +0000801
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000802 Counter ParentCount = getRegion().getCounter();
803 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000804
Justin Bogner91f2e3c2015-02-19 03:10:30 +0000805 // Emitting a counter for the condition makes it easier to interpret the
806 // counter for the body when looking at the coverage.
807 propagateCounts(ParentCount, S->getCond());
808
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000809 extendRegion(S->getThen());
810 Counter OutCount = propagateCounts(ThenCount, S->getThen());
811
812 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
813 if (const Stmt *Else = S->getElse()) {
814 extendRegion(S->getElse());
815 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
816 } else
817 OutCount = addCounters(OutCount, ElseCount);
818
819 if (OutCount != ParentCount)
820 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000821 }
822
823 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000824 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000825 Visit(S->getTryBlock());
826 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
827 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000828
829 Counter ExitCount = getRegionCounter(S);
830 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000831 }
832
833 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000834 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +0000835 }
836
837 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000838 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000839
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000840 Counter ParentCount = getRegion().getCounter();
841 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000842
Justin Bognere3654ce2015-04-24 23:37:57 +0000843 Visit(E->getCond());
844
845 if (!isa<BinaryConditionalOperator>(E)) {
846 extendRegion(E->getTrueExpr());
847 propagateCounts(TrueCount, E->getTrueExpr());
848 }
849 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000850 propagateCounts(subtractCounters(ParentCount, TrueCount),
851 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +0000852 }
853
854 void VisitBinLAnd(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000855 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000856 Visit(E->getLHS());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000857
858 extendRegion(E->getRHS());
859 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000860 }
861
862 void VisitBinLOr(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000863 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +0000864 Visit(E->getLHS());
Alex Lorenzee024992014-08-04 18:41:51 +0000865
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000866 extendRegion(E->getRHS());
867 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +0000868 }
Justin Bognerc1091022015-02-24 04:13:56 +0000869
870 void VisitLambdaExpr(const LambdaExpr *LE) {
871 // Lambdas are treated as their own functions for now, so we shouldn't
872 // propagate counts into them.
873 }
Alex Lorenzee024992014-08-04 18:41:51 +0000874};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000875}
Alex Lorenzee024992014-08-04 18:41:51 +0000876
877static bool isMachO(const CodeGenModule &CGM) {
878 return CGM.getTarget().getTriple().isOSBinFormatMachO();
879}
880
881static StringRef getCoverageSection(const CodeGenModule &CGM) {
Xinliang David Li03711cb2015-10-22 22:25:11 +0000882 return llvm::getInstrProfCoverageSectionName(isMachO(CGM));
Alex Lorenzee024992014-08-04 18:41:51 +0000883}
884
Justin Bognera432d172015-02-03 00:20:24 +0000885static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
886 ArrayRef<CounterExpression> Expressions,
887 ArrayRef<CounterMappingRegion> Regions) {
888 OS << FunctionName << ":\n";
889 CounterMappingContext Ctx(Expressions);
890 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000891 OS.indent(2);
892 switch (R.Kind) {
893 case CounterMappingRegion::CodeRegion:
894 break;
895 case CounterMappingRegion::ExpansionRegion:
896 OS << "Expansion,";
897 break;
898 case CounterMappingRegion::SkippedRegion:
899 OS << "Skipped,";
900 break;
901 }
902
Justin Bogner4da909b2015-02-03 21:35:49 +0000903 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
904 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +0000905 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000906 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +0000907 OS << " (Expanded file = " << R.ExpandedFileID << ")";
908 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000909 }
910}
911
Alex Lorenzee024992014-08-04 18:41:51 +0000912void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +0000913 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
914 const std::string &CoverageMapping, bool isUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +0000915 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +0000916 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +0000917#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +0000918 llvm::Type *FunctionRecordTypes[] = {
919 #include "llvm/ProfileData/InstrProfData.inc"
920 };
Alex Lorenzee024992014-08-04 18:41:51 +0000921 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +0000922 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
923 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +0000924 }
925
Xinliang David Lia026a432015-11-05 05:46:39 +0000926 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +0000927 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +0000928 #include "llvm/ProfileData/InstrProfData.inc"
929 };
Alex Lorenzee024992014-08-04 18:41:51 +0000930 FunctionRecords.push_back(llvm::ConstantStruct::get(
931 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li2129ae52016-01-07 20:05:55 +0000932 if (!isUsed)
933 FunctionNames.push_back(
934 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Alex Lorenzee024992014-08-04 18:41:51 +0000935 CoverageMappings += CoverageMapping;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000936
937 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
938 // Dump the coverage mapping data for this function by decoding the
939 // encoded data. This allows us to dump the mapping regions which were
940 // also processed by the CoverageMappingWriter which performs
941 // additional minimization operations such as reducing the number of
942 // expressions.
943 std::vector<StringRef> Filenames;
944 std::vector<CounterExpression> Expressions;
945 std::vector<CounterMappingRegion> Regions;
946 llvm::SmallVector<StringRef, 16> FilenameRefs;
947 FilenameRefs.resize(FileEntries.size());
948 for (const auto &Entry : FileEntries)
949 FilenameRefs[Entry.second] = Entry.first->getName();
Justin Bognera432d172015-02-03 00:20:24 +0000950 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
951 Expressions, Regions);
952 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000953 return;
Xinliang David Lia026a432015-11-05 05:46:39 +0000954 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +0000955 }
Alex Lorenzee024992014-08-04 18:41:51 +0000956}
957
958void CoverageMappingModuleGen::emit() {
959 if (FunctionRecords.empty())
960 return;
961 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
962 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
963
964 // Create the filenames and merge them with coverage mappings
965 llvm::SmallVector<std::string, 16> FilenameStrs;
966 llvm::SmallVector<StringRef, 16> FilenameRefs;
967 FilenameStrs.resize(FileEntries.size());
968 FilenameRefs.resize(FileEntries.size());
969 for (const auto &Entry : FileEntries) {
970 llvm::SmallString<256> Path(Entry.first->getName());
971 llvm::sys::fs::make_absolute(Path);
972
973 auto I = Entry.second;
Richard Trieud1ffdda2015-04-30 23:13:52 +0000974 FilenameStrs[I] = std::string(Path.begin(), Path.end());
Alex Lorenzee024992014-08-04 18:41:51 +0000975 FilenameRefs[I] = FilenameStrs[I];
976 }
977
978 std::string FilenamesAndCoverageMappings;
979 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
980 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
981 OS << CoverageMappings;
982 size_t CoverageMappingSize = CoverageMappings.size();
983 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
984 // Append extra zeroes if necessary to ensure that the size of the filenames
985 // and coverage mappings is a multiple of 8.
986 if (size_t Rem = OS.str().size() % 8) {
987 CoverageMappingSize += 8 - Rem;
988 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
989 OS << '\0';
990 }
991 auto *FilenamesAndMappingsVal =
992 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
993
994 // Create the deferred function records array
995 auto RecordsTy =
996 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
997 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
998
Xinliang David Li20b188c2016-01-03 19:25:54 +0000999 llvm::Type *CovDataHeaderTypes[] = {
1000#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1001#include "llvm/ProfileData/InstrProfData.inc"
1002 };
1003 auto CovDataHeaderTy =
1004 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1005 llvm::Constant *CovDataHeaderVals[] = {
1006#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1007#include "llvm/ProfileData/InstrProfData.inc"
1008 };
1009 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1010 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1011
Alex Lorenzee024992014-08-04 18:41:51 +00001012 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001013 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1014 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001015 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001016 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1017 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001018 auto CovDataVal =
1019 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001020 auto CovData = new llvm::GlobalVariable(
1021 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1022 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001023
1024 CovData->setSection(getCoverageSection(CGM));
1025 CovData->setAlignment(8);
1026
1027 // Make sure the data doesn't get deleted.
1028 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001029 // Create the deferred function records array
1030 if (!FunctionNames.empty()) {
1031 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1032 FunctionNames.size());
1033 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1034 // This variable will *NOT* be emitted to the object file. It is used
1035 // to pass the list of names referenced to codegen.
1036 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1037 llvm::GlobalValue::InternalLinkage, NamesArrVal,
1038 llvm::getCoverageNamesVarName());
1039 }
Alex Lorenzee024992014-08-04 18:41:51 +00001040}
1041
1042unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1043 auto It = FileEntries.find(File);
1044 if (It != FileEntries.end())
1045 return It->second;
1046 unsigned FileID = FileEntries.size();
1047 FileEntries.insert(std::make_pair(File, FileID));
1048 return FileID;
1049}
1050
1051void CoverageMappingGen::emitCounterMapping(const Decl *D,
1052 llvm::raw_ostream &OS) {
1053 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001054 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001055 Walker.VisitDecl(D);
1056 Walker.write(OS);
1057}
1058
1059void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1060 llvm::raw_ostream &OS) {
1061 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1062 Walker.VisitDecl(D);
1063 Walker.write(OS);
1064}