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.
8671b3d721SVedant Kumar   std::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 
210743574b8SVedant Kumar   // Don't load records for functions we've already seen.
211743574b8SVedant Kumar   if (!FunctionNames.insert(OrigFuncName).second)
212743574b8SVedant Kumar     return Error::success();
213743574b8SVedant Kumar 
214dc707122SEaswaran Raman   CounterMappingContext Ctx(Record.Expressions);
215dc707122SEaswaran Raman 
21668216d7bSVedant Kumar   std::vector<uint64_t> Counts;
21768216d7bSVedant Kumar   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
21868216d7bSVedant Kumar                                                 Record.FunctionHash, Counts)) {
2199152fd17SVedant Kumar     instrprof_error IPE = InstrProfError::take(std::move(E));
2209152fd17SVedant Kumar     if (IPE == instrprof_error::hash_mismatch) {
22118dd9e88SVedant Kumar       FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash);
22268216d7bSVedant Kumar       return Error::success();
2239152fd17SVedant Kumar     } else if (IPE != instrprof_error::unknown_function)
2249152fd17SVedant Kumar       return make_error<InstrProfError>(IPE);
225dc707122SEaswaran Raman     Counts.assign(Record.MappingRegions.size(), 0);
226dc707122SEaswaran Raman   }
227dc707122SEaswaran Raman   Ctx.setCounts(Counts);
228dc707122SEaswaran Raman 
229dc707122SEaswaran Raman   assert(!Record.MappingRegions.empty() && "Function has no regions");
230dc707122SEaswaran Raman 
231dc707122SEaswaran Raman   FunctionRecord Function(OrigFuncName, Record.Filenames);
232dc707122SEaswaran Raman   for (const auto &Region : Record.MappingRegions) {
2339152fd17SVedant Kumar     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
2349152fd17SVedant Kumar     if (auto E = ExecutionCount.takeError()) {
235e78d131aSEugene Zelenko       consumeError(std::move(E));
23668216d7bSVedant Kumar       return Error::success();
2379152fd17SVedant Kumar     }
238dc707122SEaswaran Raman     Function.pushRegion(Region, *ExecutionCount);
239dc707122SEaswaran Raman   }
240dc707122SEaswaran Raman   if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
24118dd9e88SVedant Kumar     FuncCounterMismatches.emplace_back(Record.FunctionName,
24218dd9e88SVedant Kumar                                        Function.CountedRegions.size());
24368216d7bSVedant Kumar     return Error::success();
244dc707122SEaswaran Raman   }
245dc707122SEaswaran Raman 
24668216d7bSVedant Kumar   Functions.push_back(std::move(Function));
24768216d7bSVedant Kumar   return Error::success();
248dc707122SEaswaran Raman }
249dc707122SEaswaran Raman 
250743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
251743574b8SVedant Kumar     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
252743574b8SVedant Kumar     IndexedInstrProfReader &ProfileReader) {
253743574b8SVedant Kumar   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
254743574b8SVedant Kumar 
255bae83970SVedant Kumar   for (const auto &CoverageReader : CoverageReaders) {
256bae83970SVedant Kumar     for (auto RecordOrErr : *CoverageReader) {
257bae83970SVedant Kumar       if (Error E = RecordOrErr.takeError())
258bae83970SVedant Kumar         return std::move(E);
259bae83970SVedant Kumar       const auto &Record = *RecordOrErr;
260743574b8SVedant Kumar       if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
2619152fd17SVedant Kumar         return std::move(E);
262bae83970SVedant Kumar     }
263bae83970SVedant Kumar   }
264743574b8SVedant Kumar 
265743574b8SVedant Kumar   return std::move(Coverage);
266743574b8SVedant Kumar }
267743574b8SVedant Kumar 
268743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>>
269743574b8SVedant Kumar CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
2704b102c3dSVedant Kumar                       StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
271dc707122SEaswaran Raman   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
2729152fd17SVedant Kumar   if (Error E = ProfileReaderOrErr.takeError())
2739152fd17SVedant Kumar     return std::move(E);
274dc707122SEaswaran Raman   auto ProfileReader = std::move(ProfileReaderOrErr.get());
275743574b8SVedant Kumar 
276743574b8SVedant Kumar   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
277743574b8SVedant Kumar   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
2784b102c3dSVedant Kumar   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
2794b102c3dSVedant Kumar     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
280743574b8SVedant Kumar     if (std::error_code EC = CovMappingBufOrErr.getError())
281743574b8SVedant Kumar       return errorCodeToError(EC);
2824b102c3dSVedant Kumar     StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
283743574b8SVedant Kumar     auto CoverageReaderOrErr =
284743574b8SVedant Kumar         BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
285743574b8SVedant Kumar     if (Error E = CoverageReaderOrErr.takeError())
286743574b8SVedant Kumar       return std::move(E);
287743574b8SVedant Kumar     Readers.push_back(std::move(CoverageReaderOrErr.get()));
288743574b8SVedant Kumar     Buffers.push_back(std::move(CovMappingBufOrErr.get()));
289743574b8SVedant Kumar   }
290743574b8SVedant Kumar   return load(Readers, *ProfileReader);
291dc707122SEaswaran Raman }
292dc707122SEaswaran Raman 
293dc707122SEaswaran Raman namespace {
294e78d131aSEugene Zelenko 
295dc707122SEaswaran Raman /// \brief Distributes functions into instantiation sets.
296dc707122SEaswaran Raman ///
297dc707122SEaswaran Raman /// An instantiation set is a collection of functions that have the same source
298dc707122SEaswaran Raman /// code, ie, template functions specializations.
299dc707122SEaswaran Raman class FunctionInstantiationSetCollector {
3007bef6da6SVedant Kumar   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
301dc707122SEaswaran Raman   MapT InstantiatedFunctions;
302dc707122SEaswaran Raman 
303dc707122SEaswaran Raman public:
304dc707122SEaswaran Raman   void insert(const FunctionRecord &Function, unsigned FileID) {
305dc707122SEaswaran Raman     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
306dc707122SEaswaran Raman     while (I != E && I->FileID != FileID)
307dc707122SEaswaran Raman       ++I;
308dc707122SEaswaran Raman     assert(I != E && "function does not cover the given file");
309dc707122SEaswaran Raman     auto &Functions = InstantiatedFunctions[I->startLoc()];
310dc707122SEaswaran Raman     Functions.push_back(&Function);
311dc707122SEaswaran Raman   }
312dc707122SEaswaran Raman 
313dc707122SEaswaran Raman   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
314dc707122SEaswaran Raman   MapT::iterator end() { return InstantiatedFunctions.end(); }
315dc707122SEaswaran Raman };
316dc707122SEaswaran Raman 
317dc707122SEaswaran Raman class SegmentBuilder {
318dc707122SEaswaran Raman   std::vector<CoverageSegment> &Segments;
319dc707122SEaswaran Raman   SmallVector<const CountedRegion *, 8> ActiveRegions;
320dc707122SEaswaran Raman 
321dc707122SEaswaran Raman   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
322dc707122SEaswaran Raman 
32379a1b5eeSVedant Kumar   /// Emit a segment with the count from \p Region starting at \p StartLoc.
32479a1b5eeSVedant Kumar   //
325ad8f637bSVedant Kumar   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
32679a1b5eeSVedant Kumar   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
32779a1b5eeSVedant Kumar   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
32879a1b5eeSVedant Kumar                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
32979a1b5eeSVedant Kumar     bool HasCount = !EmitSkippedRegion &&
33079a1b5eeSVedant Kumar                     (Region.Kind != CounterMappingRegion::SkippedRegion);
33179a1b5eeSVedant Kumar 
33279a1b5eeSVedant Kumar     // If the new segment wouldn't affect coverage rendering, skip it.
33379a1b5eeSVedant Kumar     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
33479a1b5eeSVedant Kumar       const auto &Last = Segments.back();
33579a1b5eeSVedant Kumar       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
33679a1b5eeSVedant Kumar           !Last.IsRegionEntry)
33779a1b5eeSVedant Kumar         return;
338dc707122SEaswaran Raman     }
339dc707122SEaswaran Raman 
34079a1b5eeSVedant Kumar     if (HasCount)
34179a1b5eeSVedant Kumar       Segments.emplace_back(StartLoc.first, StartLoc.second,
342ad8f637bSVedant Kumar                             Region.ExecutionCount, IsRegionEntry,
343ad8f637bSVedant Kumar                             Region.Kind == CounterMappingRegion::GapRegion);
344dc707122SEaswaran Raman     else
34579a1b5eeSVedant Kumar       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
34679a1b5eeSVedant Kumar 
34779a1b5eeSVedant Kumar     DEBUG({
34879a1b5eeSVedant Kumar       const auto &Last = Segments.back();
34979a1b5eeSVedant Kumar       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
35079a1b5eeSVedant Kumar              << " (count = " << Last.Count << ")"
35179a1b5eeSVedant Kumar              << (Last.IsRegionEntry ? ", RegionEntry" : "")
352ad8f637bSVedant Kumar              << (!Last.HasCount ? ", Skipped" : "")
353ad8f637bSVedant Kumar              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
35479a1b5eeSVedant Kumar     });
35579a1b5eeSVedant Kumar   }
35679a1b5eeSVedant Kumar 
35779a1b5eeSVedant Kumar   /// Emit segments for active regions which end before \p Loc.
35879a1b5eeSVedant Kumar   ///
35979a1b5eeSVedant Kumar   /// \p Loc: The start location of the next region. If None, all active
36079a1b5eeSVedant Kumar   /// regions are completed.
36179a1b5eeSVedant Kumar   /// \p FirstCompletedRegion: Index of the first completed region.
36279a1b5eeSVedant Kumar   void completeRegionsUntil(Optional<LineColPair> Loc,
36379a1b5eeSVedant Kumar                             unsigned FirstCompletedRegion) {
36479a1b5eeSVedant Kumar     // Sort the completed regions by end location. This makes it simple to
36579a1b5eeSVedant Kumar     // emit closing segments in sorted order.
36679a1b5eeSVedant Kumar     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
36779a1b5eeSVedant Kumar     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
36879a1b5eeSVedant Kumar                       [](const CountedRegion *L, const CountedRegion *R) {
36979a1b5eeSVedant Kumar                         return L->endLoc() < R->endLoc();
37079a1b5eeSVedant Kumar                       });
37179a1b5eeSVedant Kumar 
37279a1b5eeSVedant Kumar     // Emit segments for all completed regions.
37379a1b5eeSVedant Kumar     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
37479a1b5eeSVedant Kumar          ++I) {
37579a1b5eeSVedant Kumar       const auto *CompletedRegion = ActiveRegions[I];
37679a1b5eeSVedant Kumar       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
37779a1b5eeSVedant Kumar              "Completed region ends after start of new region");
37879a1b5eeSVedant Kumar 
37979a1b5eeSVedant Kumar       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
38079a1b5eeSVedant Kumar       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
38179a1b5eeSVedant Kumar 
38279a1b5eeSVedant Kumar       // Don't emit any more segments if they start where the new region begins.
38379a1b5eeSVedant Kumar       if (Loc && CompletedSegmentLoc == *Loc)
38479a1b5eeSVedant Kumar         break;
38579a1b5eeSVedant Kumar 
38679a1b5eeSVedant Kumar       // Don't emit a segment if the next completed region ends at the same
38779a1b5eeSVedant Kumar       // location as this one.
38879a1b5eeSVedant Kumar       if (CompletedSegmentLoc == CompletedRegion->endLoc())
38979a1b5eeSVedant Kumar         continue;
39079a1b5eeSVedant Kumar 
391*80fbb855SVedant Kumar       // Use the count from the next completed region if it ends at the same
392*80fbb855SVedant Kumar       // location.
393*80fbb855SVedant Kumar       if (I + 1 < E &&
394*80fbb855SVedant Kumar           CompletedRegion->endLoc() == ActiveRegions[I + 1]->endLoc())
395*80fbb855SVedant Kumar         CompletedRegion = ActiveRegions[I + 1];
396*80fbb855SVedant Kumar 
39779a1b5eeSVedant Kumar       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
39879a1b5eeSVedant Kumar     }
39979a1b5eeSVedant Kumar 
40079a1b5eeSVedant Kumar     auto Last = ActiveRegions.back();
40179a1b5eeSVedant Kumar     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
40279a1b5eeSVedant Kumar       // If there's a gap after the end of the last completed region and the
40379a1b5eeSVedant Kumar       // start of the new region, use the last active region to fill the gap.
40479a1b5eeSVedant Kumar       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
40579a1b5eeSVedant Kumar                    false);
40679a1b5eeSVedant Kumar     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
40779a1b5eeSVedant Kumar       // Emit a skipped segment if there are no more active regions. This
40879a1b5eeSVedant Kumar       // ensures that gaps between functions are marked correctly.
40979a1b5eeSVedant Kumar       startSegment(*Last, Last->endLoc(), false, true);
41079a1b5eeSVedant Kumar     }
41179a1b5eeSVedant Kumar 
41279a1b5eeSVedant Kumar     // Pop the completed regions.
41379a1b5eeSVedant Kumar     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
414dc707122SEaswaran Raman   }
415dc707122SEaswaran Raman 
416dc707122SEaswaran Raman   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
41779a1b5eeSVedant Kumar     for (const auto &CR : enumerate(Regions)) {
41879a1b5eeSVedant Kumar       auto CurStartLoc = CR.value().startLoc();
41979a1b5eeSVedant Kumar 
42079a1b5eeSVedant Kumar       // Active regions which end before the current region need to be popped.
42179a1b5eeSVedant Kumar       auto CompletedRegions =
42279a1b5eeSVedant Kumar           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
42379a1b5eeSVedant Kumar                                 [&](const CountedRegion *Region) {
42479a1b5eeSVedant Kumar                                   return !(Region->endLoc() <= CurStartLoc);
42579a1b5eeSVedant Kumar                                 });
42679a1b5eeSVedant Kumar       if (CompletedRegions != ActiveRegions.end()) {
42779a1b5eeSVedant Kumar         unsigned FirstCompletedRegion =
42879a1b5eeSVedant Kumar             std::distance(ActiveRegions.begin(), CompletedRegions);
42979a1b5eeSVedant Kumar         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
430dc707122SEaswaran Raman       }
43179a1b5eeSVedant Kumar 
432ad8f637bSVedant Kumar       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
433ad8f637bSVedant Kumar 
43479a1b5eeSVedant Kumar       // Try to emit a segment for the current region.
43579a1b5eeSVedant Kumar       if (CurStartLoc == CR.value().endLoc()) {
43679a1b5eeSVedant Kumar         // Avoid making zero-length regions active. If it's the last region,
43779a1b5eeSVedant Kumar         // emit a skipped segment. Otherwise use its predecessor's count.
43879a1b5eeSVedant Kumar         const bool Skipped = (CR.index() + 1) == Regions.size();
43979a1b5eeSVedant Kumar         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
440ad8f637bSVedant Kumar                      CurStartLoc, !GapRegion, Skipped);
44179a1b5eeSVedant Kumar         continue;
44279a1b5eeSVedant Kumar       }
44379a1b5eeSVedant Kumar       if (CR.index() + 1 == Regions.size() ||
44479a1b5eeSVedant Kumar           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
44579a1b5eeSVedant Kumar         // Emit a segment if the next region doesn't start at the same location
44679a1b5eeSVedant Kumar         // as this one.
447ad8f637bSVedant Kumar         startSegment(CR.value(), CurStartLoc, !GapRegion);
44879a1b5eeSVedant Kumar       }
44979a1b5eeSVedant Kumar 
45079a1b5eeSVedant Kumar       // This region is active (i.e not completed).
45179a1b5eeSVedant Kumar       ActiveRegions.push_back(&CR.value());
45279a1b5eeSVedant Kumar     }
45379a1b5eeSVedant Kumar 
45479a1b5eeSVedant Kumar     // Complete any remaining active regions.
45579a1b5eeSVedant Kumar     if (!ActiveRegions.empty())
45679a1b5eeSVedant Kumar       completeRegionsUntil(None, 0);
457dc707122SEaswaran Raman   }
458dc707122SEaswaran Raman 
459dc707122SEaswaran Raman   /// Sort a nested sequence of regions from a single file.
460dc707122SEaswaran Raman   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
46127d8dd39SIgor Kudrin     std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
46227d8dd39SIgor Kudrin                                                  const CountedRegion &RHS) {
46327d8dd39SIgor Kudrin       if (LHS.startLoc() != RHS.startLoc())
46427d8dd39SIgor Kudrin         return LHS.startLoc() < RHS.startLoc();
46527d8dd39SIgor Kudrin       if (LHS.endLoc() != RHS.endLoc())
466dc707122SEaswaran Raman         // When LHS completely contains RHS, we sort LHS first.
467dc707122SEaswaran Raman         return RHS.endLoc() < LHS.endLoc();
46827d8dd39SIgor Kudrin       // If LHS and RHS cover the same area, we need to sort them according
46927d8dd39SIgor Kudrin       // to their kinds so that the most suitable region will become "active"
47027d8dd39SIgor Kudrin       // in combineRegions(). Because we accumulate counter values only from
47127d8dd39SIgor Kudrin       // regions of the same kind as the first region of the area, prefer
47227d8dd39SIgor Kudrin       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
473e78d131aSEugene Zelenko       static_assert(CounterMappingRegion::CodeRegion <
474e78d131aSEugene Zelenko                             CounterMappingRegion::ExpansionRegion &&
475e78d131aSEugene Zelenko                         CounterMappingRegion::ExpansionRegion <
476e78d131aSEugene Zelenko                             CounterMappingRegion::SkippedRegion,
47727d8dd39SIgor Kudrin                     "Unexpected order of region kind values");
47827d8dd39SIgor Kudrin       return LHS.Kind < RHS.Kind;
479dc707122SEaswaran Raman     });
480dc707122SEaswaran Raman   }
481dc707122SEaswaran Raman 
482dc707122SEaswaran Raman   /// Combine counts of regions which cover the same area.
483dc707122SEaswaran Raman   static ArrayRef<CountedRegion>
484dc707122SEaswaran Raman   combineRegions(MutableArrayRef<CountedRegion> Regions) {
485dc707122SEaswaran Raman     if (Regions.empty())
486dc707122SEaswaran Raman       return Regions;
487dc707122SEaswaran Raman     auto Active = Regions.begin();
488dc707122SEaswaran Raman     auto End = Regions.end();
489dc707122SEaswaran Raman     for (auto I = Regions.begin() + 1; I != End; ++I) {
490dc707122SEaswaran Raman       if (Active->startLoc() != I->startLoc() ||
491dc707122SEaswaran Raman           Active->endLoc() != I->endLoc()) {
492dc707122SEaswaran Raman         // Shift to the next region.
493dc707122SEaswaran Raman         ++Active;
494dc707122SEaswaran Raman         if (Active != I)
495dc707122SEaswaran Raman           *Active = *I;
496dc707122SEaswaran Raman         continue;
497dc707122SEaswaran Raman       }
498dc707122SEaswaran Raman       // Merge duplicate region.
49927d8dd39SIgor Kudrin       // If CodeRegions and ExpansionRegions cover the same area, it's probably
50027d8dd39SIgor Kudrin       // a macro which is fully expanded to another macro. In that case, we need
50127d8dd39SIgor Kudrin       // to accumulate counts only from CodeRegions, or else the area will be
50227d8dd39SIgor Kudrin       // counted twice.
50327d8dd39SIgor Kudrin       // On the other hand, a macro may have a nested macro in its body. If the
50427d8dd39SIgor Kudrin       // outer macro is used several times, the ExpansionRegion for the nested
50527d8dd39SIgor Kudrin       // macro will also be added several times. These ExpansionRegions cover
50627d8dd39SIgor Kudrin       // the same source locations and have to be combined to reach the correct
50727d8dd39SIgor Kudrin       // value for that area.
50827d8dd39SIgor Kudrin       // We add counts of the regions of the same kind as the active region
50927d8dd39SIgor Kudrin       // to handle the both situations.
51027d8dd39SIgor Kudrin       if (I->Kind == Active->Kind)
511dc707122SEaswaran Raman         Active->ExecutionCount += I->ExecutionCount;
512dc707122SEaswaran Raman     }
513dc707122SEaswaran Raman     return Regions.drop_back(std::distance(++Active, End));
514dc707122SEaswaran Raman   }
515dc707122SEaswaran Raman 
516dc707122SEaswaran Raman public:
51779a1b5eeSVedant Kumar   /// Build a sorted list of CoverageSegments from a list of Regions.
518dc707122SEaswaran Raman   static std::vector<CoverageSegment>
519dc707122SEaswaran Raman   buildSegments(MutableArrayRef<CountedRegion> Regions) {
520dc707122SEaswaran Raman     std::vector<CoverageSegment> Segments;
521dc707122SEaswaran Raman     SegmentBuilder Builder(Segments);
522dc707122SEaswaran Raman 
523dc707122SEaswaran Raman     sortNestedRegions(Regions);
524dc707122SEaswaran Raman     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
525dc707122SEaswaran Raman 
52679a1b5eeSVedant Kumar     DEBUG({
52779a1b5eeSVedant Kumar       dbgs() << "Combined regions:\n";
52879a1b5eeSVedant Kumar       for (const auto &CR : CombinedRegions)
52979a1b5eeSVedant Kumar         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
53079a1b5eeSVedant Kumar                << CR.LineEnd << ":" << CR.ColumnEnd
53179a1b5eeSVedant Kumar                << " (count=" << CR.ExecutionCount << ")\n";
53279a1b5eeSVedant Kumar     });
53379a1b5eeSVedant Kumar 
534dc707122SEaswaran Raman     Builder.buildSegmentsImpl(CombinedRegions);
53579a1b5eeSVedant Kumar 
53679a1b5eeSVedant Kumar #ifndef NDEBUG
53779a1b5eeSVedant Kumar     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
53879a1b5eeSVedant Kumar       const auto &L = Segments[I - 1];
53979a1b5eeSVedant Kumar       const auto &R = Segments[I];
54079a1b5eeSVedant Kumar       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
54179a1b5eeSVedant Kumar         DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
54279a1b5eeSVedant Kumar                      << " followed by " << R.Line << ":" << R.Col << "\n");
54379a1b5eeSVedant Kumar         assert(false && "Coverage segments not unique or sorted");
54479a1b5eeSVedant Kumar       }
54579a1b5eeSVedant Kumar     }
54679a1b5eeSVedant Kumar #endif
54779a1b5eeSVedant Kumar 
548dc707122SEaswaran Raman     return Segments;
549dc707122SEaswaran Raman   }
550dc707122SEaswaran Raman };
551e78d131aSEugene Zelenko 
552e78d131aSEugene Zelenko } // end anonymous namespace
553dc707122SEaswaran Raman 
554dc707122SEaswaran Raman std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
555dc707122SEaswaran Raman   std::vector<StringRef> Filenames;
556dc707122SEaswaran Raman   for (const auto &Function : getCoveredFunctions())
557dc707122SEaswaran Raman     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
558dc707122SEaswaran Raman                      Function.Filenames.end());
559dc707122SEaswaran Raman   std::sort(Filenames.begin(), Filenames.end());
560dc707122SEaswaran Raman   auto Last = std::unique(Filenames.begin(), Filenames.end());
561dc707122SEaswaran Raman   Filenames.erase(Last, Filenames.end());
562dc707122SEaswaran Raman   return Filenames;
563dc707122SEaswaran Raman }
564dc707122SEaswaran Raman 
565dc707122SEaswaran Raman static SmallBitVector gatherFileIDs(StringRef SourceFile,
566dc707122SEaswaran Raman                                     const FunctionRecord &Function) {
567dc707122SEaswaran Raman   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
568dc707122SEaswaran Raman   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
569dc707122SEaswaran Raman     if (SourceFile == Function.Filenames[I])
570dc707122SEaswaran Raman       FilenameEquivalence[I] = true;
571dc707122SEaswaran Raman   return FilenameEquivalence;
572dc707122SEaswaran Raman }
573dc707122SEaswaran Raman 
574dc707122SEaswaran Raman /// Return the ID of the file where the definition of the function is located.
575dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
576dc707122SEaswaran Raman   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
577dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
578dc707122SEaswaran Raman     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
579dc707122SEaswaran Raman       IsNotExpandedFile[CR.ExpandedFileID] = false;
580dc707122SEaswaran Raman   int I = IsNotExpandedFile.find_first();
581dc707122SEaswaran Raman   if (I == -1)
582dc707122SEaswaran Raman     return None;
583dc707122SEaswaran Raman   return I;
584dc707122SEaswaran Raman }
585dc707122SEaswaran Raman 
586dc707122SEaswaran Raman /// Check if SourceFile is the file that contains the definition of
587dc707122SEaswaran Raman /// the Function. Return the ID of the file in that case or None otherwise.
588dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
589dc707122SEaswaran Raman                                              const FunctionRecord &Function) {
590dc707122SEaswaran Raman   Optional<unsigned> I = findMainViewFileID(Function);
591dc707122SEaswaran Raman   if (I && SourceFile == Function.Filenames[*I])
592dc707122SEaswaran Raman     return I;
593dc707122SEaswaran Raman   return None;
594dc707122SEaswaran Raman }
595dc707122SEaswaran Raman 
596dc707122SEaswaran Raman static bool isExpansion(const CountedRegion &R, unsigned FileID) {
597dc707122SEaswaran Raman   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
598dc707122SEaswaran Raman }
599dc707122SEaswaran Raman 
6007fcc5472SVedant Kumar CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
601dc707122SEaswaran Raman   CoverageData FileCoverage(Filename);
602e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
603dc707122SEaswaran Raman 
604dc707122SEaswaran Raman   for (const auto &Function : Functions) {
605dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
606dc707122SEaswaran Raman     auto FileIDs = gatherFileIDs(Filename, Function);
607dc707122SEaswaran Raman     for (const auto &CR : Function.CountedRegions)
608dc707122SEaswaran Raman       if (FileIDs.test(CR.FileID)) {
609dc707122SEaswaran Raman         Regions.push_back(CR);
610dc707122SEaswaran Raman         if (MainFileID && isExpansion(CR, *MainFileID))
611dc707122SEaswaran Raman           FileCoverage.Expansions.emplace_back(CR, Function);
612dc707122SEaswaran Raman       }
613dc707122SEaswaran Raman   }
614dc707122SEaswaran Raman 
615dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
616dc707122SEaswaran Raman   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
617dc707122SEaswaran Raman 
618dc707122SEaswaran Raman   return FileCoverage;
619dc707122SEaswaran Raman }
620dc707122SEaswaran Raman 
621dde19c5aSVedant Kumar std::vector<InstantiationGroup>
622dde19c5aSVedant Kumar CoverageMapping::getInstantiationGroups(StringRef Filename) const {
623dc707122SEaswaran Raman   FunctionInstantiationSetCollector InstantiationSetCollector;
624dc707122SEaswaran Raman   for (const auto &Function : Functions) {
625dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
626dc707122SEaswaran Raman     if (!MainFileID)
627dc707122SEaswaran Raman       continue;
628dc707122SEaswaran Raman     InstantiationSetCollector.insert(Function, *MainFileID);
629dc707122SEaswaran Raman   }
630dc707122SEaswaran Raman 
631dde19c5aSVedant Kumar   std::vector<InstantiationGroup> Result;
632dc707122SEaswaran Raman   for (const auto &InstantiationSet : InstantiationSetCollector) {
633dde19c5aSVedant Kumar     InstantiationGroup IG{InstantiationSet.first.first,
634dde19c5aSVedant Kumar                           InstantiationSet.first.second,
635dde19c5aSVedant Kumar                           std::move(InstantiationSet.second)};
636dde19c5aSVedant Kumar     Result.emplace_back(std::move(IG));
637dc707122SEaswaran Raman   }
638dc707122SEaswaran Raman   return Result;
639dc707122SEaswaran Raman }
640dc707122SEaswaran Raman 
641dc707122SEaswaran Raman CoverageData
642f681e2e5SVedant Kumar CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
643dc707122SEaswaran Raman   auto MainFileID = findMainViewFileID(Function);
644dc707122SEaswaran Raman   if (!MainFileID)
645dc707122SEaswaran Raman     return CoverageData();
646dc707122SEaswaran Raman 
647dc707122SEaswaran Raman   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
648e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
649dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
650dc707122SEaswaran Raman     if (CR.FileID == *MainFileID) {
651dc707122SEaswaran Raman       Regions.push_back(CR);
652dc707122SEaswaran Raman       if (isExpansion(CR, *MainFileID))
653dc707122SEaswaran Raman         FunctionCoverage.Expansions.emplace_back(CR, Function);
654dc707122SEaswaran Raman     }
655dc707122SEaswaran Raman 
656dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
657dc707122SEaswaran Raman   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
658dc707122SEaswaran Raman 
659dc707122SEaswaran Raman   return FunctionCoverage;
660dc707122SEaswaran Raman }
661dc707122SEaswaran Raman 
662f681e2e5SVedant Kumar CoverageData CoverageMapping::getCoverageForExpansion(
663f681e2e5SVedant Kumar     const ExpansionRecord &Expansion) const {
664dc707122SEaswaran Raman   CoverageData ExpansionCoverage(
665dc707122SEaswaran Raman       Expansion.Function.Filenames[Expansion.FileID]);
666e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
667dc707122SEaswaran Raman   for (const auto &CR : Expansion.Function.CountedRegions)
668dc707122SEaswaran Raman     if (CR.FileID == Expansion.FileID) {
669dc707122SEaswaran Raman       Regions.push_back(CR);
670dc707122SEaswaran Raman       if (isExpansion(CR, Expansion.FileID))
671dc707122SEaswaran Raman         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
672dc707122SEaswaran Raman     }
673dc707122SEaswaran Raman 
674dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
675dc707122SEaswaran Raman                << "\n");
676dc707122SEaswaran Raman   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
677dc707122SEaswaran Raman 
678dc707122SEaswaran Raman   return ExpansionCoverage;
679dc707122SEaswaran Raman }
680dc707122SEaswaran Raman 
681821160d5SVedant Kumar LineCoverageStats::LineCoverageStats(
682f5f153ddSVedant Kumar     ArrayRef<const CoverageSegment *> LineSegments,
683f5f153ddSVedant Kumar     const CoverageSegment *WrappedSegment, unsigned Line)
684821160d5SVedant Kumar     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
685821160d5SVedant Kumar       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
686821160d5SVedant Kumar   // Find the minimum number of regions which start in this line.
687821160d5SVedant Kumar   unsigned MinRegionCount = 0;
688f5f153ddSVedant Kumar   auto isStartOfRegion = [](const CoverageSegment *S) {
689821160d5SVedant Kumar     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
690821160d5SVedant Kumar   };
691821160d5SVedant Kumar   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
692821160d5SVedant Kumar     if (isStartOfRegion(LineSegments[I]))
693821160d5SVedant Kumar       ++MinRegionCount;
694821160d5SVedant Kumar 
695821160d5SVedant Kumar   bool StartOfSkippedRegion = !LineSegments.empty() &&
696821160d5SVedant Kumar                               !LineSegments.front()->HasCount &&
697821160d5SVedant Kumar                               LineSegments.front()->IsRegionEntry;
698821160d5SVedant Kumar 
699821160d5SVedant Kumar   HasMultipleRegions = MinRegionCount > 1;
700821160d5SVedant Kumar   Mapped =
701821160d5SVedant Kumar       !StartOfSkippedRegion &&
702821160d5SVedant Kumar       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
703821160d5SVedant Kumar 
704821160d5SVedant Kumar   if (!Mapped)
705821160d5SVedant Kumar     return;
706821160d5SVedant Kumar 
70743247f05SVedant Kumar   // Pick the max count from the non-gap, region entry segments and the
70843247f05SVedant Kumar   // wrapped count.
70943247f05SVedant Kumar   if (WrappedSegment)
710821160d5SVedant Kumar     ExecutionCount = WrappedSegment->Count;
71143247f05SVedant Kumar   if (!MinRegionCount)
712821160d5SVedant Kumar     return;
713821160d5SVedant Kumar   for (const auto *LS : LineSegments)
714821160d5SVedant Kumar     if (isStartOfRegion(LS))
715821160d5SVedant Kumar       ExecutionCount = std::max(ExecutionCount, LS->Count);
716821160d5SVedant Kumar }
717821160d5SVedant Kumar 
718821160d5SVedant Kumar LineCoverageIterator &LineCoverageIterator::operator++() {
719821160d5SVedant Kumar   if (Next == CD.end()) {
720821160d5SVedant Kumar     Stats = LineCoverageStats();
721821160d5SVedant Kumar     Ended = true;
722821160d5SVedant Kumar     return *this;
723821160d5SVedant Kumar   }
724821160d5SVedant Kumar   if (Segments.size())
725821160d5SVedant Kumar     WrappedSegment = Segments.back();
726821160d5SVedant Kumar   Segments.clear();
727821160d5SVedant Kumar   while (Next != CD.end() && Next->Line == Line)
728821160d5SVedant Kumar     Segments.push_back(&*Next++);
729821160d5SVedant Kumar   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
730821160d5SVedant Kumar   ++Line;
731821160d5SVedant Kumar   return *this;
732821160d5SVedant Kumar }
733821160d5SVedant Kumar 
734e78d131aSEugene Zelenko static std::string getCoverageMapErrString(coveragemap_error Err) {
7359152fd17SVedant Kumar   switch (Err) {
736dc707122SEaswaran Raman   case coveragemap_error::success:
737dc707122SEaswaran Raman     return "Success";
738dc707122SEaswaran Raman   case coveragemap_error::eof:
739dc707122SEaswaran Raman     return "End of File";
740dc707122SEaswaran Raman   case coveragemap_error::no_data_found:
741dc707122SEaswaran Raman     return "No coverage data found";
742dc707122SEaswaran Raman   case coveragemap_error::unsupported_version:
743dc707122SEaswaran Raman     return "Unsupported coverage format version";
744dc707122SEaswaran Raman   case coveragemap_error::truncated:
745dc707122SEaswaran Raman     return "Truncated coverage data";
746dc707122SEaswaran Raman   case coveragemap_error::malformed:
747dc707122SEaswaran Raman     return "Malformed coverage data";
748dc707122SEaswaran Raman   }
749dc707122SEaswaran Raman   llvm_unreachable("A value of coveragemap_error has no message.");
750dc707122SEaswaran Raman }
7519152fd17SVedant Kumar 
752e78d131aSEugene Zelenko namespace {
753e78d131aSEugene Zelenko 
7544718f8b5SPeter Collingbourne // FIXME: This class is only here to support the transition to llvm::Error. It
7554718f8b5SPeter Collingbourne // will be removed once this transition is complete. Clients should prefer to
7564718f8b5SPeter Collingbourne // deal with the Error value directly, rather than converting to error_code.
7579152fd17SVedant Kumar class CoverageMappingErrorCategoryType : public std::error_category {
758990504e6SReid Kleckner   const char *name() const noexcept override { return "llvm.coveragemap"; }
7599152fd17SVedant Kumar   std::string message(int IE) const override {
7609152fd17SVedant Kumar     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
7619152fd17SVedant Kumar   }
762dc707122SEaswaran Raman };
763e78d131aSEugene Zelenko 
7649152fd17SVedant Kumar } // end anonymous namespace
7659152fd17SVedant Kumar 
7669152fd17SVedant Kumar std::string CoverageMapError::message() const {
7679152fd17SVedant Kumar   return getCoverageMapErrString(Err);
768dc707122SEaswaran Raman }
769dc707122SEaswaran Raman 
770dc707122SEaswaran Raman static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
771dc707122SEaswaran Raman 
772dc707122SEaswaran Raman const std::error_category &llvm::coverage::coveragemap_category() {
773dc707122SEaswaran Raman   return *ErrorCategory;
774dc707122SEaswaran Raman }
7759152fd17SVedant Kumar 
7769152fd17SVedant Kumar char CoverageMapError::ID = 0;
777