blob: cf736a484e54c2f09ad7fb258afba7818ef14cfd [file] [log] [blame]
Alex Lorenzee024992014-08-04 18:41:51 +00001//===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Instrumentation-based code coverage mapping generator
11//
12//===----------------------------------------------------------------------===//
13
14#include "CoverageMappingGen.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/StmtVisitor.h"
17#include "clang/Lex/Lexer.h"
Vedant Kumarbc6b80a2016-01-28 17:52:18 +000018#include "llvm/ADT/SmallSet.h"
Vedant Kumarca3326c2016-01-21 19:25:35 +000019#include "llvm/ADT/StringExtras.h"
Justin Bognerbf42cfd2015-02-18 21:24:51 +000020#include "llvm/ADT/Optional.h"
Easwaran Ramanb014ee42016-04-29 18:53:16 +000021#include "llvm/ProfileData/Coverage/CoverageMapping.h"
22#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23#include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "llvm/ProfileData/InstrProfReader.h"
Alex Lorenzee024992014-08-04 18:41:51 +000025#include "llvm/Support/FileSystem.h"
Vedant Kumar14f8fb62016-07-18 21:01:27 +000026#include "llvm/Support/Path.h"
Alex Lorenzee024992014-08-04 18:41:51 +000027
28using namespace clang;
29using namespace CodeGen;
30using namespace llvm::coverage;
31
Vedant Kumar3919a502017-09-11 20:47:42 +000032void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
Alex Lorenzee024992014-08-04 18:41:51 +000033 SkippedRanges.push_back(Range);
34}
35
36namespace {
37
38/// \brief A region of source code that can be mapped to a counter.
Justin Bogner09c71792014-10-01 03:33:49 +000039class SourceMappingRegion {
Alex Lorenzee024992014-08-04 18:41:51 +000040 Counter Count;
41
Alex Lorenzee024992014-08-04 18:41:51 +000042 /// \brief The region's starting location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000043 Optional<SourceLocation> LocStart;
Alex Lorenzee024992014-08-04 18:41:51 +000044
45 /// \brief The region's ending location.
Justin Bognerbf42cfd2015-02-18 21:24:51 +000046 Optional<SourceLocation> LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000047
Vedant Kumar747b0e22017-09-08 18:44:56 +000048 /// Whether this region should be emitted after its parent is emitted.
49 bool DeferRegion;
50
Justin Bogner09c71792014-10-01 03:33:49 +000051public:
Justin Bognerbf42cfd2015-02-18 21:24:51 +000052 SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
Vedant Kumar747b0e22017-09-08 18:44:56 +000053 Optional<SourceLocation> LocEnd, bool DeferRegion = false)
54 : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
55 DeferRegion(DeferRegion) {}
Alex Lorenzee024992014-08-04 18:41:51 +000056
Justin Bogner09c71792014-10-01 03:33:49 +000057 const Counter &getCounter() const { return Count; }
58
Justin Bognerbf42cfd2015-02-18 21:24:51 +000059 void setCounter(Counter C) { Count = C; }
Justin Bogner09c71792014-10-01 03:33:49 +000060
Justin Bognerbf42cfd2015-02-18 21:24:51 +000061 bool hasStartLoc() const { return LocStart.hasValue(); }
62
63 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
64
Craig Topper462c77b2015-09-26 05:10:14 +000065 SourceLocation getStartLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000066 assert(LocStart && "Region has no start location");
67 return *LocStart;
Justin Bogner09c71792014-10-01 03:33:49 +000068 }
69
Justin Bognerbf42cfd2015-02-18 21:24:51 +000070 bool hasEndLoc() const { return LocEnd.hasValue(); }
Alex Lorenzee024992014-08-04 18:41:51 +000071
Justin Bognerbf42cfd2015-02-18 21:24:51 +000072 void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
Alex Lorenzee024992014-08-04 18:41:51 +000073
Craig Topper462c77b2015-09-26 05:10:14 +000074 SourceLocation getEndLoc() const {
Justin Bognerbf42cfd2015-02-18 21:24:51 +000075 assert(LocEnd && "Region has no end location");
76 return *LocEnd;
Alex Lorenzee024992014-08-04 18:41:51 +000077 }
Vedant Kumar747b0e22017-09-08 18:44:56 +000078
79 bool isDeferred() const { return DeferRegion; }
80
81 void setDeferred(bool Deferred) { DeferRegion = Deferred; }
Alex Lorenzee024992014-08-04 18:41:51 +000082};
83
Vedant Kumard7369642017-07-27 02:20:25 +000084/// Spelling locations for the start and end of a source region.
85struct SpellingRegion {
86 /// The line where the region starts.
87 unsigned LineStart;
88
89 /// The column where the region starts.
90 unsigned ColumnStart;
91
92 /// The line where the region ends.
93 unsigned LineEnd;
94
95 /// The column where the region ends.
96 unsigned ColumnEnd;
97
98 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
99 SourceLocation LocEnd) {
100 LineStart = SM.getSpellingLineNumber(LocStart);
101 ColumnStart = SM.getSpellingColumnNumber(LocStart);
102 LineEnd = SM.getSpellingLineNumber(LocEnd);
103 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
104 }
105
106 /// Check if the start and end locations appear in source order, i.e
107 /// top->bottom, left->right.
108 bool isInSourceOrder() const {
109 return (LineStart < LineEnd) ||
110 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
111 }
112};
113
Alex Lorenzee024992014-08-04 18:41:51 +0000114/// \brief Provides the common functionality for the different
115/// coverage mapping region builders.
116class CoverageMappingBuilder {
117public:
118 CoverageMappingModuleGen &CVM;
119 SourceManager &SM;
120 const LangOptions &LangOpts;
121
122private:
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000123 /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
124 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
125 FileIDMapping;
Alex Lorenzee024992014-08-04 18:41:51 +0000126
127public:
Alex Lorenzee024992014-08-04 18:41:51 +0000128 /// \brief The coverage mapping regions for this function
129 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
130 /// \brief The source mapping regions for this function.
Justin Bognerf59329b2014-10-01 03:33:52 +0000131 std::vector<SourceMappingRegion> SourceRegions;
Alex Lorenzee024992014-08-04 18:41:51 +0000132
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000133 /// \brief A set of regions which can be used as a filter.
134 ///
135 /// It is produced by emitExpansionRegions() and is used in
136 /// emitSourceRegions() to suppress producing code regions if
137 /// the same area is covered by expansion regions.
138 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
139 SourceRegionFilter;
140
Alex Lorenzee024992014-08-04 18:41:51 +0000141 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
142 const LangOptions &LangOpts)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000143 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000144
145 /// \brief Return the precise end location for the given token.
146 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000147 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
148 // macro locations, which we just treat as expanded files.
149 unsigned TokLen =
150 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
151 return Loc.getLocWithOffset(TokLen);
Alex Lorenzee024992014-08-04 18:41:51 +0000152 }
153
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000154 /// \brief Return the start location of an included file or expanded macro.
155 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
156 if (Loc.isMacroID())
157 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
158 return SM.getLocForStartOfFile(SM.getFileID(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000159 }
160
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000161 /// \brief Return the end location of an included file or expanded macro.
162 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
163 if (Loc.isMacroID())
164 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
Justin Bognerf14b2072015-03-25 04:13:49 +0000165 SM.getFileOffset(Loc));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000166 return SM.getLocForEndOfFile(SM.getFileID(Loc));
167 }
168
169 /// \brief Find out where the current file is included or macro is expanded.
170 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
171 return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
172 : SM.getIncludeLoc(SM.getFileID(Loc));
173 }
174
Justin Bogner682bfbf2015-05-14 22:14:10 +0000175 /// \brief Return true if \c Loc is a location in a built-in macro.
176 bool isInBuiltin(SourceLocation Loc) {
Mehdi Amini99d1b292016-10-01 16:38:28 +0000177 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
Justin Bogner682bfbf2015-05-14 22:14:10 +0000178 }
179
Igor Kudrind9e1a612016-06-07 10:07:51 +0000180 /// \brief Check whether \c Loc is included or expanded from \c Parent.
181 bool isNestedIn(SourceLocation Loc, FileID Parent) {
182 do {
183 Loc = getIncludeOrExpansionLoc(Loc);
184 if (Loc.isInvalid())
185 return false;
186 } while (!SM.isInFileID(Loc, Parent));
187 return true;
188 }
189
Justin Bogner682bfbf2015-05-14 22:14:10 +0000190 /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000191 SourceLocation getStart(const Stmt *S) {
192 SourceLocation Loc = S->getLocStart();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000193 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000194 Loc = SM.getImmediateExpansionRange(Loc).first;
195 return Loc;
196 }
197
Justin Bogner682bfbf2015-05-14 22:14:10 +0000198 /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000199 SourceLocation getEnd(const Stmt *S) {
200 SourceLocation Loc = S->getLocEnd();
Justin Bogner682bfbf2015-05-14 22:14:10 +0000201 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000202 Loc = SM.getImmediateExpansionRange(Loc).first;
Justin Bognerf14b2072015-03-25 04:13:49 +0000203 return getPreciseTokenLocEnd(Loc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000204 }
205
206 /// \brief Find the set of files we have regions for and assign IDs
207 ///
208 /// Fills \c Mapping with the virtual file mapping needed to write out
209 /// coverage and collects the necessary file information to emit source and
210 /// expansion regions.
211 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
212 FileIDMapping.clear();
213
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000214 llvm::SmallSet<FileID, 8> Visited;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000215 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
216 for (const auto &Region : SourceRegions) {
217 SourceLocation Loc = Region.getStartLoc();
218 FileID File = SM.getFileID(Loc);
Vedant Kumarbc6b80a2016-01-28 17:52:18 +0000219 if (!Visited.insert(File).second)
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000220 continue;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000221
Vedant Kumar93205af2016-07-11 22:57:46 +0000222 // Do not map FileID's associated with system headers.
223 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
224 continue;
225
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000226 unsigned Depth = 0;
227 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000228 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000229 ++Depth;
230 FileLocs.push_back(std::make_pair(Loc, Depth));
231 }
232 std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
233
234 for (const auto &FL : FileLocs) {
235 SourceLocation Loc = FL.first;
236 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
237 auto Entry = SM.getFileEntryForID(SpellingFile);
238 if (!Entry)
239 continue;
240
241 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
242 Mapping.push_back(CVM.getFileID(Entry));
243 }
244 }
245
246 /// \brief Get the coverage mapping file ID for \c Loc.
247 ///
248 /// If such file id doesn't exist, return None.
249 Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
250 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
Justin Bogner903678c2015-01-24 20:22:32 +0000251 if (Mapping != FileIDMapping.end())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000252 return Mapping->second.first;
253 return None;
Alex Lorenzee024992014-08-04 18:41:51 +0000254 }
255
Alex Lorenzee024992014-08-04 18:41:51 +0000256 /// \brief Gather all the regions that were skipped by the preprocessor
257 /// using the constructs like #if.
258 void gatherSkippedRegions() {
259 /// An array of the minimum lineStarts and the maximum lineEnds
260 /// for mapping regions from the appropriate source files.
261 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
262 FileLineRanges.resize(
263 FileIDMapping.size(),
264 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
265 for (const auto &R : MappingRegions) {
266 FileLineRanges[R.FileID].first =
267 std::min(FileLineRanges[R.FileID].first, R.LineStart);
268 FileLineRanges[R.FileID].second =
269 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
270 }
271
272 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
273 for (const auto &I : SkippedRanges) {
274 auto LocStart = I.getBegin();
275 auto LocEnd = I.getEnd();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000276 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
277 "region spans multiple files");
Alex Lorenzee024992014-08-04 18:41:51 +0000278
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000279 auto CovFileID = getCoverageFileID(LocStart);
Justin Bogner903678c2015-01-24 20:22:32 +0000280 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000281 continue;
Vedant Kumard7369642017-07-27 02:20:25 +0000282 SpellingRegion SR{SM, LocStart, LocEnd};
Justin Bognerfd34280b2015-02-03 23:59:48 +0000283 auto Region = CounterMappingRegion::makeSkipped(
Vedant Kumard7369642017-07-27 02:20:25 +0000284 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd);
Alex Lorenzee024992014-08-04 18:41:51 +0000285 // Make sure that we only collect the regions that are inside
286 // the souce code of this function.
Justin Bogner903678c2015-01-24 20:22:32 +0000287 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
288 Region.LineEnd <= FileLineRanges[*CovFileID].second)
Alex Lorenzee024992014-08-04 18:41:51 +0000289 MappingRegions.push_back(Region);
290 }
291 }
292
Alex Lorenzee024992014-08-04 18:41:51 +0000293 /// \brief Generate the coverage counter mapping regions from collected
294 /// source regions.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000295 void emitSourceRegions(const SourceRegionFilter &Filter) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000296 for (const auto &Region : SourceRegions) {
297 assert(Region.hasEndLoc() && "incomplete region");
Alex Lorenzee024992014-08-04 18:41:51 +0000298
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000299 SourceLocation LocStart = Region.getStartLoc();
Yaron Keren8b563662015-10-03 10:46:20 +0000300 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
Justin Bognerf59329b2014-10-01 03:33:52 +0000301
Vedant Kumar93205af2016-07-11 22:57:46 +0000302 // Ignore regions from system headers.
303 if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
304 continue;
305
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000306 auto CovFileID = getCoverageFileID(LocStart);
307 // Ignore regions that don't have a file, such as builtin macros.
308 if (!CovFileID)
Alex Lorenzee024992014-08-04 18:41:51 +0000309 continue;
310
Justin Bognerf14b2072015-03-25 04:13:49 +0000311 SourceLocation LocEnd = Region.getEndLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000312 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
313 "region spans multiple files");
314
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000315 // Don't add code regions for the area covered by expansion regions.
316 // This not only suppresses redundant regions, but sometimes prevents
317 // creating regions with wrong counters if, for example, a statement's
318 // body ends at the end of a nested macro.
319 if (Filter.count(std::make_pair(LocStart, LocEnd)))
320 continue;
321
Vedant Kumard7369642017-07-27 02:20:25 +0000322 // Find the spelling locations for the mapping region.
323 SpellingRegion SR{SM, LocStart, LocEnd};
324 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000325 MappingRegions.push_back(CounterMappingRegion::makeRegion(
Vedant Kumard7369642017-07-27 02:20:25 +0000326 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
327 SR.LineEnd, SR.ColumnEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000328 }
329 }
330
331 /// \brief Generate expansion regions for each virtual file we've seen.
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000332 SourceRegionFilter emitExpansionRegions() {
333 SourceRegionFilter Filter;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000334 for (const auto &FM : FileIDMapping) {
335 SourceLocation ExpandedLoc = FM.second.second;
336 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
337 if (ParentLoc.isInvalid())
Alex Lorenzee024992014-08-04 18:41:51 +0000338 continue;
339
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000340 auto ParentFileID = getCoverageFileID(ParentLoc);
341 if (!ParentFileID)
342 continue;
343 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
344 assert(ExpandedFileID && "expansion in uncovered file");
345
346 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
347 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
348 "region spans multiple files");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000349 Filter.insert(std::make_pair(ParentLoc, LocEnd));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000350
Vedant Kumard7369642017-07-27 02:20:25 +0000351 SpellingRegion SR{SM, ParentLoc, LocEnd};
352 assert(SR.isInSourceOrder() && "region start and end out of order");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000353 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
Vedant Kumard7369642017-07-27 02:20:25 +0000354 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
355 SR.LineEnd, SR.ColumnEnd));
Alex Lorenzee024992014-08-04 18:41:51 +0000356 }
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000357 return Filter;
Alex Lorenzee024992014-08-04 18:41:51 +0000358 }
359};
360
361/// \brief Creates unreachable coverage regions for the functions that
362/// are not emitted.
363struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
364 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
365 const LangOptions &LangOpts)
366 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
367
368 void VisitDecl(const Decl *D) {
369 if (!D->hasBody())
370 return;
371 auto Body = D->getBody();
Igor Kudrind9e1a612016-06-07 10:07:51 +0000372 SourceLocation Start = getStart(Body);
373 SourceLocation End = getEnd(Body);
374 if (!SM.isWrittenInSameFile(Start, End)) {
375 // Walk up to find the common ancestor.
376 // Correct the locations accordingly.
377 FileID StartFileID = SM.getFileID(Start);
378 FileID EndFileID = SM.getFileID(End);
379 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
380 Start = getIncludeOrExpansionLoc(Start);
381 assert(Start.isValid() &&
382 "Declaration start location not nested within a known region");
383 StartFileID = SM.getFileID(Start);
384 }
385 while (StartFileID != EndFileID) {
386 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
387 assert(End.isValid() &&
388 "Declaration end location not nested within a known region");
389 EndFileID = SM.getFileID(End);
390 }
391 }
392 SourceRegions.emplace_back(Counter(), Start, End);
Alex Lorenzee024992014-08-04 18:41:51 +0000393 }
394
395 /// \brief Write the mapping data to the output stream
396 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000397 SmallVector<unsigned, 16> FileIDMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000398 gatherFileIDs(FileIDMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000399 emitSourceRegions(SourceRegionFilter());
Alex Lorenzee024992014-08-04 18:41:51 +0000400
Vedant Kumarefd319a2016-07-26 00:24:59 +0000401 if (MappingRegions.empty())
402 return;
403
Craig Topper5fc8fc22014-08-27 06:28:36 +0000404 CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000405 Writer.write(OS);
406 }
407};
408
409/// \brief A StmtVisitor that creates coverage mapping regions which map
410/// from the source code locations to the PGO counters.
411struct CounterCoverageMappingBuilder
412 : public CoverageMappingBuilder,
413 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
414 /// \brief The map of statements to count values.
415 llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
416
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000417 /// \brief A stack of currently live regions.
418 std::vector<SourceMappingRegion> RegionStack;
Alex Lorenzee024992014-08-04 18:41:51 +0000419
Vedant Kumar747b0e22017-09-08 18:44:56 +0000420 /// The currently deferred region: its end location and count can be set once
421 /// its parent has been popped from the region stack.
422 Optional<SourceMappingRegion> DeferredRegion;
423
Alex Lorenzee024992014-08-04 18:41:51 +0000424 CounterExpressionBuilder Builder;
425
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000426 /// \brief A location in the most recently visited file or macro.
427 ///
428 /// This is used to adjust the active source regions appropriately when
429 /// expressions cross file or macro boundaries.
430 SourceLocation MostRecentLocation;
431
432 /// \brief Return a counter for the subtraction of \c RHS from \c LHS
Alex Lorenzee024992014-08-04 18:41:51 +0000433 Counter subtractCounters(Counter LHS, Counter RHS) {
434 return Builder.subtract(LHS, RHS);
435 }
436
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000437 /// \brief Return a counter for the sum of \c LHS and \c RHS.
Alex Lorenzee024992014-08-04 18:41:51 +0000438 Counter addCounters(Counter LHS, Counter RHS) {
439 return Builder.add(LHS, RHS);
440 }
441
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000442 Counter addCounters(Counter C1, Counter C2, Counter C3) {
443 return addCounters(addCounters(C1, C2), C3);
444 }
445
Alex Lorenzee024992014-08-04 18:41:51 +0000446 /// \brief Return the region counter for the given statement.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000447 ///
Alex Lorenzee024992014-08-04 18:41:51 +0000448 /// This should only be called on statements that have a dedicated counter.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000449 Counter getRegionCounter(const Stmt *S) {
450 return Counter::getCounter(CounterMap[S]);
Alex Lorenzee024992014-08-04 18:41:51 +0000451 }
452
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000453 /// \brief Push a region onto the stack.
454 ///
455 /// Returns the index on the stack where the region was pushed. This can be
456 /// used with popRegions to exit a "scope", ending the region that was pushed.
457 size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
458 Optional<SourceLocation> EndLoc = None) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000459 if (StartLoc) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000460 MostRecentLocation = *StartLoc;
Vedant Kumar747b0e22017-09-08 18:44:56 +0000461 completeDeferred(Count, MostRecentLocation);
462 }
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000463 RegionStack.emplace_back(Count, StartLoc, EndLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000464
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000465 return RegionStack.size() - 1;
Alex Lorenzee024992014-08-04 18:41:51 +0000466 }
467
Vedant Kumar747b0e22017-09-08 18:44:56 +0000468 /// Complete any pending deferred region by setting its end location and
469 /// count, and then pushing it onto the region stack.
470 size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
471 size_t Index = RegionStack.size();
472 if (!DeferredRegion)
473 return Index;
474
475 // Consume the pending region.
476 SourceMappingRegion DR = DeferredRegion.getValue();
477 DeferredRegion = None;
478
479 // If the region ends in an expansion, find the expansion site.
480 if (SM.getFileID(DeferredEndLoc) != SM.getMainFileID()) {
481 FileID StartFile = SM.getFileID(DR.getStartLoc());
482 if (isNestedIn(DeferredEndLoc, StartFile)) {
483 do {
484 DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
485 } while (StartFile != SM.getFileID(DeferredEndLoc));
486 }
487 }
488
489 // The parent of this deferred region ends where the containing decl ends,
490 // so the region isn't useful.
491 if (DR.getStartLoc() == DeferredEndLoc)
492 return Index;
493
494 // If we're visiting statements in non-source order (e.g switch cases or
495 // a loop condition) we can't construct a sensible deferred region.
496 if (!SpellingRegion(SM, DR.getStartLoc(), DeferredEndLoc).isInSourceOrder())
497 return Index;
498
499 DR.setCounter(Count);
500 DR.setEndLoc(DeferredEndLoc);
501 handleFileExit(DeferredEndLoc);
502 RegionStack.push_back(DR);
503 return Index;
504 }
505
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000506 /// \brief Pop regions from the stack into the function's list of regions.
507 ///
508 /// Adds all regions from \c ParentIndex to the top of the stack to the
509 /// function's \c SourceRegions.
510 void popRegions(size_t ParentIndex) {
511 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
Vedant Kumar747b0e22017-09-08 18:44:56 +0000512 bool ParentOfDeferredRegion = false;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000513 while (RegionStack.size() > ParentIndex) {
514 SourceMappingRegion &Region = RegionStack.back();
515 if (Region.hasStartLoc()) {
516 SourceLocation StartLoc = Region.getStartLoc();
517 SourceLocation EndLoc = Region.hasEndLoc()
518 ? Region.getEndLoc()
519 : RegionStack[ParentIndex].getEndLoc();
520 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
521 // The region ends in a nested file or macro expansion. Create a
522 // separate region for each expansion.
523 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
524 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
525
Igor Kudrin8545dae2016-08-29 11:48:50 +0000526 if (!isRegionAlreadyAdded(NestedLoc, EndLoc))
527 SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000528
Justin Bognerf14b2072015-03-25 04:13:49 +0000529 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
Justin Bognerdceaaad2015-07-17 23:31:21 +0000530 if (EndLoc.isInvalid())
531 llvm::report_fatal_error("File exit not handled before popRegions");
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000532 }
533 Region.setEndLoc(EndLoc);
534
535 MostRecentLocation = EndLoc;
536 // If this region happens to span an entire expansion, we need to make
537 // sure we don't overlap the parent region with it.
538 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
539 EndLoc == getEndOfFileOrMacro(EndLoc))
540 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
541
542 assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
Craig Topperf36a5c42015-09-26 05:10:16 +0000543 SourceRegions.push_back(Region);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000544
545 if (ParentOfDeferredRegion) {
546 ParentOfDeferredRegion = false;
547
548 // If there's an existing deferred region, keep the old one, because
549 // it means there are two consecutive returns (or a similar pattern).
550 if (!DeferredRegion.hasValue() &&
551 // File IDs aren't gathered within macro expansions, so it isn't
552 // useful to try and create a deferred region inside of one.
553 (SM.getFileID(EndLoc) == SM.getMainFileID()))
554 DeferredRegion =
555 SourceMappingRegion(Counter::getZero(), EndLoc, None);
556 }
557 } else if (Region.isDeferred()) {
558 assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
559 ParentOfDeferredRegion = true;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000560 }
561 RegionStack.pop_back();
562 }
Vedant Kumar747b0e22017-09-08 18:44:56 +0000563 assert(!ParentOfDeferredRegion && "Deferred region with no parent");
Alex Lorenzee024992014-08-04 18:41:51 +0000564 }
565
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000566 /// \brief Return the currently active region.
567 SourceMappingRegion &getRegion() {
568 assert(!RegionStack.empty() && "statement has no region");
569 return RegionStack.back();
570 }
Alex Lorenzee024992014-08-04 18:41:51 +0000571
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000572 /// \brief Propagate counts through the children of \c S.
573 Counter propagateCounts(Counter TopCount, const Stmt *S) {
Vedant Kumar78386962017-07-27 02:20:20 +0000574 SourceLocation StartLoc = getStart(S);
575 SourceLocation EndLoc = getEnd(S);
576 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000577 Visit(S);
578 Counter ExitCount = getRegion().getCounter();
579 popRegions(Index);
Vedant Kumar39f01972016-02-08 19:25:45 +0000580
581 // The statement may be spanned by an expansion. Make sure we handle a file
582 // exit out of this expansion before moving to the next statement.
Vedant Kumar78386962017-07-27 02:20:20 +0000583 if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart()))
584 MostRecentLocation = EndLoc;
Vedant Kumar39f01972016-02-08 19:25:45 +0000585
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000586 return ExitCount;
587 }
Alex Lorenzee024992014-08-04 18:41:51 +0000588
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000589 /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
590 /// is already added to \c SourceRegions.
591 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
592 return SourceRegions.rend() !=
593 std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
594 [&](const SourceMappingRegion &Region) {
595 return Region.getStartLoc() == StartLoc &&
596 Region.getEndLoc() == EndLoc;
597 });
598 }
599
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000600 /// \brief Adjust the most recently visited location to \c EndLoc.
601 ///
602 /// This should be used after visiting any statements in non-source order.
603 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
604 MostRecentLocation = EndLoc;
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000605 // The code region for a whole macro is created in handleFileExit() when
606 // it detects exiting of the virtual file of that macro. If we visited
607 // statements in non-source order, we might already have such a region
608 // added, for example, if a body of a loop is divided among multiple
609 // macros. Avoid adding duplicate regions in such case.
Justin Bogner96ae73f2015-05-01 19:23:34 +0000610 if (getRegion().hasEndLoc() &&
Igor Kudrin0a7c9d12016-05-04 15:38:26 +0000611 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
612 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
613 MostRecentLocation))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000614 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
615 }
Alex Lorenzee024992014-08-04 18:41:51 +0000616
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000617 /// \brief Adjust regions and state when \c NewLoc exits a file.
618 ///
619 /// If moving from our most recently tracked location to \c NewLoc exits any
620 /// files, this adjusts our current region stack and creates the file regions
621 /// for the exited file.
622 void handleFileExit(SourceLocation NewLoc) {
Justin Bognere44dd6d2015-06-23 20:29:09 +0000623 if (NewLoc.isInvalid() ||
624 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000625 return;
626
627 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
628 // find the common ancestor.
629 SourceLocation LCA = NewLoc;
630 FileID ParentFile = SM.getFileID(LCA);
631 while (!isNestedIn(MostRecentLocation, ParentFile)) {
632 LCA = getIncludeOrExpansionLoc(LCA);
633 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
634 // Since there isn't a common ancestor, no file was exited. We just need
635 // to adjust our location to the new file.
636 MostRecentLocation = NewLoc;
637 return;
638 }
639 ParentFile = SM.getFileID(LCA);
Alex Lorenzee024992014-08-04 18:41:51 +0000640 }
641
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000642 llvm::SmallSet<SourceLocation, 8> StartLocs;
643 Optional<Counter> ParentCounter;
Pete Cooper57d3f142015-07-30 17:22:52 +0000644 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
645 if (!I.hasStartLoc())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000646 continue;
Pete Cooper57d3f142015-07-30 17:22:52 +0000647 SourceLocation Loc = I.getStartLoc();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000648 if (!isNestedIn(Loc, ParentFile)) {
Pete Cooper57d3f142015-07-30 17:22:52 +0000649 ParentCounter = I.getCounter();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000650 break;
651 }
Alex Lorenzee024992014-08-04 18:41:51 +0000652
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000653 while (!SM.isInFileID(Loc, ParentFile)) {
654 // The most nested region for each start location is the one with the
655 // correct count. We avoid creating redundant regions by stopping once
656 // we've seen this region.
657 if (StartLocs.insert(Loc).second)
Pete Cooper57d3f142015-07-30 17:22:52 +0000658 SourceRegions.emplace_back(I.getCounter(), Loc,
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000659 getEndOfFileOrMacro(Loc));
660 Loc = getIncludeOrExpansionLoc(Loc);
661 }
Pete Cooper57d3f142015-07-30 17:22:52 +0000662 I.setStartLoc(getPreciseTokenLocEnd(Loc));
Alex Lorenzee024992014-08-04 18:41:51 +0000663 }
664
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000665 if (ParentCounter) {
666 // If the file is contained completely by another region and doesn't
667 // immediately start its own region, the whole file gets a region
668 // corresponding to the parent.
669 SourceLocation Loc = MostRecentLocation;
670 while (isNestedIn(Loc, ParentFile)) {
671 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
672 if (StartLocs.insert(FileStart).second)
673 SourceRegions.emplace_back(*ParentCounter, FileStart,
674 getEndOfFileOrMacro(Loc));
675 Loc = getIncludeOrExpansionLoc(Loc);
676 }
Alex Lorenzee024992014-08-04 18:41:51 +0000677 }
678
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000679 MostRecentLocation = NewLoc;
680 }
Alex Lorenzee024992014-08-04 18:41:51 +0000681
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000682 /// \brief Ensure that \c S is included in the current region.
683 void extendRegion(const Stmt *S) {
684 SourceMappingRegion &Region = getRegion();
685 SourceLocation StartLoc = getStart(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000686
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000687 handleFileExit(StartLoc);
688 if (!Region.hasStartLoc())
689 Region.setStartLoc(StartLoc);
Vedant Kumar747b0e22017-09-08 18:44:56 +0000690
691 completeDeferred(Region.getCounter(), StartLoc);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000692 }
693
694 /// \brief Mark \c S as a terminator, starting a zero region.
695 void terminateRegion(const Stmt *S) {
696 extendRegion(S);
697 SourceMappingRegion &Region = getRegion();
698 if (!Region.hasEndLoc())
699 Region.setEndLoc(getEnd(S));
700 pushRegion(Counter::getZero());
Vedant Kumar747b0e22017-09-08 18:44:56 +0000701 getRegion().setDeferred(true);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000702 }
Alex Lorenzee024992014-08-04 18:41:51 +0000703
704 /// \brief Keep counts of breaks and continues inside loops.
705 struct BreakContinue {
706 Counter BreakCount;
707 Counter ContinueCount;
708 };
709 SmallVector<BreakContinue, 8> BreakContinueStack;
710
711 CounterCoverageMappingBuilder(
712 CoverageMappingModuleGen &CVM,
Justin Bognere5ee6c52014-10-02 16:44:01 +0000713 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
Alex Lorenzee024992014-08-04 18:41:51 +0000714 const LangOptions &LangOpts)
Vedant Kumar747b0e22017-09-08 18:44:56 +0000715 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
716 DeferredRegion(None) {}
Alex Lorenzee024992014-08-04 18:41:51 +0000717
718 /// \brief Write the mapping data to the output stream
719 void write(llvm::raw_ostream &OS) {
Alex Lorenzee024992014-08-04 18:41:51 +0000720 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000721 gatherFileIDs(VirtualFileMapping);
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000722 SourceRegionFilter Filter = emitExpansionRegions();
Vedant Kumar747b0e22017-09-08 18:44:56 +0000723 assert(!DeferredRegion && "Deferred region never completed");
Igor Kudrinfc05ee32016-08-31 07:04:16 +0000724 emitSourceRegions(Filter);
Alex Lorenzee024992014-08-04 18:41:51 +0000725 gatherSkippedRegions();
726
Vedant Kumarefd319a2016-07-26 00:24:59 +0000727 if (MappingRegions.empty())
728 return;
729
Justin Bogner4da909b2015-02-03 21:35:49 +0000730 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
731 MappingRegions);
Alex Lorenzee024992014-08-04 18:41:51 +0000732 Writer.write(OS);
733 }
734
Alex Lorenzee024992014-08-04 18:41:51 +0000735 void VisitStmt(const Stmt *S) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000736 if (S->getLocStart().isValid())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000737 extendRegion(S);
Benjamin Kramer642f1732015-07-02 21:03:14 +0000738 for (const Stmt *Child : S->children())
739 if (Child)
740 this->Visit(Child);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000741 handleFileExit(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000742 }
743
Alex Lorenzee024992014-08-04 18:41:51 +0000744 void VisitDecl(const Decl *D) {
Vedant Kumar747b0e22017-09-08 18:44:56 +0000745 assert(!DeferredRegion && "Deferred region never completed");
746
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000747 Stmt *Body = D->getBody();
Vedant Kumarefd319a2016-07-26 00:24:59 +0000748
749 // Do not propagate region counts into system headers.
750 if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
751 return;
752
Vedant Kumar747b0e22017-09-08 18:44:56 +0000753 Counter ExitCount = propagateCounts(getRegionCounter(Body), Body);
754 assert(RegionStack.empty() && "Regions entered but never exited");
755
756 // Complete any deferred regions introduced by the last statement in a decl.
757 popRegions(completeDeferred(ExitCount, getEnd(Body)));
Alex Lorenzee024992014-08-04 18:41:51 +0000758 }
759
760 void VisitReturnStmt(const ReturnStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000761 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000762 if (S->getRetValue())
763 Visit(S->getRetValue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000764 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000765 }
766
Justin Bognerf959feb2015-04-28 06:31:55 +0000767 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
768 extendRegion(E);
769 if (E->getSubExpr())
770 Visit(E->getSubExpr());
771 terminateRegion(E);
772 }
773
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000774 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
Alex Lorenzee024992014-08-04 18:41:51 +0000775
776 void VisitLabelStmt(const LabelStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000777 SourceLocation Start = getStart(S);
778 // We can't extendRegion here or we risk overlapping with our new region.
779 handleFileExit(Start);
780 pushRegion(getRegionCounter(S), Start);
Alex Lorenzee024992014-08-04 18:41:51 +0000781 Visit(S->getSubStmt());
782 }
783
784 void VisitBreakStmt(const BreakStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000785 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
786 BreakContinueStack.back().BreakCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000787 BreakContinueStack.back().BreakCount, getRegion().getCounter());
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000788 // FIXME: a break in a switch should terminate regions for all preceding
789 // case statements, not just the most recent one.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000790 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000791 }
792
793 void VisitContinueStmt(const ContinueStmt *S) {
Alex Lorenzee024992014-08-04 18:41:51 +0000794 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
795 BreakContinueStack.back().ContinueCount = addCounters(
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000796 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
797 terminateRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000798 }
799
Eli Friedman181dfe42017-08-08 20:10:14 +0000800 void VisitCallExpr(const CallExpr *E) {
801 VisitStmt(E);
802
803 // Terminate the region when we hit a noreturn function.
804 // (This is helpful dealing with switch statements.)
805 QualType CalleeType = E->getCallee()->getType();
806 if (getFunctionExtInfo(*CalleeType).getNoReturn())
807 terminateRegion(E);
808 }
809
Alex Lorenzee024992014-08-04 18:41:51 +0000810 void VisitWhileStmt(const WhileStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000811 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000812
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000813 Counter ParentCount = getRegion().getCounter();
814 Counter BodyCount = getRegionCounter(S);
815
816 // Handle the body first so that we can get the backedge count.
817 BreakContinueStack.push_back(BreakContinue());
818 extendRegion(S->getBody());
819 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000820 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000821
822 // Go back to handle the condition.
823 Counter CondCount =
824 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
825 propagateCounts(CondCount, S->getCond());
826 adjustForOutOfOrderTraversal(getEnd(S));
827
828 Counter OutCount =
829 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
830 if (OutCount != ParentCount)
831 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000832 }
833
834 void VisitDoStmt(const DoStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000835 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000836
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000837 Counter ParentCount = getRegion().getCounter();
838 Counter BodyCount = getRegionCounter(S);
839
840 BreakContinueStack.push_back(BreakContinue());
841 extendRegion(S->getBody());
842 Counter BackedgeCount =
843 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000844 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000845
846 Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
847 propagateCounts(CondCount, S->getCond());
848
849 Counter OutCount =
850 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
851 if (OutCount != ParentCount)
852 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000853 }
854
855 void VisitForStmt(const ForStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000856 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000857 if (S->getInit())
858 Visit(S->getInit());
859
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000860 Counter ParentCount = getRegion().getCounter();
861 Counter BodyCount = getRegionCounter(S);
862
863 // Handle the body first so that we can get the backedge count.
Alex Lorenzee024992014-08-04 18:41:51 +0000864 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000865 extendRegion(S->getBody());
866 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
867 BreakContinue BC = BreakContinueStack.pop_back_val();
Alex Lorenzee024992014-08-04 18:41:51 +0000868
869 // The increment is essentially part of the body but it needs to include
870 // the count for all the continue statements.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000871 if (const Stmt *Inc = S->getInc())
872 propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
873
874 // Go back to handle the condition.
875 Counter CondCount =
876 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
877 if (const Expr *Cond = S->getCond()) {
878 propagateCounts(CondCount, Cond);
879 adjustForOutOfOrderTraversal(getEnd(S));
Alex Lorenzee024992014-08-04 18:41:51 +0000880 }
881
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000882 Counter OutCount =
883 addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
884 if (OutCount != ParentCount)
885 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000886 }
887
888 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000889 extendRegion(S);
890 Visit(S->getLoopVarStmt());
Alex Lorenzee024992014-08-04 18:41:51 +0000891 Visit(S->getRangeStmt());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000892
893 Counter ParentCount = getRegion().getCounter();
894 Counter BodyCount = getRegionCounter(S);
895
Alex Lorenzee024992014-08-04 18:41:51 +0000896 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000897 extendRegion(S->getBody());
898 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000899 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000900
Justin Bogner15874322015-04-30 21:31:02 +0000901 Counter LoopCount =
902 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
903 Counter OutCount =
904 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000905 if (OutCount != ParentCount)
906 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000907 }
908
909 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000910 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000911 Visit(S->getElement());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000912
913 Counter ParentCount = getRegion().getCounter();
914 Counter BodyCount = getRegionCounter(S);
915
Alex Lorenzee024992014-08-04 18:41:51 +0000916 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000917 extendRegion(S->getBody());
918 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
Alex Lorenzee024992014-08-04 18:41:51 +0000919 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000920
Justin Bogner15874322015-04-30 21:31:02 +0000921 Counter LoopCount =
922 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
923 Counter OutCount =
924 addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000925 if (OutCount != ParentCount)
926 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +0000927 }
928
929 void VisitSwitchStmt(const SwitchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000930 extendRegion(S);
Vedant Kumarf2a6ec52016-10-14 23:38:13 +0000931 if (S->getInit())
932 Visit(S->getInit());
Alex Lorenzee024992014-08-04 18:41:51 +0000933 Visit(S->getCond());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000934
Alex Lorenzee024992014-08-04 18:41:51 +0000935 BreakContinueStack.push_back(BreakContinue());
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000936
937 const Stmt *Body = S->getBody();
938 extendRegion(Body);
939 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
940 if (!CS->body_empty()) {
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000941 // Make a region for the body of the switch. If the body starts with
942 // a case, that case will reuse this region; otherwise, this covers
943 // the unreachable code at the beginning of the switch body.
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000944 size_t Index =
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000945 pushRegion(Counter::getZero(), getStart(CS->body_front()));
Richard Trieub5841332015-04-15 01:21:42 +0000946 for (const auto *Child : CS->children())
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000947 Visit(Child);
Eli Friedman7f53fbfc2017-08-02 23:22:50 +0000948
949 // Set the end for the body of the switch, if it isn't already set.
950 for (size_t i = RegionStack.size(); i != Index; --i) {
951 if (!RegionStack[i - 1].hasEndLoc())
952 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
953 }
954
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000955 popRegions(Index);
Alex Lorenzee024992014-08-04 18:41:51 +0000956 }
Vedant Kumar87ea3b02016-05-31 20:35:12 +0000957 } else
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000958 propagateCounts(Counter::getZero(), Body);
Alex Lorenzee024992014-08-04 18:41:51 +0000959 BreakContinue BC = BreakContinueStack.pop_back_val();
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000960
Alex Lorenzee024992014-08-04 18:41:51 +0000961 if (!BreakContinueStack.empty())
962 BreakContinueStack.back().ContinueCount = addCounters(
963 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000964
965 Counter ExitCount = getRegionCounter(S);
Vedant Kumar38364822016-05-31 18:06:19 +0000966 SourceLocation ExitLoc = getEnd(S);
Alex Lorenz08780522016-09-27 23:30:36 +0000967 pushRegion(ExitCount);
968
969 // Ensure that handleFileExit recognizes when the end location is located
970 // in a different file.
971 MostRecentLocation = getStart(S);
Vedant Kumar38364822016-05-31 18:06:19 +0000972 handleFileExit(ExitLoc);
Alex Lorenzee024992014-08-04 18:41:51 +0000973 }
974
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000975 void VisitSwitchCase(const SwitchCase *S) {
976 extendRegion(S);
Alex Lorenzee024992014-08-04 18:41:51 +0000977
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000978 SourceMappingRegion &Parent = getRegion();
979
980 Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
981 // Reuse the existing region if it starts at our label. This is typical of
982 // the first case in a switch.
983 if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
984 Parent.setCounter(Count);
985 else
986 pushRegion(Count, getStart(S));
987
Sanjay Patel376c06c2015-12-24 21:11:29 +0000988 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000989 Visit(CS->getLHS());
990 if (const Expr *RHS = CS->getRHS())
991 Visit(RHS);
992 }
Alex Lorenzee024992014-08-04 18:41:51 +0000993 Visit(S->getSubStmt());
994 }
995
996 void VisitIfStmt(const IfStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +0000997 extendRegion(S);
Vedant Kumar9d2a16b2016-10-14 23:38:16 +0000998 if (S->getInit())
999 Visit(S->getInit());
1000
Justin Bogner055ebc32015-06-16 06:24:15 +00001001 // Extend into the condition before we propagate through it below - this is
1002 // needed to handle macros that generate the "if" but not the condition.
1003 extendRegion(S->getCond());
Alex Lorenzee024992014-08-04 18:41:51 +00001004
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001005 Counter ParentCount = getRegion().getCounter();
1006 Counter ThenCount = getRegionCounter(S);
Alex Lorenzee024992014-08-04 18:41:51 +00001007
Justin Bogner91f2e3c2015-02-19 03:10:30 +00001008 // Emitting a counter for the condition makes it easier to interpret the
1009 // counter for the body when looking at the coverage.
1010 propagateCounts(ParentCount, S->getCond());
1011
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001012 extendRegion(S->getThen());
1013 Counter OutCount = propagateCounts(ThenCount, S->getThen());
1014
1015 Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1016 if (const Stmt *Else = S->getElse()) {
1017 extendRegion(S->getElse());
1018 OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1019 } else
1020 OutCount = addCounters(OutCount, ElseCount);
1021
1022 if (OutCount != ParentCount)
1023 pushRegion(OutCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001024 }
1025
1026 void VisitCXXTryStmt(const CXXTryStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001027 extendRegion(S);
Vedant Kumar049908b2016-06-22 19:57:58 +00001028 // Handle macros that generate the "try" but not the rest.
1029 extendRegion(S->getTryBlock());
1030
1031 Counter ParentCount = getRegion().getCounter();
1032 propagateCounts(ParentCount, S->getTryBlock());
1033
Alex Lorenzee024992014-08-04 18:41:51 +00001034 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1035 Visit(S->getHandler(I));
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001036
1037 Counter ExitCount = getRegionCounter(S);
1038 pushRegion(ExitCount);
Alex Lorenzee024992014-08-04 18:41:51 +00001039 }
1040
1041 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001042 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
Alex Lorenzee024992014-08-04 18:41:51 +00001043 }
1044
1045 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001046 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001047
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001048 Counter ParentCount = getRegion().getCounter();
1049 Counter TrueCount = getRegionCounter(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001050
Justin Bognere3654ce2015-04-24 23:37:57 +00001051 Visit(E->getCond());
1052
1053 if (!isa<BinaryConditionalOperator>(E)) {
1054 extendRegion(E->getTrueExpr());
1055 propagateCounts(TrueCount, E->getTrueExpr());
1056 }
1057 extendRegion(E->getFalseExpr());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001058 propagateCounts(subtractCounters(ParentCount, TrueCount),
1059 E->getFalseExpr());
Alex Lorenzee024992014-08-04 18:41:51 +00001060 }
1061
1062 void VisitBinLAnd(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001063 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001064 Visit(E->getLHS());
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001065
1066 extendRegion(E->getRHS());
1067 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001068 }
1069
1070 void VisitBinLOr(const BinaryOperator *E) {
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001071 extendRegion(E);
Alex Lorenzee024992014-08-04 18:41:51 +00001072 Visit(E->getLHS());
Alex Lorenzee024992014-08-04 18:41:51 +00001073
Justin Bognerbf42cfd2015-02-18 21:24:51 +00001074 extendRegion(E->getRHS());
1075 propagateCounts(getRegionCounter(E), E->getRHS());
Alex Lorenz01a0d062014-08-20 17:10:56 +00001076 }
Justin Bognerc1091022015-02-24 04:13:56 +00001077
1078 void VisitLambdaExpr(const LambdaExpr *LE) {
1079 // Lambdas are treated as their own functions for now, so we shouldn't
1080 // propagate counts into them.
1081 }
Alex Lorenzee024992014-08-04 18:41:51 +00001082};
Alex Lorenzee024992014-08-04 18:41:51 +00001083
Xinliang David Li1f39fcf2017-04-14 04:14:29 +00001084std::string getCoverageSection(const CodeGenModule &CGM) {
Vedant Kumar8a767a42017-04-15 00:10:05 +00001085 return llvm::getInstrProfSectionName(
1086 llvm::IPSK_covmap,
1087 CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
Alex Lorenzee024992014-08-04 18:41:51 +00001088}
1089
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001090std::string normalizeFilename(StringRef Filename) {
1091 llvm::SmallString<256> Path(Filename);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001092 llvm::sys::fs::make_absolute(Path);
Vedant Kumard04929d2016-07-18 22:32:02 +00001093 llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true);
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001094 return Path.str().str();
1095}
1096
1097} // end anonymous namespace
1098
Justin Bognera432d172015-02-03 00:20:24 +00001099static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1100 ArrayRef<CounterExpression> Expressions,
1101 ArrayRef<CounterMappingRegion> Regions) {
1102 OS << FunctionName << ":\n";
1103 CounterMappingContext Ctx(Expressions);
1104 for (const auto &R : Regions) {
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001105 OS.indent(2);
1106 switch (R.Kind) {
1107 case CounterMappingRegion::CodeRegion:
1108 break;
1109 case CounterMappingRegion::ExpansionRegion:
1110 OS << "Expansion,";
1111 break;
1112 case CounterMappingRegion::SkippedRegion:
1113 OS << "Skipped,";
1114 break;
1115 }
1116
Justin Bogner4da909b2015-02-03 21:35:49 +00001117 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1118 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
Justin Bognerf69dc342015-01-23 23:46:13 +00001119 Ctx.dump(R.Count, OS);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001120 if (R.Kind == CounterMappingRegion::ExpansionRegion)
Justin Bogner4da909b2015-02-03 21:35:49 +00001121 OS << " (Expanded file = " << R.ExpandedFileID << ")";
1122 OS << "\n";
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001123 }
1124}
1125
Alex Lorenzee024992014-08-04 18:41:51 +00001126void CoverageMappingModuleGen::addFunctionMappingRecord(
Xinliang David Li2129ae52016-01-07 20:05:55 +00001127 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
Xinliang David Li848da132016-01-19 00:49:06 +00001128 const std::string &CoverageMapping, bool IsUsed) {
Alex Lorenzee024992014-08-04 18:41:51 +00001129 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
Alex Lorenzee024992014-08-04 18:41:51 +00001130 if (!FunctionRecordTy) {
Xinliang David Li2129ae52016-01-07 20:05:55 +00001131#define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
Xinliang David Lia026a432015-11-05 05:46:39 +00001132 llvm::Type *FunctionRecordTypes[] = {
1133 #include "llvm/ProfileData/InstrProfData.inc"
1134 };
Alex Lorenzee024992014-08-04 18:41:51 +00001135 FunctionRecordTy =
Justin Bogner4dc5adc2015-07-02 20:47:25 +00001136 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1137 /*isPacked=*/true);
Alex Lorenzee024992014-08-04 18:41:51 +00001138 }
1139
Xinliang David Lia026a432015-11-05 05:46:39 +00001140 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
Alex Lorenzee024992014-08-04 18:41:51 +00001141 llvm::Constant *FunctionRecordVals[] = {
Xinliang David Lia026a432015-11-05 05:46:39 +00001142 #include "llvm/ProfileData/InstrProfData.inc"
1143 };
Alex Lorenzee024992014-08-04 18:41:51 +00001144 FunctionRecords.push_back(llvm::ConstantStruct::get(
1145 FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
Xinliang David Li848da132016-01-19 00:49:06 +00001146 if (!IsUsed)
Xinliang David Li2129ae52016-01-07 20:05:55 +00001147 FunctionNames.push_back(
1148 llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
Vedant Kumarca3326c2016-01-21 19:25:35 +00001149 CoverageMappings.push_back(CoverageMapping);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001150
1151 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1152 // Dump the coverage mapping data for this function by decoding the
1153 // encoded data. This allows us to dump the mapping regions which were
1154 // also processed by the CoverageMappingWriter which performs
1155 // additional minimization operations such as reducing the number of
1156 // expressions.
1157 std::vector<StringRef> Filenames;
1158 std::vector<CounterExpression> Expressions;
1159 std::vector<CounterMappingRegion> Regions;
Jordan Roseb31ee812016-11-07 17:28:04 +00001160 llvm::SmallVector<std::string, 16> FilenameStrs;
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001161 llvm::SmallVector<StringRef, 16> FilenameRefs;
Jordan Roseb31ee812016-11-07 17:28:04 +00001162 FilenameStrs.resize(FileEntries.size());
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001163 FilenameRefs.resize(FileEntries.size());
Jordan Roseb31ee812016-11-07 17:28:04 +00001164 for (const auto &Entry : FileEntries) {
1165 auto I = Entry.second;
1166 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1167 FilenameRefs[I] = FilenameStrs[I];
1168 }
Justin Bognera432d172015-02-03 00:20:24 +00001169 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1170 Expressions, Regions);
1171 if (Reader.read())
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001172 return;
Xinliang David Lia026a432015-11-05 05:46:39 +00001173 dump(llvm::outs(), NameValue, Expressions, Regions);
Alex Lorenzf2cf38e2014-08-08 23:41:24 +00001174 }
Alex Lorenzee024992014-08-04 18:41:51 +00001175}
1176
1177void CoverageMappingModuleGen::emit() {
1178 if (FunctionRecords.empty())
1179 return;
1180 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1181 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1182
1183 // Create the filenames and merge them with coverage mappings
1184 llvm::SmallVector<std::string, 16> FilenameStrs;
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001185 llvm::SmallVector<StringRef, 16> FilenameRefs;
Alex Lorenzee024992014-08-04 18:41:51 +00001186 FilenameStrs.resize(FileEntries.size());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001187 FilenameRefs.resize(FileEntries.size());
Alex Lorenzee024992014-08-04 18:41:51 +00001188 for (const auto &Entry : FileEntries) {
Alex Lorenzee024992014-08-04 18:41:51 +00001189 auto I = Entry.second;
Vedant Kumar14f8fb62016-07-18 21:01:27 +00001190 FilenameStrs[I] = normalizeFilename(Entry.first->getName());
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001191 FilenameRefs[I] = FilenameStrs[I];
Alex Lorenzee024992014-08-04 18:41:51 +00001192 }
1193
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001194 std::string FilenamesAndCoverageMappings;
1195 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
1196 CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1197 std::string RawCoverageMappings =
1198 llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
1199 OS << RawCoverageMappings;
1200 size_t CoverageMappingSize = RawCoverageMappings.size();
1201 size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
1202 // Append extra zeroes if necessary to ensure that the size of the filenames
1203 // and coverage mappings is a multiple of 8.
1204 if (size_t Rem = OS.str().size() % 8) {
1205 CoverageMappingSize += 8 - Rem;
1206 for (size_t I = 0, S = 8 - Rem; I < S; ++I)
1207 OS << '\0';
Alex Lorenzee024992014-08-04 18:41:51 +00001208 }
1209 auto *FilenamesAndMappingsVal =
Vedant Kumar9e324dd2016-06-29 05:33:09 +00001210 llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
Alex Lorenzee024992014-08-04 18:41:51 +00001211
1212 // Create the deferred function records array
1213 auto RecordsTy =
1214 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
1215 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
1216
Xinliang David Li20b188c2016-01-03 19:25:54 +00001217 llvm::Type *CovDataHeaderTypes[] = {
1218#define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1219#include "llvm/ProfileData/InstrProfData.inc"
1220 };
1221 auto CovDataHeaderTy =
1222 llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1223 llvm::Constant *CovDataHeaderVals[] = {
1224#define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1225#include "llvm/ProfileData/InstrProfData.inc"
1226 };
1227 auto CovDataHeaderVal = llvm::ConstantStruct::get(
1228 CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1229
Alex Lorenzee024992014-08-04 18:41:51 +00001230 // Create the coverage data record
Xinliang David Li20b188c2016-01-03 19:25:54 +00001231 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
1232 FilenamesAndMappingsVal->getType()};
Alex Lorenzee024992014-08-04 18:41:51 +00001233 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001234 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
1235 FilenamesAndMappingsVal};
Alex Lorenzee024992014-08-04 18:41:51 +00001236 auto CovDataVal =
1237 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
Xinliang David Li20b188c2016-01-03 19:25:54 +00001238 auto CovData = new llvm::GlobalVariable(
1239 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
1240 CovDataVal, llvm::getCoverageMappingVarName());
Alex Lorenzee024992014-08-04 18:41:51 +00001241
1242 CovData->setSection(getCoverageSection(CGM));
1243 CovData->setAlignment(8);
1244
1245 // Make sure the data doesn't get deleted.
1246 CGM.addUsedGlobal(CovData);
Xinliang David Li2129ae52016-01-07 20:05:55 +00001247 // Create the deferred function records array
1248 if (!FunctionNames.empty()) {
1249 auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1250 FunctionNames.size());
1251 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1252 // This variable will *NOT* be emitted to the object file. It is used
1253 // to pass the list of names referenced to codegen.
1254 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1255 llvm::GlobalValue::InternalLinkage, NamesArrVal,
Xinliang David Li7077f0a2016-01-20 00:24:52 +00001256 llvm::getCoverageUnusedNamesVarName());
Xinliang David Li2129ae52016-01-07 20:05:55 +00001257 }
Alex Lorenzee024992014-08-04 18:41:51 +00001258}
1259
1260unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1261 auto It = FileEntries.find(File);
1262 if (It != FileEntries.end())
1263 return It->second;
1264 unsigned FileID = FileEntries.size();
1265 FileEntries.insert(std::make_pair(File, FileID));
1266 return FileID;
1267}
1268
1269void CoverageMappingGen::emitCounterMapping(const Decl *D,
1270 llvm::raw_ostream &OS) {
1271 assert(CounterMap);
Justin Bognere5ee6c52014-10-02 16:44:01 +00001272 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
Alex Lorenzee024992014-08-04 18:41:51 +00001273 Walker.VisitDecl(D);
1274 Walker.write(OS);
1275}
1276
1277void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1278 llvm::raw_ostream &OS) {
1279 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1280 Walker.VisitDecl(D);
1281 Walker.write(OS);
1282}