172208a82SEugene Zelenko //===- CoverageMapping.cpp - Code coverage mapping support ----------------===// 2dc707122SEaswaran Raman // 3dc707122SEaswaran Raman // The LLVM Compiler Infrastructure 4dc707122SEaswaran Raman // 5dc707122SEaswaran Raman // This file is distributed under the University of Illinois Open Source 6dc707122SEaswaran Raman // License. See LICENSE.TXT for details. 7dc707122SEaswaran Raman // 8dc707122SEaswaran Raman //===----------------------------------------------------------------------===// 9dc707122SEaswaran Raman // 10dc707122SEaswaran Raman // This file contains support for clang's and llvm's instrumentation based 11dc707122SEaswaran Raman // code coverage. 12dc707122SEaswaran Raman // 13dc707122SEaswaran Raman //===----------------------------------------------------------------------===// 14dc707122SEaswaran Raman 156bda14b3SChandler Carruth #include "llvm/ProfileData/Coverage/CoverageMapping.h" 16e78d131aSEugene Zelenko #include "llvm/ADT/ArrayRef.h" 17dc707122SEaswaran Raman #include "llvm/ADT/DenseMap.h" 18e78d131aSEugene Zelenko #include "llvm/ADT/None.h" 19dc707122SEaswaran Raman #include "llvm/ADT/Optional.h" 20dc707122SEaswaran Raman #include "llvm/ADT/SmallBitVector.h" 21e78d131aSEugene Zelenko #include "llvm/ADT/SmallVector.h" 22e78d131aSEugene Zelenko #include "llvm/ADT/StringRef.h" 23dc707122SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 24dc707122SEaswaran Raman #include "llvm/ProfileData/InstrProfReader.h" 25dc707122SEaswaran Raman #include "llvm/Support/Debug.h" 26dc707122SEaswaran Raman #include "llvm/Support/Errc.h" 27e78d131aSEugene Zelenko #include "llvm/Support/Error.h" 28dc707122SEaswaran Raman #include "llvm/Support/ErrorHandling.h" 29dc707122SEaswaran Raman #include "llvm/Support/ManagedStatic.h" 30e78d131aSEugene Zelenko #include "llvm/Support/MemoryBuffer.h" 31dc707122SEaswaran Raman #include "llvm/Support/raw_ostream.h" 32e78d131aSEugene Zelenko #include <algorithm> 33e78d131aSEugene Zelenko #include <cassert> 34e78d131aSEugene Zelenko #include <cstdint> 35e78d131aSEugene Zelenko #include <iterator> 367bef6da6SVedant Kumar #include <map> 37e78d131aSEugene Zelenko #include <memory> 38e78d131aSEugene Zelenko #include <string> 39e78d131aSEugene Zelenko #include <system_error> 40e78d131aSEugene Zelenko #include <utility> 41e78d131aSEugene Zelenko #include <vector> 42dc707122SEaswaran Raman 43dc707122SEaswaran Raman using namespace llvm; 44dc707122SEaswaran Raman using namespace coverage; 45dc707122SEaswaran Raman 46dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping" 47dc707122SEaswaran Raman 48dc707122SEaswaran Raman Counter CounterExpressionBuilder::get(const CounterExpression &E) { 49dc707122SEaswaran Raman auto It = ExpressionIndices.find(E); 50dc707122SEaswaran Raman if (It != ExpressionIndices.end()) 51dc707122SEaswaran Raman return Counter::getExpression(It->second); 52dc707122SEaswaran Raman unsigned I = Expressions.size(); 53dc707122SEaswaran Raman Expressions.push_back(E); 54dc707122SEaswaran Raman ExpressionIndices[E] = I; 55dc707122SEaswaran Raman return Counter::getExpression(I); 56dc707122SEaswaran Raman } 57dc707122SEaswaran Raman 5871b3d721SVedant Kumar void CounterExpressionBuilder::extractTerms(Counter C, int Factor, 5971b3d721SVedant Kumar SmallVectorImpl<Term> &Terms) { 60dc707122SEaswaran Raman switch (C.getKind()) { 61dc707122SEaswaran Raman case Counter::Zero: 62dc707122SEaswaran Raman break; 63dc707122SEaswaran Raman case Counter::CounterValueReference: 6471b3d721SVedant Kumar Terms.emplace_back(C.getCounterID(), Factor); 65dc707122SEaswaran Raman break; 66dc707122SEaswaran Raman case Counter::Expression: 67dc707122SEaswaran Raman const auto &E = Expressions[C.getExpressionID()]; 6871b3d721SVedant Kumar extractTerms(E.LHS, Factor, Terms); 6971b3d721SVedant Kumar extractTerms( 7071b3d721SVedant Kumar E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms); 71dc707122SEaswaran Raman break; 72dc707122SEaswaran Raman } 73dc707122SEaswaran Raman } 74dc707122SEaswaran Raman 75dc707122SEaswaran Raman Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) { 76dc707122SEaswaran Raman // Gather constant terms. 7771b3d721SVedant Kumar SmallVector<Term, 32> Terms; 78dc707122SEaswaran Raman extractTerms(ExpressionTree, +1, Terms); 79dc707122SEaswaran Raman 80dc707122SEaswaran Raman // If there are no terms, this is just a zero. The algorithm below assumes at 81dc707122SEaswaran Raman // least one term. 82dc707122SEaswaran Raman if (Terms.size() == 0) 83dc707122SEaswaran Raman return Counter::getZero(); 84dc707122SEaswaran Raman 85dc707122SEaswaran Raman // Group the terms by counter ID. 868547f913SMandeep Singh Grang llvm::sort(Terms.begin(), Terms.end(), [](const Term &LHS, const Term &RHS) { 8771b3d721SVedant Kumar return LHS.CounterID < RHS.CounterID; 88dc707122SEaswaran Raman }); 89dc707122SEaswaran Raman 90dc707122SEaswaran Raman // Combine terms by counter ID to eliminate counters that sum to zero. 91dc707122SEaswaran Raman auto Prev = Terms.begin(); 92dc707122SEaswaran Raman for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) { 9371b3d721SVedant Kumar if (I->CounterID == Prev->CounterID) { 9471b3d721SVedant Kumar Prev->Factor += I->Factor; 95dc707122SEaswaran Raman continue; 96dc707122SEaswaran Raman } 97dc707122SEaswaran Raman ++Prev; 98dc707122SEaswaran Raman *Prev = *I; 99dc707122SEaswaran Raman } 100dc707122SEaswaran Raman Terms.erase(++Prev, Terms.end()); 101dc707122SEaswaran Raman 102dc707122SEaswaran Raman Counter C; 103dc707122SEaswaran Raman // Create additions. We do this before subtractions to avoid constructs like 104dc707122SEaswaran Raman // ((0 - X) + Y), as opposed to (Y - X). 10571b3d721SVedant Kumar for (auto T : Terms) { 10671b3d721SVedant Kumar if (T.Factor <= 0) 107dc707122SEaswaran Raman continue; 10871b3d721SVedant Kumar for (int I = 0; I < T.Factor; ++I) 109dc707122SEaswaran Raman if (C.isZero()) 11071b3d721SVedant Kumar C = Counter::getCounter(T.CounterID); 111dc707122SEaswaran Raman else 112dc707122SEaswaran Raman C = get(CounterExpression(CounterExpression::Add, C, 11371b3d721SVedant Kumar Counter::getCounter(T.CounterID))); 114dc707122SEaswaran Raman } 115dc707122SEaswaran Raman 116dc707122SEaswaran Raman // Create subtractions. 11771b3d721SVedant Kumar for (auto T : Terms) { 11871b3d721SVedant Kumar if (T.Factor >= 0) 119dc707122SEaswaran Raman continue; 12071b3d721SVedant Kumar for (int I = 0; I < -T.Factor; ++I) 121dc707122SEaswaran Raman C = get(CounterExpression(CounterExpression::Subtract, C, 12271b3d721SVedant Kumar Counter::getCounter(T.CounterID))); 123dc707122SEaswaran Raman } 124dc707122SEaswaran Raman return C; 125dc707122SEaswaran Raman } 126dc707122SEaswaran Raman 127dc707122SEaswaran Raman Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) { 128dc707122SEaswaran Raman return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS))); 129dc707122SEaswaran Raman } 130dc707122SEaswaran Raman 131dc707122SEaswaran Raman Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) { 132dc707122SEaswaran Raman return simplify( 133dc707122SEaswaran Raman get(CounterExpression(CounterExpression::Subtract, LHS, RHS))); 134dc707122SEaswaran Raman } 135dc707122SEaswaran Raman 136e78d131aSEugene Zelenko void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const { 137dc707122SEaswaran Raman switch (C.getKind()) { 138dc707122SEaswaran Raman case Counter::Zero: 139dc707122SEaswaran Raman OS << '0'; 140dc707122SEaswaran Raman return; 141dc707122SEaswaran Raman case Counter::CounterValueReference: 142dc707122SEaswaran Raman OS << '#' << C.getCounterID(); 143dc707122SEaswaran Raman break; 144dc707122SEaswaran Raman case Counter::Expression: { 145dc707122SEaswaran Raman if (C.getExpressionID() >= Expressions.size()) 146dc707122SEaswaran Raman return; 147dc707122SEaswaran Raman const auto &E = Expressions[C.getExpressionID()]; 148dc707122SEaswaran Raman OS << '('; 149dc707122SEaswaran Raman dump(E.LHS, OS); 150dc707122SEaswaran Raman OS << (E.Kind == CounterExpression::Subtract ? " - " : " + "); 151dc707122SEaswaran Raman dump(E.RHS, OS); 152dc707122SEaswaran Raman OS << ')'; 153dc707122SEaswaran Raman break; 154dc707122SEaswaran Raman } 155dc707122SEaswaran Raman } 156dc707122SEaswaran Raman if (CounterValues.empty()) 157dc707122SEaswaran Raman return; 1589152fd17SVedant Kumar Expected<int64_t> Value = evaluate(C); 1599152fd17SVedant Kumar if (auto E = Value.takeError()) { 160e78d131aSEugene Zelenko consumeError(std::move(E)); 161dc707122SEaswaran Raman return; 1629152fd17SVedant Kumar } 163dc707122SEaswaran Raman OS << '[' << *Value << ']'; 164dc707122SEaswaran Raman } 165dc707122SEaswaran Raman 1669152fd17SVedant Kumar Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const { 167dc707122SEaswaran Raman switch (C.getKind()) { 168dc707122SEaswaran Raman case Counter::Zero: 169dc707122SEaswaran Raman return 0; 170dc707122SEaswaran Raman case Counter::CounterValueReference: 171dc707122SEaswaran Raman if (C.getCounterID() >= CounterValues.size()) 1729152fd17SVedant Kumar return errorCodeToError(errc::argument_out_of_domain); 173dc707122SEaswaran Raman return CounterValues[C.getCounterID()]; 174dc707122SEaswaran Raman case Counter::Expression: { 175dc707122SEaswaran Raman if (C.getExpressionID() >= Expressions.size()) 1769152fd17SVedant Kumar return errorCodeToError(errc::argument_out_of_domain); 177dc707122SEaswaran Raman const auto &E = Expressions[C.getExpressionID()]; 1789152fd17SVedant Kumar Expected<int64_t> LHS = evaluate(E.LHS); 179dc707122SEaswaran Raman if (!LHS) 180dc707122SEaswaran Raman return LHS; 1819152fd17SVedant Kumar Expected<int64_t> RHS = evaluate(E.RHS); 182dc707122SEaswaran Raman if (!RHS) 183dc707122SEaswaran Raman return RHS; 184dc707122SEaswaran Raman return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS; 185dc707122SEaswaran Raman } 186dc707122SEaswaran Raman } 187dc707122SEaswaran Raman llvm_unreachable("Unhandled CounterKind"); 188dc707122SEaswaran Raman } 189dc707122SEaswaran Raman 190dc707122SEaswaran Raman void FunctionRecordIterator::skipOtherFiles() { 191dc707122SEaswaran Raman while (Current != Records.end() && !Filename.empty() && 192dc707122SEaswaran Raman Filename != Current->Filenames[0]) 193dc707122SEaswaran Raman ++Current; 194dc707122SEaswaran Raman if (Current == Records.end()) 195dc707122SEaswaran Raman *this = FunctionRecordIterator(); 196dc707122SEaswaran Raman } 197dc707122SEaswaran Raman 19868216d7bSVedant Kumar Error CoverageMapping::loadFunctionRecord( 19968216d7bSVedant Kumar const CoverageMappingRecord &Record, 200dc707122SEaswaran Raman IndexedInstrProfReader &ProfileReader) { 201743574b8SVedant Kumar StringRef OrigFuncName = Record.FunctionName; 202b1d331a3SVedant Kumar if (OrigFuncName.empty()) 203b1d331a3SVedant Kumar return make_error<CoverageMapError>(coveragemap_error::malformed); 204b1d331a3SVedant Kumar 205743574b8SVedant Kumar if (Record.Filenames.empty()) 206743574b8SVedant Kumar OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName); 207743574b8SVedant Kumar else 208743574b8SVedant Kumar OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]); 209743574b8SVedant Kumar 2100c5b6020SMax Moroz // Don't load records for (filenames, function) pairs we've already seen. 2110c5b6020SMax Moroz auto FilenamesHash = hash_combine_range(Record.Filenames.begin(), 2120c5b6020SMax Moroz Record.Filenames.end()); 2130c5b6020SMax Moroz if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second) 214743574b8SVedant Kumar return Error::success(); 215743574b8SVedant Kumar 216dc707122SEaswaran Raman CounterMappingContext Ctx(Record.Expressions); 217dc707122SEaswaran Raman 21868216d7bSVedant Kumar std::vector<uint64_t> Counts; 21968216d7bSVedant Kumar if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName, 22068216d7bSVedant Kumar Record.FunctionHash, Counts)) { 2219152fd17SVedant Kumar instrprof_error IPE = InstrProfError::take(std::move(E)); 2229152fd17SVedant Kumar if (IPE == instrprof_error::hash_mismatch) { 22318dd9e88SVedant Kumar FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash); 22468216d7bSVedant Kumar return Error::success(); 2259152fd17SVedant Kumar } else if (IPE != instrprof_error::unknown_function) 2269152fd17SVedant Kumar return make_error<InstrProfError>(IPE); 227dc707122SEaswaran Raman Counts.assign(Record.MappingRegions.size(), 0); 228dc707122SEaswaran Raman } 229dc707122SEaswaran Raman Ctx.setCounts(Counts); 230dc707122SEaswaran Raman 231dc707122SEaswaran Raman assert(!Record.MappingRegions.empty() && "Function has no regions"); 232dc707122SEaswaran Raman 233dc707122SEaswaran Raman FunctionRecord Function(OrigFuncName, Record.Filenames); 234dc707122SEaswaran Raman for (const auto &Region : Record.MappingRegions) { 2359152fd17SVedant Kumar Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count); 2369152fd17SVedant Kumar if (auto E = ExecutionCount.takeError()) { 237e78d131aSEugene Zelenko consumeError(std::move(E)); 23868216d7bSVedant Kumar return Error::success(); 2399152fd17SVedant Kumar } 240dc707122SEaswaran Raman Function.pushRegion(Region, *ExecutionCount); 241dc707122SEaswaran Raman } 242dc707122SEaswaran Raman if (Function.CountedRegions.size() != Record.MappingRegions.size()) { 24318dd9e88SVedant Kumar FuncCounterMismatches.emplace_back(Record.FunctionName, 24418dd9e88SVedant Kumar Function.CountedRegions.size()); 24568216d7bSVedant Kumar return Error::success(); 246dc707122SEaswaran Raman } 247dc707122SEaswaran Raman 24868216d7bSVedant Kumar Functions.push_back(std::move(Function)); 24968216d7bSVedant Kumar return Error::success(); 250dc707122SEaswaran Raman } 251dc707122SEaswaran Raman 252743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load( 253743574b8SVedant Kumar ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders, 254743574b8SVedant Kumar IndexedInstrProfReader &ProfileReader) { 255743574b8SVedant Kumar auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); 256743574b8SVedant Kumar 257bae83970SVedant Kumar for (const auto &CoverageReader : CoverageReaders) { 258bae83970SVedant Kumar for (auto RecordOrErr : *CoverageReader) { 259bae83970SVedant Kumar if (Error E = RecordOrErr.takeError()) 260bae83970SVedant Kumar return std::move(E); 261bae83970SVedant Kumar const auto &Record = *RecordOrErr; 262743574b8SVedant Kumar if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader)) 2639152fd17SVedant Kumar return std::move(E); 264bae83970SVedant Kumar } 265bae83970SVedant Kumar } 266743574b8SVedant Kumar 267743574b8SVedant Kumar return std::move(Coverage); 268743574b8SVedant Kumar } 269743574b8SVedant Kumar 270743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> 271743574b8SVedant Kumar CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames, 2724b102c3dSVedant Kumar StringRef ProfileFilename, ArrayRef<StringRef> Arches) { 273dc707122SEaswaran Raman auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename); 2749152fd17SVedant Kumar if (Error E = ProfileReaderOrErr.takeError()) 2759152fd17SVedant Kumar return std::move(E); 276dc707122SEaswaran Raman auto ProfileReader = std::move(ProfileReaderOrErr.get()); 277743574b8SVedant Kumar 278743574b8SVedant Kumar SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers; 279743574b8SVedant Kumar SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers; 2804b102c3dSVedant Kumar for (const auto &File : llvm::enumerate(ObjectFilenames)) { 2814b102c3dSVedant Kumar auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value()); 282743574b8SVedant Kumar if (std::error_code EC = CovMappingBufOrErr.getError()) 283743574b8SVedant Kumar return errorCodeToError(EC); 2844b102c3dSVedant Kumar StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()]; 285743574b8SVedant Kumar auto CoverageReaderOrErr = 286743574b8SVedant Kumar BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch); 287743574b8SVedant Kumar if (Error E = CoverageReaderOrErr.takeError()) 288743574b8SVedant Kumar return std::move(E); 289743574b8SVedant Kumar Readers.push_back(std::move(CoverageReaderOrErr.get())); 290743574b8SVedant Kumar Buffers.push_back(std::move(CovMappingBufOrErr.get())); 291743574b8SVedant Kumar } 292743574b8SVedant Kumar return load(Readers, *ProfileReader); 293dc707122SEaswaran Raman } 294dc707122SEaswaran Raman 295dc707122SEaswaran Raman namespace { 296e78d131aSEugene Zelenko 2975f8f34e4SAdrian Prantl /// Distributes functions into instantiation sets. 298dc707122SEaswaran Raman /// 299dc707122SEaswaran Raman /// An instantiation set is a collection of functions that have the same source 300dc707122SEaswaran Raman /// code, ie, template functions specializations. 301dc707122SEaswaran Raman class FunctionInstantiationSetCollector { 3027bef6da6SVedant Kumar using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>; 303dc707122SEaswaran Raman MapT InstantiatedFunctions; 304dc707122SEaswaran Raman 305dc707122SEaswaran Raman public: 306dc707122SEaswaran Raman void insert(const FunctionRecord &Function, unsigned FileID) { 307dc707122SEaswaran Raman auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end(); 308dc707122SEaswaran Raman while (I != E && I->FileID != FileID) 309dc707122SEaswaran Raman ++I; 310dc707122SEaswaran Raman assert(I != E && "function does not cover the given file"); 311dc707122SEaswaran Raman auto &Functions = InstantiatedFunctions[I->startLoc()]; 312dc707122SEaswaran Raman Functions.push_back(&Function); 313dc707122SEaswaran Raman } 314dc707122SEaswaran Raman 315dc707122SEaswaran Raman MapT::iterator begin() { return InstantiatedFunctions.begin(); } 316dc707122SEaswaran Raman MapT::iterator end() { return InstantiatedFunctions.end(); } 317dc707122SEaswaran Raman }; 318dc707122SEaswaran Raman 319dc707122SEaswaran Raman class SegmentBuilder { 320dc707122SEaswaran Raman std::vector<CoverageSegment> &Segments; 321dc707122SEaswaran Raman SmallVector<const CountedRegion *, 8> ActiveRegions; 322dc707122SEaswaran Raman 323dc707122SEaswaran Raman SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {} 324dc707122SEaswaran Raman 32579a1b5eeSVedant Kumar /// Emit a segment with the count from \p Region starting at \p StartLoc. 32679a1b5eeSVedant Kumar // 327ad8f637bSVedant Kumar /// \p IsRegionEntry: The segment is at the start of a new non-gap region. 32879a1b5eeSVedant Kumar /// \p EmitSkippedRegion: The segment must be emitted as a skipped region. 32979a1b5eeSVedant Kumar void startSegment(const CountedRegion &Region, LineColPair StartLoc, 33079a1b5eeSVedant Kumar bool IsRegionEntry, bool EmitSkippedRegion = false) { 33179a1b5eeSVedant Kumar bool HasCount = !EmitSkippedRegion && 33279a1b5eeSVedant Kumar (Region.Kind != CounterMappingRegion::SkippedRegion); 33379a1b5eeSVedant Kumar 33479a1b5eeSVedant Kumar // If the new segment wouldn't affect coverage rendering, skip it. 33579a1b5eeSVedant Kumar if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) { 33679a1b5eeSVedant Kumar const auto &Last = Segments.back(); 33779a1b5eeSVedant Kumar if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount && 33879a1b5eeSVedant Kumar !Last.IsRegionEntry) 33979a1b5eeSVedant Kumar return; 340dc707122SEaswaran Raman } 341dc707122SEaswaran Raman 34279a1b5eeSVedant Kumar if (HasCount) 34379a1b5eeSVedant Kumar Segments.emplace_back(StartLoc.first, StartLoc.second, 344ad8f637bSVedant Kumar Region.ExecutionCount, IsRegionEntry, 345ad8f637bSVedant Kumar Region.Kind == CounterMappingRegion::GapRegion); 346dc707122SEaswaran Raman else 34779a1b5eeSVedant Kumar Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry); 34879a1b5eeSVedant Kumar 349*d34e60caSNicola Zaghen LLVM_DEBUG({ 35079a1b5eeSVedant Kumar const auto &Last = Segments.back(); 35179a1b5eeSVedant Kumar dbgs() << "Segment at " << Last.Line << ":" << Last.Col 35279a1b5eeSVedant Kumar << " (count = " << Last.Count << ")" 35379a1b5eeSVedant Kumar << (Last.IsRegionEntry ? ", RegionEntry" : "") 354ad8f637bSVedant Kumar << (!Last.HasCount ? ", Skipped" : "") 355ad8f637bSVedant Kumar << (Last.IsGapRegion ? ", Gap" : "") << "\n"; 35679a1b5eeSVedant Kumar }); 35779a1b5eeSVedant Kumar } 35879a1b5eeSVedant Kumar 35979a1b5eeSVedant Kumar /// Emit segments for active regions which end before \p Loc. 36079a1b5eeSVedant Kumar /// 36179a1b5eeSVedant Kumar /// \p Loc: The start location of the next region. If None, all active 36279a1b5eeSVedant Kumar /// regions are completed. 36379a1b5eeSVedant Kumar /// \p FirstCompletedRegion: Index of the first completed region. 36479a1b5eeSVedant Kumar void completeRegionsUntil(Optional<LineColPair> Loc, 36579a1b5eeSVedant Kumar unsigned FirstCompletedRegion) { 36679a1b5eeSVedant Kumar // Sort the completed regions by end location. This makes it simple to 36779a1b5eeSVedant Kumar // emit closing segments in sorted order. 36879a1b5eeSVedant Kumar auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion; 36979a1b5eeSVedant Kumar std::stable_sort(CompletedRegionsIt, ActiveRegions.end(), 37079a1b5eeSVedant Kumar [](const CountedRegion *L, const CountedRegion *R) { 37179a1b5eeSVedant Kumar return L->endLoc() < R->endLoc(); 37279a1b5eeSVedant Kumar }); 37379a1b5eeSVedant Kumar 37479a1b5eeSVedant Kumar // Emit segments for all completed regions. 37579a1b5eeSVedant Kumar for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E; 37679a1b5eeSVedant Kumar ++I) { 37779a1b5eeSVedant Kumar const auto *CompletedRegion = ActiveRegions[I]; 37879a1b5eeSVedant Kumar assert((!Loc || CompletedRegion->endLoc() <= *Loc) && 37979a1b5eeSVedant Kumar "Completed region ends after start of new region"); 38079a1b5eeSVedant Kumar 38179a1b5eeSVedant Kumar const auto *PrevCompletedRegion = ActiveRegions[I - 1]; 38279a1b5eeSVedant Kumar auto CompletedSegmentLoc = PrevCompletedRegion->endLoc(); 38379a1b5eeSVedant Kumar 38479a1b5eeSVedant Kumar // Don't emit any more segments if they start where the new region begins. 38579a1b5eeSVedant Kumar if (Loc && CompletedSegmentLoc == *Loc) 38679a1b5eeSVedant Kumar break; 38779a1b5eeSVedant Kumar 38879a1b5eeSVedant Kumar // Don't emit a segment if the next completed region ends at the same 38979a1b5eeSVedant Kumar // location as this one. 39079a1b5eeSVedant Kumar if (CompletedSegmentLoc == CompletedRegion->endLoc()) 39179a1b5eeSVedant Kumar continue; 39279a1b5eeSVedant Kumar 393337b0db1SVedant Kumar // Use the count from the last completed region which ends at this loc. 394337b0db1SVedant Kumar for (unsigned J = I + 1; J < E; ++J) 395337b0db1SVedant Kumar if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc()) 396337b0db1SVedant Kumar CompletedRegion = ActiveRegions[J]; 39780fbb855SVedant Kumar 39879a1b5eeSVedant Kumar startSegment(*CompletedRegion, CompletedSegmentLoc, false); 39979a1b5eeSVedant Kumar } 40079a1b5eeSVedant Kumar 40179a1b5eeSVedant Kumar auto Last = ActiveRegions.back(); 40279a1b5eeSVedant Kumar if (FirstCompletedRegion && Last->endLoc() != *Loc) { 40379a1b5eeSVedant Kumar // If there's a gap after the end of the last completed region and the 40479a1b5eeSVedant Kumar // start of the new region, use the last active region to fill the gap. 40579a1b5eeSVedant Kumar startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(), 40679a1b5eeSVedant Kumar false); 40779a1b5eeSVedant Kumar } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) { 40879a1b5eeSVedant Kumar // Emit a skipped segment if there are no more active regions. This 40979a1b5eeSVedant Kumar // ensures that gaps between functions are marked correctly. 41079a1b5eeSVedant Kumar startSegment(*Last, Last->endLoc(), false, true); 41179a1b5eeSVedant Kumar } 41279a1b5eeSVedant Kumar 41379a1b5eeSVedant Kumar // Pop the completed regions. 41479a1b5eeSVedant Kumar ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end()); 415dc707122SEaswaran Raman } 416dc707122SEaswaran Raman 417dc707122SEaswaran Raman void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) { 41879a1b5eeSVedant Kumar for (const auto &CR : enumerate(Regions)) { 41979a1b5eeSVedant Kumar auto CurStartLoc = CR.value().startLoc(); 42079a1b5eeSVedant Kumar 42179a1b5eeSVedant Kumar // Active regions which end before the current region need to be popped. 42279a1b5eeSVedant Kumar auto CompletedRegions = 42379a1b5eeSVedant Kumar std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(), 42479a1b5eeSVedant Kumar [&](const CountedRegion *Region) { 42579a1b5eeSVedant Kumar return !(Region->endLoc() <= CurStartLoc); 42679a1b5eeSVedant Kumar }); 42779a1b5eeSVedant Kumar if (CompletedRegions != ActiveRegions.end()) { 42879a1b5eeSVedant Kumar unsigned FirstCompletedRegion = 42979a1b5eeSVedant Kumar std::distance(ActiveRegions.begin(), CompletedRegions); 43079a1b5eeSVedant Kumar completeRegionsUntil(CurStartLoc, FirstCompletedRegion); 431dc707122SEaswaran Raman } 43279a1b5eeSVedant Kumar 433ad8f637bSVedant Kumar bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion; 434ad8f637bSVedant Kumar 43579a1b5eeSVedant Kumar // Try to emit a segment for the current region. 43679a1b5eeSVedant Kumar if (CurStartLoc == CR.value().endLoc()) { 43779a1b5eeSVedant Kumar // Avoid making zero-length regions active. If it's the last region, 43879a1b5eeSVedant Kumar // emit a skipped segment. Otherwise use its predecessor's count. 43979a1b5eeSVedant Kumar const bool Skipped = (CR.index() + 1) == Regions.size(); 44079a1b5eeSVedant Kumar startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(), 441ad8f637bSVedant Kumar CurStartLoc, !GapRegion, Skipped); 44279a1b5eeSVedant Kumar continue; 44379a1b5eeSVedant Kumar } 44479a1b5eeSVedant Kumar if (CR.index() + 1 == Regions.size() || 44579a1b5eeSVedant Kumar CurStartLoc != Regions[CR.index() + 1].startLoc()) { 44679a1b5eeSVedant Kumar // Emit a segment if the next region doesn't start at the same location 44779a1b5eeSVedant Kumar // as this one. 448ad8f637bSVedant Kumar startSegment(CR.value(), CurStartLoc, !GapRegion); 44979a1b5eeSVedant Kumar } 45079a1b5eeSVedant Kumar 45179a1b5eeSVedant Kumar // This region is active (i.e not completed). 45279a1b5eeSVedant Kumar ActiveRegions.push_back(&CR.value()); 45379a1b5eeSVedant Kumar } 45479a1b5eeSVedant Kumar 45579a1b5eeSVedant Kumar // Complete any remaining active regions. 45679a1b5eeSVedant Kumar if (!ActiveRegions.empty()) 45779a1b5eeSVedant Kumar completeRegionsUntil(None, 0); 458dc707122SEaswaran Raman } 459dc707122SEaswaran Raman 460dc707122SEaswaran Raman /// Sort a nested sequence of regions from a single file. 461dc707122SEaswaran Raman static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) { 4628547f913SMandeep Singh Grang llvm::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS, 46327d8dd39SIgor Kudrin const CountedRegion &RHS) { 46427d8dd39SIgor Kudrin if (LHS.startLoc() != RHS.startLoc()) 46527d8dd39SIgor Kudrin return LHS.startLoc() < RHS.startLoc(); 46627d8dd39SIgor Kudrin if (LHS.endLoc() != RHS.endLoc()) 467dc707122SEaswaran Raman // When LHS completely contains RHS, we sort LHS first. 468dc707122SEaswaran Raman return RHS.endLoc() < LHS.endLoc(); 46927d8dd39SIgor Kudrin // If LHS and RHS cover the same area, we need to sort them according 47027d8dd39SIgor Kudrin // to their kinds so that the most suitable region will become "active" 47127d8dd39SIgor Kudrin // in combineRegions(). Because we accumulate counter values only from 47227d8dd39SIgor Kudrin // regions of the same kind as the first region of the area, prefer 47327d8dd39SIgor Kudrin // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion. 474e78d131aSEugene Zelenko static_assert(CounterMappingRegion::CodeRegion < 475e78d131aSEugene Zelenko CounterMappingRegion::ExpansionRegion && 476e78d131aSEugene Zelenko CounterMappingRegion::ExpansionRegion < 477e78d131aSEugene Zelenko CounterMappingRegion::SkippedRegion, 47827d8dd39SIgor Kudrin "Unexpected order of region kind values"); 47927d8dd39SIgor Kudrin return LHS.Kind < RHS.Kind; 480dc707122SEaswaran Raman }); 481dc707122SEaswaran Raman } 482dc707122SEaswaran Raman 483dc707122SEaswaran Raman /// Combine counts of regions which cover the same area. 484dc707122SEaswaran Raman static ArrayRef<CountedRegion> 485dc707122SEaswaran Raman combineRegions(MutableArrayRef<CountedRegion> Regions) { 486dc707122SEaswaran Raman if (Regions.empty()) 487dc707122SEaswaran Raman return Regions; 488dc707122SEaswaran Raman auto Active = Regions.begin(); 489dc707122SEaswaran Raman auto End = Regions.end(); 490dc707122SEaswaran Raman for (auto I = Regions.begin() + 1; I != End; ++I) { 491dc707122SEaswaran Raman if (Active->startLoc() != I->startLoc() || 492dc707122SEaswaran Raman Active->endLoc() != I->endLoc()) { 493dc707122SEaswaran Raman // Shift to the next region. 494dc707122SEaswaran Raman ++Active; 495dc707122SEaswaran Raman if (Active != I) 496dc707122SEaswaran Raman *Active = *I; 497dc707122SEaswaran Raman continue; 498dc707122SEaswaran Raman } 499dc707122SEaswaran Raman // Merge duplicate region. 50027d8dd39SIgor Kudrin // If CodeRegions and ExpansionRegions cover the same area, it's probably 50127d8dd39SIgor Kudrin // a macro which is fully expanded to another macro. In that case, we need 50227d8dd39SIgor Kudrin // to accumulate counts only from CodeRegions, or else the area will be 50327d8dd39SIgor Kudrin // counted twice. 50427d8dd39SIgor Kudrin // On the other hand, a macro may have a nested macro in its body. If the 50527d8dd39SIgor Kudrin // outer macro is used several times, the ExpansionRegion for the nested 50627d8dd39SIgor Kudrin // macro will also be added several times. These ExpansionRegions cover 50727d8dd39SIgor Kudrin // the same source locations and have to be combined to reach the correct 50827d8dd39SIgor Kudrin // value for that area. 50927d8dd39SIgor Kudrin // We add counts of the regions of the same kind as the active region 51027d8dd39SIgor Kudrin // to handle the both situations. 51127d8dd39SIgor Kudrin if (I->Kind == Active->Kind) 512dc707122SEaswaran Raman Active->ExecutionCount += I->ExecutionCount; 513dc707122SEaswaran Raman } 514dc707122SEaswaran Raman return Regions.drop_back(std::distance(++Active, End)); 515dc707122SEaswaran Raman } 516dc707122SEaswaran Raman 517dc707122SEaswaran Raman public: 51879a1b5eeSVedant Kumar /// Build a sorted list of CoverageSegments from a list of Regions. 519dc707122SEaswaran Raman static std::vector<CoverageSegment> 520dc707122SEaswaran Raman buildSegments(MutableArrayRef<CountedRegion> Regions) { 521dc707122SEaswaran Raman std::vector<CoverageSegment> Segments; 522dc707122SEaswaran Raman SegmentBuilder Builder(Segments); 523dc707122SEaswaran Raman 524dc707122SEaswaran Raman sortNestedRegions(Regions); 525dc707122SEaswaran Raman ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions); 526dc707122SEaswaran Raman 527*d34e60caSNicola Zaghen LLVM_DEBUG({ 52879a1b5eeSVedant Kumar dbgs() << "Combined regions:\n"; 52979a1b5eeSVedant Kumar for (const auto &CR : CombinedRegions) 53079a1b5eeSVedant Kumar dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " 53179a1b5eeSVedant Kumar << CR.LineEnd << ":" << CR.ColumnEnd 53279a1b5eeSVedant Kumar << " (count=" << CR.ExecutionCount << ")\n"; 53379a1b5eeSVedant Kumar }); 53479a1b5eeSVedant Kumar 535dc707122SEaswaran Raman Builder.buildSegmentsImpl(CombinedRegions); 53679a1b5eeSVedant Kumar 53779a1b5eeSVedant Kumar #ifndef NDEBUG 53879a1b5eeSVedant Kumar for (unsigned I = 1, E = Segments.size(); I < E; ++I) { 53979a1b5eeSVedant Kumar const auto &L = Segments[I - 1]; 54079a1b5eeSVedant Kumar const auto &R = Segments[I]; 54179a1b5eeSVedant Kumar if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) { 542*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col 54379a1b5eeSVedant Kumar << " followed by " << R.Line << ":" << R.Col << "\n"); 54479a1b5eeSVedant Kumar assert(false && "Coverage segments not unique or sorted"); 54579a1b5eeSVedant Kumar } 54679a1b5eeSVedant Kumar } 54779a1b5eeSVedant Kumar #endif 54879a1b5eeSVedant Kumar 549dc707122SEaswaran Raman return Segments; 550dc707122SEaswaran Raman } 551dc707122SEaswaran Raman }; 552e78d131aSEugene Zelenko 553e78d131aSEugene Zelenko } // end anonymous namespace 554dc707122SEaswaran Raman 555dc707122SEaswaran Raman std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const { 556dc707122SEaswaran Raman std::vector<StringRef> Filenames; 557dc707122SEaswaran Raman for (const auto &Function : getCoveredFunctions()) 558dc707122SEaswaran Raman Filenames.insert(Filenames.end(), Function.Filenames.begin(), 559dc707122SEaswaran Raman Function.Filenames.end()); 5608547f913SMandeep Singh Grang llvm::sort(Filenames.begin(), Filenames.end()); 561dc707122SEaswaran Raman auto Last = std::unique(Filenames.begin(), Filenames.end()); 562dc707122SEaswaran Raman Filenames.erase(Last, Filenames.end()); 563dc707122SEaswaran Raman return Filenames; 564dc707122SEaswaran Raman } 565dc707122SEaswaran Raman 566dc707122SEaswaran Raman static SmallBitVector gatherFileIDs(StringRef SourceFile, 567dc707122SEaswaran Raman const FunctionRecord &Function) { 568dc707122SEaswaran Raman SmallBitVector FilenameEquivalence(Function.Filenames.size(), false); 569dc707122SEaswaran Raman for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I) 570dc707122SEaswaran Raman if (SourceFile == Function.Filenames[I]) 571dc707122SEaswaran Raman FilenameEquivalence[I] = true; 572dc707122SEaswaran Raman return FilenameEquivalence; 573dc707122SEaswaran Raman } 574dc707122SEaswaran Raman 575dc707122SEaswaran Raman /// Return the ID of the file where the definition of the function is located. 576dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) { 577dc707122SEaswaran Raman SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true); 578dc707122SEaswaran Raman for (const auto &CR : Function.CountedRegions) 579dc707122SEaswaran Raman if (CR.Kind == CounterMappingRegion::ExpansionRegion) 580dc707122SEaswaran Raman IsNotExpandedFile[CR.ExpandedFileID] = false; 581dc707122SEaswaran Raman int I = IsNotExpandedFile.find_first(); 582dc707122SEaswaran Raman if (I == -1) 583dc707122SEaswaran Raman return None; 584dc707122SEaswaran Raman return I; 585dc707122SEaswaran Raman } 586dc707122SEaswaran Raman 587dc707122SEaswaran Raman /// Check if SourceFile is the file that contains the definition of 588dc707122SEaswaran Raman /// the Function. Return the ID of the file in that case or None otherwise. 589dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(StringRef SourceFile, 590dc707122SEaswaran Raman const FunctionRecord &Function) { 591dc707122SEaswaran Raman Optional<unsigned> I = findMainViewFileID(Function); 592dc707122SEaswaran Raman if (I && SourceFile == Function.Filenames[*I]) 593dc707122SEaswaran Raman return I; 594dc707122SEaswaran Raman return None; 595dc707122SEaswaran Raman } 596dc707122SEaswaran Raman 597dc707122SEaswaran Raman static bool isExpansion(const CountedRegion &R, unsigned FileID) { 598dc707122SEaswaran Raman return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID; 599dc707122SEaswaran Raman } 600dc707122SEaswaran Raman 6017fcc5472SVedant Kumar CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const { 602dc707122SEaswaran Raman CoverageData FileCoverage(Filename); 603e78d131aSEugene Zelenko std::vector<CountedRegion> Regions; 604dc707122SEaswaran Raman 605dc707122SEaswaran Raman for (const auto &Function : Functions) { 606dc707122SEaswaran Raman auto MainFileID = findMainViewFileID(Filename, Function); 607dc707122SEaswaran Raman auto FileIDs = gatherFileIDs(Filename, Function); 608dc707122SEaswaran Raman for (const auto &CR : Function.CountedRegions) 609dc707122SEaswaran Raman if (FileIDs.test(CR.FileID)) { 610dc707122SEaswaran Raman Regions.push_back(CR); 611dc707122SEaswaran Raman if (MainFileID && isExpansion(CR, *MainFileID)) 612dc707122SEaswaran Raman FileCoverage.Expansions.emplace_back(CR, Function); 613dc707122SEaswaran Raman } 614dc707122SEaswaran Raman } 615dc707122SEaswaran Raman 616*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n"); 617dc707122SEaswaran Raman FileCoverage.Segments = SegmentBuilder::buildSegments(Regions); 618dc707122SEaswaran Raman 619dc707122SEaswaran Raman return FileCoverage; 620dc707122SEaswaran Raman } 621dc707122SEaswaran Raman 622dde19c5aSVedant Kumar std::vector<InstantiationGroup> 623dde19c5aSVedant Kumar CoverageMapping::getInstantiationGroups(StringRef Filename) const { 624dc707122SEaswaran Raman FunctionInstantiationSetCollector InstantiationSetCollector; 625dc707122SEaswaran Raman for (const auto &Function : Functions) { 626dc707122SEaswaran Raman auto MainFileID = findMainViewFileID(Filename, Function); 627dc707122SEaswaran Raman if (!MainFileID) 628dc707122SEaswaran Raman continue; 629dc707122SEaswaran Raman InstantiationSetCollector.insert(Function, *MainFileID); 630dc707122SEaswaran Raman } 631dc707122SEaswaran Raman 632dde19c5aSVedant Kumar std::vector<InstantiationGroup> Result; 63324cb28bbSBenjamin Kramer for (auto &InstantiationSet : InstantiationSetCollector) { 634dde19c5aSVedant Kumar InstantiationGroup IG{InstantiationSet.first.first, 635dde19c5aSVedant Kumar InstantiationSet.first.second, 636dde19c5aSVedant Kumar std::move(InstantiationSet.second)}; 637dde19c5aSVedant Kumar Result.emplace_back(std::move(IG)); 638dc707122SEaswaran Raman } 639dc707122SEaswaran Raman return Result; 640dc707122SEaswaran Raman } 641dc707122SEaswaran Raman 642dc707122SEaswaran Raman CoverageData 643f681e2e5SVedant Kumar CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const { 644dc707122SEaswaran Raman auto MainFileID = findMainViewFileID(Function); 645dc707122SEaswaran Raman if (!MainFileID) 646dc707122SEaswaran Raman return CoverageData(); 647dc707122SEaswaran Raman 648dc707122SEaswaran Raman CoverageData FunctionCoverage(Function.Filenames[*MainFileID]); 649e78d131aSEugene Zelenko std::vector<CountedRegion> Regions; 650dc707122SEaswaran Raman for (const auto &CR : Function.CountedRegions) 651dc707122SEaswaran Raman if (CR.FileID == *MainFileID) { 652dc707122SEaswaran Raman Regions.push_back(CR); 653dc707122SEaswaran Raman if (isExpansion(CR, *MainFileID)) 654dc707122SEaswaran Raman FunctionCoverage.Expansions.emplace_back(CR, Function); 655dc707122SEaswaran Raman } 656dc707122SEaswaran Raman 657*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name 658*d34e60caSNicola Zaghen << "\n"); 659dc707122SEaswaran Raman FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 660dc707122SEaswaran Raman 661dc707122SEaswaran Raman return FunctionCoverage; 662dc707122SEaswaran Raman } 663dc707122SEaswaran Raman 664f681e2e5SVedant Kumar CoverageData CoverageMapping::getCoverageForExpansion( 665f681e2e5SVedant Kumar const ExpansionRecord &Expansion) const { 666dc707122SEaswaran Raman CoverageData ExpansionCoverage( 667dc707122SEaswaran Raman Expansion.Function.Filenames[Expansion.FileID]); 668e78d131aSEugene Zelenko std::vector<CountedRegion> Regions; 669dc707122SEaswaran Raman for (const auto &CR : Expansion.Function.CountedRegions) 670dc707122SEaswaran Raman if (CR.FileID == Expansion.FileID) { 671dc707122SEaswaran Raman Regions.push_back(CR); 672dc707122SEaswaran Raman if (isExpansion(CR, Expansion.FileID)) 673dc707122SEaswaran Raman ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function); 674dc707122SEaswaran Raman } 675dc707122SEaswaran Raman 676*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file " 677*d34e60caSNicola Zaghen << Expansion.FileID << "\n"); 678dc707122SEaswaran Raman ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 679dc707122SEaswaran Raman 680dc707122SEaswaran Raman return ExpansionCoverage; 681dc707122SEaswaran Raman } 682dc707122SEaswaran Raman 683821160d5SVedant Kumar LineCoverageStats::LineCoverageStats( 684f5f153ddSVedant Kumar ArrayRef<const CoverageSegment *> LineSegments, 685f5f153ddSVedant Kumar const CoverageSegment *WrappedSegment, unsigned Line) 686821160d5SVedant Kumar : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line), 687821160d5SVedant Kumar LineSegments(LineSegments), WrappedSegment(WrappedSegment) { 688821160d5SVedant Kumar // Find the minimum number of regions which start in this line. 689821160d5SVedant Kumar unsigned MinRegionCount = 0; 690f5f153ddSVedant Kumar auto isStartOfRegion = [](const CoverageSegment *S) { 691821160d5SVedant Kumar return !S->IsGapRegion && S->HasCount && S->IsRegionEntry; 692821160d5SVedant Kumar }; 693821160d5SVedant Kumar for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I) 694821160d5SVedant Kumar if (isStartOfRegion(LineSegments[I])) 695821160d5SVedant Kumar ++MinRegionCount; 696821160d5SVedant Kumar 697821160d5SVedant Kumar bool StartOfSkippedRegion = !LineSegments.empty() && 698821160d5SVedant Kumar !LineSegments.front()->HasCount && 699821160d5SVedant Kumar LineSegments.front()->IsRegionEntry; 700821160d5SVedant Kumar 701821160d5SVedant Kumar HasMultipleRegions = MinRegionCount > 1; 702821160d5SVedant Kumar Mapped = 703821160d5SVedant Kumar !StartOfSkippedRegion && 704821160d5SVedant Kumar ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0)); 705821160d5SVedant Kumar 706821160d5SVedant Kumar if (!Mapped) 707821160d5SVedant Kumar return; 708821160d5SVedant Kumar 70943247f05SVedant Kumar // Pick the max count from the non-gap, region entry segments and the 71043247f05SVedant Kumar // wrapped count. 71143247f05SVedant Kumar if (WrappedSegment) 712821160d5SVedant Kumar ExecutionCount = WrappedSegment->Count; 71343247f05SVedant Kumar if (!MinRegionCount) 714821160d5SVedant Kumar return; 715821160d5SVedant Kumar for (const auto *LS : LineSegments) 716821160d5SVedant Kumar if (isStartOfRegion(LS)) 717821160d5SVedant Kumar ExecutionCount = std::max(ExecutionCount, LS->Count); 718821160d5SVedant Kumar } 719821160d5SVedant Kumar 720821160d5SVedant Kumar LineCoverageIterator &LineCoverageIterator::operator++() { 721821160d5SVedant Kumar if (Next == CD.end()) { 722821160d5SVedant Kumar Stats = LineCoverageStats(); 723821160d5SVedant Kumar Ended = true; 724821160d5SVedant Kumar return *this; 725821160d5SVedant Kumar } 726821160d5SVedant Kumar if (Segments.size()) 727821160d5SVedant Kumar WrappedSegment = Segments.back(); 728821160d5SVedant Kumar Segments.clear(); 729821160d5SVedant Kumar while (Next != CD.end() && Next->Line == Line) 730821160d5SVedant Kumar Segments.push_back(&*Next++); 731821160d5SVedant Kumar Stats = LineCoverageStats(Segments, WrappedSegment, Line); 732821160d5SVedant Kumar ++Line; 733821160d5SVedant Kumar return *this; 734821160d5SVedant Kumar } 735821160d5SVedant Kumar 736e78d131aSEugene Zelenko static std::string getCoverageMapErrString(coveragemap_error Err) { 7379152fd17SVedant Kumar switch (Err) { 738dc707122SEaswaran Raman case coveragemap_error::success: 739dc707122SEaswaran Raman return "Success"; 740dc707122SEaswaran Raman case coveragemap_error::eof: 741dc707122SEaswaran Raman return "End of File"; 742dc707122SEaswaran Raman case coveragemap_error::no_data_found: 743dc707122SEaswaran Raman return "No coverage data found"; 744dc707122SEaswaran Raman case coveragemap_error::unsupported_version: 745dc707122SEaswaran Raman return "Unsupported coverage format version"; 746dc707122SEaswaran Raman case coveragemap_error::truncated: 747dc707122SEaswaran Raman return "Truncated coverage data"; 748dc707122SEaswaran Raman case coveragemap_error::malformed: 749dc707122SEaswaran Raman return "Malformed coverage data"; 750dc707122SEaswaran Raman } 751dc707122SEaswaran Raman llvm_unreachable("A value of coveragemap_error has no message."); 752dc707122SEaswaran Raman } 7539152fd17SVedant Kumar 754e78d131aSEugene Zelenko namespace { 755e78d131aSEugene Zelenko 7564718f8b5SPeter Collingbourne // FIXME: This class is only here to support the transition to llvm::Error. It 7574718f8b5SPeter Collingbourne // will be removed once this transition is complete. Clients should prefer to 7584718f8b5SPeter Collingbourne // deal with the Error value directly, rather than converting to error_code. 7599152fd17SVedant Kumar class CoverageMappingErrorCategoryType : public std::error_category { 760990504e6SReid Kleckner const char *name() const noexcept override { return "llvm.coveragemap"; } 7619152fd17SVedant Kumar std::string message(int IE) const override { 7629152fd17SVedant Kumar return getCoverageMapErrString(static_cast<coveragemap_error>(IE)); 7639152fd17SVedant Kumar } 764dc707122SEaswaran Raman }; 765e78d131aSEugene Zelenko 7669152fd17SVedant Kumar } // end anonymous namespace 7679152fd17SVedant Kumar 7689152fd17SVedant Kumar std::string CoverageMapError::message() const { 7699152fd17SVedant Kumar return getCoverageMapErrString(Err); 770dc707122SEaswaran Raman } 771dc707122SEaswaran Raman 772dc707122SEaswaran Raman static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory; 773dc707122SEaswaran Raman 774dc707122SEaswaran Raman const std::error_category &llvm::coverage::coveragemap_category() { 775dc707122SEaswaran Raman return *ErrorCategory; 776dc707122SEaswaran Raman } 7779152fd17SVedant Kumar 7789152fd17SVedant Kumar char CoverageMapError::ID = 0; 779