Debian Codegraph @

clang/lib/CodeGen/CoverageMappingGen.cpp

raw
1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Instrumentation-based code coverage mapping generator
10 //
11 //===----------------------------------------------------------------------===//
12
13 #include "CoverageMappingGen.h"
14 #include "CodeGenFunction.h"
15 #include "CodeGenPGO.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/DiagnosticFrontend.h"
19 #include "clang/Lex/Lexer.h"
20 #include "llvm/ADT/DenseSet.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
24 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
25 #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
26 #include "llvm/Support/FileSystem.h"
27 #include "llvm/Support/Path.h"
28 #include <optional>
29
30 // This selects the coverage mapping format defined when `InstrProfData.inc`
31 // is textually included.
32 #define COVMAP_V3
33
34 namespace llvm {
35 cl::opt<bool>
36 EnableSingleByteCoverage("enable-single-byte-coverage",
37 llvm::cl::ZeroOrMore,
38 llvm::cl::desc("Enable single byte coverage"),
39 llvm::cl::Hidden, llvm::cl::init(false));
40 } // namespace llvm
41
42 static llvm::cl::opt<bool> EmptyLineCommentCoverage(
43 "emptyline-comment-coverage",
44 llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
45 "disable it on test)"),
46 llvm::cl::init(true), llvm::cl::Hidden);
47
48 namespace llvm::coverage {
49 cl::opt<bool> SystemHeadersCoverage(
50 "system-headers-coverage",
51 cl::desc("Enable collecting coverage from system headers"), cl::init(false),
52 cl::Hidden);
53 }
54
55 using namespace clang;
56 using namespace CodeGen;
57 using namespace llvm::coverage;
58
59 CoverageSourceInfo *
60 CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
61 CoverageSourceInfo *CoverageInfo =
62 new CoverageSourceInfo(PP.getSourceManager());
63 PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
64 if (EmptyLineCommentCoverage) {
65 PP.addCommentHandler(CoverageInfo);
66 PP.setEmptylineHandler(CoverageInfo);
67 PP.setPreprocessToken(true);
68 PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
69 // Update previous token location.
70 CoverageInfo->PrevTokLoc = Tok.getLocation();
71 if (Tok.getKind() != clang::tok::eod)
72 CoverageInfo->updateNextTokLoc(Tok.getLocation());
73 });
74 }
75 return CoverageInfo;
76 }
77
78 void CoverageSourceInfo::AddSkippedRange(SourceRange Range,
79 SkippedRange::Kind RangeKind) {
80 if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
81 PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
82 SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
83 Range.getBegin()))
84 SkippedRanges.back().Range.setEnd(Range.getEnd());
85 else
86 SkippedRanges.push_back({Range, RangeKind, PrevTokLoc});
87 }
88
89 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
90 AddSkippedRange(Range, SkippedRange::PPIfElse);
91 }
92
93 void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
94 AddSkippedRange(Range, SkippedRange::EmptyLine);
95 }
96
97 bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
98 AddSkippedRange(Range, SkippedRange::Comment);
99 return false;
100 }
101
102 void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
103 if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
104 SkippedRanges.back().NextTokLoc = Loc;
105 }
106
107 namespace {
108 /// A region of source code that can be mapped to a counter.
109 class SourceMappingRegion {
110 /// Primary Counter that is also used for Branch Regions for "True" branches.
111 Counter Count;
112
113 /// Secondary Counter used for Branch Regions for "False" branches.
114 std::optional<Counter> FalseCount;
115
116 /// Parameters used for Modified Condition/Decision Coverage
117 mcdc::Parameters MCDCParams;
118
119 /// The region's starting location.
120 std::optional<SourceLocation> LocStart;
121
122 /// The region's ending location.
123 std::optional<SourceLocation> LocEnd;
124
125 /// Whether this region is a gap region. The count from a gap region is set
126 /// as the line execution count if there are no other regions on the line.
127 bool GapRegion;
128
129 /// Whetever this region is skipped ('if constexpr' or 'if consteval' untaken
130 /// branch, or anything skipped but not empty line / comments)
131 bool SkippedRegion;
132
133 public:
134 SourceMappingRegion(Counter Count, std::optional<SourceLocation> LocStart,
135 std::optional<SourceLocation> LocEnd,
136 bool GapRegion = false)
137 : Count(Count), LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
138 SkippedRegion(false) {}
139
140 SourceMappingRegion(Counter Count, std::optional<Counter> FalseCount,
141 mcdc::Parameters MCDCParams,
142 std::optional<SourceLocation> LocStart,
143 std::optional<SourceLocation> LocEnd,
144 bool GapRegion = false)
145 : Count(Count), FalseCount(FalseCount), MCDCParams(MCDCParams),
146 LocStart(LocStart), LocEnd(LocEnd), GapRegion(GapRegion),
147 SkippedRegion(false) {}
148
149 SourceMappingRegion(mcdc::Parameters MCDCParams,
150 std::optional<SourceLocation> LocStart,
151 std::optional<SourceLocation> LocEnd)
152 : MCDCParams(MCDCParams), LocStart(LocStart), LocEnd(LocEnd),
153 GapRegion(false), SkippedRegion(false) {}
154
155 const Counter &getCounter() const { return Count; }
156
157 const Counter &getFalseCounter() const {
158 assert(FalseCount && "Region has no alternate counter");
159 return *FalseCount;
160 }
161
162 void setCounter(Counter C) { Count = C; }
163
164 bool hasStartLoc() const { return LocStart.has_value(); }
165
166 void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
167
168 SourceLocation getBeginLoc() const {
169 assert(LocStart && "Region has no start location");
170 return *LocStart;
171 }
172
173 bool hasEndLoc() const { return LocEnd.has_value(); }
174
175 void setEndLoc(SourceLocation Loc) {
176 assert(Loc.isValid() && "Setting an invalid end location");
177 LocEnd = Loc;
178 }
179
180 SourceLocation getEndLoc() const {
181 assert(LocEnd && "Region has no end location");
182 return *LocEnd;
183 }
184
185 bool isGap() const { return GapRegion; }
186
187 void setGap(bool Gap) { GapRegion = Gap; }
188
189 bool isSkipped() const { return SkippedRegion; }
190
191 void setSkipped(bool Skipped) { SkippedRegion = Skipped; }
192
193 bool isBranch() const { return FalseCount.has_value(); }
194
195 bool isMCDCBranch() const {
196 return std::holds_alternative<mcdc::BranchParameters>(MCDCParams);
197 }
198
199 const auto &getMCDCBranchParams() const {
200 return mcdc::getParams<const mcdc::BranchParameters>(MCDCParams);
201 }
202
203 bool isMCDCDecision() const {
204 return std::holds_alternative<mcdc::DecisionParameters>(MCDCParams);
205 }
206
207 const auto &getMCDCDecisionParams() const {
208 return mcdc::getParams<const mcdc::DecisionParameters>(MCDCParams);
209 }
210
211 const mcdc::Parameters &getMCDCParams() const { return MCDCParams; }
212
213 void resetMCDCParams() { MCDCParams = mcdc::Parameters(); }
214 };
215
216 /// Spelling locations for the start and end of a source region.
217 struct SpellingRegion {
218 /// The line where the region starts.
219 unsigned LineStart;
220
221 /// The column where the region starts.
222 unsigned ColumnStart;
223
224 /// The line where the region ends.
225 unsigned LineEnd;
226
227 /// The column where the region ends.
228 unsigned ColumnEnd;
229
230 SpellingRegion(SourceManager &SM, SourceLocation LocStart,
231 SourceLocation LocEnd) {
232 LineStart = SM.getSpellingLineNumber(LocStart);
233 ColumnStart = SM.getSpellingColumnNumber(LocStart);
234 LineEnd = SM.getSpellingLineNumber(LocEnd);
235 ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
236 }
237
238 SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
239 : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
240
241 /// Check if the start and end locations appear in source order, i.e
242 /// top->bottom, left->right.
243 bool isInSourceOrder() const {
244 return (LineStart < LineEnd) ||
245 (LineStart == LineEnd && ColumnStart <= ColumnEnd);
246 }
247 };
248
249 /// Provides the common functionality for the different
250 /// coverage mapping region builders.
251 class CoverageMappingBuilder {
252 public:
253 CoverageMappingModuleGen &CVM;
254 SourceManager &SM;
255 const LangOptions &LangOpts;
256
257 private:
258 /// Map of clang's FileIDs to IDs used for coverage mapping.
259 llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
260 FileIDMapping;
261
262 public:
263 /// The coverage mapping regions for this function
264 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
265 /// The source mapping regions for this function.
266 std::vector<SourceMappingRegion> SourceRegions;
267
268 /// A set of regions which can be used as a filter.
269 ///
270 /// It is produced by emitExpansionRegions() and is used in
271 /// emitSourceRegions() to suppress producing code regions if
272 /// the same area is covered by expansion regions.
273 typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
274 SourceRegionFilter;
275
276 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
277 const LangOptions &LangOpts)
278 : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
279
280 /// Return the precise end location for the given token.
281 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
282 // We avoid getLocForEndOfToken here, because it doesn't do what we want for
283 // macro locations, which we just treat as expanded files.
284 unsigned TokLen =
285 Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
286 return Loc.getLocWithOffset(TokLen);
287 }
288
289 /// Return the start location of an included file or expanded macro.
290 SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
291 if (Loc.isMacroID())
292 return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
293 return SM.getLocForStartOfFile(SM.getFileID(Loc));
294 }
295
296 /// Return the end location of an included file or expanded macro.
297 SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
298 if (Loc.isMacroID())
299 return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
300 SM.getFileOffset(Loc));
301 return SM.getLocForEndOfFile(SM.getFileID(Loc));
302 }
303
304 /// Find out where a macro is expanded. If the immediate result is a
305 /// <scratch space>, keep looking until the result isn't. Return a pair of
306 /// \c SourceLocation. The first object is always the begin sloc of found
307 /// result. The second should be checked by the caller: if it has value, it's
308 /// the end sloc of the found result. Otherwise the while loop didn't get
309 /// executed, which means the location wasn't changed and the caller has to
310 /// learn the end sloc from somewhere else.
311 std::pair<SourceLocation, std::optional<SourceLocation>>
312 getNonScratchExpansionLoc(SourceLocation Loc) {
313 std::optional<SourceLocation> EndLoc = std::nullopt;
314 while (Loc.isMacroID() &&
315 SM.isWrittenInScratchSpace(SM.getSpellingLoc(Loc))) {
316 auto ExpansionRange = SM.getImmediateExpansionRange(Loc);
317 Loc = ExpansionRange.getBegin();
318 EndLoc = ExpansionRange.getEnd();
319 }
320 return std::make_pair(Loc, EndLoc);
321 }
322
323 /// Find out where the current file is included or macro is expanded. If
324 /// \c AcceptScratch is set to false, keep looking for expansions until the
325 /// found sloc is not a <scratch space>.
326 SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc,
327 bool AcceptScratch = true) {
328 if (!Loc.isMacroID())
329 return SM.getIncludeLoc(SM.getFileID(Loc));
330 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
331 if (AcceptScratch)
332 return Loc;
333 return getNonScratchExpansionLoc(Loc).first;
334 }
335
336 /// Return true if \c Loc is a location in a built-in macro.
337 bool isInBuiltin(SourceLocation Loc) {
338 return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
339 }
340
341 /// Check whether \c Loc is included or expanded from \c Parent.
342 bool isNestedIn(SourceLocation Loc, FileID Parent) {
343 do {
344 Loc = getIncludeOrExpansionLoc(Loc);
345 if (Loc.isInvalid())
346 return false;
347 } while (!SM.isInFileID(Loc, Parent));
348 return true;
349 }
350
351 /// Get the start of \c S ignoring macro arguments and builtin macros.
352 SourceLocation getStart(const Stmt *S) {
353 SourceLocation Loc = S->getBeginLoc();
354 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
355 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
356 return Loc;
357 }
358
359 /// Get the end of \c S ignoring macro arguments and builtin macros.
360 SourceLocation getEnd(const Stmt *S) {
361 SourceLocation Loc = S->getEndLoc();
362 while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
363 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
364 return getPreciseTokenLocEnd(Loc);
365 }
366
367 /// Find the set of files we have regions for and assign IDs
368 ///
369 /// Fills \c Mapping with the virtual file mapping needed to write out
370 /// coverage and collects the necessary file information to emit source and
371 /// expansion regions.
372 void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
373 FileIDMapping.clear();
374
375 llvm::SmallSet<FileID, 8> Visited;
376 SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
377 for (auto &Region : SourceRegions) {
378 SourceLocation Loc = Region.getBeginLoc();
379
380 // Replace Region with its definition if it is in <scratch space>.
381 auto NonScratchExpansionLoc = getNonScratchExpansionLoc(Loc);
382 auto EndLoc = NonScratchExpansionLoc.second;
383 if (EndLoc.has_value()) {
384 Loc = NonScratchExpansionLoc.first;
385 Region.setStartLoc(Loc);
386 Region.setEndLoc(EndLoc.value());
387 }
388
389 // For regions whose spelling is in a system header, remap macro
390 // tokens to their user-code call site so coverage is attributed to
391 // the user expression. Drop anything still in a system header
392 // (e.g. a plain FileID into a -isystem .def file).
393 if (!SystemHeadersCoverage &&
394 SM.isInSystemHeader(SM.getSpellingLoc(Loc))) {
395 if (Loc.isMacroID()) {
396 auto BeginLoc = SM.getSpellingLoc(Loc);
397 auto EndLoc = SM.getSpellingLoc(Region.getEndLoc());
398 if (SM.isWrittenInSameFile(BeginLoc, EndLoc)) {
399 Loc = SM.getFileLoc(Loc);
400 Region.setStartLoc(Loc);
401 Region.setEndLoc(SM.getFileLoc(Region.getEndLoc()));
402 }
403 }
404 if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
405 continue;
406 }
407
408 FileID File = SM.getFileID(Loc);
409 if (!Visited.insert(File).second)
410 continue;
411
412 unsigned Depth = 0;
413 for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
414 Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
415 ++Depth;
416 FileLocs.push_back(std::make_pair(Loc, Depth));
417 }
418 llvm::stable_sort(FileLocs, llvm::less_second());
419
420 for (const auto &FL : FileLocs) {
421 SourceLocation Loc = FL.first;
422 FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
423 auto Entry = SM.getFileEntryRefForID(SpellingFile);
424 if (!Entry)
425 continue;
426
427 FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
428 Mapping.push_back(CVM.getFileID(*Entry));
429 }
430 }
431
432 /// Get the coverage mapping file ID for \c Loc.
433 ///
434 /// If such file id doesn't exist, return std::nullopt.
435 std::optional<unsigned> getCoverageFileID(SourceLocation Loc) {
436 auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
437 if (Mapping != FileIDMapping.end())
438 return Mapping->second.first;
439 return std::nullopt;
440 }
441
442 /// This shrinks the skipped range if it spans a line that contains a
443 /// non-comment token. If shrinking the skipped range would make it empty,
444 /// this returns std::nullopt.
445 /// Note this function can potentially be expensive because
446 /// getSpellingLineNumber uses getLineNumber, which is expensive.
447 std::optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
448 SourceLocation LocStart,
449 SourceLocation LocEnd,
450 SourceLocation PrevTokLoc,
451 SourceLocation NextTokLoc) {
452 SpellingRegion SR{SM, LocStart, LocEnd};
453 SR.ColumnStart = 1;
454 if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
455 SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
456 SR.LineStart++;
457 if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
458 SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
459 SR.LineEnd--;
460 SR.ColumnEnd++;
461 }
462 if (SR.isInSourceOrder())
463 return SR;
464 return std::nullopt;
465 }
466
467 /// Gather all the regions that were skipped by the preprocessor
468 /// using the constructs like #if or comments.
469 void gatherSkippedRegions() {
470 /// An array of the minimum lineStarts and the maximum lineEnds
471 /// for mapping regions from the appropriate source files.
472 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
473 FileLineRanges.resize(
474 FileIDMapping.size(),
475 std::make_pair(std::numeric_limits<unsigned>::max(), 0));
476 for (const auto &R : MappingRegions) {
477 FileLineRanges[R.FileID].first =
478 std::min(FileLineRanges[R.FileID].first, R.LineStart);
479 FileLineRanges[R.FileID].second =
480 std::max(FileLineRanges[R.FileID].second, R.LineEnd);
481 }
482
483 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
484 for (auto &I : SkippedRanges) {
485 SourceRange Range = I.Range;
486 auto LocStart = Range.getBegin();
487 auto LocEnd = Range.getEnd();
488 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
489 "region spans multiple files");
490
491 auto CovFileID = getCoverageFileID(LocStart);
492 if (!CovFileID)
493 continue;
494 std::optional<SpellingRegion> SR;
495 if (I.isComment())
496 SR = adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc,
497 I.NextTokLoc);
498 else if (I.isPPIfElse() || I.isEmptyLine())
499 SR = {SM, LocStart, LocEnd};
500
501 if (!SR)
502 continue;
503 auto Region = CounterMappingRegion::makeSkipped(
504 *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
505 SR->ColumnEnd);
506 // Make sure that we only collect the regions that are inside
507 // the source code of this function.
508 if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
509 Region.LineEnd <= FileLineRanges[*CovFileID].second)
510 MappingRegions.push_back(Region);
511 }
512 }
513
514 /// Generate the coverage counter mapping regions from collected
515 /// source regions.
516 void emitSourceRegions(const SourceRegionFilter &Filter) {
517 for (const auto &Region : SourceRegions) {
518 assert(Region.hasEndLoc() && "incomplete region");
519
520 SourceLocation LocStart = Region.getBeginLoc();
521 assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
522
523 // Ignore regions from system headers unless collecting coverage from
524 // system headers is explicitly enabled.
525 if (!SystemHeadersCoverage &&
526 SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) {
527 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
528 "Don't suppress the condition in system headers");
529 continue;
530 }
531
532 auto CovFileID = getCoverageFileID(LocStart);
533 // Ignore regions that don't have a file, such as builtin macros.
534 if (!CovFileID) {
535 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
536 "Don't suppress the condition in non-file regions");
537 continue;
538 }
539
540 SourceLocation LocEnd = Region.getEndLoc();
541 assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
542 "region spans multiple files");
543
544 // Don't add code regions for the area covered by expansion regions.
545 // This not only suppresses redundant regions, but sometimes prevents
546 // creating regions with wrong counters if, for example, a statement's
547 // body ends at the end of a nested macro.
548 if (Filter.count(std::make_pair(LocStart, LocEnd))) {
549 assert(!Region.isMCDCBranch() && !Region.isMCDCDecision() &&
550 "Don't suppress the condition");
551 continue;
552 }
553
554 // Find the spelling locations for the mapping region.
555 SpellingRegion SR{SM, LocStart, LocEnd};
556 assert(SR.isInSourceOrder() && "region start and end out of order");
557
558 if (Region.isGap()) {
559 MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
560 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
561 SR.LineEnd, SR.ColumnEnd));
562 } else if (Region.isSkipped()) {
563 MappingRegions.push_back(CounterMappingRegion::makeSkipped(
564 *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd,
565 SR.ColumnEnd));
566 } else if (Region.isBranch()) {
567 MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
568 Region.getCounter(), Region.getFalseCounter(), *CovFileID,
569 SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd,
570 Region.getMCDCParams()));
571 } else if (Region.isMCDCDecision()) {
572 MappingRegions.push_back(CounterMappingRegion::makeDecisionRegion(
573 Region.getMCDCDecisionParams(), *CovFileID, SR.LineStart,
574 SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
575 } else {
576 MappingRegions.push_back(CounterMappingRegion::makeRegion(
577 Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
578 SR.LineEnd, SR.ColumnEnd));
579 }
580 }
581 }
582
583 /// Generate expansion regions for each virtual file we've seen.
584 SourceRegionFilter emitExpansionRegions() {
585 SourceRegionFilter Filter;
586 for (const auto &FM : FileIDMapping) {
587 SourceLocation ExpandedLoc = FM.second.second;
588 SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc, false);
589 if (ParentLoc.isInvalid())
590 continue;
591
592 auto ParentFileID = getCoverageFileID(ParentLoc);
593 if (!ParentFileID)
594 continue;
595 auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
596 assert(ExpandedFileID && "expansion in uncovered file");
597
598 SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
599 assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
600 "region spans multiple files");
601 Filter.insert(std::make_pair(ParentLoc, LocEnd));
602
603 SpellingRegion SR{SM, ParentLoc, LocEnd};
604 assert(SR.isInSourceOrder() && "region start and end out of order");
605 MappingRegions.push_back(CounterMappingRegion::makeExpansion(
606 *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
607 SR.LineEnd, SR.ColumnEnd));
608 }
609 return Filter;
610 }
611 };
612
613 /// Creates unreachable coverage regions for the functions that
614 /// are not emitted.
615 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
616 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
617 const LangOptions &LangOpts)
618 : CoverageMappingBuilder(CVM, SM, LangOpts) {}
619
620 void VisitDecl(const Decl *D) {
621 if (!D->hasBody())
622 return;
623 auto Body = D->getBody();
624 SourceLocation Start = getStart(Body);
625 SourceLocation End = getEnd(Body);
626 if (!SM.isWrittenInSameFile(Start, End)) {
627 // Walk up to find the common ancestor.
628 // Correct the locations accordingly.
629 FileID StartFileID = SM.getFileID(Start);
630 FileID EndFileID = SM.getFileID(End);
631 while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
632 Start = getIncludeOrExpansionLoc(Start);
633 assert(Start.isValid() &&
634 "Declaration start location not nested within a known region");
635 StartFileID = SM.getFileID(Start);
636 }
637 while (StartFileID != EndFileID) {
638 End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
639 assert(End.isValid() &&
640 "Declaration end location not nested within a known region");
641 EndFileID = SM.getFileID(End);
642 }
643 }
644 SourceRegions.emplace_back(Counter(), Start, End);
645 }
646
647 /// Write the mapping data to the output stream
648 void write(llvm::raw_ostream &OS) {
649 SmallVector<unsigned, 16> FileIDMapping;
650 gatherFileIDs(FileIDMapping);
651 emitSourceRegions(SourceRegionFilter());
652
653 if (MappingRegions.empty())
654 return;
655
656 CoverageMappingWriter Writer(FileIDMapping, {}, MappingRegions);
657 Writer.write(OS);
658 }
659 };
660
661 /// A wrapper object for maintaining stacks to track the resursive AST visitor
662 /// walks for the purpose of assigning IDs to leaf-level conditions measured by
663 /// MC/DC. The object is created with a reference to the MCDCBitmapMap that was
664 /// created during the initial AST walk. The presence of a bitmap associated
665 /// with a boolean expression (top-level logical operator nest) indicates that
666 /// the boolean expression qualified for MC/DC. The resulting condition IDs
667 /// are preserved in a map reference that is also provided during object
668 /// creation.
669 struct MCDCCoverageBuilder {
670
671 /// The AST walk recursively visits nested logical-AND or logical-OR binary
672 /// operator nodes and then visits their LHS and RHS children nodes. As this
673 /// happens, the algorithm will assign IDs to each operator's LHS and RHS side
674 /// as the walk moves deeper into the nest. At each level of the recursive
675 /// nest, the LHS and RHS may actually correspond to larger subtrees (not
676 /// leaf-conditions). If this is the case, when that node is visited, the ID
677 /// assigned to the subtree is re-assigned to its LHS, and a new ID is given
678 /// to its RHS. At the end of the walk, all leaf-level conditions will have a
679 /// unique ID -- keep in mind that the final set of IDs may not be in
680 /// numerical order from left to right.
681 ///
682 /// Example: "x = (A && B) || (C && D) || (D && F)"
683 ///
684 /// Visit Depth1:
685 /// (A && B) || (C && D) || (D && F)
686 /// ^-------LHS--------^ ^-RHS--^
687 /// ID=1 ID=2
688 ///
689 /// Visit LHS-Depth2:
690 /// (A && B) || (C && D)
691 /// ^-LHS--^ ^-RHS--^
692 /// ID=1 ID=3
693 ///
694 /// Visit LHS-Depth3:
695 /// (A && B)
696 /// LHS RHS
697 /// ID=1 ID=4
698 ///
699 /// Visit RHS-Depth3:
700 /// (C && D)
701 /// LHS RHS
702 /// ID=3 ID=5
703 ///
704 /// Visit RHS-Depth2: (D && F)
705 /// LHS RHS
706 /// ID=2 ID=6
707 ///
708 /// Visit Depth1:
709 /// (A && B) || (C && D) || (D && F)
710 /// ID=1 ID=4 ID=3 ID=5 ID=2 ID=6
711 ///
712 /// A node ID of '0' always means MC/DC isn't being tracked.
713 ///
714 /// As the AST walk proceeds recursively, the algorithm will also use a stack
715 /// to track the IDs of logical-AND and logical-OR operations on the RHS so
716 /// that it can be determined which nodes are executed next, depending on how
717 /// a LHS or RHS of a logical-AND or logical-OR is evaluated. This
718 /// information relies on the assigned IDs and are embedded within the
719 /// coverage region IDs of each branch region associated with a leaf-level
720 /// condition. This information helps the visualization tool reconstruct all
721 /// possible test vectors for the purposes of MC/DC analysis. If a "next" node
722 /// ID is '0', it means it's the end of the test vector. The following rules
723 /// are used:
724 ///
725 /// For logical-AND ("LHS && RHS"):
726 /// - If LHS is TRUE, execution goes to the RHS node.
727 /// - If LHS is FALSE, execution goes to the LHS node of the next logical-OR.
728 /// If that does not exist, execution exits (ID == 0).
729 ///
730 /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
731 /// If that does not exist, execution exits (ID == 0).
732 /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
733 /// If that does not exist, execution exits (ID == 0).
734 ///
735 /// For logical-OR ("LHS || RHS"):
736 /// - If LHS is TRUE, execution goes to the LHS node of the next logical-AND.
737 /// If that does not exist, execution exits (ID == 0).
738 /// - If LHS is FALSE, execution goes to the RHS node.
739 ///
740 /// - If RHS is TRUE, execution goes to LHS node of the next logical-AND.
741 /// If that does not exist, execution exits (ID == 0).
742 /// - If RHS is FALSE, execution goes to the LHS node of the next logical-OR.
743 /// If that does not exist, execution exits (ID == 0).
744 ///
745 /// Finally, the condition IDs are also used when instrumenting the code to
746 /// indicate a unique offset into a temporary bitmap that represents the true
747 /// or false evaluation of that particular condition.
748 ///
749 /// NOTE regarding the use of CodeGenFunction::stripCond(). Even though, for
750 /// simplicity, parentheses and unary logical-NOT operators are considered
751 /// part of their underlying condition for both MC/DC and branch coverage, the
752 /// condition IDs themselves are assigned and tracked using the underlying
753 /// condition itself. This is done solely for consistency since parentheses
754 /// and logical-NOTs are ignored when checking whether the condition is
755 /// actually an instrumentable condition. This can also make debugging a bit
756 /// easier.
757
758 private:
759 CodeGenModule &CGM;
760
761 llvm::SmallVector<mcdc::ConditionIDs> DecisionStack;
762 MCDC::State &MCDCState;
763 const Stmt *DecisionStmt = nullptr;
764 mcdc::ConditionID NextID = 0;
765 bool NotMapped = false;
766
767 /// Represent a sentinel value as a pair of final decisions for the bottom
768 // of DecisionStack.
769 static constexpr mcdc::ConditionIDs DecisionStackSentinel{-1, -1};
770
771 /// Is this a logical-AND operation?
772 bool isLAnd(const BinaryOperator *E) const {
773 return E->getOpcode() == BO_LAnd;
774 }
775
776 public:
777 MCDCCoverageBuilder(CodeGenModule &CGM, MCDC::State &MCDCState)
778 : CGM(CGM), DecisionStack(1, DecisionStackSentinel),
779 MCDCState(MCDCState) {}
780
781 /// Return whether the build of the control flow map is at the top-level
782 /// (root) of a logical operator nest in a boolean expression prior to the
783 /// assignment of condition IDs.
784 bool isIdle() const { return (NextID == 0 && !NotMapped); }
785
786 /// Return whether any IDs have been assigned in the build of the control
787 /// flow map, indicating that the map is being generated for this boolean
788 /// expression.
789 bool isBuilding() const { return (NextID > 0); }
790
791 /// Set the given condition's ID.
792 void setCondID(const Expr *Cond, mcdc::ConditionID ID) {
793 MCDCState.BranchByStmt[CodeGenFunction::stripCond(Cond)] = {ID,
794 DecisionStmt};
795 }
796
797 /// Return the ID of a given condition.
798 mcdc::ConditionID getCondID(const Expr *Cond) const {
799 auto I = MCDCState.BranchByStmt.find(CodeGenFunction::stripCond(Cond));
800 if (I == MCDCState.BranchByStmt.end())
801 return -1;
802 else
803 return I->second.ID;
804 }
805
806 /// Return the LHS Decision ([0,0] if not set).
807 const mcdc::ConditionIDs &back() const { return DecisionStack.back(); }
808
809 void swapConds() {
810 if (DecisionStack.empty())
811 return;
812
813 std::swap(DecisionStack.back()[false], DecisionStack.back()[true]);
814 }
815 /// Push the binary operator statement to track the nest level and assign IDs
816 /// to the operator's LHS and RHS. The RHS may be a larger subtree that is
817 /// broken up on successive levels.
818 void pushAndAssignIDs(const BinaryOperator *E) {
819 if (!CGM.getCodeGenOpts().MCDCCoverage)
820 return;
821
822 // If binary expression is disqualified, don't do mapping.
823 if (!isBuilding() &&
824 !MCDCState.DecisionByStmt.contains(CodeGenFunction::stripCond(E)))
825 NotMapped = true;
826
827 // Don't go any further if we don't need to map condition IDs.
828 if (NotMapped)
829 return;
830
831 if (NextID == 0) {
832 DecisionStmt = E;
833 assert(MCDCState.DecisionByStmt.contains(E));
834 }
835
836 const mcdc::ConditionIDs &ParentDecision = DecisionStack.back();
837
838 // If the operator itself has an assigned ID, this means it represents a
839 // larger subtree. In this case, assign that ID to its LHS node. Its RHS
840 // will receive a new ID below. Otherwise, assign ID+1 to LHS.
841 if (MCDCState.BranchByStmt.contains(CodeGenFunction::stripCond(E)))
842 setCondID(E->getLHS(), getCondID(E));
843 else
844 setCondID(E->getLHS(), NextID++);
845
846 // Assign a ID+1 for the RHS.
847 mcdc::ConditionID RHSid = NextID++;
848 setCondID(E->getRHS(), RHSid);
849
850 // Push the LHS decision IDs onto the DecisionStack.
851 if (isLAnd(E))
852 DecisionStack.push_back({ParentDecision[false], RHSid});
853 else
854 DecisionStack.push_back({RHSid, ParentDecision[true]});
855 }
856
857 /// Pop and return the LHS Decision ([0,0] if not set).
858 mcdc::ConditionIDs pop() {
859 if (!CGM.getCodeGenOpts().MCDCCoverage || NotMapped)
860 return DecisionStackSentinel;
861
862 assert(DecisionStack.size() > 1);
863 return DecisionStack.pop_back_val();
864 }
865
866 /// Return the total number of conditions and reset the state. The number of
867 /// conditions is zero if the expression isn't mapped.
868 unsigned getTotalConditionsAndReset(const BinaryOperator *E) {
869 if (!CGM.getCodeGenOpts().MCDCCoverage)
870 return 0;
871
872 assert(!isIdle());
873 assert(DecisionStack.size() == 1);
874
875 // Reset state if not doing mapping.
876 if (NotMapped) {
877 NotMapped = false;
878 assert(NextID == 0);
879 return 0;
880 }
881
882 // Set number of conditions and reset.
883 unsigned TotalConds = NextID;
884
885 // Reset ID back to beginning.
886 NextID = 0;
887
888 return TotalConds;
889 }
890 };
891
892 /// A StmtVisitor that creates coverage mapping regions which map
893 /// from the source code locations to the PGO counters.
894 struct CounterCoverageMappingBuilder
895 : public CoverageMappingBuilder,
896 public ConstStmtVisitor<CounterCoverageMappingBuilder> {
897 /// The map of statements to count values.
898 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap;
899
900 /// Used to expand an allocatd SkipCnt to Expression with known counters.
901 /// Key: SkipCnt
902 /// Val: Subtract Expression
903 CounterExpressionBuilder::SubstMap MapToExpand;
904
905 /// Index and number for additional counters for SkipCnt.
906 unsigned NextCounterNum;
907
908 MCDC::State &MCDCState;
909
910 /// A stack of currently live regions.
911 llvm::SmallVector<SourceMappingRegion> RegionStack;
912
913 /// Set if the Expr should be handled as a leaf even if it is kind of binary
914 /// logical ops (&&, ||).
915 llvm::DenseSet<const Stmt *> LeafExprSet;
916
917 /// An object to manage MCDC regions.
918 MCDCCoverageBuilder MCDCBuilder;
919
920 CounterExpressionBuilder Builder;
921
922 /// A location in the most recently visited file or macro.
923 ///
924 /// This is used to adjust the active source regions appropriately when
925 /// expressions cross file or macro boundaries.
926 SourceLocation MostRecentLocation;
927
928 /// Whether the visitor at a terminate statement.
929 bool HasTerminateStmt = false;
930
931 /// Gap region counter after terminate statement.
932 Counter GapRegionCounter;
933
934 /// Return a counter for the subtraction of \c RHS from \c LHS
935 Counter subtractCounters(Counter LHS, Counter RHS, bool Simplify = true) {
936 assert(!llvm::EnableSingleByteCoverage &&
937 "cannot add counters when single byte coverage mode is enabled");
938 return Builder.subtract(LHS, RHS, Simplify);
939 }
940
941 /// Return a counter for the sum of \c LHS and \c RHS.
942 Counter addCounters(Counter LHS, Counter RHS, bool Simplify = true) {
943 return Builder.add(LHS, RHS, Simplify);
944 }
945
946 Counter addCounters(Counter C1, Counter C2, Counter C3,
947 bool Simplify = true) {
948 return addCounters(addCounters(C1, C2, Simplify), C3, Simplify);
949 }
950
951 /// Return the region counter for the given statement.
952 ///
953 /// This should only be called on statements that have a dedicated counter.
954 Counter getRegionCounter(const Stmt *S) {
955 return Counter::getCounter(CounterMap[S].Executed);
956 }
957
958 struct BranchCounterPair {
959 Counter Executed; ///< The Counter previously assigned.
960 Counter Skipped; ///< An expression (Parent-Executed), or equivalent to it.
961 };
962
963 /// Retrieve or assign the pair of Counter(s).
964 ///
965 /// This returns BranchCounterPair {Executed, Skipped}.
966 /// Executed is the Counter associated with S assigned by an earlier
967 /// CounterMapping pass.
968 /// Skipped may be an expression (Executed - ParentCnt) or newly
969 /// assigned Counter in EnableSingleByteCoverage, as subtract
970 /// expressions are not available in this mode.
971 ///
972 /// \param S Key to the CounterMap
973 /// \param ParentCnt The Counter representing how many times S is evaluated.
974 /// \param SkipCntForOld (To be removed later) Optional fake Counter
975 /// to override Skipped for adjustment of
976 /// expressions in the old behavior of
977 /// EnableSingleByteCoverage that is unaware of
978 /// Branch coverage.
979 BranchCounterPair
980 getBranchCounterPair(const Stmt *S, Counter ParentCnt,
981 std::optional<Counter> SkipCntForOld = std::nullopt) {
982 auto &TheMap = CounterMap[S];
983 auto ExecCnt = Counter::getCounter(TheMap.Executed);
984
985 // The old behavior of SingleByte is unaware of Branches.
986 // Will be pruned after the migration of SingleByte.
987 if (llvm::EnableSingleByteCoverage) {
988 assert(SkipCntForOld &&
989 "SingleByte must provide SkipCntForOld as a fake Skipped count.");
990 return {ExecCnt, *SkipCntForOld};
991 }
992
993 BranchCounterPair Counters = {ExecCnt,
994 Builder.subtract(ParentCnt, ExecCnt)};
995
996 if (!llvm::EnableSingleByteCoverage || !Counters.Skipped.isExpression()) {
997 assert(
998 !TheMap.Skipped.hasValue() &&
999 "SkipCnt shouldn't be allocated but refer to an existing counter.");
1000 return Counters;
1001 }
1002
1003 // Assign second if second is not assigned yet.
1004 if (!TheMap.Skipped.hasValue())
1005 TheMap.Skipped = NextCounterNum++;
1006
1007 // Replace an expression (ParentCnt - ExecCnt) with SkipCnt.
1008 Counter SkipCnt = Counter::getCounter(TheMap.Skipped);
1009 MapToExpand[SkipCnt] = Builder.subst(Counters.Skipped, MapToExpand);
1010 Counters.Skipped = SkipCnt;
1011 return Counters;
1012 }
1013
1014 bool IsCounterEqual(Counter OutCount, Counter ParentCount) {
1015 if (OutCount == ParentCount)
1016 return true;
1017
1018 // Try comaparison with pre-replaced expressions.
1019 //
1020 // For example, getBranchCounterPair(#0) returns {#1, #0 - #1}.
1021 // The sum of the pair should be equivalent to the Parent, #0.
1022 // OTOH when (#0 - #1) is replaced with the new counter #2,
1023 // The sum is (#1 + #2). If the reverse substitution #2 => (#0 - #1)
1024 // can be applied, the sum can be transformed to (#1 + (#0 - #1)).
1025 // To apply substitutions to both hand expressions, transform (LHS - RHS)
1026 // and check isZero.
1027 if (Builder.subst(Builder.subtract(OutCount, ParentCount), MapToExpand)
1028 .isZero())
1029 return true;
1030
1031 return false;
1032 }
1033
1034 /// Push a region onto the stack.
1035 ///
1036 /// Returns the index on the stack where the region was pushed. This can be
1037 /// used with popRegions to exit a "scope", ending the region that was pushed.
1038 size_t pushRegion(Counter Count,
1039 std::optional<SourceLocation> StartLoc = std::nullopt,
1040 std::optional<SourceLocation> EndLoc = std::nullopt,
1041 std::optional<Counter> FalseCount = std::nullopt,
1042 const mcdc::Parameters &BranchParams = std::monostate()) {
1043
1044 if (StartLoc && !FalseCount) {
1045 MostRecentLocation = *StartLoc;
1046 }
1047
1048 // If either of these locations is invalid, something elsewhere in the
1049 // compiler has broken.
1050 assert((!StartLoc || StartLoc->isValid()) && "Start location is not valid");
1051 assert((!EndLoc || EndLoc->isValid()) && "End location is not valid");
1052
1053 // However, we can still recover without crashing.
1054 // If either location is invalid, set it to std::nullopt to avoid
1055 // letting users of RegionStack think that region has a valid start/end
1056 // location.
1057 if (StartLoc && StartLoc->isInvalid())
1058 StartLoc = std::nullopt;
1059 if (EndLoc && EndLoc->isInvalid())
1060 EndLoc = std::nullopt;
1061 RegionStack.emplace_back(Count, FalseCount, BranchParams, StartLoc, EndLoc);
1062
1063 return RegionStack.size() - 1;
1064 }
1065
1066 size_t pushRegion(const mcdc::DecisionParameters &DecisionParams,
1067 std::optional<SourceLocation> StartLoc = std::nullopt,
1068 std::optional<SourceLocation> EndLoc = std::nullopt) {
1069
1070 RegionStack.emplace_back(DecisionParams, StartLoc, EndLoc);
1071
1072 return RegionStack.size() - 1;
1073 }
1074
1075 size_t locationDepth(SourceLocation Loc) {
1076 size_t Depth = 0;
1077 while (Loc.isValid()) {
1078 Loc = getIncludeOrExpansionLoc(Loc);
1079 Depth++;
1080 }
1081 return Depth;
1082 }
1083
1084 /// Pop regions from the stack into the function's list of regions.
1085 ///
1086 /// Adds all regions from \c ParentIndex to the top of the stack to the
1087 /// function's \c SourceRegions.
1088 void popRegions(size_t ParentIndex) {
1089 assert(RegionStack.size() >= ParentIndex && "parent not in stack");
1090 while (RegionStack.size() > ParentIndex) {
1091 SourceMappingRegion &Region = RegionStack.back();
1092 if (Region.hasStartLoc() &&
1093 (Region.hasEndLoc() || RegionStack[ParentIndex].hasEndLoc())) {
1094 SourceLocation StartLoc = Region.getBeginLoc();
1095 SourceLocation EndLoc = Region.hasEndLoc()
1096 ? Region.getEndLoc()
1097 : RegionStack[ParentIndex].getEndLoc();
1098 bool isBranch = Region.isBranch();
1099 size_t StartDepth = locationDepth(StartLoc);
1100 size_t EndDepth = locationDepth(EndLoc);
1101 while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
1102 bool UnnestStart = StartDepth >= EndDepth;
1103 bool UnnestEnd = EndDepth >= StartDepth;
1104 if (UnnestEnd) {
1105 // The region ends in a nested file or macro expansion. If the
1106 // region is not a branch region, create a separate region for each
1107 // expansion, and for all regions, update the EndLoc. Branch
1108 // regions should not be split in order to keep a straightforward
1109 // correspondance between the region and its associated branch
1110 // condition, even if the condition spans multiple depths.
1111 SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
1112 assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
1113
1114 if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
1115 SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
1116 EndLoc);
1117
1118 EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
1119 if (EndLoc.isInvalid())
1120 llvm::report_fatal_error(
1121 "File exit not handled before popRegions");
1122 EndDepth--;
1123 }
1124 if (UnnestStart) {
1125 // The region ends in a nested file or macro expansion. If the
1126 // region is not a branch region, create a separate region for each
1127 // expansion, and for all regions, update the StartLoc. Branch
1128 // regions should not be split in order to keep a straightforward
1129 // correspondance between the region and its associated branch
1130 // condition, even if the condition spans multiple depths.
1131 SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
1132 assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
1133
1134 if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
1135 SourceRegions.emplace_back(Region.getCounter(), StartLoc,
1136 NestedLoc);
1137
1138 StartLoc = getIncludeOrExpansionLoc(StartLoc);
1139 if (StartLoc.isInvalid())
1140 llvm::report_fatal_error(
1141 "File exit not handled before popRegions");
1142 StartDepth--;
1143 }
1144 }
1145 Region.setStartLoc(StartLoc);
1146 Region.setEndLoc(EndLoc);
1147
1148 if (!isBranch) {
1149 MostRecentLocation = EndLoc;
1150 // If this region happens to span an entire expansion, we need to
1151 // make sure we don't overlap the parent region with it.
1152 if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
1153 EndLoc == getEndOfFileOrMacro(EndLoc))
1154 MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
1155 }
1156
1157 assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
1158 assert(SpellingRegion(SM, Region).isInSourceOrder());
1159 SourceRegions.push_back(Region);
1160 }
1161 RegionStack.pop_back();
1162 }
1163 }
1164
1165 /// Return the currently active region.
1166 SourceMappingRegion &getRegion() {
1167 assert(!RegionStack.empty() && "statement has no region");
1168 return RegionStack.back();
1169 }
1170
1171 /// Propagate counts through the children of \p S if \p VisitChildren is true.
1172 /// Otherwise, only emit a count for \p S itself.
1173 Counter propagateCounts(Counter TopCount, const Stmt *S,
1174 bool VisitChildren = true) {
1175 SourceLocation StartLoc = getStart(S);
1176 SourceLocation EndLoc = getEnd(S);
1177 size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
1178 if (VisitChildren)
1179 Visit(S);
1180 Counter ExitCount = getRegion().getCounter();
1181 popRegions(Index);
1182
1183 // The statement may be spanned by an expansion. Make sure we handle a file
1184 // exit out of this expansion before moving to the next statement.
1185 if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
1186 MostRecentLocation = EndLoc;
1187
1188 return ExitCount;
1189 }
1190
1191 /// Create a Branch Region around an instrumentable condition for coverage
1192 /// and add it to the function's SourceRegions. A branch region tracks a
1193 /// "True" counter and a "False" counter for boolean expressions that
1194 /// result in the generation of a branch.
1195 void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt,
1196 const mcdc::ConditionIDs &Conds = {}) {
1197 // Check for NULL conditions.
1198 if (!C)
1199 return;
1200
1201 // Ensure we are an instrumentable condition (i.e. no "&&" or "||"). Push
1202 // region onto RegionStack but immediately pop it (which adds it to the
1203 // function's SourceRegions) because it doesn't apply to any other source
1204 // code other than the Condition.
1205 // With !SystemHeadersCoverage, binary logical ops in system headers may be
1206 // treated as instrumentable conditions.
1207 if (CodeGenFunction::isInstrumentedCondition(C) ||
1208 LeafExprSet.count(CodeGenFunction::stripCond(C))) {
1209 mcdc::Parameters BranchParams;
1210 mcdc::ConditionID ID = MCDCBuilder.getCondID(C);
1211 if (ID >= 0)
1212 BranchParams = mcdc::BranchParameters{ID, Conds};
1213
1214 // If a condition can fold to true or false, the corresponding branch
1215 // will be removed. Create a region with both counters hard-coded to
1216 // zero. This allows us to visualize them in a special way.
1217 // Alternatively, we can prevent any optimization done via
1218 // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
1219 // CodeGenFunction.c always returns false, but that is very heavy-handed.
1220 Expr::EvalResult Result;
1221 if (C->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext())) {
1222 if (Result.Val.getInt().getBoolValue())
1223 FalseCnt = Counter::getZero();
1224 else
1225 TrueCnt = Counter::getZero();
1226 }
1227 popRegions(
1228 pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt, BranchParams));
1229 }
1230 }
1231
1232 /// Create a Decision Region with a BitmapIdx and number of Conditions. This
1233 /// type of region "contains" branch regions, one for each of the conditions.
1234 /// The visualization tool will group everything together.
1235 void createDecisionRegion(const Expr *C,
1236 const mcdc::DecisionParameters &DecisionParams) {
1237 popRegions(pushRegion(DecisionParams, getStart(C), getEnd(C)));
1238 }
1239
1240 /// Create a Branch Region around a SwitchCase for code coverage
1241 /// and add it to the function's SourceRegions.
1242 /// Returns Counter that corresponds to SC.
1243 Counter createSwitchCaseRegion(const SwitchCase *SC, Counter ParentCount) {
1244 Counter TrueCnt = getRegionCounter(SC);
1245 Counter FalseCnt = (llvm::EnableSingleByteCoverage
1246 ? Counter::getZero() // Folded
1247 : subtractCounters(ParentCount, TrueCnt));
1248 // Push region onto RegionStack but immediately pop it (which adds it to
1249 // the function's SourceRegions) because it doesn't apply to any other
1250 // source other than the SwitchCase.
1251 popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
1252 return TrueCnt;
1253 }
1254
1255 /// Check whether a region with bounds \c StartLoc and \c EndLoc
1256 /// is already added to \c SourceRegions.
1257 bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
1258 bool isBranch = false) {
1259 return llvm::any_of(
1260 llvm::reverse(SourceRegions), [&](const SourceMappingRegion &Region) {
1261 return Region.getBeginLoc() == StartLoc &&
1262 Region.getEndLoc() == EndLoc && Region.isBranch() == isBranch;
1263 });
1264 }
1265
1266 /// Adjust the most recently visited location to \c EndLoc.
1267 ///
1268 /// This should be used after visiting any statements in non-source order.
1269 void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
1270 MostRecentLocation = EndLoc;
1271 // The code region for a whole macro is created in handleFileExit() when
1272 // it detects exiting of the virtual file of that macro. If we visited
1273 // statements in non-source order, we might already have such a region
1274 // added, for example, if a body of a loop is divided among multiple
1275 // macros. Avoid adding duplicate regions in such case.
1276 if (getRegion().hasEndLoc() &&
1277 MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
1278 isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
1279 MostRecentLocation, getRegion().isBranch()))
1280 MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
1281 }
1282
1283 /// Adjust regions and state when \c NewLoc exits a file.
1284 ///
1285 /// If moving from our most recently tracked location to \c NewLoc exits any
1286 /// files, this adjusts our current region stack and creates the file regions
1287 /// for the exited file.
1288 void handleFileExit(SourceLocation NewLoc) {
1289 if (NewLoc.isInvalid() ||
1290 SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
1291 return;
1292
1293 // If NewLoc is not in a file that contains MostRecentLocation, walk up to
1294 // find the common ancestor.
1295 SourceLocation LCA = NewLoc;
1296 FileID ParentFile = SM.getFileID(LCA);
1297 while (!isNestedIn(MostRecentLocation, ParentFile)) {
1298 LCA = getIncludeOrExpansionLoc(LCA);
1299 if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
1300 // Since there isn't a common ancestor, no file was exited. We just need
1301 // to adjust our location to the new file.
1302 MostRecentLocation = NewLoc;
1303 return;
1304 }
1305 ParentFile = SM.getFileID(LCA);
1306 }
1307
1308 llvm::SmallSet<SourceLocation, 8> StartLocs;
1309 std::optional<Counter> ParentCounter;
1310 for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
1311 if (!I.hasStartLoc())
1312 continue;
1313 SourceLocation Loc = I.getBeginLoc();
1314 if (!isNestedIn(Loc, ParentFile)) {
1315 ParentCounter = I.getCounter();
1316 break;
1317 }
1318
1319 while (!SM.isInFileID(Loc, ParentFile)) {
1320 // The most nested region for each start location is the one with the
1321 // correct count. We avoid creating redundant regions by stopping once
1322 // we've seen this region.
1323 if (StartLocs.insert(Loc).second) {
1324 if (I.isBranch())
1325 SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(),
1326 I.getMCDCParams(), Loc,
1327 getEndOfFileOrMacro(Loc), I.isBranch());
1328 else
1329 SourceRegions.emplace_back(I.getCounter(), Loc,
1330 getEndOfFileOrMacro(Loc));
1331 }
1332 Loc = getIncludeOrExpansionLoc(Loc);
1333 }
1334 I.setStartLoc(getPreciseTokenLocEnd(Loc));
1335 }
1336
1337 if (ParentCounter) {
1338 // If the file is contained completely by another region and doesn't
1339 // immediately start its own region, the whole file gets a region
1340 // corresponding to the parent.
1341 SourceLocation Loc = MostRecentLocation;
1342 while (isNestedIn(Loc, ParentFile)) {
1343 SourceLocation FileStart = getStartOfFileOrMacro(Loc);
1344 if (StartLocs.insert(FileStart).second) {
1345 SourceRegions.emplace_back(*ParentCounter, FileStart,
1346 getEndOfFileOrMacro(Loc));
1347 assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
1348 }
1349 Loc = getIncludeOrExpansionLoc(Loc);
1350 }
1351 }
1352
1353 MostRecentLocation = NewLoc;
1354 }
1355
1356 /// Ensure that \c S is included in the current region.
1357 void extendRegion(const Stmt *S) {
1358 SourceMappingRegion &Region = getRegion();
1359 SourceLocation StartLoc = getStart(S);
1360
1361 handleFileExit(StartLoc);
1362 if (!Region.hasStartLoc())
1363 Region.setStartLoc(StartLoc);
1364 }
1365
1366 /// Mark \c S as a terminator, starting a zero region.
1367 void terminateRegion(const Stmt *S) {
1368 extendRegion(S);
1369 SourceMappingRegion &Region = getRegion();
1370 SourceLocation EndLoc = getEnd(S);
1371 if (!Region.hasEndLoc())
1372 Region.setEndLoc(EndLoc);
1373 pushRegion(Counter::getZero());
1374 HasTerminateStmt = true;
1375 }
1376
1377 /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
1378 std::optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
1379 SourceLocation BeforeLoc) {
1380 // Some statements (like AttributedStmt and ImplicitValueInitExpr) don't
1381 // have valid source locations. Do not emit a gap region if this is the case
1382 // in either AfterLoc end or BeforeLoc end.
1383 if (AfterLoc.isInvalid() || BeforeLoc.isInvalid())
1384 return std::nullopt;
1385
1386 // If AfterLoc is in function-like macro, use the right parenthesis
1387 // location.
1388 if (AfterLoc.isMacroID()) {
1389 FileID FID = SM.getFileID(AfterLoc);
1390 const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
1391 if (EI->isFunctionMacroExpansion())
1392 AfterLoc = EI->getExpansionLocEnd();
1393 }
1394
1395 size_t StartDepth = locationDepth(AfterLoc);
1396 size_t EndDepth = locationDepth(BeforeLoc);
1397 while (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc)) {
1398 bool UnnestStart = StartDepth >= EndDepth;
1399 bool UnnestEnd = EndDepth >= StartDepth;
1400 if (UnnestEnd) {
1401 assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1402 BeforeLoc));
1403
1404 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1405 assert(BeforeLoc.isValid());
1406 EndDepth--;
1407 }
1408 if (UnnestStart) {
1409 assert(SM.isWrittenInSameFile(AfterLoc,
1410 getEndOfFileOrMacro(AfterLoc)));
1411
1412 AfterLoc = getIncludeOrExpansionLoc(AfterLoc);
1413 assert(AfterLoc.isValid());
1414 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1415 assert(AfterLoc.isValid());
1416 StartDepth--;
1417 }
1418 }
1419 AfterLoc = getPreciseTokenLocEnd(AfterLoc);
1420 // If the start and end locations of the gap are both within the same macro
1421 // file, the range may not be in source order.
1422 if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
1423 return std::nullopt;
1424 if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc) ||
1425 !SpellingRegion(SM, AfterLoc, BeforeLoc).isInSourceOrder())
1426 return std::nullopt;
1427 return {{AfterLoc, BeforeLoc}};
1428 }
1429
1430 /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
1431 void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
1432 Counter Count) {
1433 if (StartLoc == EndLoc)
1434 return;
1435 assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
1436 handleFileExit(StartLoc);
1437 size_t Index = pushRegion(Count, StartLoc, EndLoc);
1438 getRegion().setGap(true);
1439 handleFileExit(EndLoc);
1440 popRegions(Index);
1441 }
1442
1443 /// Find a valid range starting with \p StartingLoc and ending before \p
1444 /// BeforeLoc.
1445 std::optional<SourceRange> findAreaStartingFromTo(SourceLocation StartingLoc,
1446 SourceLocation BeforeLoc) {
1447 // If StartingLoc is in function-like macro, use its start location.
1448 if (StartingLoc.isMacroID()) {
1449 FileID FID = SM.getFileID(StartingLoc);
1450 const SrcMgr::ExpansionInfo *EI = &SM.getSLocEntry(FID).getExpansion();
1451 if (EI->isFunctionMacroExpansion())
1452 StartingLoc = EI->getExpansionLocStart();
1453 }
1454
1455 size_t StartDepth = locationDepth(StartingLoc);
1456 size_t EndDepth = locationDepth(BeforeLoc);
1457 while (!SM.isWrittenInSameFile(StartingLoc, BeforeLoc)) {
1458 bool UnnestStart = StartDepth >= EndDepth;
1459 bool UnnestEnd = EndDepth >= StartDepth;
1460 if (UnnestEnd) {
1461 assert(SM.isWrittenInSameFile(getStartOfFileOrMacro(BeforeLoc),
1462 BeforeLoc));
1463
1464 BeforeLoc = getIncludeOrExpansionLoc(BeforeLoc);
1465 assert(BeforeLoc.isValid());
1466 EndDepth--;
1467 }
1468 if (UnnestStart) {
1469 assert(SM.isWrittenInSameFile(StartingLoc,
1470 getStartOfFileOrMacro(StartingLoc)));
1471
1472 StartingLoc = getIncludeOrExpansionLoc(StartingLoc);
1473 assert(StartingLoc.isValid());
1474 StartDepth--;
1475 }
1476 }
1477 // If the start and end locations of the gap are both within the same macro
1478 // file, the range may not be in source order.
1479 if (StartingLoc.isMacroID() || BeforeLoc.isMacroID())
1480 return std::nullopt;
1481 if (!SM.isWrittenInSameFile(StartingLoc, BeforeLoc) ||
1482 !SpellingRegion(SM, StartingLoc, BeforeLoc).isInSourceOrder())
1483 return std::nullopt;
1484 return {{StartingLoc, BeforeLoc}};
1485 }
1486
1487 void markSkipped(SourceLocation StartLoc, SourceLocation BeforeLoc) {
1488 const auto Skipped = findAreaStartingFromTo(StartLoc, BeforeLoc);
1489
1490 if (!Skipped)
1491 return;
1492
1493 const auto NewStartLoc = Skipped->getBegin();
1494 const auto EndLoc = Skipped->getEnd();
1495
1496 if (NewStartLoc == EndLoc)
1497 return;
1498 assert(SpellingRegion(SM, NewStartLoc, EndLoc).isInSourceOrder());
1499 handleFileExit(NewStartLoc);
1500 size_t Index = pushRegion(Counter{}, NewStartLoc, EndLoc);
1501 getRegion().setSkipped(true);
1502 handleFileExit(EndLoc);
1503 popRegions(Index);
1504 }
1505
1506 /// Keep counts of breaks and continues inside loops.
1507 struct BreakContinue {
1508 Counter BreakCount;
1509 Counter ContinueCount;
1510 };
1511 SmallVector<BreakContinue, 8> BreakContinueStack;
1512
1513 CounterCoverageMappingBuilder(
1514 CoverageMappingModuleGen &CVM,
1515 llvm::DenseMap<const Stmt *, CounterPair> &CounterMap,
1516 MCDC::State &MCDCState, SourceManager &SM, const LangOptions &LangOpts)
1517 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
1518 NextCounterNum(CounterMap.size()), MCDCState(MCDCState),
1519 MCDCBuilder(CVM.getCodeGenModule(), MCDCState) {}
1520
1521 /// Write the mapping data to the output stream
1522 void write(llvm::raw_ostream &OS) {
1523 llvm::SmallVector<unsigned, 8> VirtualFileMapping;
1524 gatherFileIDs(VirtualFileMapping);
1525 SourceRegionFilter Filter = emitExpansionRegions();
1526 emitSourceRegions(Filter);
1527 gatherSkippedRegions();
1528
1529 if (MappingRegions.empty())
1530 return;
1531
1532 CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1533 MappingRegions);
1534 Writer.write(OS);
1535 }
1536
1537 void VisitStmt(const Stmt *S) {
1538 if (S->getBeginLoc().isValid())
1539 extendRegion(S);
1540 const Stmt *LastStmt = nullptr;
1541 bool SaveTerminateStmt = HasTerminateStmt;
1542 HasTerminateStmt = false;
1543 GapRegionCounter = Counter::getZero();
1544 for (const Stmt *Child : S->children())
1545 if (Child) {
1546 // If last statement contains terminate statements, add a gap area
1547 // between the two statements.
1548 if (LastStmt && HasTerminateStmt) {
1549 auto Gap = findGapAreaBetween(getEnd(LastStmt), getStart(Child));
1550 if (Gap)
1551 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(),
1552 GapRegionCounter);
1553 SaveTerminateStmt = true;
1554 HasTerminateStmt = false;
1555 }
1556 this->Visit(Child);
1557 LastStmt = Child;
1558 }
1559 if (SaveTerminateStmt)
1560 HasTerminateStmt = true;
1561 handleFileExit(getEnd(S));
1562 }
1563
1564 void VisitStmtExpr(const StmtExpr *E) {
1565 Visit(E->getSubStmt());
1566 // Any region termination (such as a noreturn CallExpr) within the statement
1567 // expression has been handled by visiting the sub-statement. The visitor
1568 // cannot be at a terminate statement leaving the statement expression.
1569 HasTerminateStmt = false;
1570 }
1571
1572 void VisitDecl(const Decl *D) {
1573 Stmt *Body = D->getBody();
1574
1575 // Do not propagate region counts into system headers unless collecting
1576 // coverage from system headers is explicitly enabled.
1577 if (!SystemHeadersCoverage && Body &&
1578 SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1579 return;
1580
1581 // Do not visit the artificial children nodes of defaulted methods. The
1582 // lexer may not be able to report back precise token end locations for
1583 // these children nodes (llvm.org/PR39822), and moreover users will not be
1584 // able to see coverage for them.
1585 Counter BodyCounter = getRegionCounter(Body);
1586 bool Defaulted = false;
1587 if (auto *Method = dyn_cast<CXXMethodDecl>(D))
1588 Defaulted = Method->isDefaulted();
1589 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(D)) {
1590 for (auto *Initializer : Ctor->inits()) {
1591 if (Initializer->isWritten()) {
1592 auto *Init = Initializer->getInit();
1593 if (getStart(Init).isValid() && getEnd(Init).isValid())
1594 propagateCounts(BodyCounter, Init);
1595 }
1596 }
1597 }
1598
1599 propagateCounts(BodyCounter, Body,
1600 /*VisitChildren=*/!Defaulted);
1601 assert(RegionStack.empty() && "Regions entered but never exited");
1602 }
1603
1604 void VisitReturnStmt(const ReturnStmt *S) {
1605 extendRegion(S);
1606 if (S->getRetValue())
1607 Visit(S->getRetValue());
1608 terminateRegion(S);
1609 }
1610
1611 void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1612 extendRegion(S);
1613 Visit(S->getBody());
1614 }
1615
1616 void VisitCoreturnStmt(const CoreturnStmt *S) {
1617 extendRegion(S);
1618 if (S->getOperand())
1619 Visit(S->getOperand());
1620 terminateRegion(S);
1621 }
1622
1623 void VisitCoroutineSuspendExpr(const CoroutineSuspendExpr *E) {
1624 Visit(E->getOperand());
1625 }
1626
1627 void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1628 extendRegion(E);
1629 if (E->getSubExpr())
1630 Visit(E->getSubExpr());
1631 terminateRegion(E);
1632 }
1633
1634 void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1635
1636 void VisitLabelStmt(const LabelStmt *S) {
1637 Counter LabelCount = getRegionCounter(S);
1638 SourceLocation Start = getStart(S);
1639 // We can't extendRegion here or we risk overlapping with our new region.
1640 handleFileExit(Start);
1641 pushRegion(LabelCount, Start);
1642 Visit(S->getSubStmt());
1643 }
1644
1645 void VisitBreakStmt(const BreakStmt *S) {
1646 assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1647 if (!llvm::EnableSingleByteCoverage)
1648 BreakContinueStack.back().BreakCount = addCounters(
1649 BreakContinueStack.back().BreakCount, getRegion().getCounter());
1650 // FIXME: a break in a switch should terminate regions for all preceding
1651 // case statements, not just the most recent one.
1652 terminateRegion(S);
1653 }
1654
1655 void VisitContinueStmt(const ContinueStmt *S) {
1656 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1657 if (!llvm::EnableSingleByteCoverage)
1658 BreakContinueStack.back().ContinueCount = addCounters(
1659 BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1660 terminateRegion(S);
1661 }
1662
1663 void VisitCallExpr(const CallExpr *E) {
1664 VisitStmt(E);
1665
1666 // Terminate the region when we hit a noreturn function.
1667 // (This is helpful dealing with switch statements.)
1668 QualType CalleeType = E->getCallee()->getType();
1669 if (getFunctionExtInfo(*CalleeType).getNoReturn())
1670 terminateRegion(E);
1671 }
1672
1673 void VisitWhileStmt(const WhileStmt *S) {
1674 extendRegion(S);
1675
1676 Counter ParentCount = getRegion().getCounter();
1677 Counter BodyCount = llvm::EnableSingleByteCoverage
1678 ? getRegionCounter(S->getBody())
1679 : getRegionCounter(S);
1680
1681 // Handle the body first so that we can get the backedge count.
1682 BreakContinueStack.push_back(BreakContinue());
1683 extendRegion(S->getBody());
1684 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1685 BreakContinue BC = BreakContinueStack.pop_back_val();
1686
1687 bool BodyHasTerminateStmt = HasTerminateStmt;
1688 HasTerminateStmt = false;
1689
1690 // Go back to handle the condition.
1691 Counter CondCount =
1692 llvm::EnableSingleByteCoverage
1693 ? getRegionCounter(S->getCond())
1694 : addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1695 auto BranchCount = getBranchCounterPair(S, CondCount, getRegionCounter(S));
1696 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1697 llvm::EnableSingleByteCoverage);
1698
1699 propagateCounts(CondCount, S->getCond());
1700 adjustForOutOfOrderTraversal(getEnd(S));
1701
1702 // The body count applies to the area immediately after the increment.
1703 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1704 if (Gap)
1705 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1706
1707 assert(
1708 !llvm::EnableSingleByteCoverage ||
1709 (BC.BreakCount.isZero() && BranchCount.Skipped == getRegionCounter(S)));
1710 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1711 if (!IsCounterEqual(OutCount, ParentCount)) {
1712 pushRegion(OutCount);
1713 GapRegionCounter = OutCount;
1714 if (BodyHasTerminateStmt)
1715 HasTerminateStmt = true;
1716 }
1717
1718 // Create Branch Region around condition.
1719 if (!llvm::EnableSingleByteCoverage)
1720 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1721 }
1722
1723 void VisitDoStmt(const DoStmt *S) {
1724 extendRegion(S);
1725
1726 Counter ParentCount = getRegion().getCounter();
1727 Counter BodyCount = llvm::EnableSingleByteCoverage
1728 ? getRegionCounter(S->getBody())
1729 : getRegionCounter(S);
1730
1731 BreakContinueStack.push_back(BreakContinue());
1732 extendRegion(S->getBody());
1733
1734 Counter BackedgeCount;
1735 if (llvm::EnableSingleByteCoverage)
1736 propagateCounts(BodyCount, S->getBody());
1737 else
1738 BackedgeCount =
1739 propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1740
1741 BreakContinue BC = BreakContinueStack.pop_back_val();
1742
1743 bool BodyHasTerminateStmt = HasTerminateStmt;
1744 HasTerminateStmt = false;
1745
1746 Counter CondCount = llvm::EnableSingleByteCoverage
1747 ? getRegionCounter(S->getCond())
1748 : addCounters(BackedgeCount, BC.ContinueCount);
1749 auto BranchCount = getBranchCounterPair(S, CondCount, getRegionCounter(S));
1750 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1751 llvm::EnableSingleByteCoverage);
1752
1753 propagateCounts(CondCount, S->getCond());
1754
1755 assert(
1756 !llvm::EnableSingleByteCoverage ||
1757 (BC.BreakCount.isZero() && BranchCount.Skipped == getRegionCounter(S)));
1758 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1759 if (!IsCounterEqual(OutCount, ParentCount)) {
1760 pushRegion(OutCount);
1761 GapRegionCounter = OutCount;
1762 if (BodyHasTerminateStmt)
1763 HasTerminateStmt = true;
1764 }
1765
1766 // Create Branch Region around condition.
1767 if (!llvm::EnableSingleByteCoverage)
1768 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1769 }
1770
1771 void VisitForStmt(const ForStmt *S) {
1772 extendRegion(S);
1773 if (S->getInit())
1774 Visit(S->getInit());
1775
1776 Counter ParentCount = getRegion().getCounter();
1777 Counter BodyCount = llvm::EnableSingleByteCoverage
1778 ? getRegionCounter(S->getBody())
1779 : getRegionCounter(S);
1780
1781 // The loop increment may contain a break or continue.
1782 if (S->getInc())
1783 BreakContinueStack.emplace_back();
1784
1785 // Handle the body first so that we can get the backedge count.
1786 BreakContinueStack.emplace_back();
1787 extendRegion(S->getBody());
1788 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1789 BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1790
1791 bool BodyHasTerminateStmt = HasTerminateStmt;
1792 HasTerminateStmt = false;
1793
1794 // The increment is essentially part of the body but it needs to include
1795 // the count for all the continue statements.
1796 BreakContinue IncrementBC;
1797 if (const Stmt *Inc = S->getInc()) {
1798 Counter IncCount;
1799 if (llvm::EnableSingleByteCoverage)
1800 IncCount = getRegionCounter(S->getInc());
1801 else
1802 IncCount = addCounters(BackedgeCount, BodyBC.ContinueCount);
1803 propagateCounts(IncCount, Inc);
1804 IncrementBC = BreakContinueStack.pop_back_val();
1805 }
1806
1807 // Go back to handle the condition.
1808 Counter CondCount =
1809 llvm::EnableSingleByteCoverage
1810 ? getRegionCounter(S->getCond())
1811 : addCounters(
1812 addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1813 IncrementBC.ContinueCount);
1814 auto BranchCount = getBranchCounterPair(S, CondCount, getRegionCounter(S));
1815 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1816 llvm::EnableSingleByteCoverage);
1817
1818 if (const Expr *Cond = S->getCond()) {
1819 propagateCounts(CondCount, Cond);
1820 adjustForOutOfOrderTraversal(getEnd(S));
1821 }
1822
1823 // The body count applies to the area immediately after the increment.
1824 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1825 if (Gap)
1826 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1827
1828 assert(!llvm::EnableSingleByteCoverage ||
1829 (BodyBC.BreakCount.isZero() && IncrementBC.BreakCount.isZero()));
1830 Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1831 BranchCount.Skipped);
1832 if (!IsCounterEqual(OutCount, ParentCount)) {
1833 pushRegion(OutCount);
1834 GapRegionCounter = OutCount;
1835 if (BodyHasTerminateStmt)
1836 HasTerminateStmt = true;
1837 }
1838
1839 // Create Branch Region around condition.
1840 if (!llvm::EnableSingleByteCoverage)
1841 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1842 }
1843
1844 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1845 extendRegion(S);
1846 if (S->getInit())
1847 Visit(S->getInit());
1848 Visit(S->getLoopVarStmt());
1849 Visit(S->getRangeStmt());
1850
1851 Counter ParentCount = getRegion().getCounter();
1852 Counter BodyCount = llvm::EnableSingleByteCoverage
1853 ? getRegionCounter(S->getBody())
1854 : getRegionCounter(S);
1855
1856 BreakContinueStack.push_back(BreakContinue());
1857 extendRegion(S->getBody());
1858 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1859 BreakContinue BC = BreakContinueStack.pop_back_val();
1860
1861 bool BodyHasTerminateStmt = HasTerminateStmt;
1862 HasTerminateStmt = false;
1863
1864 // The body count applies to the area immediately after the range.
1865 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1866 if (Gap)
1867 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1868
1869 Counter LoopCount =
1870 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1871 auto BranchCount = getBranchCounterPair(S, LoopCount, getRegionCounter(S));
1872 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount ||
1873 llvm::EnableSingleByteCoverage);
1874 assert(
1875 !llvm::EnableSingleByteCoverage ||
1876 (BC.BreakCount.isZero() && BranchCount.Skipped == getRegionCounter(S)));
1877
1878 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1879 if (!IsCounterEqual(OutCount, ParentCount)) {
1880 pushRegion(OutCount);
1881 GapRegionCounter = OutCount;
1882 if (BodyHasTerminateStmt)
1883 HasTerminateStmt = true;
1884 }
1885
1886 // Create Branch Region around condition.
1887 if (!llvm::EnableSingleByteCoverage)
1888 createBranchRegion(S->getCond(), BodyCount, BranchCount.Skipped);
1889 }
1890
1891 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1892 extendRegion(S);
1893 Visit(S->getElement());
1894
1895 Counter ParentCount = getRegion().getCounter();
1896 Counter BodyCount = getRegionCounter(S);
1897
1898 BreakContinueStack.push_back(BreakContinue());
1899 extendRegion(S->getBody());
1900 Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1901 BreakContinue BC = BreakContinueStack.pop_back_val();
1902
1903 // The body count applies to the area immediately after the collection.
1904 auto Gap = findGapAreaBetween(S->getRParenLoc(), getStart(S->getBody()));
1905 if (Gap)
1906 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1907
1908 Counter LoopCount =
1909 addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1910 auto BranchCount = getBranchCounterPair(S, LoopCount);
1911 assert(BranchCount.Executed.isZero() || BranchCount.Executed == BodyCount);
1912 Counter OutCount = addCounters(BC.BreakCount, BranchCount.Skipped);
1913 if (!IsCounterEqual(OutCount, ParentCount)) {
1914 pushRegion(OutCount);
1915 GapRegionCounter = OutCount;
1916 }
1917 }
1918
1919 void VisitSwitchStmt(const SwitchStmt *S) {
1920 extendRegion(S);
1921 if (S->getInit())
1922 Visit(S->getInit());
1923 Visit(S->getCond());
1924
1925 BreakContinueStack.push_back(BreakContinue());
1926
1927 const Stmt *Body = S->getBody();
1928 extendRegion(Body);
1929 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1930 if (!CS->body_empty()) {
1931 // Make a region for the body of the switch. If the body starts with
1932 // a case, that case will reuse this region; otherwise, this covers
1933 // the unreachable code at the beginning of the switch body.
1934 size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1935 getRegion().setGap(true);
1936 Visit(Body);
1937
1938 // Set the end for the body of the switch, if it isn't already set.
1939 for (size_t i = RegionStack.size(); i != Index; --i) {
1940 if (!RegionStack[i - 1].hasEndLoc())
1941 RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1942 }
1943
1944 popRegions(Index);
1945 }
1946 } else
1947 propagateCounts(Counter::getZero(), Body);
1948 BreakContinue BC = BreakContinueStack.pop_back_val();
1949
1950 if (!BreakContinueStack.empty() && !llvm::EnableSingleByteCoverage)
1951 BreakContinueStack.back().ContinueCount = addCounters(
1952 BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1953
1954 Counter ParentCount = getRegion().getCounter();
1955 Counter ExitCount = getRegionCounter(S);
1956 SourceLocation ExitLoc = getEnd(S);
1957 pushRegion(ExitCount);
1958 GapRegionCounter = ExitCount;
1959
1960 // Ensure that handleFileExit recognizes when the end location is located
1961 // in a different file.
1962 MostRecentLocation = getStart(S);
1963 handleFileExit(ExitLoc);
1964
1965 // When single byte coverage mode is enabled, do not create branch region by
1966 // early returning.
1967 if (llvm::EnableSingleByteCoverage)
1968 return;
1969
1970 // Create a Branch Region around each Case. Subtract the case's
1971 // counter from the Parent counter to track the "False" branch count.
1972 Counter CaseCountSum;
1973 bool HasDefaultCase = false;
1974 const SwitchCase *Case = S->getSwitchCaseList();
1975 for (; Case; Case = Case->getNextSwitchCase()) {
1976 HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1977 auto CaseCount = createSwitchCaseRegion(Case, ParentCount);
1978 CaseCountSum = addCounters(CaseCountSum, CaseCount, /*Simplify=*/false);
1979 }
1980 // If no explicit default case exists, create a branch region to represent
1981 // the hidden branch, which will be added later by the CodeGen. This region
1982 // will be associated with the switch statement's condition.
1983 if (!HasDefaultCase) {
1984 // Simplify is skipped while building the counters above: it can get
1985 // really slow on top of switches with thousands of cases. Instead,
1986 // trigger simplification by adding zero to the last counter.
1987 CaseCountSum =
1988 addCounters(CaseCountSum, Counter::getZero(), /*Simplify=*/true);
1989
1990 // This is considered as the False count on SwitchStmt.
1991 Counter SwitchFalse = subtractCounters(ParentCount, CaseCountSum);
1992 createBranchRegion(S->getCond(), CaseCountSum, SwitchFalse);
1993 }
1994 }
1995
1996 void VisitSwitchCase(const SwitchCase *S) {
1997 extendRegion(S);
1998
1999 SourceMappingRegion &Parent = getRegion();
2000 Counter Count = llvm::EnableSingleByteCoverage
2001 ? getRegionCounter(S)
2002 : addCounters(Parent.getCounter(), getRegionCounter(S));
2003
2004 // Reuse the existing region if it starts at our label. This is typical of
2005 // the first case in a switch.
2006 if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
2007 Parent.setCounter(Count);
2008 else
2009 pushRegion(Count, getStart(S));
2010
2011 GapRegionCounter = Count;
2012
2013 if (const auto *CS = dyn_cast<CaseStmt>(S)) {
2014 Visit(CS->getLHS());
2015 if (const Expr *RHS = CS->getRHS())
2016 Visit(RHS);
2017 }
2018 Visit(S->getSubStmt());
2019 }
2020
2021 void coverIfConsteval(const IfStmt *S) {
2022 assert(S->isConsteval());
2023
2024 const auto *Then = S->getThen();
2025 const auto *Else = S->getElse();
2026
2027 // It's better for llvm-cov to create a new region with same counter
2028 // so line-coverage can be properly calculated for lines containing
2029 // a skipped region (without it the line is marked uncovered)
2030 const Counter ParentCount = getRegion().getCounter();
2031
2032 extendRegion(S);
2033
2034 if (S->isNegatedConsteval()) {
2035 // ignore 'if consteval'
2036 markSkipped(S->getIfLoc(), getStart(Then));
2037 propagateCounts(ParentCount, Then);
2038
2039 if (Else) {
2040 // ignore 'else <else>'
2041 markSkipped(getEnd(Then), getEnd(Else));
2042 }
2043 } else {
2044 assert(S->isNonNegatedConsteval());
2045 // ignore 'if consteval <then> [else]'
2046 markSkipped(S->getIfLoc(), Else ? getStart(Else) : getEnd(Then));
2047
2048 if (Else)
2049 propagateCounts(ParentCount, Else);
2050 }
2051 }
2052
2053 void coverIfConstexpr(const IfStmt *S) {
2054 assert(S->isConstexpr());
2055
2056 // evaluate constant condition...
2057 const bool isTrue =
2058 S->getCond()
2059 ->EvaluateKnownConstInt(CVM.getCodeGenModule().getContext())
2060 .getBoolValue();
2061
2062 extendRegion(S);
2063
2064 // I'm using 'propagateCounts' later as new region is better and allows me
2065 // to properly calculate line coverage in llvm-cov utility
2066 const Counter ParentCount = getRegion().getCounter();
2067
2068 // ignore 'if constexpr ('
2069 SourceLocation startOfSkipped = S->getIfLoc();
2070
2071 if (const auto *Init = S->getInit()) {
2072 const auto start = getStart(Init);
2073 const auto end = getEnd(Init);
2074
2075 // this check is to make sure typedef here which doesn't have valid source
2076 // location won't crash it
2077 if (start.isValid() && end.isValid()) {
2078 markSkipped(startOfSkipped, start);
2079 propagateCounts(ParentCount, Init);
2080 startOfSkipped = getEnd(Init);
2081 }
2082 }
2083
2084 const auto *Then = S->getThen();
2085 const auto *Else = S->getElse();
2086
2087 if (isTrue) {
2088 // ignore '<condition>)'
2089 markSkipped(startOfSkipped, getStart(Then));
2090 propagateCounts(ParentCount, Then);
2091
2092 if (Else)
2093 // ignore 'else <else>'
2094 markSkipped(getEnd(Then), getEnd(Else));
2095 } else {
2096 // ignore '<condition>) <then> [else]'
2097 markSkipped(startOfSkipped, Else ? getStart(Else) : getEnd(Then));
2098
2099 if (Else)
2100 propagateCounts(ParentCount, Else);
2101 }
2102 }
2103
2104 void VisitIfStmt(const IfStmt *S) {
2105 // "if constexpr" and "if consteval" are not normal conditional statements,
2106 // their discarded statement should be skipped
2107 if (S->isConsteval())
2108 return coverIfConsteval(S);
2109 else if (S->isConstexpr())
2110 return coverIfConstexpr(S);
2111
2112 extendRegion(S);
2113 if (S->getInit())
2114 Visit(S->getInit());
2115
2116 // Extend into the condition before we propagate through it below - this is
2117 // needed to handle macros that generate the "if" but not the condition.
2118 extendRegion(S->getCond());
2119
2120 Counter ParentCount = getRegion().getCounter();
2121 auto [ThenCount, ElseCount] =
2122 (llvm::EnableSingleByteCoverage
2123 ? BranchCounterPair{getRegionCounter(S->getThen()),
2124 (S->getElse() ? getRegionCounter(S->getElse())
2125 : Counter::getZero())}
2126 : getBranchCounterPair(S, ParentCount));
2127
2128 // Emitting a counter for the condition makes it easier to interpret the
2129 // counter for the body when looking at the coverage.
2130 propagateCounts(ParentCount, S->getCond());
2131
2132 // The 'then' count applies to the area immediately after the condition.
2133 std::optional<SourceRange> Gap =
2134 findGapAreaBetween(S->getRParenLoc(), getStart(S->getThen()));
2135 if (Gap)
2136 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
2137
2138 extendRegion(S->getThen());
2139 Counter OutCount = propagateCounts(ThenCount, S->getThen());
2140
2141 if (const Stmt *Else = S->getElse()) {
2142 bool ThenHasTerminateStmt = HasTerminateStmt;
2143 HasTerminateStmt = false;
2144 // The 'else' count applies to the area immediately after the 'then'.
2145 std::optional<SourceRange> Gap =
2146 findGapAreaBetween(getEnd(S->getThen()), getStart(Else));
2147 if (Gap)
2148 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
2149 extendRegion(Else);
2150
2151 Counter ElseOutCount = propagateCounts(ElseCount, Else);
2152 if (!llvm::EnableSingleByteCoverage)
2153 OutCount = addCounters(OutCount, ElseOutCount);
2154
2155 if (ThenHasTerminateStmt)
2156 HasTerminateStmt = true;
2157 } else if (!llvm::EnableSingleByteCoverage)
2158 OutCount = addCounters(OutCount, ElseCount);
2159
2160 if (llvm::EnableSingleByteCoverage)
2161 OutCount = getRegionCounter(S);
2162
2163 if (!IsCounterEqual(OutCount, ParentCount)) {
2164 pushRegion(OutCount);
2165 GapRegionCounter = OutCount;
2166 }
2167
2168 if (!llvm::EnableSingleByteCoverage)
2169 // Create Branch Region around condition.
2170 createBranchRegion(S->getCond(), ThenCount, ElseCount);
2171 }
2172
2173 void VisitCXXTryStmt(const CXXTryStmt *S) {
2174 extendRegion(S);
2175 // Handle macros that generate the "try" but not the rest.
2176 extendRegion(S->getTryBlock());
2177
2178 Counter ParentCount = getRegion().getCounter();
2179 propagateCounts(ParentCount, S->getTryBlock());
2180
2181 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
2182 Visit(S->getHandler(I));
2183
2184 Counter ExitCount = getRegionCounter(S);
2185 pushRegion(ExitCount);
2186 }
2187
2188 void VisitCXXCatchStmt(const CXXCatchStmt *S) {
2189 propagateCounts(getRegionCounter(S), S->getHandlerBlock());
2190 }
2191
2192 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2193 extendRegion(E);
2194
2195 Counter ParentCount = getRegion().getCounter();
2196 auto [TrueCount, FalseCount] =
2197 (llvm::EnableSingleByteCoverage
2198 ? BranchCounterPair{getRegionCounter(E->getTrueExpr()),
2199 getRegionCounter(E->getFalseExpr())}
2200 : getBranchCounterPair(E, ParentCount));
2201 Counter OutCount;
2202
2203 if (const auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) {
2204 propagateCounts(ParentCount, BCO->getCommon());
2205 OutCount = TrueCount;
2206 } else {
2207 propagateCounts(ParentCount, E->getCond());
2208 // The 'then' count applies to the area immediately after the condition.
2209 auto Gap =
2210 findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
2211 if (Gap)
2212 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
2213
2214 extendRegion(E->getTrueExpr());
2215 OutCount = propagateCounts(TrueCount, E->getTrueExpr());
2216 }
2217
2218 extendRegion(E->getFalseExpr());
2219 Counter FalseOutCount = propagateCounts(FalseCount, E->getFalseExpr());
2220 if (llvm::EnableSingleByteCoverage)
2221 OutCount = getRegionCounter(E);
2222 else
2223 OutCount = addCounters(OutCount, FalseOutCount);
2224
2225 if (!IsCounterEqual(OutCount, ParentCount)) {
2226 pushRegion(OutCount);
2227 GapRegionCounter = OutCount;
2228 }
2229
2230 // Create Branch Region around condition.
2231 if (!llvm::EnableSingleByteCoverage)
2232 createBranchRegion(E->getCond(), TrueCount, FalseCount);
2233 }
2234
2235 void createOrCancelDecision(const BinaryOperator *E, unsigned Since) {
2236 unsigned NumConds = MCDCBuilder.getTotalConditionsAndReset(E);
2237 if (NumConds == 0)
2238 return;
2239
2240 // Extract [ID, Conds] to construct the graph.
2241 llvm::SmallVector<mcdc::ConditionIDs> CondIDs(NumConds);
2242 for (const auto &SR : ArrayRef(SourceRegions).slice(Since)) {
2243 if (SR.isMCDCBranch()) {
2244 auto [ID, Conds] = SR.getMCDCBranchParams();
2245 CondIDs[ID] = Conds;
2246 }
2247 }
2248
2249 // Construct the graph and calculate `Indices`.
2250 mcdc::TVIdxBuilder Builder(CondIDs);
2251 unsigned NumTVs = Builder.NumTestVectors;
2252 unsigned MaxTVs = CVM.getCodeGenModule().getCodeGenOpts().MCDCMaxTVs;
2253 assert(MaxTVs < mcdc::TVIdxBuilder::HardMaxTVs);
2254
2255 if (NumTVs > MaxTVs) {
2256 // NumTVs exceeds MaxTVs -- warn and cancel the Decision.
2257 cancelDecision(E, Since, NumTVs, MaxTVs);
2258 return;
2259 }
2260
2261 // Update the state for CodeGenPGO
2262 assert(MCDCState.DecisionByStmt.contains(E));
2263 MCDCState.DecisionByStmt[E].update(MCDCState.BitmapBits, // Top
2264 std::move(Builder.Indices));
2265
2266 auto DecisionParams = mcdc::DecisionParameters{
2267 MCDCState.BitmapBits += NumTVs, // Tail
2268 NumConds,
2269 };
2270
2271 // Create MCDC Decision Region.
2272 createDecisionRegion(E, DecisionParams);
2273 }
2274
2275 // Warn and cancel the Decision.
2276 void cancelDecision(const BinaryOperator *E, unsigned Since, int NumTVs,
2277 int MaxTVs) {
2278 auto &Diag = CVM.getCodeGenModule().getDiags();
2279 Diag.Report(E->getBeginLoc(), diag::warn_pgo_test_vector_limit)
2280 << NumTVs << MaxTVs;
2281
2282 // Restore MCDCBranch to Branch.
2283 for (auto &SR : MutableArrayRef(SourceRegions).slice(Since)) {
2284 assert(!SR.isMCDCDecision() && "Decision shouldn't be seen here");
2285 if (SR.isMCDCBranch())
2286 SR.resetMCDCParams();
2287 }
2288
2289 // Tell CodeGenPGO not to instrument.
2290 MCDCState.DecisionByStmt.erase(E);
2291 }
2292
2293 /// Check if E belongs to system headers.
2294 bool isExprInSystemHeader(const BinaryOperator *E) const {
2295 return (!SystemHeadersCoverage &&
2296 SM.isInSystemHeader(SM.getSpellingLoc(E->getOperatorLoc())) &&
2297 SM.isInSystemHeader(SM.getSpellingLoc(E->getBeginLoc())) &&
2298 SM.isInSystemHeader(SM.getSpellingLoc(E->getEndLoc())));
2299 }
2300
2301 void VisitUnaryLNot(const UnaryOperator *E) {
2302 MCDCBuilder.swapConds();
2303 Visit(E->getSubExpr());
2304 MCDCBuilder.swapConds();
2305 }
2306
2307 void VisitBinLAnd(const BinaryOperator *E) {
2308 if (isExprInSystemHeader(E)) {
2309 LeafExprSet.insert(E);
2310 return;
2311 }
2312
2313 bool IsRootNode = MCDCBuilder.isIdle();
2314
2315 unsigned SourceRegionsSince = SourceRegions.size();
2316
2317 // Keep track of Binary Operator and assign MCDC condition IDs.
2318 MCDCBuilder.pushAndAssignIDs(E);
2319
2320 extendRegion(E->getLHS());
2321 propagateCounts(getRegion().getCounter(), E->getLHS());
2322 handleFileExit(getEnd(E->getLHS()));
2323
2324 // Track LHS True/False Decision.
2325 const auto DecisionLHS = MCDCBuilder.pop();
2326
2327 if (auto Gap =
2328 findGapAreaBetween(getEnd(E->getLHS()), getStart(E->getRHS()))) {
2329 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), getRegionCounter(E));
2330 }
2331
2332 // Counter tracks the right hand side of a logical and operator.
2333 extendRegion(E->getRHS());
2334 propagateCounts(getRegionCounter(E), E->getRHS());
2335
2336 if (llvm::EnableSingleByteCoverage)
2337 return;
2338
2339 // Track RHS True/False Decision.
2340 const auto DecisionRHS = MCDCBuilder.back();
2341
2342 // Extract the Parent Region Counter.
2343 Counter ParentCnt = getRegion().getCounter();
2344
2345 // Extract the RHS's Execution Counter.
2346 auto [RHSExecCnt, LHSExitCnt] = getBranchCounterPair(E, ParentCnt);
2347
2348 // Extract the RHS's "True" Instance Counter.
2349 auto [RHSTrueCnt, RHSExitCnt] =
2350 getBranchCounterPair(E->getRHS(), RHSExecCnt);
2351
2352 // Create Branch Region around LHS condition.
2353 createBranchRegion(E->getLHS(), RHSExecCnt, LHSExitCnt, DecisionLHS);
2354
2355 // Create Branch Region around RHS condition.
2356 createBranchRegion(E->getRHS(), RHSTrueCnt, RHSExitCnt, DecisionRHS);
2357
2358 // Create MCDC Decision Region if at top-level (root).
2359 if (IsRootNode)
2360 createOrCancelDecision(E, SourceRegionsSince);
2361 }
2362
2363 // Determine whether the right side of OR operation need to be visited.
2364 bool shouldVisitRHS(const Expr *LHS) {
2365 bool LHSIsTrue = false;
2366 bool LHSIsConst = false;
2367 if (!LHS->isValueDependent())
2368 LHSIsConst = LHS->EvaluateAsBooleanCondition(
2369 LHSIsTrue, CVM.getCodeGenModule().getContext());
2370 return !LHSIsConst || (LHSIsConst && !LHSIsTrue);
2371 }
2372
2373 void VisitBinLOr(const BinaryOperator *E) {
2374 if (isExprInSystemHeader(E)) {
2375 LeafExprSet.insert(E);
2376 return;
2377 }
2378
2379 bool IsRootNode = MCDCBuilder.isIdle();
2380
2381 unsigned SourceRegionsSince = SourceRegions.size();
2382
2383 // Keep track of Binary Operator and assign MCDC condition IDs.
2384 MCDCBuilder.pushAndAssignIDs(E);
2385
2386 extendRegion(E->getLHS());
2387 Counter OutCount = propagateCounts(getRegion().getCounter(), E->getLHS());
2388 handleFileExit(getEnd(E->getLHS()));
2389
2390 // Track LHS True/False Decision.
2391 const auto DecisionLHS = MCDCBuilder.pop();
2392
2393 if (auto Gap =
2394 findGapAreaBetween(getEnd(E->getLHS()), getStart(E->getRHS()))) {
2395 fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), getRegionCounter(E));
2396 }
2397
2398 // Counter tracks the right hand side of a logical or operator.
2399 extendRegion(E->getRHS());
2400 propagateCounts(getRegionCounter(E), E->getRHS());
2401
2402 if (llvm::EnableSingleByteCoverage)
2403 return;
2404
2405 // Track RHS True/False Decision.
2406 const auto DecisionRHS = MCDCBuilder.back();
2407
2408 // Extract the Parent Region Counter.
2409 Counter ParentCnt = getRegion().getCounter();
2410
2411 // Extract the RHS's Execution Counter.
2412 auto [RHSExecCnt, LHSExitCnt] = getBranchCounterPair(E, ParentCnt);
2413
2414 // Extract the RHS's "False" Instance Counter.
2415 auto [RHSFalseCnt, RHSExitCnt] =
2416 getBranchCounterPair(E->getRHS(), RHSExecCnt);
2417
2418 if (!shouldVisitRHS(E->getLHS())) {
2419 GapRegionCounter = OutCount;
2420 }
2421
2422 // Create Branch Region around LHS condition.
2423 createBranchRegion(E->getLHS(), LHSExitCnt, RHSExecCnt, DecisionLHS);
2424
2425 // Create Branch Region around RHS condition.
2426 createBranchRegion(E->getRHS(), RHSExitCnt, RHSFalseCnt, DecisionRHS);
2427
2428 // Create MCDC Decision Region if at top-level (root).
2429 if (IsRootNode)
2430 createOrCancelDecision(E, SourceRegionsSince);
2431 }
2432
2433 void VisitLambdaExpr(const LambdaExpr *LE) {
2434 // Lambdas are treated as their own functions for now, so we shouldn't
2435 // propagate counts into them.
2436 }
2437
2438 void VisitArrayInitLoopExpr(const ArrayInitLoopExpr *AILE) {
2439 Visit(AILE->getCommonExpr()->getSourceExpr());
2440 }
2441
2442 void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) {
2443 // Just visit syntatic expression as this is what users actually write.
2444 VisitStmt(POE->getSyntacticForm());
2445 }
2446
2447 void VisitOpaqueValueExpr(const OpaqueValueExpr* OVE) {
2448 if (OVE->isUnique())
2449 Visit(OVE->getSourceExpr());
2450 }
2451 };
2452
2453 } // end anonymous namespace
2454
2455 static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
2456 ArrayRef<CounterExpression> Expressions,
2457 ArrayRef<CounterMappingRegion> Regions) {
2458 OS << FunctionName << ":\n";
2459 CounterMappingContext Ctx(Expressions);
2460 for (const auto &R : Regions) {
2461 OS.indent(2);
2462 switch (R.Kind) {
2463 case CounterMappingRegion::CodeRegion:
2464 break;
2465 case CounterMappingRegion::ExpansionRegion:
2466 OS << "Expansion,";
2467 break;
2468 case CounterMappingRegion::SkippedRegion:
2469 OS << "Skipped,";
2470 break;
2471 case CounterMappingRegion::GapRegion:
2472 OS << "Gap,";
2473 break;
2474 case CounterMappingRegion::BranchRegion:
2475 case CounterMappingRegion::MCDCBranchRegion:
2476 OS << "Branch,";
2477 break;
2478 case CounterMappingRegion::MCDCDecisionRegion:
2479 OS << "Decision,";
2480 break;
2481 }
2482
2483 OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
2484 << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
2485
2486 if (const auto *DecisionParams =
2487 std::get_if<mcdc::DecisionParameters>(&R.MCDCParams)) {
2488 OS << "M:" << DecisionParams->BitmapIdx;
2489 OS << ", C:" << DecisionParams->NumConditions;
2490 } else {
2491 Ctx.dump(R.Count, OS);
2492
2493 if (R.isBranch()) {
2494 OS << ", ";
2495 Ctx.dump(R.FalseCount, OS);
2496 }
2497 }
2498
2499 if (const auto *BranchParams =
2500 std::get_if<mcdc::BranchParameters>(&R.MCDCParams)) {
2501 OS << " [" << BranchParams->ID + 1 << ","
2502 << BranchParams->Conds[true] + 1;
2503 OS << "," << BranchParams->Conds[false] + 1 << "] ";
2504 }
2505
2506 if (R.Kind == CounterMappingRegion::ExpansionRegion)
2507 OS << " (Expanded file = " << R.ExpandedFileID << ")";
2508 OS << "\n";
2509 }
2510 }
2511
2512 CoverageMappingModuleGen::CoverageMappingModuleGen(
2513 CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
2514 : CGM(CGM), SourceInfo(SourceInfo) {}
2515
2516 std::string CoverageMappingModuleGen::getCurrentDirname() {
2517 return CGM.getCodeGenOpts().CoverageCompilationDir;
2518 }
2519
2520 std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
2521 llvm::SmallString<256> Path(Filename);
2522 llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
2523
2524 /// Traverse coverage prefix map in reverse order because prefix replacements
2525 /// are applied in reverse order starting from the last one when multiple
2526 /// prefix replacement options are provided.
2527 for (const auto &[From, To] :
2528 llvm::reverse(CGM.getCodeGenOpts().CoveragePrefixMap)) {
2529 if (llvm::sys::path::replace_path_prefix(Path, From, To))
2530 break;
2531 }
2532 return Path.str().str();
2533 }
2534
2535 static std::string getInstrProfSection(const CodeGenModule &CGM,
2536 llvm::InstrProfSectKind SK) {
2537 return llvm::getInstrProfSectionName(
2538 SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
2539 }
2540
2541 void CoverageMappingModuleGen::emitFunctionMappingRecord(
2542 const FunctionInfo &Info, uint64_t FilenamesRef) {
2543 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2544
2545 // Assign a name to the function record. This is used to merge duplicates.
2546 std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
2547
2548 // A dummy description for a function included-but-not-used in a TU can be
2549 // replaced by full description provided by a different TU. The two kinds of
2550 // descriptions play distinct roles: therefore, assign them different names
2551 // to prevent `linkonce_odr` merging.
2552 if (Info.IsUsed)
2553 FuncRecordName += "u";
2554
2555 // Create the function record type.
2556 const uint64_t NameHash = Info.NameHash;
2557 const uint64_t FuncHash = Info.FuncHash;
2558 const std::string &CoverageMapping = Info.CoverageMapping;
2559 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
2560 llvm::Type *FunctionRecordTypes[] = {
2561 #include "llvm/ProfileData/InstrProfData.inc"
2562 };
2563 auto *FunctionRecordTy =
2564 llvm::StructType::get(Ctx, ArrayRef(FunctionRecordTypes),
2565 /*isPacked=*/true);
2566
2567 // Create the function record constant.
2568 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
2569 llvm::Constant *FunctionRecordVals[] = {
2570 #include "llvm/ProfileData/InstrProfData.inc"
2571 };
2572 auto *FuncRecordConstant =
2573 llvm::ConstantStruct::get(FunctionRecordTy, ArrayRef(FunctionRecordVals));
2574
2575 // Create the function record global.
2576 auto *FuncRecord = new llvm::GlobalVariable(
2577 CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
2578 llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
2579 FuncRecordName);
2580 FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
2581 FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
2582 FuncRecord->setAlignment(llvm::Align(8));
2583 if (CGM.supportsCOMDAT())
2584 FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
2585
2586 // Make sure the data doesn't get deleted.
2587 CGM.addUsedGlobal(FuncRecord);
2588 }
2589
2590 void CoverageMappingModuleGen::addFunctionMappingRecord(
2591 llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
2592 const std::string &CoverageMapping, bool IsUsed) {
2593 const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
2594 FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
2595
2596 if (!IsUsed)
2597 FunctionNames.push_back(NamePtr);
2598
2599 if (CGM.getCodeGenOpts().DumpCoverageMapping) {
2600 // Dump the coverage mapping data for this function by decoding the
2601 // encoded data. This allows us to dump the mapping regions which were
2602 // also processed by the CoverageMappingWriter which performs
2603 // additional minimization operations such as reducing the number of
2604 // expressions.
2605 llvm::SmallVector<std::string, 16> FilenameStrs;
2606 std::vector<StringRef> Filenames;
2607 std::vector<CounterExpression> Expressions;
2608 std::vector<CounterMappingRegion> Regions;
2609 FilenameStrs.resize(FileEntries.size() + 1);
2610 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2611 for (const auto &Entry : FileEntries) {
2612 auto I = Entry.second;
2613 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2614 }
2615 ArrayRef<std::string> FilenameRefs = llvm::ArrayRef(FilenameStrs);
2616 RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
2617 Expressions, Regions);
2618 if (Reader.read())
2619 return;
2620 dump(llvm::outs(), NameValue, Expressions, Regions);
2621 }
2622 }
2623
2624 void CoverageMappingModuleGen::emit() {
2625 if (FunctionRecords.empty())
2626 return;
2627 llvm::LLVMContext &Ctx = CGM.getLLVMContext();
2628 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
2629
2630 // Create the filenames and merge them with coverage mappings
2631 llvm::SmallVector<std::string, 16> FilenameStrs;
2632 FilenameStrs.resize(FileEntries.size() + 1);
2633 // The first filename is the current working directory.
2634 FilenameStrs[0] = normalizeFilename(getCurrentDirname());
2635 for (const auto &Entry : FileEntries) {
2636 auto I = Entry.second;
2637 FilenameStrs[I] = normalizeFilename(Entry.first.getName());
2638 }
2639
2640 std::string Filenames;
2641 {
2642 llvm::raw_string_ostream OS(Filenames);
2643 CoverageFilenamesSectionWriter(FilenameStrs).write(OS);
2644 }
2645 auto *FilenamesVal =
2646 llvm::ConstantDataArray::getString(Ctx, Filenames, false);
2647 const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
2648
2649 // Emit the function records.
2650 for (const FunctionInfo &Info : FunctionRecords)
2651 emitFunctionMappingRecord(Info, FilenamesRef);
2652
2653 const unsigned NRecords = 0;
2654 const size_t FilenamesSize = Filenames.size();
2655 const unsigned CoverageMappingSize = 0;
2656 llvm::Type *CovDataHeaderTypes[] = {
2657 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
2658 #include "llvm/ProfileData/InstrProfData.inc"
2659 };
2660 auto CovDataHeaderTy =
2661 llvm::StructType::get(Ctx, ArrayRef(CovDataHeaderTypes));
2662 llvm::Constant *CovDataHeaderVals[] = {
2663 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
2664 #include "llvm/ProfileData/InstrProfData.inc"
2665 };
2666 auto CovDataHeaderVal =
2667 llvm::ConstantStruct::get(CovDataHeaderTy, ArrayRef(CovDataHeaderVals));
2668
2669 // Create the coverage data record
2670 llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
2671 auto CovDataTy = llvm::StructType::get(Ctx, ArrayRef(CovDataTypes));
2672 llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
2673 auto CovDataVal = llvm::ConstantStruct::get(CovDataTy, ArrayRef(TUDataVals));
2674 auto CovData = new llvm::GlobalVariable(
2675 CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
2676 CovDataVal, llvm::getCoverageMappingVarName());
2677
2678 CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
2679 CovData->setAlignment(llvm::Align(8));
2680
2681 // Make sure the data doesn't get deleted.
2682 CGM.addUsedGlobal(CovData);
2683 // Create the deferred function records array
2684 if (!FunctionNames.empty()) {
2685 auto AddrSpace = FunctionNames.front()->getType()->getPointerAddressSpace();
2686 auto NamesArrTy = llvm::ArrayType::get(
2687 llvm::PointerType::get(Ctx, AddrSpace), FunctionNames.size());
2688 auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
2689 // This variable will *NOT* be emitted to the object file. It is used
2690 // to pass the list of names referenced to codegen.
2691 new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
2692 llvm::GlobalValue::InternalLinkage, NamesArrVal,
2693 llvm::getCoverageUnusedNamesVarName());
2694 }
2695 }
2696
2697 unsigned CoverageMappingModuleGen::getFileID(FileEntryRef File) {
2698 return FileEntries.try_emplace(File, FileEntries.size() + 1).first->second;
2699 }
2700
2701 void CoverageMappingGen::emitCounterMapping(const Decl *D,
2702 llvm::raw_ostream &OS) {
2703 assert(CounterMap && MCDCState);
2704 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, *MCDCState, SM,
2705 LangOpts);
2706 Walker.VisitDecl(D);
2707 Walker.write(OS);
2708 }
2709
2710 void CoverageMappingGen::emitEmptyMapping(const Decl *D,
2711 llvm::raw_ostream &OS) {
2712 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
2713 Walker.VisitDecl(D);
2714 Walker.write(OS);
2715 }