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" 26ee02499aSAlex Lorenz 27ee02499aSAlex Lorenz using namespace clang; 28ee02499aSAlex Lorenz using namespace CodeGen; 29ee02499aSAlex Lorenz using namespace llvm::coverage; 30ee02499aSAlex Lorenz 31ee02499aSAlex Lorenz void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) { 32ee02499aSAlex Lorenz SkippedRanges.push_back(Range); 33ee02499aSAlex Lorenz } 34ee02499aSAlex Lorenz 35ee02499aSAlex Lorenz namespace { 36ee02499aSAlex Lorenz 37ee02499aSAlex Lorenz /// \brief A region of source code that can be mapped to a counter. 3809c7179bSJustin Bogner class SourceMappingRegion { 39ee02499aSAlex Lorenz Counter Count; 40ee02499aSAlex Lorenz 41ee02499aSAlex Lorenz /// \brief The region's starting location. 42bf42cfd7SJustin Bogner Optional<SourceLocation> LocStart; 43ee02499aSAlex Lorenz 44ee02499aSAlex Lorenz /// \brief The region's ending location. 45bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd; 46ee02499aSAlex Lorenz 4709c7179bSJustin Bogner public: 48bf42cfd7SJustin Bogner SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart, 49bf42cfd7SJustin Bogner Optional<SourceLocation> LocEnd) 50bf42cfd7SJustin Bogner : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {} 51ee02499aSAlex Lorenz 5209c7179bSJustin Bogner const Counter &getCounter() const { return Count; } 5309c7179bSJustin Bogner 54bf42cfd7SJustin Bogner void setCounter(Counter C) { Count = C; } 5509c7179bSJustin Bogner 56bf42cfd7SJustin Bogner bool hasStartLoc() const { return LocStart.hasValue(); } 57bf42cfd7SJustin Bogner 58bf42cfd7SJustin Bogner void setStartLoc(SourceLocation Loc) { LocStart = Loc; } 59bf42cfd7SJustin Bogner 60462c77b4SCraig Topper SourceLocation getStartLoc() const { 61bf42cfd7SJustin Bogner assert(LocStart && "Region has no start location"); 62bf42cfd7SJustin Bogner return *LocStart; 6309c7179bSJustin Bogner } 6409c7179bSJustin Bogner 65bf42cfd7SJustin Bogner bool hasEndLoc() const { return LocEnd.hasValue(); } 66ee02499aSAlex Lorenz 67bf42cfd7SJustin Bogner void setEndLoc(SourceLocation Loc) { LocEnd = Loc; } 68ee02499aSAlex Lorenz 69462c77b4SCraig Topper SourceLocation getEndLoc() const { 70bf42cfd7SJustin Bogner assert(LocEnd && "Region has no end location"); 71bf42cfd7SJustin Bogner return *LocEnd; 72ee02499aSAlex Lorenz } 73ee02499aSAlex Lorenz }; 74ee02499aSAlex Lorenz 75ee02499aSAlex Lorenz /// \brief Provides the common functionality for the different 76ee02499aSAlex Lorenz /// coverage mapping region builders. 77ee02499aSAlex Lorenz class CoverageMappingBuilder { 78ee02499aSAlex Lorenz public: 79ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM; 80ee02499aSAlex Lorenz SourceManager &SM; 81ee02499aSAlex Lorenz const LangOptions &LangOpts; 82ee02499aSAlex Lorenz 83ee02499aSAlex Lorenz private: 84bf42cfd7SJustin Bogner /// \brief Map of clang's FileIDs to IDs used for coverage mapping. 85bf42cfd7SJustin Bogner llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8> 86bf42cfd7SJustin Bogner FileIDMapping; 87ee02499aSAlex Lorenz 88ee02499aSAlex Lorenz public: 89ee02499aSAlex Lorenz /// \brief The coverage mapping regions for this function 90ee02499aSAlex Lorenz llvm::SmallVector<CounterMappingRegion, 32> MappingRegions; 91ee02499aSAlex Lorenz /// \brief The source mapping regions for this function. 92f59329b0SJustin Bogner std::vector<SourceMappingRegion> SourceRegions; 93ee02499aSAlex Lorenz 94ee02499aSAlex Lorenz CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 95ee02499aSAlex Lorenz const LangOptions &LangOpts) 96bf42cfd7SJustin Bogner : CVM(CVM), SM(SM), LangOpts(LangOpts) {} 97ee02499aSAlex Lorenz 98ee02499aSAlex Lorenz /// \brief Return the precise end location for the given token. 99ee02499aSAlex Lorenz SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) { 100bf42cfd7SJustin Bogner // We avoid getLocForEndOfToken here, because it doesn't do what we want for 101bf42cfd7SJustin Bogner // macro locations, which we just treat as expanded files. 102bf42cfd7SJustin Bogner unsigned TokLen = 103bf42cfd7SJustin Bogner Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts); 104bf42cfd7SJustin Bogner return Loc.getLocWithOffset(TokLen); 105ee02499aSAlex Lorenz } 106ee02499aSAlex Lorenz 107bf42cfd7SJustin Bogner /// \brief Return the start location of an included file or expanded macro. 108bf42cfd7SJustin Bogner SourceLocation getStartOfFileOrMacro(SourceLocation Loc) { 109bf42cfd7SJustin Bogner if (Loc.isMacroID()) 110bf42cfd7SJustin Bogner return Loc.getLocWithOffset(-SM.getFileOffset(Loc)); 111bf42cfd7SJustin Bogner return SM.getLocForStartOfFile(SM.getFileID(Loc)); 112ee02499aSAlex Lorenz } 113ee02499aSAlex Lorenz 114bf42cfd7SJustin Bogner /// \brief Return the end location of an included file or expanded macro. 115bf42cfd7SJustin Bogner SourceLocation getEndOfFileOrMacro(SourceLocation Loc) { 116bf42cfd7SJustin Bogner if (Loc.isMacroID()) 117bf42cfd7SJustin Bogner return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) - 118f14b2078SJustin Bogner SM.getFileOffset(Loc)); 119bf42cfd7SJustin Bogner return SM.getLocForEndOfFile(SM.getFileID(Loc)); 120bf42cfd7SJustin Bogner } 121ee02499aSAlex Lorenz 122bf42cfd7SJustin Bogner /// \brief Find out where the current file is included or macro is expanded. 123bf42cfd7SJustin Bogner SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) { 124bf42cfd7SJustin Bogner return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first 125bf42cfd7SJustin Bogner : SM.getIncludeLoc(SM.getFileID(Loc)); 126bf42cfd7SJustin Bogner } 127bf42cfd7SJustin Bogner 128682bfbf3SJustin Bogner /// \brief Return true if \c Loc is a location in a built-in macro. 129682bfbf3SJustin Bogner bool isInBuiltin(SourceLocation Loc) { 130682bfbf3SJustin Bogner return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0; 131682bfbf3SJustin Bogner } 132682bfbf3SJustin Bogner 133d9e1a61dSIgor Kudrin /// \brief Check whether \c Loc is included or expanded from \c Parent. 134d9e1a61dSIgor Kudrin bool isNestedIn(SourceLocation Loc, FileID Parent) { 135d9e1a61dSIgor Kudrin do { 136d9e1a61dSIgor Kudrin Loc = getIncludeOrExpansionLoc(Loc); 137d9e1a61dSIgor Kudrin if (Loc.isInvalid()) 138d9e1a61dSIgor Kudrin return false; 139d9e1a61dSIgor Kudrin } while (!SM.isInFileID(Loc, Parent)); 140d9e1a61dSIgor Kudrin return true; 141d9e1a61dSIgor Kudrin } 142d9e1a61dSIgor Kudrin 143682bfbf3SJustin Bogner /// \brief Get the start of \c S ignoring macro arguments and builtin macros. 144bf42cfd7SJustin Bogner SourceLocation getStart(const Stmt *S) { 145bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocStart(); 146682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 147bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 148bf42cfd7SJustin Bogner return Loc; 149bf42cfd7SJustin Bogner } 150bf42cfd7SJustin Bogner 151682bfbf3SJustin Bogner /// \brief Get the end of \c S ignoring macro arguments and builtin macros. 152bf42cfd7SJustin Bogner SourceLocation getEnd(const Stmt *S) { 153bf42cfd7SJustin Bogner SourceLocation Loc = S->getLocEnd(); 154682bfbf3SJustin Bogner while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc)) 155bf42cfd7SJustin Bogner Loc = SM.getImmediateExpansionRange(Loc).first; 156f14b2078SJustin Bogner return getPreciseTokenLocEnd(Loc); 157bf42cfd7SJustin Bogner } 158bf42cfd7SJustin Bogner 159bf42cfd7SJustin Bogner /// \brief Find the set of files we have regions for and assign IDs 160bf42cfd7SJustin Bogner /// 161bf42cfd7SJustin Bogner /// Fills \c Mapping with the virtual file mapping needed to write out 162bf42cfd7SJustin Bogner /// coverage and collects the necessary file information to emit source and 163bf42cfd7SJustin Bogner /// expansion regions. 164bf42cfd7SJustin Bogner void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) { 165bf42cfd7SJustin Bogner FileIDMapping.clear(); 166bf42cfd7SJustin Bogner 167bc6b80a0SVedant Kumar llvm::SmallSet<FileID, 8> Visited; 168bf42cfd7SJustin Bogner SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs; 169bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 170bf42cfd7SJustin Bogner SourceLocation Loc = Region.getStartLoc(); 171bf42cfd7SJustin Bogner FileID File = SM.getFileID(Loc); 172bc6b80a0SVedant Kumar if (!Visited.insert(File).second) 173bf42cfd7SJustin Bogner continue; 174bf42cfd7SJustin Bogner 175*93205af0SVedant Kumar // Do not map FileID's associated with system headers. 176*93205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(Loc))) 177*93205af0SVedant Kumar continue; 178*93205af0SVedant Kumar 179bf42cfd7SJustin Bogner unsigned Depth = 0; 180bf42cfd7SJustin Bogner for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc); 181ed1fe5d0SYaron Keren Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent)) 182bf42cfd7SJustin Bogner ++Depth; 183bf42cfd7SJustin Bogner FileLocs.push_back(std::make_pair(Loc, Depth)); 184bf42cfd7SJustin Bogner } 185bf42cfd7SJustin Bogner std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second()); 186bf42cfd7SJustin Bogner 187bf42cfd7SJustin Bogner for (const auto &FL : FileLocs) { 188bf42cfd7SJustin Bogner SourceLocation Loc = FL.first; 189bf42cfd7SJustin Bogner FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first; 190ee02499aSAlex Lorenz auto Entry = SM.getFileEntryForID(SpellingFile); 191ee02499aSAlex Lorenz if (!Entry) 192bf42cfd7SJustin Bogner continue; 193ee02499aSAlex Lorenz 194bf42cfd7SJustin Bogner FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc); 195bf42cfd7SJustin Bogner Mapping.push_back(CVM.getFileID(Entry)); 196bf42cfd7SJustin Bogner } 197ee02499aSAlex Lorenz } 198ee02499aSAlex Lorenz 199bf42cfd7SJustin Bogner /// \brief Get the coverage mapping file ID for \c Loc. 200bf42cfd7SJustin Bogner /// 201bf42cfd7SJustin Bogner /// If such file id doesn't exist, return None. 202bf42cfd7SJustin Bogner Optional<unsigned> getCoverageFileID(SourceLocation Loc) { 203bf42cfd7SJustin Bogner auto Mapping = FileIDMapping.find(SM.getFileID(Loc)); 204bf42cfd7SJustin Bogner if (Mapping != FileIDMapping.end()) 205bf42cfd7SJustin Bogner return Mapping->second.first; 206903678caSJustin Bogner return None; 207ee02499aSAlex Lorenz } 208ee02499aSAlex Lorenz 209ee02499aSAlex Lorenz /// \brief Gather all the regions that were skipped by the preprocessor 210ee02499aSAlex Lorenz /// using the constructs like #if. 211ee02499aSAlex Lorenz void gatherSkippedRegions() { 212ee02499aSAlex Lorenz /// An array of the minimum lineStarts and the maximum lineEnds 213ee02499aSAlex Lorenz /// for mapping regions from the appropriate source files. 214ee02499aSAlex Lorenz llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges; 215ee02499aSAlex Lorenz FileLineRanges.resize( 216ee02499aSAlex Lorenz FileIDMapping.size(), 217ee02499aSAlex Lorenz std::make_pair(std::numeric_limits<unsigned>::max(), 0)); 218ee02499aSAlex Lorenz for (const auto &R : MappingRegions) { 219ee02499aSAlex Lorenz FileLineRanges[R.FileID].first = 220ee02499aSAlex Lorenz std::min(FileLineRanges[R.FileID].first, R.LineStart); 221ee02499aSAlex Lorenz FileLineRanges[R.FileID].second = 222ee02499aSAlex Lorenz std::max(FileLineRanges[R.FileID].second, R.LineEnd); 223ee02499aSAlex Lorenz } 224ee02499aSAlex Lorenz 225ee02499aSAlex Lorenz auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges(); 226ee02499aSAlex Lorenz for (const auto &I : SkippedRanges) { 227ee02499aSAlex Lorenz auto LocStart = I.getBegin(); 228ee02499aSAlex Lorenz auto LocEnd = I.getEnd(); 229bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 230bf42cfd7SJustin Bogner "region spans multiple files"); 231ee02499aSAlex Lorenz 232bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 233903678caSJustin Bogner if (!CovFileID) 234ee02499aSAlex Lorenz continue; 235ee02499aSAlex Lorenz unsigned LineStart = SM.getSpellingLineNumber(LocStart); 236ee02499aSAlex Lorenz unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 237ee02499aSAlex Lorenz unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 238ee02499aSAlex Lorenz unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 239fd34280bSJustin Bogner auto Region = CounterMappingRegion::makeSkipped( 240fd34280bSJustin Bogner *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd); 241ee02499aSAlex Lorenz // Make sure that we only collect the regions that are inside 242ee02499aSAlex Lorenz // the souce code of this function. 243903678caSJustin Bogner if (Region.LineStart >= FileLineRanges[*CovFileID].first && 244903678caSJustin Bogner Region.LineEnd <= FileLineRanges[*CovFileID].second) 245ee02499aSAlex Lorenz MappingRegions.push_back(Region); 246ee02499aSAlex Lorenz } 247ee02499aSAlex Lorenz } 248ee02499aSAlex Lorenz 249ee02499aSAlex Lorenz /// \brief Generate the coverage counter mapping regions from collected 250ee02499aSAlex Lorenz /// source regions. 251ee02499aSAlex Lorenz void emitSourceRegions() { 252bf42cfd7SJustin Bogner for (const auto &Region : SourceRegions) { 253bf42cfd7SJustin Bogner assert(Region.hasEndLoc() && "incomplete region"); 254ee02499aSAlex Lorenz 255bf42cfd7SJustin Bogner SourceLocation LocStart = Region.getStartLoc(); 2568b563665SYaron Keren assert(SM.getFileID(LocStart).isValid() && "region in invalid file"); 257f59329b0SJustin Bogner 258*93205af0SVedant Kumar // Ignore regions from system headers. 259*93205af0SVedant Kumar if (SM.isInSystemHeader(SM.getSpellingLoc(LocStart))) 260*93205af0SVedant Kumar continue; 261*93205af0SVedant Kumar 262bf42cfd7SJustin Bogner auto CovFileID = getCoverageFileID(LocStart); 263bf42cfd7SJustin Bogner // Ignore regions that don't have a file, such as builtin macros. 264bf42cfd7SJustin Bogner if (!CovFileID) 265ee02499aSAlex Lorenz continue; 266ee02499aSAlex Lorenz 267f14b2078SJustin Bogner SourceLocation LocEnd = Region.getEndLoc(); 268bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(LocStart, LocEnd) && 269bf42cfd7SJustin Bogner "region spans multiple files"); 270bf42cfd7SJustin Bogner 271f59329b0SJustin Bogner // Find the spilling locations for the mapping region. 272ee02499aSAlex Lorenz unsigned LineStart = SM.getSpellingLineNumber(LocStart); 273ee02499aSAlex Lorenz unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 274ee02499aSAlex Lorenz unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 275ee02499aSAlex Lorenz unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 276ee02499aSAlex Lorenz 277bf42cfd7SJustin Bogner assert(LineStart <= LineEnd && "region start and end out of order"); 278bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeRegion( 279bf42cfd7SJustin Bogner Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd, 280bf42cfd7SJustin Bogner ColumnEnd)); 281bf42cfd7SJustin Bogner } 282bf42cfd7SJustin Bogner } 283bf42cfd7SJustin Bogner 284bf42cfd7SJustin Bogner /// \brief Generate expansion regions for each virtual file we've seen. 285bf42cfd7SJustin Bogner void emitExpansionRegions() { 286bf42cfd7SJustin Bogner for (const auto &FM : FileIDMapping) { 287bf42cfd7SJustin Bogner SourceLocation ExpandedLoc = FM.second.second; 288bf42cfd7SJustin Bogner SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc); 289bf42cfd7SJustin Bogner if (ParentLoc.isInvalid()) 290ee02499aSAlex Lorenz continue; 291ee02499aSAlex Lorenz 292bf42cfd7SJustin Bogner auto ParentFileID = getCoverageFileID(ParentLoc); 293bf42cfd7SJustin Bogner if (!ParentFileID) 294bf42cfd7SJustin Bogner continue; 295bf42cfd7SJustin Bogner auto ExpandedFileID = getCoverageFileID(ExpandedLoc); 296bf42cfd7SJustin Bogner assert(ExpandedFileID && "expansion in uncovered file"); 297bf42cfd7SJustin Bogner 298bf42cfd7SJustin Bogner SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc); 299bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) && 300bf42cfd7SJustin Bogner "region spans multiple files"); 301bf42cfd7SJustin Bogner 302bf42cfd7SJustin Bogner unsigned LineStart = SM.getSpellingLineNumber(ParentLoc); 303bf42cfd7SJustin Bogner unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc); 304bf42cfd7SJustin Bogner unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 305bf42cfd7SJustin Bogner unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 306bf42cfd7SJustin Bogner 307bf42cfd7SJustin Bogner MappingRegions.push_back(CounterMappingRegion::makeExpansion( 308bf42cfd7SJustin Bogner *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd, 309fd34280bSJustin Bogner ColumnEnd)); 310ee02499aSAlex Lorenz } 311ee02499aSAlex Lorenz } 312ee02499aSAlex Lorenz }; 313ee02499aSAlex Lorenz 314ee02499aSAlex Lorenz /// \brief Creates unreachable coverage regions for the functions that 315ee02499aSAlex Lorenz /// are not emitted. 316ee02499aSAlex Lorenz struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { 317ee02499aSAlex Lorenz EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 318ee02499aSAlex Lorenz const LangOptions &LangOpts) 319ee02499aSAlex Lorenz : CoverageMappingBuilder(CVM, SM, LangOpts) {} 320ee02499aSAlex Lorenz 321ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 322ee02499aSAlex Lorenz if (!D->hasBody()) 323ee02499aSAlex Lorenz return; 324ee02499aSAlex Lorenz auto Body = D->getBody(); 325d9e1a61dSIgor Kudrin SourceLocation Start = getStart(Body); 326d9e1a61dSIgor Kudrin SourceLocation End = getEnd(Body); 327d9e1a61dSIgor Kudrin if (!SM.isWrittenInSameFile(Start, End)) { 328d9e1a61dSIgor Kudrin // Walk up to find the common ancestor. 329d9e1a61dSIgor Kudrin // Correct the locations accordingly. 330d9e1a61dSIgor Kudrin FileID StartFileID = SM.getFileID(Start); 331d9e1a61dSIgor Kudrin FileID EndFileID = SM.getFileID(End); 332d9e1a61dSIgor Kudrin while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) { 333d9e1a61dSIgor Kudrin Start = getIncludeOrExpansionLoc(Start); 334d9e1a61dSIgor Kudrin assert(Start.isValid() && 335d9e1a61dSIgor Kudrin "Declaration start location not nested within a known region"); 336d9e1a61dSIgor Kudrin StartFileID = SM.getFileID(Start); 337d9e1a61dSIgor Kudrin } 338d9e1a61dSIgor Kudrin while (StartFileID != EndFileID) { 339d9e1a61dSIgor Kudrin End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End)); 340d9e1a61dSIgor Kudrin assert(End.isValid() && 341d9e1a61dSIgor Kudrin "Declaration end location not nested within a known region"); 342d9e1a61dSIgor Kudrin EndFileID = SM.getFileID(End); 343d9e1a61dSIgor Kudrin } 344d9e1a61dSIgor Kudrin } 345d9e1a61dSIgor Kudrin SourceRegions.emplace_back(Counter(), Start, End); 346ee02499aSAlex Lorenz } 347ee02499aSAlex Lorenz 348ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 349ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 350ee02499aSAlex Lorenz SmallVector<unsigned, 16> FileIDMapping; 351bf42cfd7SJustin Bogner gatherFileIDs(FileIDMapping); 352bf42cfd7SJustin Bogner emitSourceRegions(); 353ee02499aSAlex Lorenz 3545fc8fc2dSCraig Topper CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions); 355ee02499aSAlex Lorenz Writer.write(OS); 356ee02499aSAlex Lorenz } 357ee02499aSAlex Lorenz }; 358ee02499aSAlex Lorenz 359ee02499aSAlex Lorenz /// \brief A StmtVisitor that creates coverage mapping regions which map 360ee02499aSAlex Lorenz /// from the source code locations to the PGO counters. 361ee02499aSAlex Lorenz struct CounterCoverageMappingBuilder 362ee02499aSAlex Lorenz : public CoverageMappingBuilder, 363ee02499aSAlex Lorenz public ConstStmtVisitor<CounterCoverageMappingBuilder> { 364ee02499aSAlex Lorenz /// \brief The map of statements to count values. 365ee02499aSAlex Lorenz llvm::DenseMap<const Stmt *, unsigned> &CounterMap; 366ee02499aSAlex Lorenz 367bf42cfd7SJustin Bogner /// \brief A stack of currently live regions. 368bf42cfd7SJustin Bogner std::vector<SourceMappingRegion> RegionStack; 369ee02499aSAlex Lorenz 370ee02499aSAlex Lorenz CounterExpressionBuilder Builder; 371ee02499aSAlex Lorenz 372bf42cfd7SJustin Bogner /// \brief A location in the most recently visited file or macro. 373bf42cfd7SJustin Bogner /// 374bf42cfd7SJustin Bogner /// This is used to adjust the active source regions appropriately when 375bf42cfd7SJustin Bogner /// expressions cross file or macro boundaries. 376bf42cfd7SJustin Bogner SourceLocation MostRecentLocation; 377bf42cfd7SJustin Bogner 378bf42cfd7SJustin Bogner /// \brief Return a counter for the subtraction of \c RHS from \c LHS 379ee02499aSAlex Lorenz Counter subtractCounters(Counter LHS, Counter RHS) { 380ee02499aSAlex Lorenz return Builder.subtract(LHS, RHS); 381ee02499aSAlex Lorenz } 382ee02499aSAlex Lorenz 383bf42cfd7SJustin Bogner /// \brief Return a counter for the sum of \c LHS and \c RHS. 384ee02499aSAlex Lorenz Counter addCounters(Counter LHS, Counter RHS) { 385ee02499aSAlex Lorenz return Builder.add(LHS, RHS); 386ee02499aSAlex Lorenz } 387ee02499aSAlex Lorenz 388bf42cfd7SJustin Bogner Counter addCounters(Counter C1, Counter C2, Counter C3) { 389bf42cfd7SJustin Bogner return addCounters(addCounters(C1, C2), C3); 390bf42cfd7SJustin Bogner } 391bf42cfd7SJustin Bogner 392ee02499aSAlex Lorenz /// \brief Return the region counter for the given statement. 393bf42cfd7SJustin Bogner /// 394ee02499aSAlex Lorenz /// This should only be called on statements that have a dedicated counter. 395bf42cfd7SJustin Bogner Counter getRegionCounter(const Stmt *S) { 396bf42cfd7SJustin Bogner return Counter::getCounter(CounterMap[S]); 397ee02499aSAlex Lorenz } 398ee02499aSAlex Lorenz 399bf42cfd7SJustin Bogner /// \brief Push a region onto the stack. 400bf42cfd7SJustin Bogner /// 401bf42cfd7SJustin Bogner /// Returns the index on the stack where the region was pushed. This can be 402bf42cfd7SJustin Bogner /// used with popRegions to exit a "scope", ending the region that was pushed. 403bf42cfd7SJustin Bogner size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None, 404bf42cfd7SJustin Bogner Optional<SourceLocation> EndLoc = None) { 405bf42cfd7SJustin Bogner if (StartLoc) 406bf42cfd7SJustin Bogner MostRecentLocation = *StartLoc; 407bf42cfd7SJustin Bogner RegionStack.emplace_back(Count, StartLoc, EndLoc); 408ee02499aSAlex Lorenz 409bf42cfd7SJustin Bogner return RegionStack.size() - 1; 410ee02499aSAlex Lorenz } 411ee02499aSAlex Lorenz 412bf42cfd7SJustin Bogner /// \brief Pop regions from the stack into the function's list of regions. 413bf42cfd7SJustin Bogner /// 414bf42cfd7SJustin Bogner /// Adds all regions from \c ParentIndex to the top of the stack to the 415bf42cfd7SJustin Bogner /// function's \c SourceRegions. 416bf42cfd7SJustin Bogner void popRegions(size_t ParentIndex) { 417bf42cfd7SJustin Bogner assert(RegionStack.size() >= ParentIndex && "parent not in stack"); 418bf42cfd7SJustin Bogner while (RegionStack.size() > ParentIndex) { 419bf42cfd7SJustin Bogner SourceMappingRegion &Region = RegionStack.back(); 420bf42cfd7SJustin Bogner if (Region.hasStartLoc()) { 421bf42cfd7SJustin Bogner SourceLocation StartLoc = Region.getStartLoc(); 422bf42cfd7SJustin Bogner SourceLocation EndLoc = Region.hasEndLoc() 423bf42cfd7SJustin Bogner ? Region.getEndLoc() 424bf42cfd7SJustin Bogner : RegionStack[ParentIndex].getEndLoc(); 425bf42cfd7SJustin Bogner while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) { 426bf42cfd7SJustin Bogner // The region ends in a nested file or macro expansion. Create a 427bf42cfd7SJustin Bogner // separate region for each expansion. 428bf42cfd7SJustin Bogner SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc); 429bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(NestedLoc, EndLoc)); 430bf42cfd7SJustin Bogner 431bf42cfd7SJustin Bogner SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc); 432bf42cfd7SJustin Bogner 433f14b2078SJustin Bogner EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc)); 434dceaaadfSJustin Bogner if (EndLoc.isInvalid()) 435dceaaadfSJustin Bogner llvm::report_fatal_error("File exit not handled before popRegions"); 436bf42cfd7SJustin Bogner } 437bf42cfd7SJustin Bogner Region.setEndLoc(EndLoc); 438bf42cfd7SJustin Bogner 439bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 440bf42cfd7SJustin Bogner // If this region happens to span an entire expansion, we need to make 441bf42cfd7SJustin Bogner // sure we don't overlap the parent region with it. 442bf42cfd7SJustin Bogner if (StartLoc == getStartOfFileOrMacro(StartLoc) && 443bf42cfd7SJustin Bogner EndLoc == getEndOfFileOrMacro(EndLoc)) 444bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(EndLoc); 445bf42cfd7SJustin Bogner 446bf42cfd7SJustin Bogner assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc)); 447f36a5c4aSCraig Topper SourceRegions.push_back(Region); 448bf42cfd7SJustin Bogner } 449bf42cfd7SJustin Bogner RegionStack.pop_back(); 450bf42cfd7SJustin Bogner } 451ee02499aSAlex Lorenz } 452ee02499aSAlex Lorenz 453bf42cfd7SJustin Bogner /// \brief Return the currently active region. 454bf42cfd7SJustin Bogner SourceMappingRegion &getRegion() { 455bf42cfd7SJustin Bogner assert(!RegionStack.empty() && "statement has no region"); 456bf42cfd7SJustin Bogner return RegionStack.back(); 457ee02499aSAlex Lorenz } 458ee02499aSAlex Lorenz 459bf42cfd7SJustin Bogner /// \brief Propagate counts through the children of \c S. 460bf42cfd7SJustin Bogner Counter propagateCounts(Counter TopCount, const Stmt *S) { 461bf42cfd7SJustin Bogner size_t Index = pushRegion(TopCount, getStart(S), getEnd(S)); 462bf42cfd7SJustin Bogner Visit(S); 463bf42cfd7SJustin Bogner Counter ExitCount = getRegion().getCounter(); 464bf42cfd7SJustin Bogner popRegions(Index); 46539f01975SVedant Kumar 46639f01975SVedant Kumar // The statement may be spanned by an expansion. Make sure we handle a file 46739f01975SVedant Kumar // exit out of this expansion before moving to the next statement. 46839f01975SVedant Kumar if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart())) 46939f01975SVedant Kumar MostRecentLocation = getEnd(S); 47039f01975SVedant Kumar 471bf42cfd7SJustin Bogner return ExitCount; 472ee02499aSAlex Lorenz } 473ee02499aSAlex Lorenz 4740a7c9d11SIgor Kudrin /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc 4750a7c9d11SIgor Kudrin /// is already added to \c SourceRegions. 4760a7c9d11SIgor Kudrin bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) { 4770a7c9d11SIgor Kudrin return SourceRegions.rend() != 4780a7c9d11SIgor Kudrin std::find_if(SourceRegions.rbegin(), SourceRegions.rend(), 4790a7c9d11SIgor Kudrin [&](const SourceMappingRegion &Region) { 4800a7c9d11SIgor Kudrin return Region.getStartLoc() == StartLoc && 4810a7c9d11SIgor Kudrin Region.getEndLoc() == EndLoc; 4820a7c9d11SIgor Kudrin }); 4830a7c9d11SIgor Kudrin } 4840a7c9d11SIgor Kudrin 485bf42cfd7SJustin Bogner /// \brief Adjust the most recently visited location to \c EndLoc. 486bf42cfd7SJustin Bogner /// 487bf42cfd7SJustin Bogner /// This should be used after visiting any statements in non-source order. 488bf42cfd7SJustin Bogner void adjustForOutOfOrderTraversal(SourceLocation EndLoc) { 489bf42cfd7SJustin Bogner MostRecentLocation = EndLoc; 4900a7c9d11SIgor Kudrin // The code region for a whole macro is created in handleFileExit() when 4910a7c9d11SIgor Kudrin // it detects exiting of the virtual file of that macro. If we visited 4920a7c9d11SIgor Kudrin // statements in non-source order, we might already have such a region 4930a7c9d11SIgor Kudrin // added, for example, if a body of a loop is divided among multiple 4940a7c9d11SIgor Kudrin // macros. Avoid adding duplicate regions in such case. 49596ae73f7SJustin Bogner if (getRegion().hasEndLoc() && 4960a7c9d11SIgor Kudrin MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) && 4970a7c9d11SIgor Kudrin isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation), 4980a7c9d11SIgor Kudrin MostRecentLocation)) 499bf42cfd7SJustin Bogner MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation); 500ee02499aSAlex Lorenz } 501ee02499aSAlex Lorenz 502bf42cfd7SJustin Bogner /// \brief Adjust regions and state when \c NewLoc exits a file. 503bf42cfd7SJustin Bogner /// 504bf42cfd7SJustin Bogner /// If moving from our most recently tracked location to \c NewLoc exits any 505bf42cfd7SJustin Bogner /// files, this adjusts our current region stack and creates the file regions 506bf42cfd7SJustin Bogner /// for the exited file. 507bf42cfd7SJustin Bogner void handleFileExit(SourceLocation NewLoc) { 508e44dd6dbSJustin Bogner if (NewLoc.isInvalid() || 509e44dd6dbSJustin Bogner SM.isWrittenInSameFile(MostRecentLocation, NewLoc)) 510bf42cfd7SJustin Bogner return; 511bf42cfd7SJustin Bogner 512bf42cfd7SJustin Bogner // If NewLoc is not in a file that contains MostRecentLocation, walk up to 513bf42cfd7SJustin Bogner // find the common ancestor. 514bf42cfd7SJustin Bogner SourceLocation LCA = NewLoc; 515bf42cfd7SJustin Bogner FileID ParentFile = SM.getFileID(LCA); 516bf42cfd7SJustin Bogner while (!isNestedIn(MostRecentLocation, ParentFile)) { 517bf42cfd7SJustin Bogner LCA = getIncludeOrExpansionLoc(LCA); 518bf42cfd7SJustin Bogner if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) { 519bf42cfd7SJustin Bogner // Since there isn't a common ancestor, no file was exited. We just need 520bf42cfd7SJustin Bogner // to adjust our location to the new file. 521bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 522bf42cfd7SJustin Bogner return; 523bf42cfd7SJustin Bogner } 524bf42cfd7SJustin Bogner ParentFile = SM.getFileID(LCA); 525ee02499aSAlex Lorenz } 526ee02499aSAlex Lorenz 527bf42cfd7SJustin Bogner llvm::SmallSet<SourceLocation, 8> StartLocs; 528bf42cfd7SJustin Bogner Optional<Counter> ParentCounter; 52957d3f145SPete Cooper for (SourceMappingRegion &I : llvm::reverse(RegionStack)) { 53057d3f145SPete Cooper if (!I.hasStartLoc()) 531bf42cfd7SJustin Bogner continue; 53257d3f145SPete Cooper SourceLocation Loc = I.getStartLoc(); 533bf42cfd7SJustin Bogner if (!isNestedIn(Loc, ParentFile)) { 53457d3f145SPete Cooper ParentCounter = I.getCounter(); 535bf42cfd7SJustin Bogner break; 536ee02499aSAlex Lorenz } 537bf42cfd7SJustin Bogner 538bf42cfd7SJustin Bogner while (!SM.isInFileID(Loc, ParentFile)) { 539bf42cfd7SJustin Bogner // The most nested region for each start location is the one with the 540bf42cfd7SJustin Bogner // correct count. We avoid creating redundant regions by stopping once 541bf42cfd7SJustin Bogner // we've seen this region. 542bf42cfd7SJustin Bogner if (StartLocs.insert(Loc).second) 54357d3f145SPete Cooper SourceRegions.emplace_back(I.getCounter(), Loc, 544bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 545bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 546ee02499aSAlex Lorenz } 54757d3f145SPete Cooper I.setStartLoc(getPreciseTokenLocEnd(Loc)); 548bf42cfd7SJustin Bogner } 549bf42cfd7SJustin Bogner 550bf42cfd7SJustin Bogner if (ParentCounter) { 551bf42cfd7SJustin Bogner // If the file is contained completely by another region and doesn't 552bf42cfd7SJustin Bogner // immediately start its own region, the whole file gets a region 553bf42cfd7SJustin Bogner // corresponding to the parent. 554bf42cfd7SJustin Bogner SourceLocation Loc = MostRecentLocation; 555bf42cfd7SJustin Bogner while (isNestedIn(Loc, ParentFile)) { 556bf42cfd7SJustin Bogner SourceLocation FileStart = getStartOfFileOrMacro(Loc); 557bf42cfd7SJustin Bogner if (StartLocs.insert(FileStart).second) 558bf42cfd7SJustin Bogner SourceRegions.emplace_back(*ParentCounter, FileStart, 559bf42cfd7SJustin Bogner getEndOfFileOrMacro(Loc)); 560bf42cfd7SJustin Bogner Loc = getIncludeOrExpansionLoc(Loc); 561bf42cfd7SJustin Bogner } 562bf42cfd7SJustin Bogner } 563bf42cfd7SJustin Bogner 564bf42cfd7SJustin Bogner MostRecentLocation = NewLoc; 565bf42cfd7SJustin Bogner } 566bf42cfd7SJustin Bogner 567bf42cfd7SJustin Bogner /// \brief Ensure that \c S is included in the current region. 568bf42cfd7SJustin Bogner void extendRegion(const Stmt *S) { 569bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 570bf42cfd7SJustin Bogner SourceLocation StartLoc = getStart(S); 571bf42cfd7SJustin Bogner 572bf42cfd7SJustin Bogner handleFileExit(StartLoc); 573bf42cfd7SJustin Bogner if (!Region.hasStartLoc()) 574bf42cfd7SJustin Bogner Region.setStartLoc(StartLoc); 575bf42cfd7SJustin Bogner } 576bf42cfd7SJustin Bogner 577bf42cfd7SJustin Bogner /// \brief Mark \c S as a terminator, starting a zero region. 578bf42cfd7SJustin Bogner void terminateRegion(const Stmt *S) { 579bf42cfd7SJustin Bogner extendRegion(S); 580bf42cfd7SJustin Bogner SourceMappingRegion &Region = getRegion(); 581bf42cfd7SJustin Bogner if (!Region.hasEndLoc()) 582bf42cfd7SJustin Bogner Region.setEndLoc(getEnd(S)); 583bf42cfd7SJustin Bogner pushRegion(Counter::getZero()); 584bf42cfd7SJustin Bogner } 585ee02499aSAlex Lorenz 586ee02499aSAlex Lorenz /// \brief Keep counts of breaks and continues inside loops. 587ee02499aSAlex Lorenz struct BreakContinue { 588ee02499aSAlex Lorenz Counter BreakCount; 589ee02499aSAlex Lorenz Counter ContinueCount; 590ee02499aSAlex Lorenz }; 591ee02499aSAlex Lorenz SmallVector<BreakContinue, 8> BreakContinueStack; 592ee02499aSAlex Lorenz 593ee02499aSAlex Lorenz CounterCoverageMappingBuilder( 594ee02499aSAlex Lorenz CoverageMappingModuleGen &CVM, 595e5ee6c58SJustin Bogner llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM, 596ee02499aSAlex Lorenz const LangOptions &LangOpts) 597e5ee6c58SJustin Bogner : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {} 598ee02499aSAlex Lorenz 599ee02499aSAlex Lorenz /// \brief Write the mapping data to the output stream 600ee02499aSAlex Lorenz void write(llvm::raw_ostream &OS) { 601ee02499aSAlex Lorenz llvm::SmallVector<unsigned, 8> VirtualFileMapping; 602bf42cfd7SJustin Bogner gatherFileIDs(VirtualFileMapping); 603bf42cfd7SJustin Bogner emitSourceRegions(); 604bf42cfd7SJustin Bogner emitExpansionRegions(); 605ee02499aSAlex Lorenz gatherSkippedRegions(); 606ee02499aSAlex Lorenz 6074da909b2SJustin Bogner CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(), 6084da909b2SJustin Bogner MappingRegions); 609ee02499aSAlex Lorenz Writer.write(OS); 610ee02499aSAlex Lorenz } 611ee02499aSAlex Lorenz 612ee02499aSAlex Lorenz void VisitStmt(const Stmt *S) { 613ed1fe5d0SYaron Keren if (S->getLocStart().isValid()) 614bf42cfd7SJustin Bogner extendRegion(S); 615642f173aSBenjamin Kramer for (const Stmt *Child : S->children()) 616642f173aSBenjamin Kramer if (Child) 617642f173aSBenjamin Kramer this->Visit(Child); 618bf42cfd7SJustin Bogner handleFileExit(getEnd(S)); 619ee02499aSAlex Lorenz } 620ee02499aSAlex Lorenz 621ee02499aSAlex Lorenz void VisitDecl(const Decl *D) { 622bf42cfd7SJustin Bogner Stmt *Body = D->getBody(); 623bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(Body), Body); 624ee02499aSAlex Lorenz } 625ee02499aSAlex Lorenz 626ee02499aSAlex Lorenz void VisitReturnStmt(const ReturnStmt *S) { 627bf42cfd7SJustin Bogner extendRegion(S); 628ee02499aSAlex Lorenz if (S->getRetValue()) 629ee02499aSAlex Lorenz Visit(S->getRetValue()); 630bf42cfd7SJustin Bogner terminateRegion(S); 631ee02499aSAlex Lorenz } 632ee02499aSAlex Lorenz 633f959febfSJustin Bogner void VisitCXXThrowExpr(const CXXThrowExpr *E) { 634f959febfSJustin Bogner extendRegion(E); 635f959febfSJustin Bogner if (E->getSubExpr()) 636f959febfSJustin Bogner Visit(E->getSubExpr()); 637f959febfSJustin Bogner terminateRegion(E); 638f959febfSJustin Bogner } 639f959febfSJustin Bogner 640bf42cfd7SJustin Bogner void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); } 641ee02499aSAlex Lorenz 642ee02499aSAlex Lorenz void VisitLabelStmt(const LabelStmt *S) { 643bf42cfd7SJustin Bogner SourceLocation Start = getStart(S); 644bf42cfd7SJustin Bogner // We can't extendRegion here or we risk overlapping with our new region. 645bf42cfd7SJustin Bogner handleFileExit(Start); 646bf42cfd7SJustin Bogner pushRegion(getRegionCounter(S), Start); 647ee02499aSAlex Lorenz Visit(S->getSubStmt()); 648ee02499aSAlex Lorenz } 649ee02499aSAlex Lorenz 650ee02499aSAlex Lorenz void VisitBreakStmt(const BreakStmt *S) { 651ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 652ee02499aSAlex Lorenz BreakContinueStack.back().BreakCount = addCounters( 653bf42cfd7SJustin Bogner BreakContinueStack.back().BreakCount, getRegion().getCounter()); 654bf42cfd7SJustin Bogner terminateRegion(S); 655ee02499aSAlex Lorenz } 656ee02499aSAlex Lorenz 657ee02499aSAlex Lorenz void VisitContinueStmt(const ContinueStmt *S) { 658ee02499aSAlex Lorenz assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 659ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 660bf42cfd7SJustin Bogner BreakContinueStack.back().ContinueCount, getRegion().getCounter()); 661bf42cfd7SJustin Bogner terminateRegion(S); 662ee02499aSAlex Lorenz } 663ee02499aSAlex Lorenz 664ee02499aSAlex Lorenz void VisitWhileStmt(const WhileStmt *S) { 665bf42cfd7SJustin Bogner extendRegion(S); 666ee02499aSAlex Lorenz 667bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 668bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 669bf42cfd7SJustin Bogner 670bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 671bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 672bf42cfd7SJustin Bogner extendRegion(S->getBody()); 673bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 674ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 675bf42cfd7SJustin Bogner 676bf42cfd7SJustin Bogner // Go back to handle the condition. 677bf42cfd7SJustin Bogner Counter CondCount = 678bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 679bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 680bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 681bf42cfd7SJustin Bogner 682bf42cfd7SJustin Bogner Counter OutCount = 683bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 684bf42cfd7SJustin Bogner if (OutCount != ParentCount) 685bf42cfd7SJustin Bogner pushRegion(OutCount); 686ee02499aSAlex Lorenz } 687ee02499aSAlex Lorenz 688ee02499aSAlex Lorenz void VisitDoStmt(const DoStmt *S) { 689bf42cfd7SJustin Bogner extendRegion(S); 690ee02499aSAlex Lorenz 691bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 692bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 693bf42cfd7SJustin Bogner 694bf42cfd7SJustin Bogner BreakContinueStack.push_back(BreakContinue()); 695bf42cfd7SJustin Bogner extendRegion(S->getBody()); 696bf42cfd7SJustin Bogner Counter BackedgeCount = 697bf42cfd7SJustin Bogner propagateCounts(addCounters(ParentCount, BodyCount), S->getBody()); 698ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 699bf42cfd7SJustin Bogner 700bf42cfd7SJustin Bogner Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount); 701bf42cfd7SJustin Bogner propagateCounts(CondCount, S->getCond()); 702bf42cfd7SJustin Bogner 703bf42cfd7SJustin Bogner Counter OutCount = 704bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 705bf42cfd7SJustin Bogner if (OutCount != ParentCount) 706bf42cfd7SJustin Bogner pushRegion(OutCount); 707ee02499aSAlex Lorenz } 708ee02499aSAlex Lorenz 709ee02499aSAlex Lorenz void VisitForStmt(const ForStmt *S) { 710bf42cfd7SJustin Bogner extendRegion(S); 711ee02499aSAlex Lorenz if (S->getInit()) 712ee02499aSAlex Lorenz Visit(S->getInit()); 713ee02499aSAlex Lorenz 714bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 715bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 716bf42cfd7SJustin Bogner 717bf42cfd7SJustin Bogner // Handle the body first so that we can get the backedge count. 718ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 719bf42cfd7SJustin Bogner extendRegion(S->getBody()); 720bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 721bf42cfd7SJustin Bogner BreakContinue BC = BreakContinueStack.pop_back_val(); 722ee02499aSAlex Lorenz 723ee02499aSAlex Lorenz // The increment is essentially part of the body but it needs to include 724ee02499aSAlex Lorenz // the count for all the continue statements. 725bf42cfd7SJustin Bogner if (const Stmt *Inc = S->getInc()) 726bf42cfd7SJustin Bogner propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc); 727bf42cfd7SJustin Bogner 728bf42cfd7SJustin Bogner // Go back to handle the condition. 729bf42cfd7SJustin Bogner Counter CondCount = 730bf42cfd7SJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 731bf42cfd7SJustin Bogner if (const Expr *Cond = S->getCond()) { 732bf42cfd7SJustin Bogner propagateCounts(CondCount, Cond); 733bf42cfd7SJustin Bogner adjustForOutOfOrderTraversal(getEnd(S)); 734ee02499aSAlex Lorenz } 735ee02499aSAlex Lorenz 736bf42cfd7SJustin Bogner Counter OutCount = 737bf42cfd7SJustin Bogner addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount)); 738bf42cfd7SJustin Bogner if (OutCount != ParentCount) 739bf42cfd7SJustin Bogner pushRegion(OutCount); 740ee02499aSAlex Lorenz } 741ee02499aSAlex Lorenz 742ee02499aSAlex Lorenz void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 743bf42cfd7SJustin Bogner extendRegion(S); 744bf42cfd7SJustin Bogner Visit(S->getLoopVarStmt()); 745ee02499aSAlex Lorenz Visit(S->getRangeStmt()); 746bf42cfd7SJustin Bogner 747bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 748bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 749bf42cfd7SJustin Bogner 750ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 751bf42cfd7SJustin Bogner extendRegion(S->getBody()); 752bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 753ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 754bf42cfd7SJustin Bogner 7551587432dSJustin Bogner Counter LoopCount = 7561587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 7571587432dSJustin Bogner Counter OutCount = 7581587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 759bf42cfd7SJustin Bogner if (OutCount != ParentCount) 760bf42cfd7SJustin Bogner pushRegion(OutCount); 761ee02499aSAlex Lorenz } 762ee02499aSAlex Lorenz 763ee02499aSAlex Lorenz void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 764bf42cfd7SJustin Bogner extendRegion(S); 765ee02499aSAlex Lorenz Visit(S->getElement()); 766bf42cfd7SJustin Bogner 767bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 768bf42cfd7SJustin Bogner Counter BodyCount = getRegionCounter(S); 769bf42cfd7SJustin Bogner 770ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 771bf42cfd7SJustin Bogner extendRegion(S->getBody()); 772bf42cfd7SJustin Bogner Counter BackedgeCount = propagateCounts(BodyCount, S->getBody()); 773ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 774bf42cfd7SJustin Bogner 7751587432dSJustin Bogner Counter LoopCount = 7761587432dSJustin Bogner addCounters(ParentCount, BackedgeCount, BC.ContinueCount); 7771587432dSJustin Bogner Counter OutCount = 7781587432dSJustin Bogner addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount)); 779bf42cfd7SJustin Bogner if (OutCount != ParentCount) 780bf42cfd7SJustin Bogner pushRegion(OutCount); 781ee02499aSAlex Lorenz } 782ee02499aSAlex Lorenz 783ee02499aSAlex Lorenz void VisitSwitchStmt(const SwitchStmt *S) { 784bf42cfd7SJustin Bogner extendRegion(S); 785ee02499aSAlex Lorenz Visit(S->getCond()); 786bf42cfd7SJustin Bogner 787ee02499aSAlex Lorenz BreakContinueStack.push_back(BreakContinue()); 788bf42cfd7SJustin Bogner 789bf42cfd7SJustin Bogner const Stmt *Body = S->getBody(); 790bf42cfd7SJustin Bogner extendRegion(Body); 791bf42cfd7SJustin Bogner if (const auto *CS = dyn_cast<CompoundStmt>(Body)) { 792bf42cfd7SJustin Bogner if (!CS->body_empty()) { 793bf42cfd7SJustin Bogner // The body of the switch needs a zero region so that fallthrough counts 794bf42cfd7SJustin Bogner // behave correctly, but it would be misleading to include the braces of 795bf42cfd7SJustin Bogner // the compound statement in the zeroed area, so we need to handle this 796bf42cfd7SJustin Bogner // specially. 797bf42cfd7SJustin Bogner size_t Index = 798bf42cfd7SJustin Bogner pushRegion(Counter::getZero(), getStart(CS->body_front()), 799bf42cfd7SJustin Bogner getEnd(CS->body_back())); 800b5841332SRichard Trieu for (const auto *Child : CS->children()) 801bf42cfd7SJustin Bogner Visit(Child); 802bf42cfd7SJustin Bogner popRegions(Index); 803ee02499aSAlex Lorenz } 80487ea3b05SVedant Kumar } else 805bf42cfd7SJustin Bogner propagateCounts(Counter::getZero(), Body); 806ee02499aSAlex Lorenz BreakContinue BC = BreakContinueStack.pop_back_val(); 807bf42cfd7SJustin Bogner 808ee02499aSAlex Lorenz if (!BreakContinueStack.empty()) 809ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount = addCounters( 810ee02499aSAlex Lorenz BreakContinueStack.back().ContinueCount, BC.ContinueCount); 811bf42cfd7SJustin Bogner 812bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 8133836482aSVedant Kumar SourceLocation ExitLoc = getEnd(S); 8143836482aSVedant Kumar pushRegion(ExitCount, getStart(S), ExitLoc); 8153836482aSVedant Kumar handleFileExit(ExitLoc); 816ee02499aSAlex Lorenz } 817ee02499aSAlex Lorenz 818bf42cfd7SJustin Bogner void VisitSwitchCase(const SwitchCase *S) { 819bf42cfd7SJustin Bogner extendRegion(S); 820ee02499aSAlex Lorenz 821bf42cfd7SJustin Bogner SourceMappingRegion &Parent = getRegion(); 822bf42cfd7SJustin Bogner 823bf42cfd7SJustin Bogner Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S)); 824bf42cfd7SJustin Bogner // Reuse the existing region if it starts at our label. This is typical of 825bf42cfd7SJustin Bogner // the first case in a switch. 826bf42cfd7SJustin Bogner if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S)) 827bf42cfd7SJustin Bogner Parent.setCounter(Count); 828bf42cfd7SJustin Bogner else 829bf42cfd7SJustin Bogner pushRegion(Count, getStart(S)); 830bf42cfd7SJustin Bogner 831376c06c2SSanjay Patel if (const auto *CS = dyn_cast<CaseStmt>(S)) { 832bf42cfd7SJustin Bogner Visit(CS->getLHS()); 833bf42cfd7SJustin Bogner if (const Expr *RHS = CS->getRHS()) 834bf42cfd7SJustin Bogner Visit(RHS); 835bf42cfd7SJustin Bogner } 836ee02499aSAlex Lorenz Visit(S->getSubStmt()); 837ee02499aSAlex Lorenz } 838ee02499aSAlex Lorenz 839ee02499aSAlex Lorenz void VisitIfStmt(const IfStmt *S) { 840bf42cfd7SJustin Bogner extendRegion(S); 841055ebc34SJustin Bogner // Extend into the condition before we propagate through it below - this is 842055ebc34SJustin Bogner // needed to handle macros that generate the "if" but not the condition. 843055ebc34SJustin Bogner extendRegion(S->getCond()); 844ee02499aSAlex Lorenz 845bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 846bf42cfd7SJustin Bogner Counter ThenCount = getRegionCounter(S); 847ee02499aSAlex Lorenz 84891f2e3c9SJustin Bogner // Emitting a counter for the condition makes it easier to interpret the 84991f2e3c9SJustin Bogner // counter for the body when looking at the coverage. 85091f2e3c9SJustin Bogner propagateCounts(ParentCount, S->getCond()); 85191f2e3c9SJustin Bogner 852bf42cfd7SJustin Bogner extendRegion(S->getThen()); 853bf42cfd7SJustin Bogner Counter OutCount = propagateCounts(ThenCount, S->getThen()); 854bf42cfd7SJustin Bogner 855bf42cfd7SJustin Bogner Counter ElseCount = subtractCounters(ParentCount, ThenCount); 856bf42cfd7SJustin Bogner if (const Stmt *Else = S->getElse()) { 857bf42cfd7SJustin Bogner extendRegion(S->getElse()); 858bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else)); 859bf42cfd7SJustin Bogner } else 860bf42cfd7SJustin Bogner OutCount = addCounters(OutCount, ElseCount); 861bf42cfd7SJustin Bogner 862bf42cfd7SJustin Bogner if (OutCount != ParentCount) 863bf42cfd7SJustin Bogner pushRegion(OutCount); 864ee02499aSAlex Lorenz } 865ee02499aSAlex Lorenz 866ee02499aSAlex Lorenz void VisitCXXTryStmt(const CXXTryStmt *S) { 867bf42cfd7SJustin Bogner extendRegion(S); 868049908b2SVedant Kumar // Handle macros that generate the "try" but not the rest. 869049908b2SVedant Kumar extendRegion(S->getTryBlock()); 870049908b2SVedant Kumar 871049908b2SVedant Kumar Counter ParentCount = getRegion().getCounter(); 872049908b2SVedant Kumar propagateCounts(ParentCount, S->getTryBlock()); 873049908b2SVedant Kumar 874ee02499aSAlex Lorenz for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 875ee02499aSAlex Lorenz Visit(S->getHandler(I)); 876bf42cfd7SJustin Bogner 877bf42cfd7SJustin Bogner Counter ExitCount = getRegionCounter(S); 878bf42cfd7SJustin Bogner pushRegion(ExitCount); 879ee02499aSAlex Lorenz } 880ee02499aSAlex Lorenz 881ee02499aSAlex Lorenz void VisitCXXCatchStmt(const CXXCatchStmt *S) { 882bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(S), S->getHandlerBlock()); 883ee02499aSAlex Lorenz } 884ee02499aSAlex Lorenz 885ee02499aSAlex Lorenz void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 886bf42cfd7SJustin Bogner extendRegion(E); 887ee02499aSAlex Lorenz 888bf42cfd7SJustin Bogner Counter ParentCount = getRegion().getCounter(); 889bf42cfd7SJustin Bogner Counter TrueCount = getRegionCounter(E); 890ee02499aSAlex Lorenz 891e3654ce7SJustin Bogner Visit(E->getCond()); 892e3654ce7SJustin Bogner 893e3654ce7SJustin Bogner if (!isa<BinaryConditionalOperator>(E)) { 894e3654ce7SJustin Bogner extendRegion(E->getTrueExpr()); 895bf42cfd7SJustin Bogner propagateCounts(TrueCount, E->getTrueExpr()); 896e3654ce7SJustin Bogner } 897e3654ce7SJustin Bogner extendRegion(E->getFalseExpr()); 898bf42cfd7SJustin Bogner propagateCounts(subtractCounters(ParentCount, TrueCount), 899bf42cfd7SJustin Bogner E->getFalseExpr()); 900ee02499aSAlex Lorenz } 901ee02499aSAlex Lorenz 902ee02499aSAlex Lorenz void VisitBinLAnd(const BinaryOperator *E) { 903bf42cfd7SJustin Bogner extendRegion(E); 904ee02499aSAlex Lorenz Visit(E->getLHS()); 905bf42cfd7SJustin Bogner 906bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 907bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 908ee02499aSAlex Lorenz } 909ee02499aSAlex Lorenz 910ee02499aSAlex Lorenz void VisitBinLOr(const BinaryOperator *E) { 911bf42cfd7SJustin Bogner extendRegion(E); 912ee02499aSAlex Lorenz Visit(E->getLHS()); 913ee02499aSAlex Lorenz 914bf42cfd7SJustin Bogner extendRegion(E->getRHS()); 915bf42cfd7SJustin Bogner propagateCounts(getRegionCounter(E), E->getRHS()); 91601a0d062SAlex Lorenz } 917c109102eSJustin Bogner 918c109102eSJustin Bogner void VisitLambdaExpr(const LambdaExpr *LE) { 919c109102eSJustin Bogner // Lambdas are treated as their own functions for now, so we shouldn't 920c109102eSJustin Bogner // propagate counts into them. 921c109102eSJustin Bogner } 922ee02499aSAlex Lorenz }; 923ab9db510SAlexander Kornienko } 924ee02499aSAlex Lorenz 925ee02499aSAlex Lorenz static bool isMachO(const CodeGenModule &CGM) { 926ee02499aSAlex Lorenz return CGM.getTarget().getTriple().isOSBinFormatMachO(); 927ee02499aSAlex Lorenz } 928ee02499aSAlex Lorenz 929ee02499aSAlex Lorenz static StringRef getCoverageSection(const CodeGenModule &CGM) { 93003711cbdSXinliang David Li return llvm::getInstrProfCoverageSectionName(isMachO(CGM)); 931ee02499aSAlex Lorenz } 932ee02499aSAlex Lorenz 933a432d176SJustin Bogner static void dump(llvm::raw_ostream &OS, StringRef FunctionName, 934a432d176SJustin Bogner ArrayRef<CounterExpression> Expressions, 935a432d176SJustin Bogner ArrayRef<CounterMappingRegion> Regions) { 936a432d176SJustin Bogner OS << FunctionName << ":\n"; 937a432d176SJustin Bogner CounterMappingContext Ctx(Expressions); 938a432d176SJustin Bogner for (const auto &R : Regions) { 939f2cf38e0SAlex Lorenz OS.indent(2); 940f2cf38e0SAlex Lorenz switch (R.Kind) { 941f2cf38e0SAlex Lorenz case CounterMappingRegion::CodeRegion: 942f2cf38e0SAlex Lorenz break; 943f2cf38e0SAlex Lorenz case CounterMappingRegion::ExpansionRegion: 944f2cf38e0SAlex Lorenz OS << "Expansion,"; 945f2cf38e0SAlex Lorenz break; 946f2cf38e0SAlex Lorenz case CounterMappingRegion::SkippedRegion: 947f2cf38e0SAlex Lorenz OS << "Skipped,"; 948f2cf38e0SAlex Lorenz break; 949f2cf38e0SAlex Lorenz } 950f2cf38e0SAlex Lorenz 9514da909b2SJustin Bogner OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart 9524da909b2SJustin Bogner << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = "; 953f69dc349SJustin Bogner Ctx.dump(R.Count, OS); 954f2cf38e0SAlex Lorenz if (R.Kind == CounterMappingRegion::ExpansionRegion) 9554da909b2SJustin Bogner OS << " (Expanded file = " << R.ExpandedFileID << ")"; 9564da909b2SJustin Bogner OS << "\n"; 957f2cf38e0SAlex Lorenz } 958f2cf38e0SAlex Lorenz } 959f2cf38e0SAlex Lorenz 960ee02499aSAlex Lorenz void CoverageMappingModuleGen::addFunctionMappingRecord( 9612129ae53SXinliang David Li llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash, 962848da137SXinliang David Li const std::string &CoverageMapping, bool IsUsed) { 963ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 964ee02499aSAlex Lorenz if (!FunctionRecordTy) { 965a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType, 966a026a437SXinliang David Li llvm::Type *FunctionRecordTypes[] = { 967a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 968a026a437SXinliang David Li }; 969ee02499aSAlex Lorenz FunctionRecordTy = 9704dc5adc7SJustin Bogner llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes), 9714dc5adc7SJustin Bogner /*isPacked=*/true); 972ee02499aSAlex Lorenz } 973ee02499aSAlex Lorenz 974a026a437SXinliang David Li #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init, 975ee02499aSAlex Lorenz llvm::Constant *FunctionRecordVals[] = { 976a026a437SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 977a026a437SXinliang David Li }; 978ee02499aSAlex Lorenz FunctionRecords.push_back(llvm::ConstantStruct::get( 979ee02499aSAlex Lorenz FunctionRecordTy, makeArrayRef(FunctionRecordVals))); 980848da137SXinliang David Li if (!IsUsed) 9812129ae53SXinliang David Li FunctionNames.push_back( 9822129ae53SXinliang David Li llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx))); 983ca3326c0SVedant Kumar CoverageMappings.push_back(CoverageMapping); 984f2cf38e0SAlex Lorenz 985f2cf38e0SAlex Lorenz if (CGM.getCodeGenOpts().DumpCoverageMapping) { 986f2cf38e0SAlex Lorenz // Dump the coverage mapping data for this function by decoding the 987f2cf38e0SAlex Lorenz // encoded data. This allows us to dump the mapping regions which were 988f2cf38e0SAlex Lorenz // also processed by the CoverageMappingWriter which performs 989f2cf38e0SAlex Lorenz // additional minimization operations such as reducing the number of 990f2cf38e0SAlex Lorenz // expressions. 991f2cf38e0SAlex Lorenz std::vector<StringRef> Filenames; 992f2cf38e0SAlex Lorenz std::vector<CounterExpression> Expressions; 993f2cf38e0SAlex Lorenz std::vector<CounterMappingRegion> Regions; 994f2cf38e0SAlex Lorenz llvm::SmallVector<StringRef, 16> FilenameRefs; 995f2cf38e0SAlex Lorenz FilenameRefs.resize(FileEntries.size()); 996f2cf38e0SAlex Lorenz for (const auto &Entry : FileEntries) 997f2cf38e0SAlex Lorenz FilenameRefs[Entry.second] = Entry.first->getName(); 998a432d176SJustin Bogner RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames, 999a432d176SJustin Bogner Expressions, Regions); 1000a432d176SJustin Bogner if (Reader.read()) 1001f2cf38e0SAlex Lorenz return; 1002a026a437SXinliang David Li dump(llvm::outs(), NameValue, Expressions, Regions); 1003f2cf38e0SAlex Lorenz } 1004ee02499aSAlex Lorenz } 1005ee02499aSAlex Lorenz 1006ee02499aSAlex Lorenz void CoverageMappingModuleGen::emit() { 1007ee02499aSAlex Lorenz if (FunctionRecords.empty()) 1008ee02499aSAlex Lorenz return; 1009ee02499aSAlex Lorenz llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1010ee02499aSAlex Lorenz auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 1011ee02499aSAlex Lorenz 1012ee02499aSAlex Lorenz // Create the filenames and merge them with coverage mappings 1013ee02499aSAlex Lorenz llvm::SmallVector<std::string, 16> FilenameStrs; 10149e324dd1SVedant Kumar llvm::SmallVector<StringRef, 16> FilenameRefs; 1015ee02499aSAlex Lorenz FilenameStrs.resize(FileEntries.size()); 10169e324dd1SVedant Kumar FilenameRefs.resize(FileEntries.size()); 1017ee02499aSAlex Lorenz for (const auto &Entry : FileEntries) { 1018ee02499aSAlex Lorenz llvm::SmallString<256> Path(Entry.first->getName()); 1019ee02499aSAlex Lorenz llvm::sys::fs::make_absolute(Path); 1020ee02499aSAlex Lorenz 1021ee02499aSAlex Lorenz auto I = Entry.second; 1022d1ffdda4SRichard Trieu FilenameStrs[I] = std::string(Path.begin(), Path.end()); 10239e324dd1SVedant Kumar FilenameRefs[I] = FilenameStrs[I]; 1024ee02499aSAlex Lorenz } 1025ee02499aSAlex Lorenz 10269e324dd1SVedant Kumar std::string FilenamesAndCoverageMappings; 10279e324dd1SVedant Kumar llvm::raw_string_ostream OS(FilenamesAndCoverageMappings); 10289e324dd1SVedant Kumar CoverageFilenamesSectionWriter(FilenameRefs).write(OS); 10299e324dd1SVedant Kumar std::string RawCoverageMappings = 10309e324dd1SVedant Kumar llvm::join(CoverageMappings.begin(), CoverageMappings.end(), ""); 10319e324dd1SVedant Kumar OS << RawCoverageMappings; 10329e324dd1SVedant Kumar size_t CoverageMappingSize = RawCoverageMappings.size(); 10339e324dd1SVedant Kumar size_t FilenamesSize = OS.str().size() - CoverageMappingSize; 10349e324dd1SVedant Kumar // Append extra zeroes if necessary to ensure that the size of the filenames 10359e324dd1SVedant Kumar // and coverage mappings is a multiple of 8. 10369e324dd1SVedant Kumar if (size_t Rem = OS.str().size() % 8) { 10379e324dd1SVedant Kumar CoverageMappingSize += 8 - Rem; 10389e324dd1SVedant Kumar for (size_t I = 0, S = 8 - Rem; I < S; ++I) 10399e324dd1SVedant Kumar OS << '\0'; 1040ee02499aSAlex Lorenz } 1041ee02499aSAlex Lorenz auto *FilenamesAndMappingsVal = 10429e324dd1SVedant Kumar llvm::ConstantDataArray::getString(Ctx, OS.str(), false); 1043ee02499aSAlex Lorenz 1044ee02499aSAlex Lorenz // Create the deferred function records array 1045ee02499aSAlex Lorenz auto RecordsTy = 1046ee02499aSAlex Lorenz llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size()); 1047ee02499aSAlex Lorenz auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords); 1048ee02499aSAlex Lorenz 104920b188c0SXinliang David Li llvm::Type *CovDataHeaderTypes[] = { 105020b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType, 105120b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 105220b188c0SXinliang David Li }; 105320b188c0SXinliang David Li auto CovDataHeaderTy = 105420b188c0SXinliang David Li llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes)); 105520b188c0SXinliang David Li llvm::Constant *CovDataHeaderVals[] = { 105620b188c0SXinliang David Li #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init, 105720b188c0SXinliang David Li #include "llvm/ProfileData/InstrProfData.inc" 105820b188c0SXinliang David Li }; 105920b188c0SXinliang David Li auto CovDataHeaderVal = llvm::ConstantStruct::get( 106020b188c0SXinliang David Li CovDataHeaderTy, makeArrayRef(CovDataHeaderVals)); 106120b188c0SXinliang David Li 1062ee02499aSAlex Lorenz // Create the coverage data record 106320b188c0SXinliang David Li llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy, 106420b188c0SXinliang David Li FilenamesAndMappingsVal->getType()}; 1065ee02499aSAlex Lorenz auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes)); 106620b188c0SXinliang David Li llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal, 106720b188c0SXinliang David Li FilenamesAndMappingsVal}; 1068ee02499aSAlex Lorenz auto CovDataVal = 1069ee02499aSAlex Lorenz llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals)); 107020b188c0SXinliang David Li auto CovData = new llvm::GlobalVariable( 107120b188c0SXinliang David Li CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage, 107220b188c0SXinliang David Li CovDataVal, llvm::getCoverageMappingVarName()); 1073ee02499aSAlex Lorenz 1074ee02499aSAlex Lorenz CovData->setSection(getCoverageSection(CGM)); 1075ee02499aSAlex Lorenz CovData->setAlignment(8); 1076ee02499aSAlex Lorenz 1077ee02499aSAlex Lorenz // Make sure the data doesn't get deleted. 1078ee02499aSAlex Lorenz CGM.addUsedGlobal(CovData); 10792129ae53SXinliang David Li // Create the deferred function records array 10802129ae53SXinliang David Li if (!FunctionNames.empty()) { 10812129ae53SXinliang David Li auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx), 10822129ae53SXinliang David Li FunctionNames.size()); 10832129ae53SXinliang David Li auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames); 10842129ae53SXinliang David Li // This variable will *NOT* be emitted to the object file. It is used 10852129ae53SXinliang David Li // to pass the list of names referenced to codegen. 10862129ae53SXinliang David Li new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true, 10872129ae53SXinliang David Li llvm::GlobalValue::InternalLinkage, NamesArrVal, 10887077f0afSXinliang David Li llvm::getCoverageUnusedNamesVarName()); 10892129ae53SXinliang David Li } 1090ee02499aSAlex Lorenz } 1091ee02499aSAlex Lorenz 1092ee02499aSAlex Lorenz unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) { 1093ee02499aSAlex Lorenz auto It = FileEntries.find(File); 1094ee02499aSAlex Lorenz if (It != FileEntries.end()) 1095ee02499aSAlex Lorenz return It->second; 1096ee02499aSAlex Lorenz unsigned FileID = FileEntries.size(); 1097ee02499aSAlex Lorenz FileEntries.insert(std::make_pair(File, FileID)); 1098ee02499aSAlex Lorenz return FileID; 1099ee02499aSAlex Lorenz } 1100ee02499aSAlex Lorenz 1101ee02499aSAlex Lorenz void CoverageMappingGen::emitCounterMapping(const Decl *D, 1102ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1103ee02499aSAlex Lorenz assert(CounterMap); 1104e5ee6c58SJustin Bogner CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts); 1105ee02499aSAlex Lorenz Walker.VisitDecl(D); 1106ee02499aSAlex Lorenz Walker.write(OS); 1107ee02499aSAlex Lorenz } 1108ee02499aSAlex Lorenz 1109ee02499aSAlex Lorenz void CoverageMappingGen::emitEmptyMapping(const Decl *D, 1110ee02499aSAlex Lorenz llvm::raw_ostream &OS) { 1111ee02499aSAlex Lorenz EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); 1112ee02499aSAlex Lorenz Walker.VisitDecl(D); 1113ee02499aSAlex Lorenz Walker.write(OS); 1114ee02499aSAlex Lorenz } 1115