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 "clang/AST/StmtVisitor.h"
16 #include "clang/Basic/Diagnostic.h"
17 #include "clang/Basic/FileManager.h"
18 #include "clang/Frontend/FrontendDiagnostic.h"
19 #include "clang/Lex/Lexer.h"
20 #include "llvm/ADT/Optional.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/ProfileData/InstrProfReader.h"
27 #include "llvm/Support/FileSystem.h"
28 #include "llvm/Support/Path.h"
29 
30 // This selects the coverage mapping format defined when `InstrProfData.inc`
31 // is textually included.
32 #define COVMAP_V3
33 
34 static llvm::cl::opt<bool> EmptyLineCommentCoverage(
35     "emptyline-comment-coverage",
36     llvm::cl::desc("Emit emptylines and comment lines as skipped regions (only "
37                    "disable it on test)"),
38     llvm::cl::init(true), llvm::cl::Hidden);
39 
40 using namespace clang;
41 using namespace CodeGen;
42 using namespace llvm::coverage;
43 
44 CoverageSourceInfo *
45 CoverageMappingModuleGen::setUpCoverageCallbacks(Preprocessor &PP) {
46   CoverageSourceInfo *CoverageInfo =
47       new CoverageSourceInfo(PP.getSourceManager());
48   PP.addPPCallbacks(std::unique_ptr<PPCallbacks>(CoverageInfo));
49   if (EmptyLineCommentCoverage) {
50     PP.addCommentHandler(CoverageInfo);
51     PP.setEmptylineHandler(CoverageInfo);
52     PP.setPreprocessToken(true);
53     PP.setTokenWatcher([CoverageInfo](clang::Token Tok) {
54       // Update previous token location.
55       CoverageInfo->PrevTokLoc = Tok.getLocation();
56       if (Tok.getKind() != clang::tok::eod)
57         CoverageInfo->updateNextTokLoc(Tok.getLocation());
58     });
59   }
60   return CoverageInfo;
61 }
62 
63 void CoverageSourceInfo::AddSkippedRange(SourceRange Range) {
64   if (EmptyLineCommentCoverage && !SkippedRanges.empty() &&
65       PrevTokLoc == SkippedRanges.back().PrevTokLoc &&
66       SourceMgr.isWrittenInSameFile(SkippedRanges.back().Range.getEnd(),
67                                     Range.getBegin()))
68     SkippedRanges.back().Range.setEnd(Range.getEnd());
69   else
70     SkippedRanges.push_back({Range, PrevTokLoc});
71 }
72 
73 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) {
74   AddSkippedRange(Range);
75 }
76 
77 void CoverageSourceInfo::HandleEmptyline(SourceRange Range) {
78   AddSkippedRange(Range);
79 }
80 
81 bool CoverageSourceInfo::HandleComment(Preprocessor &PP, SourceRange Range) {
82   AddSkippedRange(Range);
83   return false;
84 }
85 
86 void CoverageSourceInfo::updateNextTokLoc(SourceLocation Loc) {
87   if (!SkippedRanges.empty() && SkippedRanges.back().NextTokLoc.isInvalid())
88     SkippedRanges.back().NextTokLoc = Loc;
89 }
90 
91 namespace {
92 
93 /// A region of source code that can be mapped to a counter.
94 class SourceMappingRegion {
95   /// Primary Counter that is also used for Branch Regions for "True" branches.
96   Counter Count;
97 
98   /// Secondary Counter used for Branch Regions for "False" branches.
99   Optional<Counter> FalseCount;
100 
101   /// The region's starting location.
102   Optional<SourceLocation> LocStart;
103 
104   /// The region's ending location.
105   Optional<SourceLocation> LocEnd;
106 
107   /// Whether this region should be emitted after its parent is emitted.
108   bool DeferRegion;
109 
110   /// Whether this region is a gap region. The count from a gap region is set
111   /// as the line execution count if there are no other regions on the line.
112   bool GapRegion;
113 
114 public:
115   SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
116                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
117                       bool GapRegion = false)
118       : Count(Count), LocStart(LocStart), LocEnd(LocEnd),
119         DeferRegion(DeferRegion), GapRegion(GapRegion) {}
120 
121   SourceMappingRegion(Counter Count, Optional<Counter> FalseCount,
122                       Optional<SourceLocation> LocStart,
123                       Optional<SourceLocation> LocEnd, bool DeferRegion = false,
124                       bool GapRegion = false)
125       : Count(Count), FalseCount(FalseCount), LocStart(LocStart),
126         LocEnd(LocEnd), DeferRegion(DeferRegion), GapRegion(GapRegion) {}
127 
128   const Counter &getCounter() const { return Count; }
129 
130   const Counter &getFalseCounter() const {
131     assert(FalseCount && "Region has no alternate counter");
132     return *FalseCount;
133   }
134 
135   void setCounter(Counter C) { Count = C; }
136 
137   bool hasStartLoc() const { return LocStart.hasValue(); }
138 
139   void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
140 
141   SourceLocation getBeginLoc() const {
142     assert(LocStart && "Region has no start location");
143     return *LocStart;
144   }
145 
146   bool hasEndLoc() const { return LocEnd.hasValue(); }
147 
148   void setEndLoc(SourceLocation Loc) {
149     assert(Loc.isValid() && "Setting an invalid end location");
150     LocEnd = Loc;
151   }
152 
153   SourceLocation getEndLoc() const {
154     assert(LocEnd && "Region has no end location");
155     return *LocEnd;
156   }
157 
158   bool isDeferred() const { return DeferRegion; }
159 
160   void setDeferred(bool Deferred) { DeferRegion = Deferred; }
161 
162   bool isGap() const { return GapRegion; }
163 
164   void setGap(bool Gap) { GapRegion = Gap; }
165 
166   bool isBranch() const { return FalseCount.hasValue(); }
167 };
168 
169 /// Spelling locations for the start and end of a source region.
170 struct SpellingRegion {
171   /// The line where the region starts.
172   unsigned LineStart;
173 
174   /// The column where the region starts.
175   unsigned ColumnStart;
176 
177   /// The line where the region ends.
178   unsigned LineEnd;
179 
180   /// The column where the region ends.
181   unsigned ColumnEnd;
182 
183   SpellingRegion(SourceManager &SM, SourceLocation LocStart,
184                  SourceLocation LocEnd) {
185     LineStart = SM.getSpellingLineNumber(LocStart);
186     ColumnStart = SM.getSpellingColumnNumber(LocStart);
187     LineEnd = SM.getSpellingLineNumber(LocEnd);
188     ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
189   }
190 
191   SpellingRegion(SourceManager &SM, SourceMappingRegion &R)
192       : SpellingRegion(SM, R.getBeginLoc(), R.getEndLoc()) {}
193 
194   /// Check if the start and end locations appear in source order, i.e
195   /// top->bottom, left->right.
196   bool isInSourceOrder() const {
197     return (LineStart < LineEnd) ||
198            (LineStart == LineEnd && ColumnStart <= ColumnEnd);
199   }
200 };
201 
202 /// Provides the common functionality for the different
203 /// coverage mapping region builders.
204 class CoverageMappingBuilder {
205 public:
206   CoverageMappingModuleGen &CVM;
207   SourceManager &SM;
208   const LangOptions &LangOpts;
209 
210 private:
211   /// Map of clang's FileIDs to IDs used for coverage mapping.
212   llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
213       FileIDMapping;
214 
215 public:
216   /// The coverage mapping regions for this function
217   llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
218   /// The source mapping regions for this function.
219   std::vector<SourceMappingRegion> SourceRegions;
220 
221   /// A set of regions which can be used as a filter.
222   ///
223   /// It is produced by emitExpansionRegions() and is used in
224   /// emitSourceRegions() to suppress producing code regions if
225   /// the same area is covered by expansion regions.
226   typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8>
227       SourceRegionFilter;
228 
229   CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
230                          const LangOptions &LangOpts)
231       : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
232 
233   /// Return the precise end location for the given token.
234   SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
235     // We avoid getLocForEndOfToken here, because it doesn't do what we want for
236     // macro locations, which we just treat as expanded files.
237     unsigned TokLen =
238         Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
239     return Loc.getLocWithOffset(TokLen);
240   }
241 
242   /// Return the start location of an included file or expanded macro.
243   SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
244     if (Loc.isMacroID())
245       return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
246     return SM.getLocForStartOfFile(SM.getFileID(Loc));
247   }
248 
249   /// Return the end location of an included file or expanded macro.
250   SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
251     if (Loc.isMacroID())
252       return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
253                                   SM.getFileOffset(Loc));
254     return SM.getLocForEndOfFile(SM.getFileID(Loc));
255   }
256 
257   /// Find out where the current file is included or macro is expanded.
258   SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
259     return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).getBegin()
260                            : SM.getIncludeLoc(SM.getFileID(Loc));
261   }
262 
263   /// Return true if \c Loc is a location in a built-in macro.
264   bool isInBuiltin(SourceLocation Loc) {
265     return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>";
266   }
267 
268   /// Check whether \c Loc is included or expanded from \c Parent.
269   bool isNestedIn(SourceLocation Loc, FileID Parent) {
270     do {
271       Loc = getIncludeOrExpansionLoc(Loc);
272       if (Loc.isInvalid())
273         return false;
274     } while (!SM.isInFileID(Loc, Parent));
275     return true;
276   }
277 
278   /// Get the start of \c S ignoring macro arguments and builtin macros.
279   SourceLocation getStart(const Stmt *S) {
280     SourceLocation Loc = S->getBeginLoc();
281     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
282       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
283     return Loc;
284   }
285 
286   /// Get the end of \c S ignoring macro arguments and builtin macros.
287   SourceLocation getEnd(const Stmt *S) {
288     SourceLocation Loc = S->getEndLoc();
289     while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
290       Loc = SM.getImmediateExpansionRange(Loc).getBegin();
291     return getPreciseTokenLocEnd(Loc);
292   }
293 
294   /// Find the set of files we have regions for and assign IDs
295   ///
296   /// Fills \c Mapping with the virtual file mapping needed to write out
297   /// coverage and collects the necessary file information to emit source and
298   /// expansion regions.
299   void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
300     FileIDMapping.clear();
301 
302     llvm::SmallSet<FileID, 8> Visited;
303     SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
304     for (const auto &Region : SourceRegions) {
305       SourceLocation Loc = Region.getBeginLoc();
306       FileID File = SM.getFileID(Loc);
307       if (!Visited.insert(File).second)
308         continue;
309 
310       // Do not map FileID's associated with system headers.
311       if (SM.isInSystemHeader(SM.getSpellingLoc(Loc)))
312         continue;
313 
314       unsigned Depth = 0;
315       for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
316            Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
317         ++Depth;
318       FileLocs.push_back(std::make_pair(Loc, Depth));
319     }
320     llvm::stable_sort(FileLocs, llvm::less_second());
321 
322     for (const auto &FL : FileLocs) {
323       SourceLocation Loc = FL.first;
324       FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
325       auto Entry = SM.getFileEntryForID(SpellingFile);
326       if (!Entry)
327         continue;
328 
329       FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
330       Mapping.push_back(CVM.getFileID(Entry));
331     }
332   }
333 
334   /// Get the coverage mapping file ID for \c Loc.
335   ///
336   /// If such file id doesn't exist, return None.
337   Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
338     auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
339     if (Mapping != FileIDMapping.end())
340       return Mapping->second.first;
341     return None;
342   }
343 
344   /// This shrinks the skipped range if it spans a line that contains a
345   /// non-comment token. If shrinking the skipped range would make it empty,
346   /// this returns None.
347   Optional<SpellingRegion> adjustSkippedRange(SourceManager &SM,
348                                               SourceLocation LocStart,
349                                               SourceLocation LocEnd,
350                                               SourceLocation PrevTokLoc,
351                                               SourceLocation NextTokLoc) {
352     SpellingRegion SR{SM, LocStart, LocEnd};
353     SR.ColumnStart = 1;
354     if (PrevTokLoc.isValid() && SM.isWrittenInSameFile(LocStart, PrevTokLoc) &&
355         SR.LineStart == SM.getSpellingLineNumber(PrevTokLoc))
356       SR.LineStart++;
357     if (NextTokLoc.isValid() && SM.isWrittenInSameFile(LocEnd, NextTokLoc) &&
358         SR.LineEnd == SM.getSpellingLineNumber(NextTokLoc)) {
359       SR.LineEnd--;
360       SR.ColumnEnd++;
361     }
362     if (SR.isInSourceOrder())
363       return SR;
364     return None;
365   }
366 
367   /// Gather all the regions that were skipped by the preprocessor
368   /// using the constructs like #if or comments.
369   void gatherSkippedRegions() {
370     /// An array of the minimum lineStarts and the maximum lineEnds
371     /// for mapping regions from the appropriate source files.
372     llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
373     FileLineRanges.resize(
374         FileIDMapping.size(),
375         std::make_pair(std::numeric_limits<unsigned>::max(), 0));
376     for (const auto &R : MappingRegions) {
377       FileLineRanges[R.FileID].first =
378           std::min(FileLineRanges[R.FileID].first, R.LineStart);
379       FileLineRanges[R.FileID].second =
380           std::max(FileLineRanges[R.FileID].second, R.LineEnd);
381     }
382 
383     auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
384     for (auto &I : SkippedRanges) {
385       SourceRange Range = I.Range;
386       auto LocStart = Range.getBegin();
387       auto LocEnd = Range.getEnd();
388       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
389              "region spans multiple files");
390 
391       auto CovFileID = getCoverageFileID(LocStart);
392       if (!CovFileID)
393         continue;
394       Optional<SpellingRegion> SR =
395           adjustSkippedRange(SM, LocStart, LocEnd, I.PrevTokLoc, I.NextTokLoc);
396       if (!SR.hasValue())
397         continue;
398       auto Region = CounterMappingRegion::makeSkipped(
399           *CovFileID, SR->LineStart, SR->ColumnStart, SR->LineEnd,
400           SR->ColumnEnd);
401       // Make sure that we only collect the regions that are inside
402       // the source code of this function.
403       if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
404           Region.LineEnd <= FileLineRanges[*CovFileID].second)
405         MappingRegions.push_back(Region);
406     }
407   }
408 
409   /// Generate the coverage counter mapping regions from collected
410   /// source regions.
411   void emitSourceRegions(const SourceRegionFilter &Filter) {
412     for (const auto &Region : SourceRegions) {
413       assert(Region.hasEndLoc() && "incomplete region");
414 
415       SourceLocation LocStart = Region.getBeginLoc();
416       assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
417 
418       // Ignore regions from system headers.
419       if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart)))
420         continue;
421 
422       auto CovFileID = getCoverageFileID(LocStart);
423       // Ignore regions that don't have a file, such as builtin macros.
424       if (!CovFileID)
425         continue;
426 
427       SourceLocation LocEnd = Region.getEndLoc();
428       assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
429              "region spans multiple files");
430 
431       // Don't add code regions for the area covered by expansion regions.
432       // This not only suppresses redundant regions, but sometimes prevents
433       // creating regions with wrong counters if, for example, a statement's
434       // body ends at the end of a nested macro.
435       if (Filter.count(std::make_pair(LocStart, LocEnd)))
436         continue;
437 
438       // Find the spelling locations for the mapping region.
439       SpellingRegion SR{SM, LocStart, LocEnd};
440       assert(SR.isInSourceOrder() && "region start and end out of order");
441 
442       if (Region.isGap()) {
443         MappingRegions.push_back(CounterMappingRegion::makeGapRegion(
444             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
445             SR.LineEnd, SR.ColumnEnd));
446       } else if (Region.isBranch()) {
447         MappingRegions.push_back(CounterMappingRegion::makeBranchRegion(
448             Region.getCounter(), Region.getFalseCounter(), *CovFileID,
449             SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd));
450       } else {
451         MappingRegions.push_back(CounterMappingRegion::makeRegion(
452             Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart,
453             SR.LineEnd, SR.ColumnEnd));
454       }
455     }
456   }
457 
458   /// Generate expansion regions for each virtual file we've seen.
459   SourceRegionFilter emitExpansionRegions() {
460     SourceRegionFilter Filter;
461     for (const auto &FM : FileIDMapping) {
462       SourceLocation ExpandedLoc = FM.second.second;
463       SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
464       if (ParentLoc.isInvalid())
465         continue;
466 
467       auto ParentFileID = getCoverageFileID(ParentLoc);
468       if (!ParentFileID)
469         continue;
470       auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
471       assert(ExpandedFileID && "expansion in uncovered file");
472 
473       SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
474       assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
475              "region spans multiple files");
476       Filter.insert(std::make_pair(ParentLoc, LocEnd));
477 
478       SpellingRegion SR{SM, ParentLoc, LocEnd};
479       assert(SR.isInSourceOrder() && "region start and end out of order");
480       MappingRegions.push_back(CounterMappingRegion::makeExpansion(
481           *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart,
482           SR.LineEnd, SR.ColumnEnd));
483     }
484     return Filter;
485   }
486 };
487 
488 /// Creates unreachable coverage regions for the functions that
489 /// are not emitted.
490 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
491   EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
492                               const LangOptions &LangOpts)
493       : CoverageMappingBuilder(CVM, SM, LangOpts) {}
494 
495   void VisitDecl(const Decl *D) {
496     if (!D->hasBody())
497       return;
498     auto Body = D->getBody();
499     SourceLocation Start = getStart(Body);
500     SourceLocation End = getEnd(Body);
501     if (!SM.isWrittenInSameFile(Start, End)) {
502       // Walk up to find the common ancestor.
503       // Correct the locations accordingly.
504       FileID StartFileID = SM.getFileID(Start);
505       FileID EndFileID = SM.getFileID(End);
506       while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
507         Start = getIncludeOrExpansionLoc(Start);
508         assert(Start.isValid() &&
509                "Declaration start location not nested within a known region");
510         StartFileID = SM.getFileID(Start);
511       }
512       while (StartFileID != EndFileID) {
513         End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
514         assert(End.isValid() &&
515                "Declaration end location not nested within a known region");
516         EndFileID = SM.getFileID(End);
517       }
518     }
519     SourceRegions.emplace_back(Counter(), Start, End);
520   }
521 
522   /// Write the mapping data to the output stream
523   void write(llvm::raw_ostream &OS) {
524     SmallVector<unsigned, 16> FileIDMapping;
525     gatherFileIDs(FileIDMapping);
526     emitSourceRegions(SourceRegionFilter());
527 
528     if (MappingRegions.empty())
529       return;
530 
531     CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
532     Writer.write(OS);
533   }
534 };
535 
536 /// A StmtVisitor that creates coverage mapping regions which map
537 /// from the source code locations to the PGO counters.
538 struct CounterCoverageMappingBuilder
539     : public CoverageMappingBuilder,
540       public ConstStmtVisitor<CounterCoverageMappingBuilder> {
541   /// The map of statements to count values.
542   llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
543 
544   /// A stack of currently live regions.
545   std::vector<SourceMappingRegion> RegionStack;
546 
547   /// The currently deferred region: its end location and count can be set once
548   /// its parent has been popped from the region stack.
549   Optional<SourceMappingRegion> DeferredRegion;
550 
551   CounterExpressionBuilder Builder;
552 
553   /// A location in the most recently visited file or macro.
554   ///
555   /// This is used to adjust the active source regions appropriately when
556   /// expressions cross file or macro boundaries.
557   SourceLocation MostRecentLocation;
558 
559   /// Location of the last terminated region.
560   Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion;
561 
562   /// Return a counter for the subtraction of \c RHS from \c LHS
563   Counter subtractCounters(Counter LHS, Counter RHS) {
564     return Builder.subtract(LHS, RHS);
565   }
566 
567   /// Return a counter for the sum of \c LHS and \c RHS.
568   Counter addCounters(Counter LHS, Counter RHS) {
569     return Builder.add(LHS, RHS);
570   }
571 
572   Counter addCounters(Counter C1, Counter C2, Counter C3) {
573     return addCounters(addCounters(C1, C2), C3);
574   }
575 
576   /// Return the region counter for the given statement.
577   ///
578   /// This should only be called on statements that have a dedicated counter.
579   Counter getRegionCounter(const Stmt *S) {
580     return Counter::getCounter(CounterMap[S]);
581   }
582 
583   /// Push a region onto the stack.
584   ///
585   /// Returns the index on the stack where the region was pushed. This can be
586   /// used with popRegions to exit a "scope", ending the region that was pushed.
587   size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
588                     Optional<SourceLocation> EndLoc = None,
589                     Optional<Counter> FalseCount = None) {
590 
591     if (StartLoc && !FalseCount.hasValue()) {
592       MostRecentLocation = *StartLoc;
593       completeDeferred(Count, MostRecentLocation);
594     }
595 
596     RegionStack.emplace_back(Count, FalseCount, StartLoc, EndLoc,
597                              FalseCount.hasValue());
598 
599     return RegionStack.size() - 1;
600   }
601 
602   /// Complete any pending deferred region by setting its end location and
603   /// count, and then pushing it onto the region stack.
604   size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) {
605     size_t Index = RegionStack.size();
606     if (!DeferredRegion)
607       return Index;
608 
609     // Consume the pending region.
610     SourceMappingRegion DR = DeferredRegion.getValue();
611     DeferredRegion = None;
612 
613     // If the region ends in an expansion, find the expansion site.
614     FileID StartFile = SM.getFileID(DR.getBeginLoc());
615     if (SM.getFileID(DeferredEndLoc) != StartFile) {
616       if (isNestedIn(DeferredEndLoc, StartFile)) {
617         do {
618           DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc);
619         } while (StartFile != SM.getFileID(DeferredEndLoc));
620       } else {
621         return Index;
622       }
623     }
624 
625     // The parent of this deferred region ends where the containing decl ends,
626     // so the region isn't useful.
627     if (DR.getBeginLoc() == DeferredEndLoc)
628       return Index;
629 
630     // If we're visiting statements in non-source order (e.g switch cases or
631     // a loop condition) we can't construct a sensible deferred region.
632     if (!SpellingRegion(SM, DR.getBeginLoc(), DeferredEndLoc).isInSourceOrder())
633       return Index;
634 
635     DR.setGap(true);
636     DR.setCounter(Count);
637     DR.setEndLoc(DeferredEndLoc);
638     handleFileExit(DeferredEndLoc);
639     RegionStack.push_back(DR);
640     return Index;
641   }
642 
643   /// Complete a deferred region created after a terminated region at the
644   /// top-level.
645   void completeTopLevelDeferredRegion(Counter Count,
646                                       SourceLocation DeferredEndLoc) {
647     if (DeferredRegion || !LastTerminatedRegion)
648       return;
649 
650     if (LastTerminatedRegion->second != RegionStack.size())
651       return;
652 
653     SourceLocation Start = LastTerminatedRegion->first;
654     if (SM.getFileID(Start) != SM.getMainFileID())
655       return;
656 
657     SourceMappingRegion DR = RegionStack.back();
658     DR.setStartLoc(Start);
659     DR.setDeferred(false);
660     DeferredRegion = DR;
661     completeDeferred(Count, DeferredEndLoc);
662   }
663 
664   size_t locationDepth(SourceLocation Loc) {
665     size_t Depth = 0;
666     while (Loc.isValid()) {
667       Loc = getIncludeOrExpansionLoc(Loc);
668       Depth++;
669     }
670     return Depth;
671   }
672 
673   /// Pop regions from the stack into the function's list of regions.
674   ///
675   /// Adds all regions from \c ParentIndex to the top of the stack to the
676   /// function's \c SourceRegions.
677   void popRegions(size_t ParentIndex) {
678     assert(RegionStack.size() >= ParentIndex && "parent not in stack");
679     bool ParentOfDeferredRegion = false;
680     while (RegionStack.size() > ParentIndex) {
681       SourceMappingRegion &Region = RegionStack.back();
682       if (Region.hasStartLoc()) {
683         SourceLocation StartLoc = Region.getBeginLoc();
684         SourceLocation EndLoc = Region.hasEndLoc()
685                                     ? Region.getEndLoc()
686                                     : RegionStack[ParentIndex].getEndLoc();
687         bool isBranch = Region.isBranch();
688         size_t StartDepth = locationDepth(StartLoc);
689         size_t EndDepth = locationDepth(EndLoc);
690         while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
691           bool UnnestStart = StartDepth >= EndDepth;
692           bool UnnestEnd = EndDepth >= StartDepth;
693           if (UnnestEnd) {
694             // The region ends in a nested file or macro expansion. If the
695             // region is not a branch region, create a separate region for each
696             // expansion, and for all regions, update the EndLoc. Branch
697             // regions should not be split in order to keep a straightforward
698             // correspondance between the region and its associated branch
699             // condition, even if the condition spans multiple depths.
700             SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
701             assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
702 
703             if (!isBranch && !isRegionAlreadyAdded(NestedLoc, EndLoc))
704               SourceRegions.emplace_back(Region.getCounter(), NestedLoc,
705                                          EndLoc);
706 
707             EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
708             if (EndLoc.isInvalid())
709               llvm::report_fatal_error(
710                   "File exit not handled before popRegions");
711             EndDepth--;
712           }
713           if (UnnestStart) {
714             // The region ends in a nested file or macro expansion. If the
715             // region is not a branch region, create a separate region for each
716             // expansion, and for all regions, update the StartLoc. Branch
717             // regions should not be split in order to keep a straightforward
718             // correspondance between the region and its associated branch
719             // condition, even if the condition spans multiple depths.
720             SourceLocation NestedLoc = getEndOfFileOrMacro(StartLoc);
721             assert(SM.isWrittenInSameFile(StartLoc, NestedLoc));
722 
723             if (!isBranch && !isRegionAlreadyAdded(StartLoc, NestedLoc))
724               SourceRegions.emplace_back(Region.getCounter(), StartLoc,
725                                          NestedLoc);
726 
727             StartLoc = getIncludeOrExpansionLoc(StartLoc);
728             if (StartLoc.isInvalid())
729               llvm::report_fatal_error(
730                   "File exit not handled before popRegions");
731             StartDepth--;
732           }
733         }
734         Region.setStartLoc(StartLoc);
735         Region.setEndLoc(EndLoc);
736 
737         if (!isBranch) {
738           MostRecentLocation = EndLoc;
739           // If this region happens to span an entire expansion, we need to
740           // make sure we don't overlap the parent region with it.
741           if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
742               EndLoc == getEndOfFileOrMacro(EndLoc))
743             MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
744         }
745 
746         assert(SM.isWrittenInSameFile(Region.getBeginLoc(), EndLoc));
747         assert(SpellingRegion(SM, Region).isInSourceOrder());
748         SourceRegions.push_back(Region);
749 
750         if (ParentOfDeferredRegion) {
751           ParentOfDeferredRegion = false;
752 
753           // If there's an existing deferred region, keep the old one, because
754           // it means there are two consecutive returns (or a similar pattern).
755           if (!DeferredRegion.hasValue() &&
756               // File IDs aren't gathered within macro expansions, so it isn't
757               // useful to try and create a deferred region inside of one.
758               !EndLoc.isMacroID())
759             DeferredRegion =
760                 SourceMappingRegion(Counter::getZero(), EndLoc, None);
761         }
762       } else if (Region.isDeferred()) {
763         assert(!ParentOfDeferredRegion && "Consecutive deferred regions");
764         ParentOfDeferredRegion = true;
765       }
766       RegionStack.pop_back();
767 
768       // If the zero region pushed after the last terminated region no longer
769       // exists, clear its cached information.
770       if (LastTerminatedRegion &&
771           RegionStack.size() < LastTerminatedRegion->second)
772         LastTerminatedRegion = None;
773     }
774     assert(!ParentOfDeferredRegion && "Deferred region with no parent");
775   }
776 
777   /// Return the currently active region.
778   SourceMappingRegion &getRegion() {
779     assert(!RegionStack.empty() && "statement has no region");
780     return RegionStack.back();
781   }
782 
783   /// Propagate counts through the children of \p S if \p VisitChildren is true.
784   /// Otherwise, only emit a count for \p S itself.
785   Counter propagateCounts(Counter TopCount, const Stmt *S,
786                           bool VisitChildren = true) {
787     SourceLocation StartLoc = getStart(S);
788     SourceLocation EndLoc = getEnd(S);
789     size_t Index = pushRegion(TopCount, StartLoc, EndLoc);
790     if (VisitChildren)
791       Visit(S);
792     Counter ExitCount = getRegion().getCounter();
793     popRegions(Index);
794 
795     // The statement may be spanned by an expansion. Make sure we handle a file
796     // exit out of this expansion before moving to the next statement.
797     if (SM.isBeforeInTranslationUnit(StartLoc, S->getBeginLoc()))
798       MostRecentLocation = EndLoc;
799 
800     return ExitCount;
801   }
802 
803   /// Determine whether the given condition can be constant folded.
804   bool ConditionFoldsToBool(const Expr *Cond) {
805     Expr::EvalResult Result;
806     return (Cond->EvaluateAsInt(Result, CVM.getCodeGenModule().getContext()));
807   }
808 
809   /// Create a Branch Region around an instrumentable condition for coverage
810   /// and add it to the function's SourceRegions.  A branch region tracks a
811   /// "True" counter and a "False" counter for boolean expressions that
812   /// result in the generation of a branch.
813   void createBranchRegion(const Expr *C, Counter TrueCnt, Counter FalseCnt) {
814     // Check for NULL conditions.
815     if (!C)
816       return;
817 
818     // Ensure we are an instrumentable condition (i.e. no "&&" or "||").  Push
819     // region onto RegionStack but immediately pop it (which adds it to the
820     // function's SourceRegions) because it doesn't apply to any other source
821     // code other than the Condition.
822     if (CodeGenFunction::isInstrumentedCondition(C)) {
823       // If a condition can fold to true or false, the corresponding branch
824       // will be removed.  Create a region with both counters hard-coded to
825       // zero. This allows us to visualize them in a special way.
826       // Alternatively, we can prevent any optimization done via
827       // constant-folding by ensuring that ConstantFoldsToSimpleInteger() in
828       // CodeGenFunction.c always returns false, but that is very heavy-handed.
829       if (ConditionFoldsToBool(C))
830         popRegions(pushRegion(Counter::getZero(), getStart(C), getEnd(C),
831                               Counter::getZero()));
832       else
833         // Otherwise, create a region with the True counter and False counter.
834         popRegions(pushRegion(TrueCnt, getStart(C), getEnd(C), FalseCnt));
835     }
836   }
837 
838   /// Create a Branch Region around a SwitchCase for code coverage
839   /// and add it to the function's SourceRegions.
840   void createSwitchCaseRegion(const SwitchCase *SC, Counter TrueCnt,
841                               Counter FalseCnt) {
842     // Push region onto RegionStack but immediately pop it (which adds it to
843     // the function's SourceRegions) because it doesn't apply to any other
844     // source other than the SwitchCase.
845     popRegions(pushRegion(TrueCnt, getStart(SC), SC->getColonLoc(), FalseCnt));
846   }
847 
848   /// Check whether a region with bounds \c StartLoc and \c EndLoc
849   /// is already added to \c SourceRegions.
850   bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc,
851                             bool isBranch = false) {
852     return SourceRegions.rend() !=
853            std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
854                         [&](const SourceMappingRegion &Region) {
855                           return Region.getBeginLoc() == StartLoc &&
856                                  Region.getEndLoc() == EndLoc &&
857                                  Region.isBranch() == isBranch;
858                         });
859   }
860 
861   /// Adjust the most recently visited location to \c EndLoc.
862   ///
863   /// This should be used after visiting any statements in non-source order.
864   void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
865     MostRecentLocation = EndLoc;
866     // The code region for a whole macro is created in handleFileExit() when
867     // it detects exiting of the virtual file of that macro. If we visited
868     // statements in non-source order, we might already have such a region
869     // added, for example, if a body of a loop is divided among multiple
870     // macros. Avoid adding duplicate regions in such case.
871     if (getRegion().hasEndLoc() &&
872         MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
873         isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
874                              MostRecentLocation, getRegion().isBranch()))
875       MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
876   }
877 
878   /// Adjust regions and state when \c NewLoc exits a file.
879   ///
880   /// If moving from our most recently tracked location to \c NewLoc exits any
881   /// files, this adjusts our current region stack and creates the file regions
882   /// for the exited file.
883   void handleFileExit(SourceLocation NewLoc) {
884     if (NewLoc.isInvalid() ||
885         SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
886       return;
887 
888     // If NewLoc is not in a file that contains MostRecentLocation, walk up to
889     // find the common ancestor.
890     SourceLocation LCA = NewLoc;
891     FileID ParentFile = SM.getFileID(LCA);
892     while (!isNestedIn(MostRecentLocation, ParentFile)) {
893       LCA = getIncludeOrExpansionLoc(LCA);
894       if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
895         // Since there isn't a common ancestor, no file was exited. We just need
896         // to adjust our location to the new file.
897         MostRecentLocation = NewLoc;
898         return;
899       }
900       ParentFile = SM.getFileID(LCA);
901     }
902 
903     llvm::SmallSet<SourceLocation, 8> StartLocs;
904     Optional<Counter> ParentCounter;
905     for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
906       if (!I.hasStartLoc())
907         continue;
908       SourceLocation Loc = I.getBeginLoc();
909       if (!isNestedIn(Loc, ParentFile)) {
910         ParentCounter = I.getCounter();
911         break;
912       }
913 
914       while (!SM.isInFileID(Loc, ParentFile)) {
915         // The most nested region for each start location is the one with the
916         // correct count. We avoid creating redundant regions by stopping once
917         // we've seen this region.
918         if (StartLocs.insert(Loc).second) {
919           if (I.isBranch())
920             SourceRegions.emplace_back(I.getCounter(), I.getFalseCounter(), Loc,
921                                        getEndOfFileOrMacro(Loc), I.isBranch());
922           else
923             SourceRegions.emplace_back(I.getCounter(), Loc,
924                                        getEndOfFileOrMacro(Loc));
925         }
926         Loc = getIncludeOrExpansionLoc(Loc);
927       }
928       I.setStartLoc(getPreciseTokenLocEnd(Loc));
929     }
930 
931     if (ParentCounter) {
932       // If the file is contained completely by another region and doesn't
933       // immediately start its own region, the whole file gets a region
934       // corresponding to the parent.
935       SourceLocation Loc = MostRecentLocation;
936       while (isNestedIn(Loc, ParentFile)) {
937         SourceLocation FileStart = getStartOfFileOrMacro(Loc);
938         if (StartLocs.insert(FileStart).second) {
939           SourceRegions.emplace_back(*ParentCounter, FileStart,
940                                      getEndOfFileOrMacro(Loc));
941           assert(SpellingRegion(SM, SourceRegions.back()).isInSourceOrder());
942         }
943         Loc = getIncludeOrExpansionLoc(Loc);
944       }
945     }
946 
947     MostRecentLocation = NewLoc;
948   }
949 
950   /// Ensure that \c S is included in the current region.
951   void extendRegion(const Stmt *S) {
952     SourceMappingRegion &Region = getRegion();
953     SourceLocation StartLoc = getStart(S);
954 
955     handleFileExit(StartLoc);
956     if (!Region.hasStartLoc())
957       Region.setStartLoc(StartLoc);
958 
959     completeDeferred(Region.getCounter(), StartLoc);
960   }
961 
962   /// Mark \c S as a terminator, starting a zero region.
963   void terminateRegion(const Stmt *S) {
964     extendRegion(S);
965     SourceMappingRegion &Region = getRegion();
966     SourceLocation EndLoc = getEnd(S);
967     if (!Region.hasEndLoc())
968       Region.setEndLoc(EndLoc);
969     pushRegion(Counter::getZero());
970     auto &ZeroRegion = getRegion();
971     ZeroRegion.setDeferred(true);
972     LastTerminatedRegion = {EndLoc, RegionStack.size()};
973   }
974 
975   /// Find a valid gap range between \p AfterLoc and \p BeforeLoc.
976   Optional<SourceRange> findGapAreaBetween(SourceLocation AfterLoc,
977                                            SourceLocation BeforeLoc) {
978     // If the start and end locations of the gap are both within the same macro
979     // file, the range may not be in source order.
980     if (AfterLoc.isMacroID() || BeforeLoc.isMacroID())
981       return None;
982     if (!SM.isWrittenInSameFile(AfterLoc, BeforeLoc))
983       return None;
984     return {{AfterLoc, BeforeLoc}};
985   }
986 
987   /// Find the source range after \p AfterStmt and before \p BeforeStmt.
988   Optional<SourceRange> findGapAreaBetween(const Stmt *AfterStmt,
989                                            const Stmt *BeforeStmt) {
990     return findGapAreaBetween(getPreciseTokenLocEnd(getEnd(AfterStmt)),
991                               getStart(BeforeStmt));
992   }
993 
994   /// Emit a gap region between \p StartLoc and \p EndLoc with the given count.
995   void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc,
996                             Counter Count) {
997     if (StartLoc == EndLoc)
998       return;
999     assert(SpellingRegion(SM, StartLoc, EndLoc).isInSourceOrder());
1000     handleFileExit(StartLoc);
1001     size_t Index = pushRegion(Count, StartLoc, EndLoc);
1002     getRegion().setGap(true);
1003     handleFileExit(EndLoc);
1004     popRegions(Index);
1005   }
1006 
1007   /// Keep counts of breaks and continues inside loops.
1008   struct BreakContinue {
1009     Counter BreakCount;
1010     Counter ContinueCount;
1011   };
1012   SmallVector<BreakContinue, 8> BreakContinueStack;
1013 
1014   CounterCoverageMappingBuilder(
1015       CoverageMappingModuleGen &CVM,
1016       llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
1017       const LangOptions &LangOpts)
1018       : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap),
1019         DeferredRegion(None) {}
1020 
1021   /// Write the mapping data to the output stream
1022   void write(llvm::raw_ostream &OS) {
1023     llvm::SmallVector<unsigned, 8> VirtualFileMapping;
1024     gatherFileIDs(VirtualFileMapping);
1025     SourceRegionFilter Filter = emitExpansionRegions();
1026     assert(!DeferredRegion && "Deferred region never completed");
1027     emitSourceRegions(Filter);
1028     gatherSkippedRegions();
1029 
1030     if (MappingRegions.empty())
1031       return;
1032 
1033     CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
1034                                  MappingRegions);
1035     Writer.write(OS);
1036   }
1037 
1038   void VisitStmt(const Stmt *S) {
1039     if (S->getBeginLoc().isValid())
1040       extendRegion(S);
1041     for (const Stmt *Child : S->children())
1042       if (Child)
1043         this->Visit(Child);
1044     handleFileExit(getEnd(S));
1045   }
1046 
1047   void VisitDecl(const Decl *D) {
1048     assert(!DeferredRegion && "Deferred region never completed");
1049 
1050     Stmt *Body = D->getBody();
1051 
1052     // Do not propagate region counts into system headers.
1053     if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body))))
1054       return;
1055 
1056     // Do not visit the artificial children nodes of defaulted methods. The
1057     // lexer may not be able to report back precise token end locations for
1058     // these children nodes (llvm.org/PR39822), and moreover users will not be
1059     // able to see coverage for them.
1060     bool Defaulted = false;
1061     if (auto *Method = dyn_cast<CXXMethodDecl>(D))
1062       Defaulted = Method->isDefaulted();
1063 
1064     propagateCounts(getRegionCounter(Body), Body,
1065                     /*VisitChildren=*/!Defaulted);
1066     assert(RegionStack.empty() && "Regions entered but never exited");
1067 
1068     // Discard the last uncompleted deferred region in a decl, if one exists.
1069     // This prevents lines at the end of a function containing only whitespace
1070     // or closing braces from being marked as uncovered.
1071     DeferredRegion = None;
1072   }
1073 
1074   void VisitReturnStmt(const ReturnStmt *S) {
1075     extendRegion(S);
1076     if (S->getRetValue())
1077       Visit(S->getRetValue());
1078     terminateRegion(S);
1079   }
1080 
1081   void VisitCoroutineBodyStmt(const CoroutineBodyStmt *S) {
1082     extendRegion(S);
1083     Visit(S->getBody());
1084   }
1085 
1086   void VisitCoreturnStmt(const CoreturnStmt *S) {
1087     extendRegion(S);
1088     if (S->getOperand())
1089       Visit(S->getOperand());
1090     terminateRegion(S);
1091   }
1092 
1093   void VisitCXXThrowExpr(const CXXThrowExpr *E) {
1094     extendRegion(E);
1095     if (E->getSubExpr())
1096       Visit(E->getSubExpr());
1097     terminateRegion(E);
1098   }
1099 
1100   void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
1101 
1102   void VisitLabelStmt(const LabelStmt *S) {
1103     Counter LabelCount = getRegionCounter(S);
1104     SourceLocation Start = getStart(S);
1105     completeTopLevelDeferredRegion(LabelCount, Start);
1106     completeDeferred(LabelCount, Start);
1107     // We can't extendRegion here or we risk overlapping with our new region.
1108     handleFileExit(Start);
1109     pushRegion(LabelCount, Start);
1110     Visit(S->getSubStmt());
1111   }
1112 
1113   void VisitBreakStmt(const BreakStmt *S) {
1114     assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
1115     BreakContinueStack.back().BreakCount = addCounters(
1116         BreakContinueStack.back().BreakCount, getRegion().getCounter());
1117     // FIXME: a break in a switch should terminate regions for all preceding
1118     // case statements, not just the most recent one.
1119     terminateRegion(S);
1120   }
1121 
1122   void VisitContinueStmt(const ContinueStmt *S) {
1123     assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
1124     BreakContinueStack.back().ContinueCount = addCounters(
1125         BreakContinueStack.back().ContinueCount, getRegion().getCounter());
1126     terminateRegion(S);
1127   }
1128 
1129   void VisitCallExpr(const CallExpr *E) {
1130     VisitStmt(E);
1131 
1132     // Terminate the region when we hit a noreturn function.
1133     // (This is helpful dealing with switch statements.)
1134     QualType CalleeType = E->getCallee()->getType();
1135     if (getFunctionExtInfo(*CalleeType).getNoReturn())
1136       terminateRegion(E);
1137   }
1138 
1139   void VisitWhileStmt(const WhileStmt *S) {
1140     extendRegion(S);
1141 
1142     Counter ParentCount = getRegion().getCounter();
1143     Counter BodyCount = getRegionCounter(S);
1144 
1145     // Handle the body first so that we can get the backedge count.
1146     BreakContinueStack.push_back(BreakContinue());
1147     extendRegion(S->getBody());
1148     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1149     BreakContinue BC = BreakContinueStack.pop_back_val();
1150 
1151     // Go back to handle the condition.
1152     Counter CondCount =
1153         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1154     propagateCounts(CondCount, S->getCond());
1155     adjustForOutOfOrderTraversal(getEnd(S));
1156 
1157     // The body count applies to the area immediately after the increment.
1158     auto Gap = findGapAreaBetween(S->getCond(), S->getBody());
1159     if (Gap)
1160       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1161 
1162     Counter OutCount =
1163         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1164     if (OutCount != ParentCount)
1165       pushRegion(OutCount);
1166 
1167     // Create Branch Region around condition.
1168     createBranchRegion(S->getCond(), BodyCount,
1169                        subtractCounters(CondCount, BodyCount));
1170   }
1171 
1172   void VisitDoStmt(const DoStmt *S) {
1173     extendRegion(S);
1174 
1175     Counter ParentCount = getRegion().getCounter();
1176     Counter BodyCount = getRegionCounter(S);
1177 
1178     BreakContinueStack.push_back(BreakContinue());
1179     extendRegion(S->getBody());
1180     Counter BackedgeCount =
1181         propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
1182     BreakContinue BC = BreakContinueStack.pop_back_val();
1183 
1184     Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
1185     propagateCounts(CondCount, S->getCond());
1186 
1187     Counter OutCount =
1188         addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
1189     if (OutCount != ParentCount)
1190       pushRegion(OutCount);
1191 
1192     // Create Branch Region around condition.
1193     createBranchRegion(S->getCond(), BodyCount,
1194                        subtractCounters(CondCount, BodyCount));
1195   }
1196 
1197   void VisitForStmt(const ForStmt *S) {
1198     extendRegion(S);
1199     if (S->getInit())
1200       Visit(S->getInit());
1201 
1202     Counter ParentCount = getRegion().getCounter();
1203     Counter BodyCount = getRegionCounter(S);
1204 
1205     // The loop increment may contain a break or continue.
1206     if (S->getInc())
1207       BreakContinueStack.emplace_back();
1208 
1209     // Handle the body first so that we can get the backedge count.
1210     BreakContinueStack.emplace_back();
1211     extendRegion(S->getBody());
1212     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1213     BreakContinue BodyBC = BreakContinueStack.pop_back_val();
1214 
1215     // The increment is essentially part of the body but it needs to include
1216     // the count for all the continue statements.
1217     BreakContinue IncrementBC;
1218     if (const Stmt *Inc = S->getInc()) {
1219       propagateCounts(addCounters(BackedgeCount, BodyBC.ContinueCount), Inc);
1220       IncrementBC = BreakContinueStack.pop_back_val();
1221     }
1222 
1223     // Go back to handle the condition.
1224     Counter CondCount = addCounters(
1225         addCounters(ParentCount, BackedgeCount, BodyBC.ContinueCount),
1226         IncrementBC.ContinueCount);
1227     if (const Expr *Cond = S->getCond()) {
1228       propagateCounts(CondCount, Cond);
1229       adjustForOutOfOrderTraversal(getEnd(S));
1230     }
1231 
1232     // The body count applies to the area immediately after the increment.
1233     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1234                                   getStart(S->getBody()));
1235     if (Gap)
1236       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1237 
1238     Counter OutCount = addCounters(BodyBC.BreakCount, IncrementBC.BreakCount,
1239                                    subtractCounters(CondCount, BodyCount));
1240     if (OutCount != ParentCount)
1241       pushRegion(OutCount);
1242 
1243     // Create Branch Region around condition.
1244     createBranchRegion(S->getCond(), BodyCount,
1245                        subtractCounters(CondCount, BodyCount));
1246   }
1247 
1248   void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
1249     extendRegion(S);
1250     if (S->getInit())
1251       Visit(S->getInit());
1252     Visit(S->getLoopVarStmt());
1253     Visit(S->getRangeStmt());
1254 
1255     Counter ParentCount = getRegion().getCounter();
1256     Counter BodyCount = getRegionCounter(S);
1257 
1258     BreakContinueStack.push_back(BreakContinue());
1259     extendRegion(S->getBody());
1260     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1261     BreakContinue BC = BreakContinueStack.pop_back_val();
1262 
1263     // The body count applies to the area immediately after the range.
1264     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1265                                   getStart(S->getBody()));
1266     if (Gap)
1267       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1268 
1269     Counter LoopCount =
1270         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1271     Counter OutCount =
1272         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1273     if (OutCount != ParentCount)
1274       pushRegion(OutCount);
1275 
1276     // Create Branch Region around condition.
1277     createBranchRegion(S->getCond(), BodyCount,
1278                        subtractCounters(LoopCount, BodyCount));
1279   }
1280 
1281   void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
1282     extendRegion(S);
1283     Visit(S->getElement());
1284 
1285     Counter ParentCount = getRegion().getCounter();
1286     Counter BodyCount = getRegionCounter(S);
1287 
1288     BreakContinueStack.push_back(BreakContinue());
1289     extendRegion(S->getBody());
1290     Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
1291     BreakContinue BC = BreakContinueStack.pop_back_val();
1292 
1293     // The body count applies to the area immediately after the collection.
1294     auto Gap = findGapAreaBetween(getPreciseTokenLocEnd(S->getRParenLoc()),
1295                                   getStart(S->getBody()));
1296     if (Gap)
1297       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), BodyCount);
1298 
1299     Counter LoopCount =
1300         addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
1301     Counter OutCount =
1302         addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
1303     if (OutCount != ParentCount)
1304       pushRegion(OutCount);
1305   }
1306 
1307   void VisitSwitchStmt(const SwitchStmt *S) {
1308     extendRegion(S);
1309     if (S->getInit())
1310       Visit(S->getInit());
1311     Visit(S->getCond());
1312 
1313     BreakContinueStack.push_back(BreakContinue());
1314 
1315     const Stmt *Body = S->getBody();
1316     extendRegion(Body);
1317     if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
1318       if (!CS->body_empty()) {
1319         // Make a region for the body of the switch.  If the body starts with
1320         // a case, that case will reuse this region; otherwise, this covers
1321         // the unreachable code at the beginning of the switch body.
1322         size_t Index = pushRegion(Counter::getZero(), getStart(CS));
1323         getRegion().setGap(true);
1324         for (const auto *Child : CS->children())
1325           Visit(Child);
1326 
1327         // Set the end for the body of the switch, if it isn't already set.
1328         for (size_t i = RegionStack.size(); i != Index; --i) {
1329           if (!RegionStack[i - 1].hasEndLoc())
1330             RegionStack[i - 1].setEndLoc(getEnd(CS->body_back()));
1331         }
1332 
1333         popRegions(Index);
1334       }
1335     } else
1336       propagateCounts(Counter::getZero(), Body);
1337     BreakContinue BC = BreakContinueStack.pop_back_val();
1338 
1339     if (!BreakContinueStack.empty())
1340       BreakContinueStack.back().ContinueCount = addCounters(
1341           BreakContinueStack.back().ContinueCount, BC.ContinueCount);
1342 
1343     Counter ParentCount = getRegion().getCounter();
1344     Counter ExitCount = getRegionCounter(S);
1345     SourceLocation ExitLoc = getEnd(S);
1346     pushRegion(ExitCount);
1347 
1348     // Ensure that handleFileExit recognizes when the end location is located
1349     // in a different file.
1350     MostRecentLocation = getStart(S);
1351     handleFileExit(ExitLoc);
1352 
1353     // Create a Branch Region around each Case. Subtract the case's
1354     // counter from the Parent counter to track the "False" branch count.
1355     Counter CaseCountSum;
1356     bool HasDefaultCase = false;
1357     const SwitchCase *Case = S->getSwitchCaseList();
1358     for (; Case; Case = Case->getNextSwitchCase()) {
1359       HasDefaultCase = HasDefaultCase || isa<DefaultStmt>(Case);
1360       CaseCountSum = addCounters(CaseCountSum, getRegionCounter(Case));
1361       createSwitchCaseRegion(
1362           Case, getRegionCounter(Case),
1363           subtractCounters(ParentCount, getRegionCounter(Case)));
1364     }
1365 
1366     // If no explicit default case exists, create a branch region to represent
1367     // the hidden branch, which will be added later by the CodeGen. This region
1368     // will be associated with the switch statement's condition.
1369     if (!HasDefaultCase) {
1370       Counter DefaultTrue = subtractCounters(ParentCount, CaseCountSum);
1371       Counter DefaultFalse = subtractCounters(ParentCount, DefaultTrue);
1372       createBranchRegion(S->getCond(), DefaultTrue, DefaultFalse);
1373     }
1374   }
1375 
1376   void VisitSwitchCase(const SwitchCase *S) {
1377     extendRegion(S);
1378 
1379     SourceMappingRegion &Parent = getRegion();
1380 
1381     Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
1382     // Reuse the existing region if it starts at our label. This is typical of
1383     // the first case in a switch.
1384     if (Parent.hasStartLoc() && Parent.getBeginLoc() == getStart(S))
1385       Parent.setCounter(Count);
1386     else
1387       pushRegion(Count, getStart(S));
1388 
1389     if (const auto *CS = dyn_cast<CaseStmt>(S)) {
1390       Visit(CS->getLHS());
1391       if (const Expr *RHS = CS->getRHS())
1392         Visit(RHS);
1393     }
1394     Visit(S->getSubStmt());
1395   }
1396 
1397   void VisitIfStmt(const IfStmt *S) {
1398     extendRegion(S);
1399     if (S->getInit())
1400       Visit(S->getInit());
1401 
1402     // Extend into the condition before we propagate through it below - this is
1403     // needed to handle macros that generate the "if" but not the condition.
1404     extendRegion(S->getCond());
1405 
1406     Counter ParentCount = getRegion().getCounter();
1407     Counter ThenCount = getRegionCounter(S);
1408 
1409     // Emitting a counter for the condition makes it easier to interpret the
1410     // counter for the body when looking at the coverage.
1411     propagateCounts(ParentCount, S->getCond());
1412 
1413     // The 'then' count applies to the area immediately after the condition.
1414     auto Gap = findGapAreaBetween(S->getCond(), S->getThen());
1415     if (Gap)
1416       fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ThenCount);
1417 
1418     extendRegion(S->getThen());
1419     Counter OutCount = propagateCounts(ThenCount, S->getThen());
1420 
1421     Counter ElseCount = subtractCounters(ParentCount, ThenCount);
1422     if (const Stmt *Else = S->getElse()) {
1423       // The 'else' count applies to the area immediately after the 'then'.
1424       Gap = findGapAreaBetween(S->getThen(), Else);
1425       if (Gap)
1426         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), ElseCount);
1427       extendRegion(Else);
1428       OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
1429     } else
1430       OutCount = addCounters(OutCount, ElseCount);
1431 
1432     if (OutCount != ParentCount)
1433       pushRegion(OutCount);
1434 
1435     // Create Branch Region around condition.
1436     createBranchRegion(S->getCond(), ThenCount,
1437                        subtractCounters(ParentCount, ThenCount));
1438   }
1439 
1440   void VisitCXXTryStmt(const CXXTryStmt *S) {
1441     extendRegion(S);
1442     // Handle macros that generate the "try" but not the rest.
1443     extendRegion(S->getTryBlock());
1444 
1445     Counter ParentCount = getRegion().getCounter();
1446     propagateCounts(ParentCount, S->getTryBlock());
1447 
1448     for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
1449       Visit(S->getHandler(I));
1450 
1451     Counter ExitCount = getRegionCounter(S);
1452     pushRegion(ExitCount);
1453   }
1454 
1455   void VisitCXXCatchStmt(const CXXCatchStmt *S) {
1456     propagateCounts(getRegionCounter(S), S->getHandlerBlock());
1457   }
1458 
1459   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
1460     extendRegion(E);
1461 
1462     Counter ParentCount = getRegion().getCounter();
1463     Counter TrueCount = getRegionCounter(E);
1464 
1465     Visit(E->getCond());
1466 
1467     if (!isa<BinaryConditionalOperator>(E)) {
1468       // The 'then' count applies to the area immediately after the condition.
1469       auto Gap =
1470           findGapAreaBetween(E->getQuestionLoc(), getStart(E->getTrueExpr()));
1471       if (Gap)
1472         fillGapAreaWithCount(Gap->getBegin(), Gap->getEnd(), TrueCount);
1473 
1474       extendRegion(E->getTrueExpr());
1475       propagateCounts(TrueCount, E->getTrueExpr());
1476     }
1477 
1478     extendRegion(E->getFalseExpr());
1479     propagateCounts(subtractCounters(ParentCount, TrueCount),
1480                     E->getFalseExpr());
1481 
1482     // Create Branch Region around condition.
1483     createBranchRegion(E->getCond(), TrueCount,
1484                        subtractCounters(ParentCount, TrueCount));
1485   }
1486 
1487   void VisitBinLAnd(const BinaryOperator *E) {
1488     extendRegion(E->getLHS());
1489     propagateCounts(getRegion().getCounter(), E->getLHS());
1490     handleFileExit(getEnd(E->getLHS()));
1491 
1492     // Counter tracks the right hand side of a logical and operator.
1493     extendRegion(E->getRHS());
1494     propagateCounts(getRegionCounter(E), E->getRHS());
1495 
1496     // Extract the RHS's Execution Counter.
1497     Counter RHSExecCnt = getRegionCounter(E);
1498 
1499     // Extract the RHS's "True" Instance Counter.
1500     Counter RHSTrueCnt = getRegionCounter(E->getRHS());
1501 
1502     // Extract the Parent Region Counter.
1503     Counter ParentCnt = getRegion().getCounter();
1504 
1505     // Create Branch Region around LHS condition.
1506     createBranchRegion(E->getLHS(), RHSExecCnt,
1507                        subtractCounters(ParentCnt, RHSExecCnt));
1508 
1509     // Create Branch Region around RHS condition.
1510     createBranchRegion(E->getRHS(), RHSTrueCnt,
1511                        subtractCounters(RHSExecCnt, RHSTrueCnt));
1512   }
1513 
1514   void VisitBinLOr(const BinaryOperator *E) {
1515     extendRegion(E->getLHS());
1516     propagateCounts(getRegion().getCounter(), E->getLHS());
1517     handleFileExit(getEnd(E->getLHS()));
1518 
1519     // Counter tracks the right hand side of a logical or operator.
1520     extendRegion(E->getRHS());
1521     propagateCounts(getRegionCounter(E), E->getRHS());
1522 
1523     // Extract the RHS's Execution Counter.
1524     Counter RHSExecCnt = getRegionCounter(E);
1525 
1526     // Extract the RHS's "False" Instance Counter.
1527     Counter RHSFalseCnt = getRegionCounter(E->getRHS());
1528 
1529     // Extract the Parent Region Counter.
1530     Counter ParentCnt = getRegion().getCounter();
1531 
1532     // Create Branch Region around LHS condition.
1533     createBranchRegion(E->getLHS(), subtractCounters(ParentCnt, RHSExecCnt),
1534                        RHSExecCnt);
1535 
1536     // Create Branch Region around RHS condition.
1537     createBranchRegion(E->getRHS(), subtractCounters(RHSExecCnt, RHSFalseCnt),
1538                        RHSFalseCnt);
1539   }
1540 
1541   void VisitLambdaExpr(const LambdaExpr *LE) {
1542     // Lambdas are treated as their own functions for now, so we shouldn't
1543     // propagate counts into them.
1544   }
1545 };
1546 
1547 } // end anonymous namespace
1548 
1549 static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
1550                  ArrayRef<CounterExpression> Expressions,
1551                  ArrayRef<CounterMappingRegion> Regions) {
1552   OS << FunctionName << ":\n";
1553   CounterMappingContext Ctx(Expressions);
1554   for (const auto &R : Regions) {
1555     OS.indent(2);
1556     switch (R.Kind) {
1557     case CounterMappingRegion::CodeRegion:
1558       break;
1559     case CounterMappingRegion::ExpansionRegion:
1560       OS << "Expansion,";
1561       break;
1562     case CounterMappingRegion::SkippedRegion:
1563       OS << "Skipped,";
1564       break;
1565     case CounterMappingRegion::GapRegion:
1566       OS << "Gap,";
1567       break;
1568     case CounterMappingRegion::BranchRegion:
1569       OS << "Branch,";
1570       break;
1571     }
1572 
1573     OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
1574        << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
1575     Ctx.dump(R.Count, OS);
1576 
1577     if (R.Kind == CounterMappingRegion::BranchRegion) {
1578       OS << ", ";
1579       Ctx.dump(R.FalseCount, OS);
1580     }
1581 
1582     if (R.Kind == CounterMappingRegion::ExpansionRegion)
1583       OS << " (Expanded file = " << R.ExpandedFileID << ")";
1584     OS << "\n";
1585   }
1586 }
1587 
1588 CoverageMappingModuleGen::CoverageMappingModuleGen(
1589     CodeGenModule &CGM, CoverageSourceInfo &SourceInfo)
1590     : CGM(CGM), SourceInfo(SourceInfo) {
1591   ProfilePrefixMap = CGM.getCodeGenOpts().ProfilePrefixMap;
1592 }
1593 
1594 std::string CoverageMappingModuleGen::normalizeFilename(StringRef Filename) {
1595   llvm::SmallString<256> Path(Filename);
1596   llvm::sys::fs::make_absolute(Path);
1597   llvm::sys::path::remove_dots(Path, /*remove_dot_dot=*/true);
1598   for (const auto &Entry : ProfilePrefixMap) {
1599     if (llvm::sys::path::replace_path_prefix(Path, Entry.first, Entry.second))
1600       break;
1601   }
1602   return Path.str().str();
1603 }
1604 
1605 static std::string getInstrProfSection(const CodeGenModule &CGM,
1606                                        llvm::InstrProfSectKind SK) {
1607   return llvm::getInstrProfSectionName(
1608       SK, CGM.getContext().getTargetInfo().getTriple().getObjectFormat());
1609 }
1610 
1611 void CoverageMappingModuleGen::emitFunctionMappingRecord(
1612     const FunctionInfo &Info, uint64_t FilenamesRef) {
1613   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1614 
1615   // Assign a name to the function record. This is used to merge duplicates.
1616   std::string FuncRecordName = "__covrec_" + llvm::utohexstr(Info.NameHash);
1617 
1618   // A dummy description for a function included-but-not-used in a TU can be
1619   // replaced by full description provided by a different TU. The two kinds of
1620   // descriptions play distinct roles: therefore, assign them different names
1621   // to prevent `linkonce_odr` merging.
1622   if (Info.IsUsed)
1623     FuncRecordName += "u";
1624 
1625   // Create the function record type.
1626   const uint64_t NameHash = Info.NameHash;
1627   const uint64_t FuncHash = Info.FuncHash;
1628   const std::string &CoverageMapping = Info.CoverageMapping;
1629 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
1630   llvm::Type *FunctionRecordTypes[] = {
1631 #include "llvm/ProfileData/InstrProfData.inc"
1632   };
1633   auto *FunctionRecordTy =
1634       llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
1635                             /*isPacked=*/true);
1636 
1637   // Create the function record constant.
1638 #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
1639   llvm::Constant *FunctionRecordVals[] = {
1640       #include "llvm/ProfileData/InstrProfData.inc"
1641   };
1642   auto *FuncRecordConstant = llvm::ConstantStruct::get(
1643       FunctionRecordTy, makeArrayRef(FunctionRecordVals));
1644 
1645   // Create the function record global.
1646   auto *FuncRecord = new llvm::GlobalVariable(
1647       CGM.getModule(), FunctionRecordTy, /*isConstant=*/true,
1648       llvm::GlobalValue::LinkOnceODRLinkage, FuncRecordConstant,
1649       FuncRecordName);
1650   FuncRecord->setVisibility(llvm::GlobalValue::HiddenVisibility);
1651   FuncRecord->setSection(getInstrProfSection(CGM, llvm::IPSK_covfun));
1652   FuncRecord->setAlignment(llvm::Align(8));
1653   if (CGM.supportsCOMDAT())
1654     FuncRecord->setComdat(CGM.getModule().getOrInsertComdat(FuncRecordName));
1655 
1656   // Make sure the data doesn't get deleted.
1657   CGM.addUsedGlobal(FuncRecord);
1658 }
1659 
1660 void CoverageMappingModuleGen::addFunctionMappingRecord(
1661     llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
1662     const std::string &CoverageMapping, bool IsUsed) {
1663   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1664   const uint64_t NameHash = llvm::IndexedInstrProf::ComputeHash(NameValue);
1665   FunctionRecords.push_back({NameHash, FuncHash, CoverageMapping, IsUsed});
1666 
1667   if (!IsUsed)
1668     FunctionNames.push_back(
1669         llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
1670 
1671   if (CGM.getCodeGenOpts().DumpCoverageMapping) {
1672     // Dump the coverage mapping data for this function by decoding the
1673     // encoded data. This allows us to dump the mapping regions which were
1674     // also processed by the CoverageMappingWriter which performs
1675     // additional minimization operations such as reducing the number of
1676     // expressions.
1677     std::vector<StringRef> Filenames;
1678     std::vector<CounterExpression> Expressions;
1679     std::vector<CounterMappingRegion> Regions;
1680     llvm::SmallVector<std::string, 16> FilenameStrs;
1681     llvm::SmallVector<StringRef, 16> FilenameRefs;
1682     FilenameStrs.resize(FileEntries.size());
1683     FilenameRefs.resize(FileEntries.size());
1684     for (const auto &Entry : FileEntries) {
1685       auto I = Entry.second;
1686       FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1687       FilenameRefs[I] = FilenameStrs[I];
1688     }
1689     RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
1690                                     Expressions, Regions);
1691     if (Reader.read())
1692       return;
1693     dump(llvm::outs(), NameValue, Expressions, Regions);
1694   }
1695 }
1696 
1697 void CoverageMappingModuleGen::emit() {
1698   if (FunctionRecords.empty())
1699     return;
1700   llvm::LLVMContext &Ctx = CGM.getLLVMContext();
1701   auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
1702 
1703   // Create the filenames and merge them with coverage mappings
1704   llvm::SmallVector<std::string, 16> FilenameStrs;
1705   llvm::SmallVector<StringRef, 16> FilenameRefs;
1706   FilenameStrs.resize(FileEntries.size());
1707   FilenameRefs.resize(FileEntries.size());
1708   for (const auto &Entry : FileEntries) {
1709     auto I = Entry.second;
1710     FilenameStrs[I] = normalizeFilename(Entry.first->getName());
1711     FilenameRefs[I] = FilenameStrs[I];
1712   }
1713 
1714   std::string Filenames;
1715   {
1716     llvm::raw_string_ostream OS(Filenames);
1717     CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
1718   }
1719   auto *FilenamesVal =
1720       llvm::ConstantDataArray::getString(Ctx, Filenames, false);
1721   const int64_t FilenamesRef = llvm::IndexedInstrProf::ComputeHash(Filenames);
1722 
1723   // Emit the function records.
1724   for (const FunctionInfo &Info : FunctionRecords)
1725     emitFunctionMappingRecord(Info, FilenamesRef);
1726 
1727   const unsigned NRecords = 0;
1728   const size_t FilenamesSize = Filenames.size();
1729   const unsigned CoverageMappingSize = 0;
1730   llvm::Type *CovDataHeaderTypes[] = {
1731 #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
1732 #include "llvm/ProfileData/InstrProfData.inc"
1733   };
1734   auto CovDataHeaderTy =
1735       llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
1736   llvm::Constant *CovDataHeaderVals[] = {
1737 #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
1738 #include "llvm/ProfileData/InstrProfData.inc"
1739   };
1740   auto CovDataHeaderVal = llvm::ConstantStruct::get(
1741       CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
1742 
1743   // Create the coverage data record
1744   llvm::Type *CovDataTypes[] = {CovDataHeaderTy, FilenamesVal->getType()};
1745   auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
1746   llvm::Constant *TUDataVals[] = {CovDataHeaderVal, FilenamesVal};
1747   auto CovDataVal =
1748       llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
1749   auto CovData = new llvm::GlobalVariable(
1750       CGM.getModule(), CovDataTy, true, llvm::GlobalValue::PrivateLinkage,
1751       CovDataVal, llvm::getCoverageMappingVarName());
1752 
1753   CovData->setSection(getInstrProfSection(CGM, llvm::IPSK_covmap));
1754   CovData->setAlignment(llvm::Align(8));
1755 
1756   // Make sure the data doesn't get deleted.
1757   CGM.addUsedGlobal(CovData);
1758   // Create the deferred function records array
1759   if (!FunctionNames.empty()) {
1760     auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
1761                                            FunctionNames.size());
1762     auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
1763     // This variable will *NOT* be emitted to the object file. It is used
1764     // to pass the list of names referenced to codegen.
1765     new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
1766                              llvm::GlobalValue::InternalLinkage, NamesArrVal,
1767                              llvm::getCoverageUnusedNamesVarName());
1768   }
1769 }
1770 
1771 unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
1772   auto It = FileEntries.find(File);
1773   if (It != FileEntries.end())
1774     return It->second;
1775   unsigned FileID = FileEntries.size();
1776   FileEntries.insert(std::make_pair(File, FileID));
1777   return FileID;
1778 }
1779 
1780 void CoverageMappingGen::emitCounterMapping(const Decl *D,
1781                                             llvm::raw_ostream &OS) {
1782   assert(CounterMap);
1783   CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
1784   Walker.VisitDecl(D);
1785   Walker.write(OS);
1786 }
1787 
1788 void CoverageMappingGen::emitEmptyMapping(const Decl *D,
1789                                           llvm::raw_ostream &OS) {
1790   EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
1791   Walker.VisitDecl(D);
1792   Walker.write(OS);
1793 }
1794