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