1ee02499aSAlex Lorenz //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===// 2ee02499aSAlex Lorenz // 3ee02499aSAlex Lorenz // The LLVM Compiler Infrastructure 4ee02499aSAlex Lorenz // 5ee02499aSAlex Lorenz // This file is distributed under the University of Illinois Open Source 6ee02499aSAlex Lorenz // License. See LICENSE.TXT for details. 7ee02499aSAlex Lorenz // 8ee02499aSAlex Lorenz //===----------------------------------------------------------------------===// 9ee02499aSAlex Lorenz // 10ee02499aSAlex Lorenz // Instrumentation-based code coverage mapping generator 11ee02499aSAlex Lorenz // 12ee02499aSAlex Lorenz //===----------------------------------------------------------------------===// 13ee02499aSAlex Lorenz 14ee02499aSAlex Lorenz #include "CoverageMappingGen.h" 15ee02499aSAlex Lorenz #include "CodeGenFunction.h" 16ee02499aSAlex Lorenz #include "clang/AST/StmtVisitor.h" 17ee02499aSAlex Lorenz #include "clang/Lex/Lexer.h" 18bc6b80a0SVedant Kumar #include "llvm/ADT/SmallSet.h" 19ca3326c0SVedant Kumar #include "llvm/ADT/StringExtras.h" 20bf42cfd7SJustin Bogner #include "llvm/ADT/Optional.h" 21b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMapping.h" 22b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 23b014ee46SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h" 240d9593ddSChandler Carruth #include "llvm/ProfileData/InstrProfReader.h" 25ee02499aSAlex Lorenz #include "llvm/Support/FileSystem.h" 2614f8fb68SVedant Kumar #include "llvm/Support/Path.h" 27ee02499aSAlex Lorenz 28ee02499aSAlex Lorenz using namespace clang; 29ee02499aSAlex Lorenz using namespace CodeGen; 30ee02499aSAlex Lorenz using namespace llvm::coverage; 31ee02499aSAlex Lorenz 323919a501SVedant Kumar void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range, SourceLocation) { 33ee02499aSAlex Lorenz SkippedRanges.push_back(Range); 34ee02499aSAlex Lorenz } 35ee02499aSAlex Lorenz 36ee02499aSAlex Lorenz namespace { 37ee02499aSAlex Lorenz 38ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter. 3909c7179bSJustin Bogner class SourceMappingRegion { 40ee02499aSAlex Lorenz Counter Count; 41ee02499aSAlex Lorenz 42ee02499aSAlex Lorenz /// \brief The region's starting location. 43bf42cfd7SJustin Bogner Optional<SourceLocation> LocStart; 44ee02499aSAlex Lorenz 45ee02499aSAlex Lorenz /// \brief The region's ending location. 46bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd; 47ee02499aSAlex Lorenz 48747b0e29SVedant Kumar /// Whether this region should be emitted after its parent is emitted. 49747b0e29SVedant Kumar bool DeferRegion; 50747b0e29SVedant Kumar 51a1c4deb7SVedant Kumar /// Whether this region is a gap region. The count from a gap region is set 52a1c4deb7SVedant Kumar /// as the line execution count if there are no other regions on the line. 53a1c4deb7SVedant Kumar bool GapRegion; 54a1c4deb7SVedant Kumar 5509c7179bSJustin Bogner public: 56bf42cfd7SJustin Bogner SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart, 57a1c4deb7SVedant Kumar Optional<SourceLocation> LocEnd, bool DeferRegion = false, 58a1c4deb7SVedant Kumar bool GapRegion = false) 59747b0e29SVedant Kumar : Count(Count), LocStart(LocStart), LocEnd(LocEnd), 60a1c4deb7SVedant Kumar DeferRegion(DeferRegion), GapRegion(GapRegion) {} 61ee02499aSAlex Lorenz 6209c7179bSJustin Bogner const Counter &getCounter() const { return Count; } 6309c7179bSJustin Bogner 64bf42cfd7SJustin Bogner void setCounter(Counter C) { Count = C; } 6509c7179bSJustin Bogner 66bf42cfd7SJustin Bogner bool hasStartLoc() const { return LocStart.hasValue(); } 67bf42cfd7SJustin Bogner 68bf42cfd7SJustin Bogner void setStartLoc(SourceLocation Loc) { LocStart = Loc; } 69bf42cfd7SJustin Bogner 70462c77b4SCraig Topper SourceLocation getStartLoc() const { 71bf42cfd7SJustin Bogner assert(LocStart && "Region has no start location"); 72bf42cfd7SJustin Bogner return *LocStart; 7309c7179bSJustin Bogner } 7409c7179bSJustin Bogner 75bf42cfd7SJustin Bogner bool hasEndLoc() const { return LocEnd.hasValue(); } 76ee02499aSAlex Lorenz 77bf42cfd7SJustin Bogner void setEndLoc(SourceLocation Loc) { LocEnd = Loc; } 78ee02499aSAlex Lorenz 79462c77b4SCraig Topper SourceLocation getEndLoc() const { 80bf42cfd7SJustin Bogner assert(LocEnd && "Region has no end location"); 81bf42cfd7SJustin Bogner return *LocEnd; 82ee02499aSAlex Lorenz } 83747b0e29SVedant Kumar 84747b0e29SVedant Kumar bool isDeferred() const { return DeferRegion; } 85747b0e29SVedant Kumar 86747b0e29SVedant Kumar void setDeferred(bool Deferred) { DeferRegion = Deferred; } 87a1c4deb7SVedant Kumar 88a1c4deb7SVedant Kumar bool isGap() const { return GapRegion; } 89a1c4deb7SVedant Kumar 90a1c4deb7SVedant Kumar void setGap(bool Gap) { GapRegion = Gap; } 91ee02499aSAlex Lorenz }; 92ee02499aSAlex Lorenz 93d7369648SVedant Kumar /// Spelling locations for the start and end of a source region. 94d7369648SVedant Kumar struct SpellingRegion { 95d7369648SVedant Kumar /// The line where the region starts. 96d7369648SVedant Kumar unsigned LineStart; 97d7369648SVedant Kumar 98d7369648SVedant Kumar /// The column where the region starts. 99d7369648SVedant Kumar unsigned ColumnStart; 100d7369648SVedant Kumar 101d7369648SVedant Kumar /// The line where the region ends. 102d7369648SVedant Kumar unsigned LineEnd; 103d7369648SVedant Kumar 104d7369648SVedant Kumar /// The column where the region ends. 105d7369648SVedant Kumar unsigned ColumnEnd; 106d7369648SVedant Kumar 107d7369648SVedant Kumar SpellingRegion(SourceManager &SM, SourceLocation LocStart, 108d7369648SVedant Kumar SourceLocation LocEnd) { 109d7369648SVedant Kumar LineStart = SM.getSpellingLineNumber(LocStart); 110d7369648SVedant Kumar ColumnStart = SM.getSpellingColumnNumber(LocStart); 111d7369648SVedant Kumar LineEnd = SM.getSpellingLineNumber(LocEnd); 112d7369648SVedant Kumar ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 113d7369648SVedant Kumar } 114d7369648SVedant Kumar 115d7369648SVedant Kumar /// Check if the start and end locations appear in source order, i.e 116d7369648SVedant Kumar /// top->bottom, left->right. 117d7369648SVedant Kumar bool isInSourceOrder() const { 118d7369648SVedant Kumar return (LineStart < LineEnd) || 119d7369648SVedant Kumar (LineStart == LineEnd && ColumnStart <= ColumnEnd); 120d7369648SVedant Kumar } 121d7369648SVedant Kumar }; 122d7369648SVedant Kumar 123ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different 124ee02499aSAlex Lorenz /// coverage mapping region builders. 125ee02499aSAlex Lorenz class CoverageMappingBuilder { 126ee02499aSAlex Lorenz public: 127ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM; 128ee02499aSAlex Lorenz SourceManager &SM; 129ee02499aSAlex Lorenz const LangOptions &LangOpts; 130ee02499aSAlex Lorenz 131ee02499aSAlex Lorenz private: 132bf42cfd7SJustin Bogner /// \brief Map of clang's FileIDs to IDs used for coverage mapping. 133bf42cfd7SJustin Bogner llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8> 134bf42cfd7SJustin Bogner FileIDMapping; 135ee02499aSAlex Lorenz 136ee02499aSAlex Lorenz public: 137ee02499aSAlex Lorenz /// \brief The coverage mapping regions for this function 138ee02499aSAlex Lorenz llvm::SmallVector<CounterMappingRegion, 32> MappingRegions; 139ee02499aSAlex Lorenz /// \brief The source mapping regions for this function. 140f59329b0SJustin Bogner std::vector<SourceMappingRegion> SourceRegions; 141ee02499aSAlex Lorenz 142fc05ee34SIgor Kudrin /// \brief A set of regions which can be used as a filter. 143fc05ee34SIgor Kudrin /// 144fc05ee34SIgor Kudrin /// It is produced by emitExpansionRegions() and is used in 145fc05ee34SIgor Kudrin /// emitSourceRegions() to suppress producing code regions if 146fc05ee34SIgor Kudrin /// the same area is covered by expansion regions. 147fc05ee34SIgor Kudrin typedef llvm::SmallSet<std::pair<SourceLocation, SourceLocation>, 8> 148fc05ee34SIgor Kudrin SourceRegionFilter; 149fc05ee34SIgor Kudrin 150ee02499aSAlex Lorenz CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 151ee02499aSAlex Lorenz const LangOptions &LangOpts) 152bf42cfd7SJustin Bogner : CVM(CVM), SM(SM), LangOpts(LangOpts) {} 153ee02499aSAlex Lorenz 154ee02499aSAlex Lorenz /// \brief Return the precise end location for the given token. 155ee02499aSAlex Lorenz SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) { 156bf42cfd7SJustin Bogner // We avoid getLocForEndOfToken here, because it doesn't do what we want for 157bf42cfd7SJustin Bogner // macro locations, which we just treat as expanded files. 158bf42cfd7SJustin Bogner unsigned TokLen = 159bf42cfd7SJustin Bogner Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts); 160bf42cfd7SJustin Bogner return Loc.getLocWithOffset(TokLen); 161ee02499aSAlex Lorenz } 162ee02499aSAlex Lorenz 163bf42cfd7SJustin Bogner /// \brief Return the start location of an included file or expanded macro. 164bf42cfd7SJustin Bogner SourceLocation getStartOfFileOrMacro(SourceLocation Loc) { 165bf42cfd7SJustin Bogner if (Loc.isMacroID()) 166bf42cfd7SJustin Bogner return Loc.getLocWithOffset(-SM.getFileOffset(Loc)); 167bf42cfd7SJustin Bogner return SM.getLocForStartOfFile(SM.getFileID(Loc)); 168ee02499aSAlex Lorenz } 169ee02499aSAlex Lorenz 170bf42cfd7SJustin Bogner /// \brief Return the end location of an included file or expanded macro. 171bf42cfd7SJustin Bogner SourceLocation getEndOfFileOrMacro(SourceLocation Loc) { 172bf42cfd7SJustin Bogner if (Loc.isMacroID()) 173bf42cfd7SJustin Bogner return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) - 174f14b2078SJustin Bogner SM.getFileOffset(Loc)); 175bf42cfd7SJustin Bogner return SM.getLocForEndOfFile(SM.getFileID(Loc)); 176bf42cfd7SJustin Bogner } 177ee02499aSAlex Lorenz 178bf42cfd7SJustin Bogner /// \brief Find out where the current file is included or macro is expanded. 179bf42cfd7SJustin Bogner SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) { 180bf42cfd7SJustin Bogner return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first 181bf42cfd7SJustin Bogner : SM.getIncludeLoc(SM.getFileID(Loc)); 182bf42cfd7SJustin Bogner } 183bf42cfd7SJustin Bogner 184682bfbf3SJustin Bogner /// \brief Return true if \c Loc is a location in a built-in macro. 185682bfbf3SJustin Bogner bool isInBuiltin(SourceLocation Loc) { 18699d1b295SMehdi Amini return SM.getBufferName(SM.getSpellingLoc(Loc)) == "<built-in>"; 187682bfbf3SJustin Bogner } 188682bfbf3SJustin Bogner 189d9e1a61dSIgor Kudrin /// \brief Check whether \c Loc is included or expanded from \c Parent. 190d9e1a61dSIgor Kudrin bool isNestedIn(SourceLocation Loc, FileID Parent) { 191d9e1a61dSIgor Kudrin do { 192d9e1a61dSIgor Kudrin Loc = getIncludeOrExpansionLoc(Loc); 193d9e1a61dSIgor Kudrin if (Loc.isInvalid()) 194d9e1a61dSIgor Kudrin return false; 195d9e1a61dSIgor Kudrin } while (!SM.isInFileID(Loc, Parent)); 196d9e1a61dSIgor Kudrin return true; 197d9e1a61dSIgor Kudrin } 198d9e1a61dSIgor Kudrin 199682bfbf3SJustin Bogner /// \brief Get the start of \c S ignoring macro arguments and builtin macros. 200bf42cfd7SJustin Bogner SourceLocation getStart(const Stmt *S) { 201bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocStart(); 202682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 203bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 204bf42cfd7SJustin Bogner return Loc; 205bf42cfd7SJustin Bogner } 206bf42cfd7SJustin Bogner 207682bfbf3SJustin Bogner /// \brief Get the end of \c S ignoring macro arguments and builtin macros. 208bf42cfd7SJustin Bogner SourceLocation getEnd(const Stmt *S) { 209bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocEnd(); 210682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 211bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 212f14b2078SJustin Bogner return getPreciseTokenLocEnd(Loc); 213bf42cfd7SJustin Bogner } 214bf42cfd7SJustin Bogner 215bf42cfd7SJustin Bogner /// \brief Find the set of files we have regions for and assign IDs 216bf42cfd7SJustin Bogner /// 217bf42cfd7SJustin Bogner /// Fills \c Mapping with the virtual file mapping needed to write out 218bf42cfd7SJustin Bogner /// coverage and collects the necessary file information to emit source and 219bf42cfd7SJustin Bogner /// expansion regions. 220bf42cfd7SJustin Bogner void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) { 221bf42cfd7SJustin Bogner FileIDMapping.clear(); 222bf42cfd7SJustin Bogner 223bc6b80a0SVedant Kumar llvm::SmallSet<FileID, 8> Visited; 224bf42cfd7SJustin Bogner SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs; 225bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 226bf42cfd7SJustin Bogner SourceLocation Loc = Region.getStartLoc(); 227bf42cfd7SJustin Bogner FileID File = SM.getFileID(Loc); 228bc6b80a0SVedant Kumar if (!Visited.insert(File).second) 229bf42cfd7SJustin Bogner continue; 230bf42cfd7SJustin Bogner 23193205af0SVedant Kumar // Do not map FileID's associated with system headers. 23293205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(Loc))) 23393205af0SVedant Kumar continue; 23493205af0SVedant Kumar 235bf42cfd7SJustin Bogner unsigned Depth = 0; 236bf42cfd7SJustin Bogner for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc); 237ed1fe5d0SYaron Keren Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent)) 238bf42cfd7SJustin Bogner ++Depth; 239bf42cfd7SJustin Bogner FileLocs.push_back(std::make_pair(Loc, Depth)); 240bf42cfd7SJustin Bogner } 241bf42cfd7SJustin Bogner std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second()); 242bf42cfd7SJustin Bogner 243bf42cfd7SJustin Bogner for (const auto &FL : FileLocs) { 244bf42cfd7SJustin Bogner SourceLocation Loc = FL.first; 245bf42cfd7SJustin Bogner FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first; 246ee02499aSAlex Lorenz auto Entry = SM.getFileEntryForID(SpellingFile); 247ee02499aSAlex Lorenz if (!Entry) 248bf42cfd7SJustin Bogner continue; 249ee02499aSAlex Lorenz 250bf42cfd7SJustin Bogner FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc); 251bf42cfd7SJustin Bogner Mapping.push_back(CVM.getFileID(Entry)); 252bf42cfd7SJustin Bogner } 253ee02499aSAlex Lorenz } 254ee02499aSAlex Lorenz 255bf42cfd7SJustin Bogner /// \brief Get the coverage mapping file ID for \c Loc. 256bf42cfd7SJustin Bogner /// 257bf42cfd7SJustin Bogner /// If such file id doesn't exist, return None. 258bf42cfd7SJustin Bogner Optional<unsigned> getCoverageFileID(SourceLocation Loc) { 259bf42cfd7SJustin Bogner auto Mapping = FileIDMapping.find(SM.getFileID(Loc)); 260bf42cfd7SJustin Bogner if (Mapping != FileIDMapping.end()) 261bf42cfd7SJustin Bogner return Mapping->second.first; 262903678caSJustin Bogner return None; 263ee02499aSAlex Lorenz } 264ee02499aSAlex Lorenz 265ee02499aSAlex Lorenz /// \brief Gather all the regions that were skipped by the preprocessor 266ee02499aSAlex Lorenz /// using the constructs like #if. 267ee02499aSAlex Lorenz void gatherSkippedRegions() { 268ee02499aSAlex Lorenz /// An array of the minimum lineStarts and the maximum lineEnds 269ee02499aSAlex Lorenz /// for mapping regions from the appropriate source files. 270ee02499aSAlex Lorenz llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges; 271ee02499aSAlex Lorenz FileLineRanges.resize( 272ee02499aSAlex Lorenz FileIDMapping.size(), 273ee02499aSAlex Lorenz std::make_pair(std::numeric_limits<unsigned>::max(), 0)); 274ee02499aSAlex Lorenz for (const auto &R : MappingRegions) { 275ee02499aSAlex Lorenz FileLineRanges[R.FileID].first = 276ee02499aSAlex Lorenz std::min(FileLineRanges[R.FileID].first, R.LineStart); 277ee02499aSAlex Lorenz FileLineRanges[R.FileID].second = 278ee02499aSAlex Lorenz std::max(FileLineRanges[R.FileID].second, R.LineEnd); 279ee02499aSAlex Lorenz } 280ee02499aSAlex Lorenz 281ee02499aSAlex Lorenz auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges(); 282ee02499aSAlex Lorenz for (const auto &I : SkippedRanges) { 283ee02499aSAlex Lorenz auto LocStart = I.getBegin(); 284ee02499aSAlex Lorenz auto LocEnd = I.getEnd(); 285bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 286bf42cfd7SJustin Bogner "region spans multiple files"); 287ee02499aSAlex Lorenz 288bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 289903678caSJustin Bogner if (!CovFileID) 290ee02499aSAlex Lorenz continue; 291d7369648SVedant Kumar SpellingRegion SR{SM, LocStart, LocEnd}; 292fd34280bSJustin Bogner auto Region = CounterMappingRegion::makeSkipped( 293d7369648SVedant Kumar *CovFileID, SR.LineStart, SR.ColumnStart, SR.LineEnd, SR.ColumnEnd); 294ee02499aSAlex Lorenz // Make sure that we only collect the regions that are inside 295ee02499aSAlex Lorenz // the souce code of this function. 296903678caSJustin Bogner if (Region.LineStart >= FileLineRanges[*CovFileID].first && 297903678caSJustin Bogner Region.LineEnd <= FileLineRanges[*CovFileID].second) 298ee02499aSAlex Lorenz MappingRegions.push_back(Region); 299ee02499aSAlex Lorenz } 300ee02499aSAlex Lorenz } 301ee02499aSAlex Lorenz 302ee02499aSAlex Lorenz /// \brief Generate the coverage counter mapping regions from collected 303ee02499aSAlex Lorenz /// source regions. 304fc05ee34SIgor Kudrin void emitSourceRegions(const SourceRegionFilter &Filter) { 305bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 306bf42cfd7SJustin Bogner assert(Region.hasEndLoc() && "incomplete region"); 307ee02499aSAlex Lorenz 308bf42cfd7SJustin Bogner SourceLocation LocStart = Region.getStartLoc(); 3098b563665SYaron Keren assert(SM.getFileID(LocStart).isValid() && "region in invalid file"); 310f59329b0SJustin Bogner 31193205af0SVedant Kumar // Ignore regions from system headers. 31293205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) 31393205af0SVedant Kumar continue; 31493205af0SVedant Kumar 315bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 316bf42cfd7SJustin Bogner // Ignore regions that don't have a file, such as builtin macros. 317bf42cfd7SJustin Bogner if (!CovFileID) 318ee02499aSAlex Lorenz continue; 319ee02499aSAlex Lorenz 320f14b2078SJustin Bogner SourceLocation LocEnd = Region.getEndLoc(); 321bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 322bf42cfd7SJustin Bogner "region spans multiple files"); 323bf42cfd7SJustin Bogner 324fc05ee34SIgor Kudrin // Don't add code regions for the area covered by expansion regions. 325fc05ee34SIgor Kudrin // This not only suppresses redundant regions, but sometimes prevents 326fc05ee34SIgor Kudrin // creating regions with wrong counters if, for example, a statement's 327fc05ee34SIgor Kudrin // body ends at the end of a nested macro. 328fc05ee34SIgor Kudrin if (Filter.count(std::make_pair(LocStart, LocEnd))) 329fc05ee34SIgor Kudrin continue; 330fc05ee34SIgor Kudrin 331d7369648SVedant Kumar // Find the spelling locations for the mapping region. 332d7369648SVedant Kumar SpellingRegion SR{SM, LocStart, LocEnd}; 333d7369648SVedant Kumar assert(SR.isInSourceOrder() && "region start and end out of order"); 334a1c4deb7SVedant Kumar 335a1c4deb7SVedant Kumar if (Region.isGap()) { 336a1c4deb7SVedant Kumar MappingRegions.push_back(CounterMappingRegion::makeGapRegion( 337a1c4deb7SVedant Kumar Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart, 338a1c4deb7SVedant Kumar SR.LineEnd, SR.ColumnEnd)); 339a1c4deb7SVedant Kumar } else { 340bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeRegion( 341d7369648SVedant Kumar Region.getCounter(), *CovFileID, SR.LineStart, SR.ColumnStart, 342d7369648SVedant Kumar SR.LineEnd, SR.ColumnEnd)); 343bf42cfd7SJustin Bogner } 344bf42cfd7SJustin Bogner } 345a1c4deb7SVedant Kumar } 346bf42cfd7SJustin Bogner 347bf42cfd7SJustin Bogner /// \brief Generate expansion regions for each virtual file we've seen. 348fc05ee34SIgor Kudrin SourceRegionFilter emitExpansionRegions() { 349fc05ee34SIgor Kudrin SourceRegionFilter Filter; 350bf42cfd7SJustin Bogner for (const auto &FM : FileIDMapping) { 351bf42cfd7SJustin Bogner SourceLocation ExpandedLoc = FM.second.second; 352bf42cfd7SJustin Bogner SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc); 353bf42cfd7SJustin Bogner if (ParentLoc.isInvalid()) 354ee02499aSAlex Lorenz continue; 355ee02499aSAlex Lorenz 356bf42cfd7SJustin Bogner auto ParentFileID = getCoverageFileID(ParentLoc); 357bf42cfd7SJustin Bogner if (!ParentFileID) 358bf42cfd7SJustin Bogner continue; 359bf42cfd7SJustin Bogner auto ExpandedFileID = getCoverageFileID(ExpandedLoc); 360bf42cfd7SJustin Bogner assert(ExpandedFileID && "expansion in uncovered file"); 361bf42cfd7SJustin Bogner 362bf42cfd7SJustin Bogner SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc); 363bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) && 364bf42cfd7SJustin Bogner "region spans multiple files"); 365fc05ee34SIgor Kudrin Filter.insert(std::make_pair(ParentLoc, LocEnd)); 366bf42cfd7SJustin Bogner 367d7369648SVedant Kumar SpellingRegion SR{SM, ParentLoc, LocEnd}; 368d7369648SVedant Kumar assert(SR.isInSourceOrder() && "region start and end out of order"); 369bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeExpansion( 370d7369648SVedant Kumar *ParentFileID, *ExpandedFileID, SR.LineStart, SR.ColumnStart, 371d7369648SVedant Kumar SR.LineEnd, SR.ColumnEnd)); 372ee02499aSAlex Lorenz } 373fc05ee34SIgor Kudrin return Filter; 374ee02499aSAlex Lorenz } 375ee02499aSAlex Lorenz }; 376ee02499aSAlex Lorenz 377ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that 378ee02499aSAlex Lorenz /// are not emitted. 379ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { 380ee02499aSAlex Lorenz EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 381ee02499aSAlex Lorenz const LangOptions &LangOpts) 382ee02499aSAlex Lorenz : CoverageMappingBuilder(CVM, SM, LangOpts) {} 383ee02499aSAlex Lorenz 384ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 385ee02499aSAlex Lorenz if (!D->hasBody()) 386ee02499aSAlex Lorenz return; 387ee02499aSAlex Lorenz auto Body = D->getBody(); 388d9e1a61dSIgor Kudrin SourceLocation Start = getStart(Body); 389d9e1a61dSIgor Kudrin SourceLocation End = getEnd(Body); 390d9e1a61dSIgor Kudrin if (!SM.isWrittenInSameFile(Start, End)) { 391d9e1a61dSIgor Kudrin // Walk up to find the common ancestor. 392d9e1a61dSIgor Kudrin // Correct the locations accordingly. 393d9e1a61dSIgor Kudrin FileID StartFileID = SM.getFileID(Start); 394d9e1a61dSIgor Kudrin FileID EndFileID = SM.getFileID(End); 395d9e1a61dSIgor Kudrin while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) { 396d9e1a61dSIgor Kudrin Start = getIncludeOrExpansionLoc(Start); 397d9e1a61dSIgor Kudrin assert(Start.isValid() && 398d9e1a61dSIgor Kudrin "Declaration start location not nested within a known region"); 399d9e1a61dSIgor Kudrin StartFileID = SM.getFileID(Start); 400d9e1a61dSIgor Kudrin } 401d9e1a61dSIgor Kudrin while (StartFileID != EndFileID) { 402d9e1a61dSIgor Kudrin End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End)); 403d9e1a61dSIgor Kudrin assert(End.isValid() && 404d9e1a61dSIgor Kudrin "Declaration end location not nested within a known region"); 405d9e1a61dSIgor Kudrin EndFileID = SM.getFileID(End); 406d9e1a61dSIgor Kudrin } 407d9e1a61dSIgor Kudrin } 408d9e1a61dSIgor Kudrin SourceRegions.emplace_back(Counter(), Start, End); 409ee02499aSAlex Lorenz } 410ee02499aSAlex Lorenz 411ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 412ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 413ee02499aSAlex Lorenz SmallVector<unsigned, 16> FileIDMapping; 414bf42cfd7SJustin Bogner gatherFileIDs(FileIDMapping); 415fc05ee34SIgor Kudrin emitSourceRegions(SourceRegionFilter()); 416ee02499aSAlex Lorenz 417efd319a2SVedant Kumar if (MappingRegions.empty()) 418efd319a2SVedant Kumar return; 419efd319a2SVedant Kumar 4205fc8fc2dSCraig Topper CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions); 421ee02499aSAlex Lorenz Writer.write(OS); 422ee02499aSAlex Lorenz } 423ee02499aSAlex Lorenz }; 424ee02499aSAlex Lorenz 425ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map 426ee02499aSAlex Lorenz /// from the source code locations to the PGO counters. 427ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder 428ee02499aSAlex Lorenz : public CoverageMappingBuilder, 429ee02499aSAlex Lorenz public ConstStmtVisitor<CounterCoverageMappingBuilder> { 430ee02499aSAlex Lorenz /// \brief The map of statements to count values. 431ee02499aSAlex Lorenz llvm::DenseMap<const Stmt *, unsigned> &CounterMap; 432ee02499aSAlex Lorenz 433bf42cfd7SJustin Bogner /// \brief A stack of currently live regions. 434bf42cfd7SJustin Bogner std::vector<SourceMappingRegion> RegionStack; 435ee02499aSAlex Lorenz 436747b0e29SVedant Kumar /// The currently deferred region: its end location and count can be set once 437747b0e29SVedant Kumar /// its parent has been popped from the region stack. 438747b0e29SVedant Kumar Optional<SourceMappingRegion> DeferredRegion; 439747b0e29SVedant Kumar 440ee02499aSAlex Lorenz CounterExpressionBuilder Builder; 441ee02499aSAlex Lorenz 442bf42cfd7SJustin Bogner /// \brief A location in the most recently visited file or macro. 443bf42cfd7SJustin Bogner /// 444bf42cfd7SJustin Bogner /// This is used to adjust the active source regions appropriately when 445bf42cfd7SJustin Bogner /// expressions cross file or macro boundaries. 446bf42cfd7SJustin Bogner SourceLocation MostRecentLocation; 447bf42cfd7SJustin Bogner 448*8046d22aSVedant Kumar /// Location of the last terminated region. 449*8046d22aSVedant Kumar Optional<std::pair<SourceLocation, size_t>> LastTerminatedRegion; 450*8046d22aSVedant Kumar 451bf42cfd7SJustin Bogner /// \brief Return a counter for the subtraction of \c RHS from \c LHS 452ee02499aSAlex Lorenz Counter subtractCounters(Counter LHS, Counter RHS) { 453ee02499aSAlex Lorenz return Builder.subtract(LHS, RHS); 454ee02499aSAlex Lorenz } 455ee02499aSAlex Lorenz 456bf42cfd7SJustin Bogner /// \brief Return a counter for the sum of \c LHS and \c RHS. 457ee02499aSAlex Lorenz Counter addCounters(Counter LHS, Counter RHS) { 458ee02499aSAlex Lorenz return Builder.add(LHS, RHS); 459ee02499aSAlex Lorenz } 460ee02499aSAlex Lorenz 461bf42cfd7SJustin Bogner Counter addCounters(Counter C1, Counter C2, Counter C3) { 462bf42cfd7SJustin Bogner return addCounters(addCounters(C1, C2), C3); 463bf42cfd7SJustin Bogner } 464bf42cfd7SJustin Bogner 465ee02499aSAlex Lorenz /// \brief Return the region counter for the given statement. 466bf42cfd7SJustin Bogner /// 467ee02499aSAlex Lorenz /// This should only be called on statements that have a dedicated counter. 468bf42cfd7SJustin Bogner Counter getRegionCounter(const Stmt *S) { 469bf42cfd7SJustin Bogner return Counter::getCounter(CounterMap[S]); 470ee02499aSAlex Lorenz } 471ee02499aSAlex Lorenz 472bf42cfd7SJustin Bogner /// \brief Push a region onto the stack. 473bf42cfd7SJustin Bogner /// 474bf42cfd7SJustin Bogner /// Returns the index on the stack where the region was pushed. This can be 475bf42cfd7SJustin Bogner /// used with popRegions to exit a "scope", ending the region that was pushed. 476bf42cfd7SJustin Bogner size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None, 477bf42cfd7SJustin Bogner Optional<SourceLocation> EndLoc = None) { 478747b0e29SVedant Kumar if (StartLoc) { 479bf42cfd7SJustin Bogner MostRecentLocation = *StartLoc; 480747b0e29SVedant Kumar completeDeferred(Count, MostRecentLocation); 481747b0e29SVedant Kumar } 482bf42cfd7SJustin Bogner RegionStack.emplace_back(Count, StartLoc, EndLoc); 483ee02499aSAlex Lorenz 484bf42cfd7SJustin Bogner return RegionStack.size() - 1; 485ee02499aSAlex Lorenz } 486ee02499aSAlex Lorenz 487747b0e29SVedant Kumar /// Complete any pending deferred region by setting its end location and 488747b0e29SVedant Kumar /// count, and then pushing it onto the region stack. 489747b0e29SVedant Kumar size_t completeDeferred(Counter Count, SourceLocation DeferredEndLoc) { 490747b0e29SVedant Kumar size_t Index = RegionStack.size(); 491747b0e29SVedant Kumar if (!DeferredRegion) 492747b0e29SVedant Kumar return Index; 493747b0e29SVedant Kumar 494747b0e29SVedant Kumar // Consume the pending region. 495747b0e29SVedant Kumar SourceMappingRegion DR = DeferredRegion.getValue(); 496747b0e29SVedant Kumar DeferredRegion = None; 497747b0e29SVedant Kumar 498747b0e29SVedant Kumar // If the region ends in an expansion, find the expansion site. 499747b0e29SVedant Kumar if (SM.getFileID(DeferredEndLoc) != SM.getMainFileID()) { 500747b0e29SVedant Kumar FileID StartFile = SM.getFileID(DR.getStartLoc()); 501747b0e29SVedant Kumar if (isNestedIn(DeferredEndLoc, StartFile)) { 502747b0e29SVedant Kumar do { 503747b0e29SVedant Kumar DeferredEndLoc = getIncludeOrExpansionLoc(DeferredEndLoc); 504747b0e29SVedant Kumar } while (StartFile != SM.getFileID(DeferredEndLoc)); 505747b0e29SVedant Kumar } 506747b0e29SVedant Kumar } 507747b0e29SVedant Kumar 508747b0e29SVedant Kumar // The parent of this deferred region ends where the containing decl ends, 509747b0e29SVedant Kumar // so the region isn't useful. 510747b0e29SVedant Kumar if (DR.getStartLoc() == DeferredEndLoc) 511747b0e29SVedant Kumar return Index; 512747b0e29SVedant Kumar 513747b0e29SVedant Kumar // If we're visiting statements in non-source order (e.g switch cases or 514747b0e29SVedant Kumar // a loop condition) we can't construct a sensible deferred region. 515747b0e29SVedant Kumar if (!SpellingRegion(SM, DR.getStartLoc(), DeferredEndLoc).isInSourceOrder()) 516747b0e29SVedant Kumar return Index; 517747b0e29SVedant Kumar 518a1c4deb7SVedant Kumar DR.setGap(true); 519747b0e29SVedant Kumar DR.setCounter(Count); 520747b0e29SVedant Kumar DR.setEndLoc(DeferredEndLoc); 521747b0e29SVedant Kumar handleFileExit(DeferredEndLoc); 522747b0e29SVedant Kumar RegionStack.push_back(DR); 523747b0e29SVedant Kumar return Index; 524747b0e29SVedant Kumar } 525747b0e29SVedant Kumar 526*8046d22aSVedant Kumar /// Complete a deferred region created after a terminated region at the 527*8046d22aSVedant Kumar /// top-level. 528*8046d22aSVedant Kumar void completeTopLevelDeferredRegion(Counter Count, 529*8046d22aSVedant Kumar SourceLocation DeferredEndLoc) { 530*8046d22aSVedant Kumar if (DeferredRegion || !LastTerminatedRegion) 531*8046d22aSVedant Kumar return; 532*8046d22aSVedant Kumar 533*8046d22aSVedant Kumar if (LastTerminatedRegion->second != RegionStack.size()) 534*8046d22aSVedant Kumar return; 535*8046d22aSVedant Kumar 536*8046d22aSVedant Kumar SourceLocation Start = LastTerminatedRegion->first; 537*8046d22aSVedant Kumar if (SM.getFileID(Start) != SM.getMainFileID()) 538*8046d22aSVedant Kumar return; 539*8046d22aSVedant Kumar 540*8046d22aSVedant Kumar SourceMappingRegion DR = RegionStack.back(); 541*8046d22aSVedant Kumar DR.setStartLoc(Start); 542*8046d22aSVedant Kumar DR.setDeferred(false); 543*8046d22aSVedant Kumar DeferredRegion = DR; 544*8046d22aSVedant Kumar completeDeferred(Count, DeferredEndLoc); 545*8046d22aSVedant Kumar } 546*8046d22aSVedant Kumar 547bf42cfd7SJustin Bogner /// \brief Pop regions from the stack into the function's list of regions. 548bf42cfd7SJustin Bogner /// 549bf42cfd7SJustin Bogner /// Adds all regions from \c ParentIndex to the top of the stack to the 550bf42cfd7SJustin Bogner /// function's \c SourceRegions. 551bf42cfd7SJustin Bogner void popRegions(size_t ParentIndex) { 552bf42cfd7SJustin Bogner assert(RegionStack.size() >= ParentIndex && "parent not in stack"); 553747b0e29SVedant Kumar bool ParentOfDeferredRegion = false; 554bf42cfd7SJustin Bogner while (RegionStack.size() > ParentIndex) { 555bf42cfd7SJustin Bogner SourceMappingRegion &Region = RegionStack.back(); 556bf42cfd7SJustin Bogner if (Region.hasStartLoc()) { 557bf42cfd7SJustin Bogner SourceLocation StartLoc = Region.getStartLoc(); 558bf42cfd7SJustin Bogner SourceLocation EndLoc = Region.hasEndLoc() 559bf42cfd7SJustin Bogner ? Region.getEndLoc() 560bf42cfd7SJustin Bogner : RegionStack[ParentIndex].getEndLoc(); 561bf42cfd7SJustin Bogner while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) { 562bf42cfd7SJustin Bogner // The region ends in a nested file or macro expansion. Create a 563bf42cfd7SJustin Bogner // separate region for each expansion. 564bf42cfd7SJustin Bogner SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc); 565bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(NestedLoc, EndLoc)); 566bf42cfd7SJustin Bogner 5678545dae2SIgor Kudrin if (!isRegionAlreadyAdded(NestedLoc, EndLoc)) 568bf42cfd7SJustin Bogner SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc); 569bf42cfd7SJustin Bogner 570f14b2078SJustin Bogner EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc)); 571dceaaadfSJustin Bogner if (EndLoc.isInvalid()) 572dceaaadfSJustin Bogner llvm::report_fatal_error("File exit not handled before popRegions"); 573bf42cfd7SJustin Bogner } 574bf42cfd7SJustin Bogner Region.setEndLoc(EndLoc); 575bf42cfd7SJustin Bogner 576bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 577bf42cfd7SJustin Bogner // If this region happens to span an entire expansion, we need to make 578bf42cfd7SJustin Bogner // sure we don't overlap the parent region with it. 579bf42cfd7SJustin Bogner if (StartLoc == getStartOfFileOrMacro(StartLoc) && 580bf42cfd7SJustin Bogner EndLoc == getEndOfFileOrMacro(EndLoc)) 581bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(EndLoc); 582bf42cfd7SJustin Bogner 583bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc)); 584f36a5c4aSCraig Topper SourceRegions.push_back(Region); 585747b0e29SVedant Kumar 586747b0e29SVedant Kumar if (ParentOfDeferredRegion) { 587747b0e29SVedant Kumar ParentOfDeferredRegion = false; 588747b0e29SVedant Kumar 589747b0e29SVedant Kumar // If there's an existing deferred region, keep the old one, because 590747b0e29SVedant Kumar // it means there are two consecutive returns (or a similar pattern). 591747b0e29SVedant Kumar if (!DeferredRegion.hasValue() && 592747b0e29SVedant Kumar // File IDs aren't gathered within macro expansions, so it isn't 593747b0e29SVedant Kumar // useful to try and create a deferred region inside of one. 594747b0e29SVedant Kumar (SM.getFileID(EndLoc) == SM.getMainFileID())) 595747b0e29SVedant Kumar DeferredRegion = 596747b0e29SVedant Kumar SourceMappingRegion(Counter::getZero(), EndLoc, None); 597747b0e29SVedant Kumar } 598747b0e29SVedant Kumar } else if (Region.isDeferred()) { 599747b0e29SVedant Kumar assert(!ParentOfDeferredRegion && "Consecutive deferred regions"); 600747b0e29SVedant Kumar ParentOfDeferredRegion = true; 601bf42cfd7SJustin Bogner } 602bf42cfd7SJustin Bogner RegionStack.pop_back(); 603*8046d22aSVedant Kumar 604*8046d22aSVedant Kumar // If the zero region pushed after the last terminated region no longer 605*8046d22aSVedant Kumar // exists, clear its cached information. 606*8046d22aSVedant Kumar if (LastTerminatedRegion && 607*8046d22aSVedant Kumar RegionStack.size() < LastTerminatedRegion->second) 608*8046d22aSVedant Kumar LastTerminatedRegion = None; 609bf42cfd7SJustin Bogner } 610747b0e29SVedant Kumar assert(!ParentOfDeferredRegion && "Deferred region with no parent"); 611ee02499aSAlex Lorenz } 612ee02499aSAlex Lorenz 613bf42cfd7SJustin Bogner /// \brief Return the currently active region. 614bf42cfd7SJustin Bogner SourceMappingRegion &getRegion() { 615bf42cfd7SJustin Bogner assert(!RegionStack.empty() && "statement has no region"); 616bf42cfd7SJustin Bogner return RegionStack.back(); 617ee02499aSAlex Lorenz } 618ee02499aSAlex Lorenz 619bf42cfd7SJustin Bogner /// \brief Propagate counts through the children of \c S. 620bf42cfd7SJustin Bogner Counter propagateCounts(Counter TopCount, const Stmt *S) { 6217838696eSVedant Kumar SourceLocation StartLoc = getStart(S); 6227838696eSVedant Kumar SourceLocation EndLoc = getEnd(S); 6237838696eSVedant Kumar size_t Index = pushRegion(TopCount, StartLoc, EndLoc); 624bf42cfd7SJustin Bogner Visit(S); 625bf42cfd7SJustin Bogner Counter ExitCount = getRegion().getCounter(); 626bf42cfd7SJustin Bogner popRegions(Index); 62739f01975SVedant Kumar 62839f01975SVedant Kumar // The statement may be spanned by an expansion. Make sure we handle a file 62939f01975SVedant Kumar // exit out of this expansion before moving to the next statement. 6307838696eSVedant Kumar if (SM.isBeforeInTranslationUnit(StartLoc, S->getLocStart())) 6317838696eSVedant Kumar MostRecentLocation = EndLoc; 63239f01975SVedant Kumar 633bf42cfd7SJustin Bogner return ExitCount; 634ee02499aSAlex Lorenz } 635ee02499aSAlex Lorenz 6360a7c9d11SIgor Kudrin /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc 6370a7c9d11SIgor Kudrin /// is already added to \c SourceRegions. 6380a7c9d11SIgor Kudrin bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) { 6390a7c9d11SIgor Kudrin return SourceRegions.rend() != 6400a7c9d11SIgor Kudrin std::find_if(SourceRegions.rbegin(), SourceRegions.rend(), 6410a7c9d11SIgor Kudrin [&](const SourceMappingRegion &Region) { 6420a7c9d11SIgor Kudrin return Region.getStartLoc() == StartLoc && 6430a7c9d11SIgor Kudrin Region.getEndLoc() == EndLoc; 6440a7c9d11SIgor Kudrin }); 6450a7c9d11SIgor Kudrin } 6460a7c9d11SIgor Kudrin 647bf42cfd7SJustin Bogner /// \brief Adjust the most recently visited location to \c EndLoc. 648bf42cfd7SJustin Bogner /// 649bf42cfd7SJustin Bogner /// This should be used after visiting any statements in non-source order. 650bf42cfd7SJustin Bogner void adjustForOutOfOrderTraversal(SourceLocation EndLoc) { 651bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 6520a7c9d11SIgor Kudrin // The code region for a whole macro is created in handleFileExit() when 6530a7c9d11SIgor Kudrin // it detects exiting of the virtual file of that macro. If we visited 6540a7c9d11SIgor Kudrin // statements in non-source order, we might already have such a region 6550a7c9d11SIgor Kudrin // added, for example, if a body of a loop is divided among multiple 6560a7c9d11SIgor Kudrin // macros. Avoid adding duplicate regions in such case. 65796ae73f7SJustin Bogner if (getRegion().hasEndLoc() && 6580a7c9d11SIgor Kudrin MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) && 6590a7c9d11SIgor Kudrin isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation), 6600a7c9d11SIgor Kudrin MostRecentLocation)) 661bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation); 662ee02499aSAlex Lorenz } 663ee02499aSAlex Lorenz 664bf42cfd7SJustin Bogner /// \brief Adjust regions and state when \c NewLoc exits a file. 665bf42cfd7SJustin Bogner /// 666bf42cfd7SJustin Bogner /// If moving from our most recently tracked location to \c NewLoc exits any 667bf42cfd7SJustin Bogner /// files, this adjusts our current region stack and creates the file regions 668bf42cfd7SJustin Bogner /// for the exited file. 669bf42cfd7SJustin Bogner void handleFileExit(SourceLocation NewLoc) { 670e44dd6dbSJustin Bogner if (NewLoc.isInvalid() || 671e44dd6dbSJustin Bogner SM.isWrittenInSameFile(MostRecentLocation, NewLoc)) 672bf42cfd7SJustin Bogner return; 673bf42cfd7SJustin Bogner 674bf42cfd7SJustin Bogner // If NewLoc is not in a file that contains MostRecentLocation, walk up to 675bf42cfd7SJustin Bogner // find the common ancestor. 676bf42cfd7SJustin Bogner SourceLocation LCA = NewLoc; 677bf42cfd7SJustin Bogner FileID ParentFile = SM.getFileID(LCA); 678bf42cfd7SJustin Bogner while (!isNestedIn(MostRecentLocation, ParentFile)) { 679bf42cfd7SJustin Bogner LCA = getIncludeOrExpansionLoc(LCA); 680bf42cfd7SJustin Bogner if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) { 681bf42cfd7SJustin Bogner // Since there isn't a common ancestor, no file was exited. We just need 682bf42cfd7SJustin Bogner // to adjust our location to the new file. 683bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 684bf42cfd7SJustin Bogner return; 685bf42cfd7SJustin Bogner } 686bf42cfd7SJustin Bogner ParentFile = SM.getFileID(LCA); 687ee02499aSAlex Lorenz } 688ee02499aSAlex Lorenz 689bf42cfd7SJustin Bogner llvm::SmallSet<SourceLocation, 8> StartLocs; 690bf42cfd7SJustin Bogner Optional<Counter> ParentCounter; 69157d3f145SPete Cooper for (SourceMappingRegion &I : llvm::reverse(RegionStack)) { 69257d3f145SPete Cooper if (!I.hasStartLoc()) 693bf42cfd7SJustin Bogner continue; 69457d3f145SPete Cooper SourceLocation Loc = I.getStartLoc(); 695bf42cfd7SJustin Bogner if (!isNestedIn(Loc, ParentFile)) { 69657d3f145SPete Cooper ParentCounter = I.getCounter(); 697bf42cfd7SJustin Bogner break; 698ee02499aSAlex Lorenz } 699bf42cfd7SJustin Bogner 700bf42cfd7SJustin Bogner while (!SM.isInFileID(Loc, ParentFile)) { 701bf42cfd7SJustin Bogner // The most nested region for each start location is the one with the 702bf42cfd7SJustin Bogner // correct count. We avoid creating redundant regions by stopping once 703bf42cfd7SJustin Bogner // we've seen this region. 704bf42cfd7SJustin Bogner if (StartLocs.insert(Loc).second) 70557d3f145SPete Cooper SourceRegions.emplace_back(I.getCounter(), Loc, 706bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 707bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 708ee02499aSAlex Lorenz } 70957d3f145SPete Cooper I.setStartLoc(getPreciseTokenLocEnd(Loc)); 710bf42cfd7SJustin Bogner } 711bf42cfd7SJustin Bogner 712bf42cfd7SJustin Bogner if (ParentCounter) { 713bf42cfd7SJustin Bogner // If the file is contained completely by another region and doesn't 714bf42cfd7SJustin Bogner // immediately start its own region, the whole file gets a region 715bf42cfd7SJustin Bogner // corresponding to the parent. 716bf42cfd7SJustin Bogner SourceLocation Loc = MostRecentLocation; 717bf42cfd7SJustin Bogner while (isNestedIn(Loc, ParentFile)) { 718bf42cfd7SJustin Bogner SourceLocation FileStart = getStartOfFileOrMacro(Loc); 719bf42cfd7SJustin Bogner if (StartLocs.insert(FileStart).second) 720bf42cfd7SJustin Bogner SourceRegions.emplace_back(*ParentCounter, FileStart, 721bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 722bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 723bf42cfd7SJustin Bogner } 724bf42cfd7SJustin Bogner } 725bf42cfd7SJustin Bogner 726bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 727bf42cfd7SJustin Bogner } 728bf42cfd7SJustin Bogner 729bf42cfd7SJustin Bogner /// \brief Ensure that \c S is included in the current region. 730bf42cfd7SJustin Bogner void extendRegion(const Stmt *S) { 731bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 732bf42cfd7SJustin Bogner SourceLocation StartLoc = getStart(S); 733bf42cfd7SJustin Bogner 734bf42cfd7SJustin Bogner handleFileExit(StartLoc); 735bf42cfd7SJustin Bogner if (!Region.hasStartLoc()) 736bf42cfd7SJustin Bogner Region.setStartLoc(StartLoc); 737747b0e29SVedant Kumar 738747b0e29SVedant Kumar completeDeferred(Region.getCounter(), StartLoc); 739bf42cfd7SJustin Bogner } 740bf42cfd7SJustin Bogner 741bf42cfd7SJustin Bogner /// \brief Mark \c S as a terminator, starting a zero region. 742bf42cfd7SJustin Bogner void terminateRegion(const Stmt *S) { 743bf42cfd7SJustin Bogner extendRegion(S); 744bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 745*8046d22aSVedant Kumar SourceLocation EndLoc = getEnd(S); 746bf42cfd7SJustin Bogner if (!Region.hasEndLoc()) 747*8046d22aSVedant Kumar Region.setEndLoc(EndLoc); 748bf42cfd7SJustin Bogner pushRegion(Counter::getZero()); 749*8046d22aSVedant Kumar auto &ZeroRegion = getRegion(); 750*8046d22aSVedant Kumar ZeroRegion.setDeferred(true); 751*8046d22aSVedant Kumar LastTerminatedRegion = {EndLoc, RegionStack.size()}; 752bf42cfd7SJustin Bogner } 753ee02499aSAlex Lorenz 7542e8c8759SVedant Kumar /// Emit a gap region between \p StartLoc and \p EndLoc with the given count. 7552e8c8759SVedant Kumar void fillGapAreaWithCount(SourceLocation StartLoc, SourceLocation EndLoc, 7562e8c8759SVedant Kumar Counter Count) { 7572e8c8759SVedant Kumar if (StartLoc == EndLoc || StartLoc.isMacroID() || EndLoc.isMacroID() || 7582e8c8759SVedant Kumar !SM.isWrittenInSameFile(StartLoc, EndLoc)) 7592e8c8759SVedant Kumar return; 7602e8c8759SVedant Kumar handleFileExit(StartLoc); 7612e8c8759SVedant Kumar size_t Index = pushRegion(Count, StartLoc, EndLoc); 7622e8c8759SVedant Kumar getRegion().setGap(true); 7632e8c8759SVedant Kumar handleFileExit(EndLoc); 7642e8c8759SVedant Kumar popRegions(Index); 7652e8c8759SVedant Kumar } 7662e8c8759SVedant Kumar 767ee02499aSAlex Lorenz /// \brief Keep counts of breaks and continues inside loops. 768ee02499aSAlex Lorenz struct BreakContinue { 769ee02499aSAlex Lorenz Counter BreakCount; 770ee02499aSAlex Lorenz Counter ContinueCount; 771ee02499aSAlex Lorenz }; 772ee02499aSAlex Lorenz SmallVector<BreakContinue, 8> BreakContinueStack; 773ee02499aSAlex Lorenz 774ee02499aSAlex Lorenz CounterCoverageMappingBuilder( 775ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM, 776e5ee6c58SJustin Bogner llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM, 777ee02499aSAlex Lorenz const LangOptions &LangOpts) 778747b0e29SVedant Kumar : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap), 779747b0e29SVedant Kumar DeferredRegion(None) {} 780ee02499aSAlex Lorenz 781ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 782ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 783ee02499aSAlex Lorenz llvm::SmallVector<unsigned, 8> VirtualFileMapping; 784bf42cfd7SJustin Bogner gatherFileIDs(VirtualFileMapping); 785fc05ee34SIgor Kudrin SourceRegionFilter Filter = emitExpansionRegions(); 786747b0e29SVedant Kumar assert(!DeferredRegion && "Deferred region never completed"); 787fc05ee34SIgor Kudrin emitSourceRegions(Filter); 788ee02499aSAlex Lorenz gatherSkippedRegions(); 789ee02499aSAlex Lorenz 790efd319a2SVedant Kumar if (MappingRegions.empty()) 791efd319a2SVedant Kumar return; 792efd319a2SVedant Kumar 7934da909b2SJustin Bogner CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(), 7944da909b2SJustin Bogner MappingRegions); 795ee02499aSAlex Lorenz Writer.write(OS); 796ee02499aSAlex Lorenz } 797ee02499aSAlex Lorenz 798ee02499aSAlex Lorenz void VisitStmt(const Stmt *S) { 799ed1fe5d0SYaron Keren if (S->getLocStart().isValid()) 800bf42cfd7SJustin Bogner extendRegion(S); 801642f173aSBenjamin Kramer for (const Stmt *Child : S->children()) 802642f173aSBenjamin Kramer if (Child) 803642f173aSBenjamin Kramer this->Visit(Child); 804bf42cfd7SJustin Bogner handleFileExit(getEnd(S)); 805ee02499aSAlex Lorenz } 806ee02499aSAlex Lorenz 807341bf429SVedant Kumar /// Determine whether the final deferred region emitted in \p Body should be 808341bf429SVedant Kumar /// discarded. 809341bf429SVedant Kumar static bool discardFinalDeferredRegionInDecl(Stmt *Body) { 810341bf429SVedant Kumar if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 811341bf429SVedant Kumar Stmt *LastStmt = CS->body_back(); 812341bf429SVedant Kumar if (auto *IfElse = dyn_cast<IfStmt>(LastStmt)) { 813341bf429SVedant Kumar if (auto *Else = dyn_cast_or_null<CompoundStmt>(IfElse->getElse())) 814341bf429SVedant Kumar LastStmt = Else->body_back(); 815341bf429SVedant Kumar else 816341bf429SVedant Kumar LastStmt = IfElse->getElse(); 817341bf429SVedant Kumar } 818341bf429SVedant Kumar return dyn_cast_or_null<ReturnStmt>(LastStmt); 819341bf429SVedant Kumar } 820341bf429SVedant Kumar return false; 821341bf429SVedant Kumar } 822341bf429SVedant Kumar 823ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 824747b0e29SVedant Kumar assert(!DeferredRegion && "Deferred region never completed"); 825747b0e29SVedant Kumar 826bf42cfd7SJustin Bogner Stmt *Body = D->getBody(); 827efd319a2SVedant Kumar 828efd319a2SVedant Kumar // Do not propagate region counts into system headers. 829efd319a2SVedant Kumar if (Body && SM.isInSystemHeader(SM.getSpellingLoc(getStart(Body)))) 830efd319a2SVedant Kumar return; 831efd319a2SVedant Kumar 832747b0e29SVedant Kumar Counter ExitCount = propagateCounts(getRegionCounter(Body), Body); 833747b0e29SVedant Kumar assert(RegionStack.empty() && "Regions entered but never exited"); 834747b0e29SVedant Kumar 835341bf429SVedant Kumar if (DeferredRegion) { 836341bf429SVedant Kumar // Complete (or discard) any deferred regions introduced by the last 837341bf429SVedant Kumar // statement. 838341bf429SVedant Kumar if (discardFinalDeferredRegionInDecl(Body)) 839ef8e05ffSVedant Kumar DeferredRegion = None; 840341bf429SVedant Kumar else 841747b0e29SVedant Kumar popRegions(completeDeferred(ExitCount, getEnd(Body))); 842ee02499aSAlex Lorenz } 843341bf429SVedant Kumar } 844ee02499aSAlex Lorenz 845ee02499aSAlex Lorenz void VisitReturnStmt(const ReturnStmt *S) { 846bf42cfd7SJustin Bogner extendRegion(S); 847ee02499aSAlex Lorenz if (S->getRetValue()) 848ee02499aSAlex Lorenz Visit(S->getRetValue()); 849bf42cfd7SJustin Bogner terminateRegion(S); 850ee02499aSAlex Lorenz } 851ee02499aSAlex Lorenz 852f959febfSJustin Bogner void VisitCXXThrowExpr(const CXXThrowExpr *E) { 853f959febfSJustin Bogner extendRegion(E); 854f959febfSJustin Bogner if (E->getSubExpr()) 855f959febfSJustin Bogner Visit(E->getSubExpr()); 856f959febfSJustin Bogner terminateRegion(E); 857f959febfSJustin Bogner } 858f959febfSJustin Bogner 859bf42cfd7SJustin Bogner void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); } 860ee02499aSAlex Lorenz 861ee02499aSAlex Lorenz void VisitLabelStmt(const LabelStmt *S) { 862*8046d22aSVedant Kumar Counter LabelCount = getRegionCounter(S); 863bf42cfd7SJustin Bogner SourceLocation Start = getStart(S); 864*8046d22aSVedant Kumar completeTopLevelDeferredRegion(LabelCount, Start); 865bf42cfd7SJustin Bogner // We can't extendRegion here or we risk overlapping with our new region. 866bf42cfd7SJustin Bogner handleFileExit(Start); 867*8046d22aSVedant Kumar pushRegion(LabelCount, Start); 868ee02499aSAlex Lorenz Visit(S->getSubStmt()); 869ee02499aSAlex Lorenz } 870ee02499aSAlex Lorenz 871ee02499aSAlex Lorenz void VisitBreakStmt(const BreakStmt *S) { 872ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 873ee02499aSAlex Lorenz BreakContinueStack.back().BreakCount = addCounters( 874bf42cfd7SJustin Bogner BreakContinueStack.back().BreakCount, getRegion().getCounter()); 8757f53fbfcSEli Friedman // FIXME: a break in a switch should terminate regions for all preceding 8767f53fbfcSEli Friedman // case statements, not just the most recent one. 877bf42cfd7SJustin Bogner terminateRegion(S); 878ee02499aSAlex Lorenz } 879ee02499aSAlex Lorenz 880ee02499aSAlex Lorenz void VisitContinueStmt(const ContinueStmt *S) { 881ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 882ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 883bf42cfd7SJustin Bogner BreakContinueStack.back().ContinueCount, getRegion().getCounter()); 884bf42cfd7SJustin Bogner terminateRegion(S); 885ee02499aSAlex Lorenz } 886ee02499aSAlex Lorenz 887181dfe4cSEli Friedman void VisitCallExpr(const CallExpr *E) { 888181dfe4cSEli Friedman VisitStmt(E); 889181dfe4cSEli Friedman 890181dfe4cSEli Friedman // Terminate the region when we hit a noreturn function. 891181dfe4cSEli Friedman // (This is helpful dealing with switch statements.) 892181dfe4cSEli Friedman QualType CalleeType = E->getCallee()->getType(); 893181dfe4cSEli Friedman if (getFunctionExtInfo(*CalleeType).getNoReturn()) 894181dfe4cSEli Friedman terminateRegion(E); 895181dfe4cSEli Friedman } 896181dfe4cSEli Friedman 897ee02499aSAlex Lorenz void VisitWhileStmt(const WhileStmt *S) { 898bf42cfd7SJustin Bogner extendRegion(S); 899ee02499aSAlex Lorenz 900bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 901bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 902bf42cfd7SJustin Bogner 903bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 904bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 905bf42cfd7SJustin Bogner extendRegion(S->getBody()); 906bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 907ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 908bf42cfd7SJustin Bogner 909bf42cfd7SJustin Bogner // Go back to handle the condition. 910bf42cfd7SJustin Bogner Counter CondCount = 911bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 912bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 913bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 914bf42cfd7SJustin Bogner 915bf42cfd7SJustin Bogner Counter OutCount = 916bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 917bf42cfd7SJustin Bogner if (OutCount != ParentCount) 918bf42cfd7SJustin Bogner pushRegion(OutCount); 919ee02499aSAlex Lorenz } 920ee02499aSAlex Lorenz 921ee02499aSAlex Lorenz void VisitDoStmt(const DoStmt *S) { 922bf42cfd7SJustin Bogner extendRegion(S); 923ee02499aSAlex Lorenz 924bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 925bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 926bf42cfd7SJustin Bogner 927bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 928bf42cfd7SJustin Bogner extendRegion(S->getBody()); 929bf42cfd7SJustin Bogner Counter BackedgeCount = 930bf42cfd7SJustin Bogner propagateCounts(addCounters(ParentCount, BodyCount), S->getBody()); 931ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 932bf42cfd7SJustin Bogner 933bf42cfd7SJustin Bogner Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount); 934bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 935bf42cfd7SJustin Bogner 936bf42cfd7SJustin Bogner Counter OutCount = 937bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 938bf42cfd7SJustin Bogner if (OutCount != ParentCount) 939bf42cfd7SJustin Bogner pushRegion(OutCount); 940ee02499aSAlex Lorenz } 941ee02499aSAlex Lorenz 942ee02499aSAlex Lorenz void VisitForStmt(const ForStmt *S) { 943bf42cfd7SJustin Bogner extendRegion(S); 944ee02499aSAlex Lorenz if (S->getInit()) 945ee02499aSAlex Lorenz Visit(S->getInit()); 946ee02499aSAlex Lorenz 947bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 948bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 949bf42cfd7SJustin Bogner 950bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 951ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 952bf42cfd7SJustin Bogner extendRegion(S->getBody()); 953bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 954bf42cfd7SJustin Bogner BreakContinue BC = BreakContinueStack.pop_back_val(); 955ee02499aSAlex Lorenz 956ee02499aSAlex Lorenz // The increment is essentially part of the body but it needs to include 957ee02499aSAlex Lorenz // the count for all the continue statements. 958bf42cfd7SJustin Bogner if (const Stmt *Inc = S->getInc()) 959bf42cfd7SJustin Bogner propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc); 960bf42cfd7SJustin Bogner 961bf42cfd7SJustin Bogner // Go back to handle the condition. 962bf42cfd7SJustin Bogner Counter CondCount = 963bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 964bf42cfd7SJustin Bogner if (const Expr *Cond = S->getCond()) { 965bf42cfd7SJustin Bogner propagateCounts(CondCount, Cond); 966bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 967ee02499aSAlex Lorenz } 968ee02499aSAlex Lorenz 969bf42cfd7SJustin Bogner Counter OutCount = 970bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 971bf42cfd7SJustin Bogner if (OutCount != ParentCount) 972bf42cfd7SJustin Bogner pushRegion(OutCount); 973ee02499aSAlex Lorenz } 974ee02499aSAlex Lorenz 975ee02499aSAlex Lorenz void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 976bf42cfd7SJustin Bogner extendRegion(S); 977bf42cfd7SJustin Bogner Visit(S->getLoopVarStmt()); 978ee02499aSAlex Lorenz Visit(S->getRangeStmt()); 979bf42cfd7SJustin Bogner 980bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 981bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 982bf42cfd7SJustin Bogner 983ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 984bf42cfd7SJustin Bogner extendRegion(S->getBody()); 985bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 986ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 987bf42cfd7SJustin Bogner 9881587432dSJustin Bogner Counter LoopCount = 9891587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 9901587432dSJustin Bogner Counter OutCount = 9911587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 992bf42cfd7SJustin Bogner if (OutCount != ParentCount) 993bf42cfd7SJustin Bogner pushRegion(OutCount); 994ee02499aSAlex Lorenz } 995ee02499aSAlex Lorenz 996ee02499aSAlex Lorenz void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 997bf42cfd7SJustin Bogner extendRegion(S); 998ee02499aSAlex Lorenz Visit(S->getElement()); 999bf42cfd7SJustin Bogner 1000bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1001bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 1002bf42cfd7SJustin Bogner 1003ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 1004bf42cfd7SJustin Bogner extendRegion(S->getBody()); 1005bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 1006ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 1007bf42cfd7SJustin Bogner 10081587432dSJustin Bogner Counter LoopCount = 10091587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 10101587432dSJustin Bogner Counter OutCount = 10111587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 1012bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1013bf42cfd7SJustin Bogner pushRegion(OutCount); 1014ee02499aSAlex Lorenz } 1015ee02499aSAlex Lorenz 1016ee02499aSAlex Lorenz void VisitSwitchStmt(const SwitchStmt *S) { 1017bf42cfd7SJustin Bogner extendRegion(S); 1018f2a6ec55SVedant Kumar if (S->getInit()) 1019f2a6ec55SVedant Kumar Visit(S->getInit()); 1020ee02499aSAlex Lorenz Visit(S->getCond()); 1021bf42cfd7SJustin Bogner 1022ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 1023bf42cfd7SJustin Bogner 1024bf42cfd7SJustin Bogner const Stmt *Body = S->getBody(); 1025bf42cfd7SJustin Bogner extendRegion(Body); 1026bf42cfd7SJustin Bogner if (const auto *CS = dyn_cast<CompoundStmt>(Body)) { 1027bf42cfd7SJustin Bogner if (!CS->body_empty()) { 10287f53fbfcSEli Friedman // Make a region for the body of the switch. If the body starts with 10297f53fbfcSEli Friedman // a case, that case will reuse this region; otherwise, this covers 10307f53fbfcSEli Friedman // the unreachable code at the beginning of the switch body. 1031bf42cfd7SJustin Bogner size_t Index = 10327f53fbfcSEli Friedman pushRegion(Counter::getZero(), getStart(CS->body_front())); 1033b5841332SRichard Trieu for (const auto *Child : CS->children()) 1034bf42cfd7SJustin Bogner Visit(Child); 10357f53fbfcSEli Friedman 10367f53fbfcSEli Friedman // Set the end for the body of the switch, if it isn't already set. 10377f53fbfcSEli Friedman for (size_t i = RegionStack.size(); i != Index; --i) { 10387f53fbfcSEli Friedman if (!RegionStack[i - 1].hasEndLoc()) 10397f53fbfcSEli Friedman RegionStack[i - 1].setEndLoc(getEnd(CS->body_back())); 10407f53fbfcSEli Friedman } 10417f53fbfcSEli Friedman 1042bf42cfd7SJustin Bogner popRegions(Index); 1043ee02499aSAlex Lorenz } 104487ea3b05SVedant Kumar } else 1045bf42cfd7SJustin Bogner propagateCounts(Counter::getZero(), Body); 1046ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 1047bf42cfd7SJustin Bogner 1048ee02499aSAlex Lorenz if (!BreakContinueStack.empty()) 1049ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 1050ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount, BC.ContinueCount); 1051bf42cfd7SJustin Bogner 1052bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 10533836482aSVedant Kumar SourceLocation ExitLoc = getEnd(S); 105408780529SAlex Lorenz pushRegion(ExitCount); 105508780529SAlex Lorenz 105608780529SAlex Lorenz // Ensure that handleFileExit recognizes when the end location is located 105708780529SAlex Lorenz // in a different file. 105808780529SAlex Lorenz MostRecentLocation = getStart(S); 10593836482aSVedant Kumar handleFileExit(ExitLoc); 1060ee02499aSAlex Lorenz } 1061ee02499aSAlex Lorenz 1062bf42cfd7SJustin Bogner void VisitSwitchCase(const SwitchCase *S) { 1063bf42cfd7SJustin Bogner extendRegion(S); 1064ee02499aSAlex Lorenz 1065bf42cfd7SJustin Bogner SourceMappingRegion &Parent = getRegion(); 1066bf42cfd7SJustin Bogner 1067bf42cfd7SJustin Bogner Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S)); 1068bf42cfd7SJustin Bogner // Reuse the existing region if it starts at our label. This is typical of 1069bf42cfd7SJustin Bogner // the first case in a switch. 1070bf42cfd7SJustin Bogner if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S)) 1071bf42cfd7SJustin Bogner Parent.setCounter(Count); 1072bf42cfd7SJustin Bogner else 1073bf42cfd7SJustin Bogner pushRegion(Count, getStart(S)); 1074bf42cfd7SJustin Bogner 1075376c06c2SSanjay Patel if (const auto *CS = dyn_cast<CaseStmt>(S)) { 1076bf42cfd7SJustin Bogner Visit(CS->getLHS()); 1077bf42cfd7SJustin Bogner if (const Expr *RHS = CS->getRHS()) 1078bf42cfd7SJustin Bogner Visit(RHS); 1079bf42cfd7SJustin Bogner } 1080ee02499aSAlex Lorenz Visit(S->getSubStmt()); 1081ee02499aSAlex Lorenz } 1082ee02499aSAlex Lorenz 1083ee02499aSAlex Lorenz void VisitIfStmt(const IfStmt *S) { 1084bf42cfd7SJustin Bogner extendRegion(S); 10859d2a16b9SVedant Kumar if (S->getInit()) 10869d2a16b9SVedant Kumar Visit(S->getInit()); 10879d2a16b9SVedant Kumar 1088055ebc34SJustin Bogner // Extend into the condition before we propagate through it below - this is 1089055ebc34SJustin Bogner // needed to handle macros that generate the "if" but not the condition. 1090055ebc34SJustin Bogner extendRegion(S->getCond()); 1091ee02499aSAlex Lorenz 1092bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1093bf42cfd7SJustin Bogner Counter ThenCount = getRegionCounter(S); 1094ee02499aSAlex Lorenz 109591f2e3c9SJustin Bogner // Emitting a counter for the condition makes it easier to interpret the 109691f2e3c9SJustin Bogner // counter for the body when looking at the coverage. 109791f2e3c9SJustin Bogner propagateCounts(ParentCount, S->getCond()); 109891f2e3c9SJustin Bogner 10992e8c8759SVedant Kumar // The 'then' count applies to the area immediately after the condition. 11002e8c8759SVedant Kumar fillGapAreaWithCount(getPreciseTokenLocEnd(getEnd(S->getCond())), 11012e8c8759SVedant Kumar getStart(S->getThen()), ThenCount); 11022e8c8759SVedant Kumar 1103bf42cfd7SJustin Bogner extendRegion(S->getThen()); 1104bf42cfd7SJustin Bogner Counter OutCount = propagateCounts(ThenCount, S->getThen()); 1105bf42cfd7SJustin Bogner 1106bf42cfd7SJustin Bogner Counter ElseCount = subtractCounters(ParentCount, ThenCount); 1107bf42cfd7SJustin Bogner if (const Stmt *Else = S->getElse()) { 11082e8c8759SVedant Kumar // The 'else' count applies to the area immediately after the 'then'. 11092e8c8759SVedant Kumar fillGapAreaWithCount(getPreciseTokenLocEnd(getEnd(S->getThen())), 11102e8c8759SVedant Kumar getStart(Else), ElseCount); 11112e8c8759SVedant Kumar extendRegion(Else); 1112bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else)); 1113bf42cfd7SJustin Bogner } else 1114bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, ElseCount); 1115bf42cfd7SJustin Bogner 1116bf42cfd7SJustin Bogner if (OutCount != ParentCount) 1117bf42cfd7SJustin Bogner pushRegion(OutCount); 1118ee02499aSAlex Lorenz } 1119ee02499aSAlex Lorenz 1120ee02499aSAlex Lorenz void VisitCXXTryStmt(const CXXTryStmt *S) { 1121bf42cfd7SJustin Bogner extendRegion(S); 1122049908b2SVedant Kumar // Handle macros that generate the "try" but not the rest. 1123049908b2SVedant Kumar extendRegion(S->getTryBlock()); 1124049908b2SVedant Kumar 1125049908b2SVedant Kumar Counter ParentCount = getRegion().getCounter(); 1126049908b2SVedant Kumar propagateCounts(ParentCount, S->getTryBlock()); 1127049908b2SVedant Kumar 1128ee02499aSAlex Lorenz for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 1129ee02499aSAlex Lorenz Visit(S->getHandler(I)); 1130bf42cfd7SJustin Bogner 1131bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 1132bf42cfd7SJustin Bogner pushRegion(ExitCount); 1133ee02499aSAlex Lorenz } 1134ee02499aSAlex Lorenz 1135ee02499aSAlex Lorenz void VisitCXXCatchStmt(const CXXCatchStmt *S) { 1136bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(S), S->getHandlerBlock()); 1137ee02499aSAlex Lorenz } 1138ee02499aSAlex Lorenz 1139ee02499aSAlex Lorenz void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 1140bf42cfd7SJustin Bogner extendRegion(E); 1141ee02499aSAlex Lorenz 1142bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 1143bf42cfd7SJustin Bogner Counter TrueCount = getRegionCounter(E); 1144ee02499aSAlex Lorenz 1145e3654ce7SJustin Bogner Visit(E->getCond()); 1146e3654ce7SJustin Bogner 1147e3654ce7SJustin Bogner if (!isa<BinaryConditionalOperator>(E)) { 11482e8c8759SVedant Kumar // The 'then' count applies to the area immediately after the condition. 11492e8c8759SVedant Kumar fillGapAreaWithCount(E->getQuestionLoc(), getStart(E->getTrueExpr()), 11502e8c8759SVedant Kumar TrueCount); 11512e8c8759SVedant Kumar 1152e3654ce7SJustin Bogner extendRegion(E->getTrueExpr()); 1153bf42cfd7SJustin Bogner propagateCounts(TrueCount, E->getTrueExpr()); 1154e3654ce7SJustin Bogner } 11552e8c8759SVedant Kumar 1156e3654ce7SJustin Bogner extendRegion(E->getFalseExpr()); 1157bf42cfd7SJustin Bogner propagateCounts(subtractCounters(ParentCount, TrueCount), 1158bf42cfd7SJustin Bogner E->getFalseExpr()); 1159ee02499aSAlex Lorenz } 1160ee02499aSAlex Lorenz 1161ee02499aSAlex Lorenz void VisitBinLAnd(const BinaryOperator *E) { 1162e5f06a81SVedant Kumar extendRegion(E->getLHS()); 1163e5f06a81SVedant Kumar propagateCounts(getRegion().getCounter(), E->getLHS()); 1164e5f06a81SVedant Kumar handleFileExit(getEnd(E->getLHS())); 1165bf42cfd7SJustin Bogner 1166bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 1167bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 1168ee02499aSAlex Lorenz } 1169ee02499aSAlex Lorenz 1170ee02499aSAlex Lorenz void VisitBinLOr(const BinaryOperator *E) { 1171e5f06a81SVedant Kumar extendRegion(E->getLHS()); 1172e5f06a81SVedant Kumar propagateCounts(getRegion().getCounter(), E->getLHS()); 1173e5f06a81SVedant Kumar handleFileExit(getEnd(E->getLHS())); 1174ee02499aSAlex Lorenz 1175bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 1176bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 117701a0d062SAlex Lorenz } 1178c109102eSJustin Bogner 1179c109102eSJustin Bogner void VisitLambdaExpr(const LambdaExpr *LE) { 1180c109102eSJustin Bogner // Lambdas are treated as their own functions for now, so we shouldn't 1181c109102eSJustin Bogner // propagate counts into them. 1182c109102eSJustin Bogner } 1183ee02499aSAlex Lorenz }; 1184ee02499aSAlex Lorenz 11851f39fcf2SXinliang David Li std::string getCoverageSection(const CodeGenModule &CGM) { 11868a767a43SVedant Kumar return llvm::getInstrProfSectionName( 11878a767a43SVedant Kumar llvm::IPSK_covmap, 11888a767a43SVedant Kumar CGM.getContext().getTargetInfo().getTriple().getObjectFormat()); 1189ee02499aSAlex Lorenz } 1190ee02499aSAlex Lorenz 119114f8fb68SVedant Kumar std::string normalizeFilename(StringRef Filename) { 119214f8fb68SVedant Kumar llvm::SmallString<256> Path(Filename); 119314f8fb68SVedant Kumar llvm::sys::fs::make_absolute(Path); 1194d04929d8SVedant Kumar llvm::sys::path::remove_dots(Path, /*remove_dot_dots=*/true); 119514f8fb68SVedant Kumar return Path.str().str(); 119614f8fb68SVedant Kumar } 119714f8fb68SVedant Kumar 119814f8fb68SVedant Kumar } // end anonymous namespace 119914f8fb68SVedant Kumar 1200a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName, 1201a432d176SJustin Bogner ArrayRef<CounterExpression> Expressions, 1202a432d176SJustin Bogner ArrayRef<CounterMappingRegion> Regions) { 1203a432d176SJustin Bogner OS << FunctionName << ":\n"; 1204a432d176SJustin Bogner CounterMappingContext Ctx(Expressions); 1205a432d176SJustin Bogner for (const auto &R : Regions) { 1206f2cf38e0SAlex Lorenz OS.indent(2); 1207f2cf38e0SAlex Lorenz switch (R.Kind) { 1208f2cf38e0SAlex Lorenz case CounterMappingRegion::CodeRegion: 1209f2cf38e0SAlex Lorenz break; 1210f2cf38e0SAlex Lorenz case CounterMappingRegion::ExpansionRegion: 1211f2cf38e0SAlex Lorenz OS << "Expansion,"; 1212f2cf38e0SAlex Lorenz break; 1213f2cf38e0SAlex Lorenz case CounterMappingRegion::SkippedRegion: 1214f2cf38e0SAlex Lorenz OS << "Skipped,"; 1215f2cf38e0SAlex Lorenz break; 1216a1c4deb7SVedant Kumar case CounterMappingRegion::GapRegion: 1217a1c4deb7SVedant Kumar OS << "Gap,"; 1218a1c4deb7SVedant Kumar break; 1219f2cf38e0SAlex Lorenz } 1220f2cf38e0SAlex Lorenz 12214da909b2SJustin Bogner OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart 12224da909b2SJustin Bogner << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = "; 1223f69dc349SJustin Bogner Ctx.dump(R.Count, OS); 1224f2cf38e0SAlex Lorenz if (R.Kind == CounterMappingRegion::ExpansionRegion) 12254da909b2SJustin Bogner OS << " (Expanded file = " << R.ExpandedFileID << ")"; 12264da909b2SJustin Bogner OS << "\n"; 1227f2cf38e0SAlex Lorenz } 1228f2cf38e0SAlex Lorenz } 1229f2cf38e0SAlex Lorenz 1230ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord( 12312129ae53SXinliang David Li llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash, 1232848da137SXinliang David Li const std::string &CoverageMapping, bool IsUsed) { 1233ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1234ee02499aSAlex Lorenz if (!FunctionRecordTy) { 1235a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType, 1236a026a437SXinliang David Li llvm::Type *FunctionRecordTypes[] = { 1237a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 1238a026a437SXinliang David Li }; 1239ee02499aSAlex Lorenz FunctionRecordTy = 12404dc5adc7SJustin Bogner llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes), 12414dc5adc7SJustin Bogner /*isPacked=*/true); 1242ee02499aSAlex Lorenz } 1243ee02499aSAlex Lorenz 1244a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init, 1245ee02499aSAlex Lorenz llvm::Constant *FunctionRecordVals[] = { 1246a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 1247a026a437SXinliang David Li }; 1248ee02499aSAlex Lorenz FunctionRecords.push_back(llvm::ConstantStruct::get( 1249ee02499aSAlex Lorenz FunctionRecordTy, makeArrayRef(FunctionRecordVals))); 1250848da137SXinliang David Li if (!IsUsed) 12512129ae53SXinliang David Li FunctionNames.push_back( 12522129ae53SXinliang David Li llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx))); 1253ca3326c0SVedant Kumar CoverageMappings.push_back(CoverageMapping); 1254f2cf38e0SAlex Lorenz 1255f2cf38e0SAlex Lorenz if (CGM.getCodeGenOpts().DumpCoverageMapping) { 1256f2cf38e0SAlex Lorenz // Dump the coverage mapping data for this function by decoding the 1257f2cf38e0SAlex Lorenz // encoded data. This allows us to dump the mapping regions which were 1258f2cf38e0SAlex Lorenz // also processed by the CoverageMappingWriter which performs 1259f2cf38e0SAlex Lorenz // additional minimization operations such as reducing the number of 1260f2cf38e0SAlex Lorenz // expressions. 1261f2cf38e0SAlex Lorenz std::vector<StringRef> Filenames; 1262f2cf38e0SAlex Lorenz std::vector<CounterExpression> Expressions; 1263f2cf38e0SAlex Lorenz std::vector<CounterMappingRegion> Regions; 1264b31ee819SJordan Rose llvm::SmallVector<std::string, 16> FilenameStrs; 1265f2cf38e0SAlex Lorenz llvm::SmallVector<StringRef, 16> FilenameRefs; 1266b31ee819SJordan Rose FilenameStrs.resize(FileEntries.size()); 1267f2cf38e0SAlex Lorenz FilenameRefs.resize(FileEntries.size()); 1268b31ee819SJordan Rose for (const auto &Entry : FileEntries) { 1269b31ee819SJordan Rose auto I = Entry.second; 1270b31ee819SJordan Rose FilenameStrs[I] = normalizeFilename(Entry.first->getName()); 1271b31ee819SJordan Rose FilenameRefs[I] = FilenameStrs[I]; 1272b31ee819SJordan Rose } 1273a432d176SJustin Bogner RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames, 1274a432d176SJustin Bogner Expressions, Regions); 1275a432d176SJustin Bogner if (Reader.read()) 1276f2cf38e0SAlex Lorenz return; 1277a026a437SXinliang David Li dump(llvm::outs(), NameValue, Expressions, Regions); 1278f2cf38e0SAlex Lorenz } 1279ee02499aSAlex Lorenz } 1280ee02499aSAlex Lorenz 1281ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() { 1282ee02499aSAlex Lorenz if (FunctionRecords.empty()) 1283ee02499aSAlex Lorenz return; 1284ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1285ee02499aSAlex Lorenz auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 1286ee02499aSAlex Lorenz 1287ee02499aSAlex Lorenz // Create the filenames and merge them with coverage mappings 1288ee02499aSAlex Lorenz llvm::SmallVector<std::string, 16> FilenameStrs; 12899e324dd1SVedant Kumar llvm::SmallVector<StringRef, 16> FilenameRefs; 1290ee02499aSAlex Lorenz FilenameStrs.resize(FileEntries.size()); 12919e324dd1SVedant Kumar FilenameRefs.resize(FileEntries.size()); 1292ee02499aSAlex Lorenz for (const auto &Entry : FileEntries) { 1293ee02499aSAlex Lorenz auto I = Entry.second; 129414f8fb68SVedant Kumar FilenameStrs[I] = normalizeFilename(Entry.first->getName()); 12959e324dd1SVedant Kumar FilenameRefs[I] = FilenameStrs[I]; 1296ee02499aSAlex Lorenz } 1297ee02499aSAlex Lorenz 12989e324dd1SVedant Kumar std::string FilenamesAndCoverageMappings; 12999e324dd1SVedant Kumar llvm::raw_string_ostream OS(FilenamesAndCoverageMappings); 13009e324dd1SVedant Kumar CoverageFilenamesSectionWriter(FilenameRefs).write(OS); 13019e324dd1SVedant Kumar std::string RawCoverageMappings = 13029e324dd1SVedant Kumar llvm::join(CoverageMappings.begin(), CoverageMappings.end(), ""); 13039e324dd1SVedant Kumar OS << RawCoverageMappings; 13049e324dd1SVedant Kumar size_t CoverageMappingSize = RawCoverageMappings.size(); 13059e324dd1SVedant Kumar size_t FilenamesSize = OS.str().size() - CoverageMappingSize; 13069e324dd1SVedant Kumar // Append extra zeroes if necessary to ensure that the size of the filenames 13079e324dd1SVedant Kumar // and coverage mappings is a multiple of 8. 13089e324dd1SVedant Kumar if (size_t Rem = OS.str().size() % 8) { 13099e324dd1SVedant Kumar CoverageMappingSize += 8 - Rem; 13109e324dd1SVedant Kumar for (size_t I = 0, S = 8 - Rem; I < S; ++I) 13119e324dd1SVedant Kumar OS << '\0'; 1312ee02499aSAlex Lorenz } 1313ee02499aSAlex Lorenz auto *FilenamesAndMappingsVal = 13149e324dd1SVedant Kumar llvm::ConstantDataArray::getString(Ctx, OS.str(), false); 1315ee02499aSAlex Lorenz 1316ee02499aSAlex Lorenz // Create the deferred function records array 1317ee02499aSAlex Lorenz auto RecordsTy = 1318ee02499aSAlex Lorenz llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size()); 1319ee02499aSAlex Lorenz auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords); 1320ee02499aSAlex Lorenz 132120b188c0SXinliang David Li llvm::Type *CovDataHeaderTypes[] = { 132220b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType, 132320b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 132420b188c0SXinliang David Li }; 132520b188c0SXinliang David Li auto CovDataHeaderTy = 132620b188c0SXinliang David Li llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes)); 132720b188c0SXinliang David Li llvm::Constant *CovDataHeaderVals[] = { 132820b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init, 132920b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 133020b188c0SXinliang David Li }; 133120b188c0SXinliang David Li auto CovDataHeaderVal = llvm::ConstantStruct::get( 133220b188c0SXinliang David Li CovDataHeaderTy, makeArrayRef(CovDataHeaderVals)); 133320b188c0SXinliang David Li 1334ee02499aSAlex Lorenz // Create the coverage data record 133520b188c0SXinliang David Li llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy, 133620b188c0SXinliang David Li FilenamesAndMappingsVal->getType()}; 1337ee02499aSAlex Lorenz auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes)); 133820b188c0SXinliang David Li llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal, 133920b188c0SXinliang David Li FilenamesAndMappingsVal}; 1340ee02499aSAlex Lorenz auto CovDataVal = 1341ee02499aSAlex Lorenz llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals)); 134220b188c0SXinliang David Li auto CovData = new llvm::GlobalVariable( 134320b188c0SXinliang David Li CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage, 134420b188c0SXinliang David Li CovDataVal, llvm::getCoverageMappingVarName()); 1345ee02499aSAlex Lorenz 1346ee02499aSAlex Lorenz CovData->setSection(getCoverageSection(CGM)); 1347ee02499aSAlex Lorenz CovData->setAlignment(8); 1348ee02499aSAlex Lorenz 1349ee02499aSAlex Lorenz // Make sure the data doesn't get deleted. 1350ee02499aSAlex Lorenz CGM.addUsedGlobal(CovData); 13512129ae53SXinliang David Li // Create the deferred function records array 13522129ae53SXinliang David Li if (!FunctionNames.empty()) { 13532129ae53SXinliang David Li auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 13542129ae53SXinliang David Li FunctionNames.size()); 13552129ae53SXinliang David Li auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames); 13562129ae53SXinliang David Li // This variable will *NOT* be emitted to the object file. It is used 13572129ae53SXinliang David Li // to pass the list of names referenced to codegen. 13582129ae53SXinliang David Li new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true, 13592129ae53SXinliang David Li llvm::GlobalValue::InternalLinkage, NamesArrVal, 13607077f0afSXinliang David Li llvm::getCoverageUnusedNamesVarName()); 13612129ae53SXinliang David Li } 1362ee02499aSAlex Lorenz } 1363ee02499aSAlex Lorenz 1364ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) { 1365ee02499aSAlex Lorenz auto It = FileEntries.find(File); 1366ee02499aSAlex Lorenz if (It != FileEntries.end()) 1367ee02499aSAlex Lorenz return It->second; 1368ee02499aSAlex Lorenz unsigned FileID = FileEntries.size(); 1369ee02499aSAlex Lorenz FileEntries.insert(std::make_pair(File, FileID)); 1370ee02499aSAlex Lorenz return FileID; 1371ee02499aSAlex Lorenz } 1372ee02499aSAlex Lorenz 1373ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D, 1374ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1375ee02499aSAlex Lorenz assert(CounterMap); 1376e5ee6c58SJustin Bogner CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts); 1377ee02499aSAlex Lorenz Walker.VisitDecl(D); 1378ee02499aSAlex Lorenz Walker.write(OS); 1379ee02499aSAlex Lorenz } 1380ee02499aSAlex Lorenz 1381ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D, 1382ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1383ee02499aSAlex Lorenz EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); 1384ee02499aSAlex Lorenz Walker.VisitDecl(D); 1385ee02499aSAlex Lorenz Walker.write(OS); 1386ee02499aSAlex Lorenz } 1387