1e78d131aSEugene Zelenko //===- CoverageMapping.cpp - Code coverage mapping support ------*- C++ -*-===//
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>
36e78d131aSEugene Zelenko #include <memory>
37e78d131aSEugene Zelenko #include <string>
38e78d131aSEugene Zelenko #include <system_error>
39e78d131aSEugene Zelenko #include <utility>
40e78d131aSEugene Zelenko #include <vector>
41dc707122SEaswaran Raman 
42dc707122SEaswaran Raman using namespace llvm;
43dc707122SEaswaran Raman using namespace coverage;
44dc707122SEaswaran Raman 
45dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping"
46dc707122SEaswaran Raman 
47dc707122SEaswaran Raman Counter CounterExpressionBuilder::get(const CounterExpression &E) {
48dc707122SEaswaran Raman   auto It = ExpressionIndices.find(E);
49dc707122SEaswaran Raman   if (It != ExpressionIndices.end())
50dc707122SEaswaran Raman     return Counter::getExpression(It->second);
51dc707122SEaswaran Raman   unsigned I = Expressions.size();
52dc707122SEaswaran Raman   Expressions.push_back(E);
53dc707122SEaswaran Raman   ExpressionIndices[E] = I;
54dc707122SEaswaran Raman   return Counter::getExpression(I);
55dc707122SEaswaran Raman }
56dc707122SEaswaran Raman 
57dc707122SEaswaran Raman void CounterExpressionBuilder::extractTerms(
58dc707122SEaswaran Raman     Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
59dc707122SEaswaran Raman   switch (C.getKind()) {
60dc707122SEaswaran Raman   case Counter::Zero:
61dc707122SEaswaran Raman     break;
62dc707122SEaswaran Raman   case Counter::CounterValueReference:
63dc707122SEaswaran Raman     Terms.push_back(std::make_pair(C.getCounterID(), Sign));
64dc707122SEaswaran Raman     break;
65dc707122SEaswaran Raman   case Counter::Expression:
66dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
67dc707122SEaswaran Raman     extractTerms(E.LHS, Sign, Terms);
68dc707122SEaswaran Raman     extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
69dc707122SEaswaran Raman                  Terms);
70dc707122SEaswaran Raman     break;
71dc707122SEaswaran Raman   }
72dc707122SEaswaran Raman }
73dc707122SEaswaran Raman 
74dc707122SEaswaran Raman Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
75dc707122SEaswaran Raman   // Gather constant terms.
76e78d131aSEugene Zelenko   SmallVector<std::pair<unsigned, int>, 32> Terms;
77dc707122SEaswaran Raman   extractTerms(ExpressionTree, +1, Terms);
78dc707122SEaswaran Raman 
79dc707122SEaswaran Raman   // If there are no terms, this is just a zero. The algorithm below assumes at
80dc707122SEaswaran Raman   // least one term.
81dc707122SEaswaran Raman   if (Terms.size() == 0)
82dc707122SEaswaran Raman     return Counter::getZero();
83dc707122SEaswaran Raman 
84dc707122SEaswaran Raman   // Group the terms by counter ID.
85dc707122SEaswaran Raman   std::sort(Terms.begin(), Terms.end(),
86dc707122SEaswaran Raman             [](const std::pair<unsigned, int> &LHS,
87dc707122SEaswaran Raman                const std::pair<unsigned, int> &RHS) {
88dc707122SEaswaran Raman     return LHS.first < RHS.first;
89dc707122SEaswaran Raman   });
90dc707122SEaswaran Raman 
91dc707122SEaswaran Raman   // Combine terms by counter ID to eliminate counters that sum to zero.
92dc707122SEaswaran Raman   auto Prev = Terms.begin();
93dc707122SEaswaran Raman   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
94dc707122SEaswaran Raman     if (I->first == Prev->first) {
95dc707122SEaswaran Raman       Prev->second += I->second;
96dc707122SEaswaran Raman       continue;
97dc707122SEaswaran Raman     }
98dc707122SEaswaran Raman     ++Prev;
99dc707122SEaswaran Raman     *Prev = *I;
100dc707122SEaswaran Raman   }
101dc707122SEaswaran Raman   Terms.erase(++Prev, Terms.end());
102dc707122SEaswaran Raman 
103dc707122SEaswaran Raman   Counter C;
104dc707122SEaswaran Raman   // Create additions. We do this before subtractions to avoid constructs like
105dc707122SEaswaran Raman   // ((0 - X) + Y), as opposed to (Y - X).
106dc707122SEaswaran Raman   for (auto Term : Terms) {
107dc707122SEaswaran Raman     if (Term.second <= 0)
108dc707122SEaswaran Raman       continue;
109dc707122SEaswaran Raman     for (int I = 0; I < Term.second; ++I)
110dc707122SEaswaran Raman       if (C.isZero())
111dc707122SEaswaran Raman         C = Counter::getCounter(Term.first);
112dc707122SEaswaran Raman       else
113dc707122SEaswaran Raman         C = get(CounterExpression(CounterExpression::Add, C,
114dc707122SEaswaran Raman                                   Counter::getCounter(Term.first)));
115dc707122SEaswaran Raman   }
116dc707122SEaswaran Raman 
117dc707122SEaswaran Raman   // Create subtractions.
118dc707122SEaswaran Raman   for (auto Term : Terms) {
119dc707122SEaswaran Raman     if (Term.second >= 0)
120dc707122SEaswaran Raman       continue;
121dc707122SEaswaran Raman     for (int I = 0; I < -Term.second; ++I)
122dc707122SEaswaran Raman       C = get(CounterExpression(CounterExpression::Subtract, C,
123dc707122SEaswaran Raman                                 Counter::getCounter(Term.first)));
124dc707122SEaswaran Raman   }
125dc707122SEaswaran Raman   return C;
126dc707122SEaswaran Raman }
127dc707122SEaswaran Raman 
128dc707122SEaswaran Raman Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
129dc707122SEaswaran Raman   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
130dc707122SEaswaran Raman }
131dc707122SEaswaran Raman 
132dc707122SEaswaran Raman Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
133dc707122SEaswaran Raman   return simplify(
134dc707122SEaswaran Raman       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
135dc707122SEaswaran Raman }
136dc707122SEaswaran Raman 
137e78d131aSEugene Zelenko void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
138dc707122SEaswaran Raman   switch (C.getKind()) {
139dc707122SEaswaran Raman   case Counter::Zero:
140dc707122SEaswaran Raman     OS << '0';
141dc707122SEaswaran Raman     return;
142dc707122SEaswaran Raman   case Counter::CounterValueReference:
143dc707122SEaswaran Raman     OS << '#' << C.getCounterID();
144dc707122SEaswaran Raman     break;
145dc707122SEaswaran Raman   case Counter::Expression: {
146dc707122SEaswaran Raman     if (C.getExpressionID() >= Expressions.size())
147dc707122SEaswaran Raman       return;
148dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
149dc707122SEaswaran Raman     OS << '(';
150dc707122SEaswaran Raman     dump(E.LHS, OS);
151dc707122SEaswaran Raman     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
152dc707122SEaswaran Raman     dump(E.RHS, OS);
153dc707122SEaswaran Raman     OS << ')';
154dc707122SEaswaran Raman     break;
155dc707122SEaswaran Raman   }
156dc707122SEaswaran Raman   }
157dc707122SEaswaran Raman   if (CounterValues.empty())
158dc707122SEaswaran Raman     return;
1599152fd17SVedant Kumar   Expected<int64_t> Value = evaluate(C);
1609152fd17SVedant Kumar   if (auto E = Value.takeError()) {
161e78d131aSEugene Zelenko     consumeError(std::move(E));
162dc707122SEaswaran Raman     return;
1639152fd17SVedant Kumar   }
164dc707122SEaswaran Raman   OS << '[' << *Value << ']';
165dc707122SEaswaran Raman }
166dc707122SEaswaran Raman 
1679152fd17SVedant Kumar Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
168dc707122SEaswaran Raman   switch (C.getKind()) {
169dc707122SEaswaran Raman   case Counter::Zero:
170dc707122SEaswaran Raman     return 0;
171dc707122SEaswaran Raman   case Counter::CounterValueReference:
172dc707122SEaswaran Raman     if (C.getCounterID() >= CounterValues.size())
1739152fd17SVedant Kumar       return errorCodeToError(errc::argument_out_of_domain);
174dc707122SEaswaran Raman     return CounterValues[C.getCounterID()];
175dc707122SEaswaran Raman   case Counter::Expression: {
176dc707122SEaswaran Raman     if (C.getExpressionID() >= Expressions.size())
1779152fd17SVedant Kumar       return errorCodeToError(errc::argument_out_of_domain);
178dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
1799152fd17SVedant Kumar     Expected<int64_t> LHS = evaluate(E.LHS);
180dc707122SEaswaran Raman     if (!LHS)
181dc707122SEaswaran Raman       return LHS;
1829152fd17SVedant Kumar     Expected<int64_t> RHS = evaluate(E.RHS);
183dc707122SEaswaran Raman     if (!RHS)
184dc707122SEaswaran Raman       return RHS;
185dc707122SEaswaran Raman     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
186dc707122SEaswaran Raman   }
187dc707122SEaswaran Raman   }
188dc707122SEaswaran Raman   llvm_unreachable("Unhandled CounterKind");
189dc707122SEaswaran Raman }
190dc707122SEaswaran Raman 
191dc707122SEaswaran Raman void FunctionRecordIterator::skipOtherFiles() {
192dc707122SEaswaran Raman   while (Current != Records.end() && !Filename.empty() &&
193dc707122SEaswaran Raman          Filename != Current->Filenames[0])
194dc707122SEaswaran Raman     ++Current;
195dc707122SEaswaran Raman   if (Current == Records.end())
196dc707122SEaswaran Raman     *this = FunctionRecordIterator();
197dc707122SEaswaran Raman }
198dc707122SEaswaran Raman 
19968216d7bSVedant Kumar Error CoverageMapping::loadFunctionRecord(
20068216d7bSVedant Kumar     const CoverageMappingRecord &Record,
201dc707122SEaswaran Raman     IndexedInstrProfReader &ProfileReader) {
202743574b8SVedant Kumar   StringRef OrigFuncName = Record.FunctionName;
203*b1d331a3SVedant Kumar   if (OrigFuncName.empty())
204*b1d331a3SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
205*b1d331a3SVedant Kumar 
206743574b8SVedant Kumar   if (Record.Filenames.empty())
207743574b8SVedant Kumar     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
208743574b8SVedant Kumar   else
209743574b8SVedant Kumar     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
210743574b8SVedant Kumar 
211743574b8SVedant Kumar   // Don't load records for functions we've already seen.
212743574b8SVedant Kumar   if (!FunctionNames.insert(OrigFuncName).second)
213743574b8SVedant Kumar     return Error::success();
214743574b8SVedant Kumar 
215dc707122SEaswaran Raman   CounterMappingContext Ctx(Record.Expressions);
216dc707122SEaswaran Raman 
21768216d7bSVedant Kumar   std::vector<uint64_t> Counts;
21868216d7bSVedant Kumar   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
21968216d7bSVedant Kumar                                                 Record.FunctionHash, Counts)) {
2209152fd17SVedant Kumar     instrprof_error IPE = InstrProfError::take(std::move(E));
2219152fd17SVedant Kumar     if (IPE == instrprof_error::hash_mismatch) {
22268216d7bSVedant Kumar       MismatchedFunctionCount++;
22368216d7bSVedant Kumar       return Error::success();
2249152fd17SVedant Kumar     } else if (IPE != instrprof_error::unknown_function)
2259152fd17SVedant Kumar       return make_error<InstrProfError>(IPE);
226dc707122SEaswaran Raman     Counts.assign(Record.MappingRegions.size(), 0);
227dc707122SEaswaran Raman   }
228dc707122SEaswaran Raman   Ctx.setCounts(Counts);
229dc707122SEaswaran Raman 
230dc707122SEaswaran Raman   assert(!Record.MappingRegions.empty() && "Function has no regions");
231dc707122SEaswaran Raman 
232dc707122SEaswaran Raman   FunctionRecord Function(OrigFuncName, Record.Filenames);
233dc707122SEaswaran Raman   for (const auto &Region : Record.MappingRegions) {
2349152fd17SVedant Kumar     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
2359152fd17SVedant Kumar     if (auto E = ExecutionCount.takeError()) {
236e78d131aSEugene Zelenko       consumeError(std::move(E));
23768216d7bSVedant Kumar       return Error::success();
2389152fd17SVedant Kumar     }
239dc707122SEaswaran Raman     Function.pushRegion(Region, *ExecutionCount);
240dc707122SEaswaran Raman   }
241dc707122SEaswaran Raman   if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
24268216d7bSVedant Kumar     MismatchedFunctionCount++;
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 
25068216d7bSVedant Kumar Expected<std::unique_ptr<CoverageMapping>>
25168216d7bSVedant Kumar CoverageMapping::load(CoverageMappingReader &CoverageReader,
25268216d7bSVedant Kumar                       IndexedInstrProfReader &ProfileReader) {
25368216d7bSVedant Kumar   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
25468216d7bSVedant Kumar 
25568216d7bSVedant Kumar   for (const auto &Record : CoverageReader)
25668216d7bSVedant Kumar     if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
25768216d7bSVedant Kumar       return std::move(E);
25868216d7bSVedant Kumar 
259dc707122SEaswaran Raman   return std::move(Coverage);
260dc707122SEaswaran Raman }
261dc707122SEaswaran Raman 
262743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
263743574b8SVedant Kumar     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
264743574b8SVedant Kumar     IndexedInstrProfReader &ProfileReader) {
265743574b8SVedant Kumar   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
266743574b8SVedant Kumar 
267743574b8SVedant Kumar   for (const auto &CoverageReader : CoverageReaders)
268743574b8SVedant Kumar     for (const auto &Record : *CoverageReader)
269743574b8SVedant Kumar       if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
2709152fd17SVedant Kumar         return std::move(E);
271743574b8SVedant Kumar 
272743574b8SVedant Kumar   return std::move(Coverage);
273743574b8SVedant Kumar }
274743574b8SVedant Kumar 
275743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>>
276743574b8SVedant Kumar CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
277743574b8SVedant Kumar                       StringRef ProfileFilename, StringRef Arch) {
278dc707122SEaswaran Raman   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
2799152fd17SVedant Kumar   if (Error E = ProfileReaderOrErr.takeError())
2809152fd17SVedant Kumar     return std::move(E);
281dc707122SEaswaran Raman   auto ProfileReader = std::move(ProfileReaderOrErr.get());
282743574b8SVedant Kumar 
283743574b8SVedant Kumar   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
284743574b8SVedant Kumar   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
285743574b8SVedant Kumar   for (StringRef ObjectFilename : ObjectFilenames) {
286743574b8SVedant Kumar     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
287743574b8SVedant Kumar     if (std::error_code EC = CovMappingBufOrErr.getError())
288743574b8SVedant Kumar       return errorCodeToError(EC);
289743574b8SVedant Kumar     auto CoverageReaderOrErr =
290743574b8SVedant Kumar         BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
291743574b8SVedant Kumar     if (Error E = CoverageReaderOrErr.takeError())
292743574b8SVedant Kumar       return std::move(E);
293743574b8SVedant Kumar     Readers.push_back(std::move(CoverageReaderOrErr.get()));
294743574b8SVedant Kumar     Buffers.push_back(std::move(CovMappingBufOrErr.get()));
295743574b8SVedant Kumar   }
296743574b8SVedant Kumar   return load(Readers, *ProfileReader);
297dc707122SEaswaran Raman }
298dc707122SEaswaran Raman 
299dc707122SEaswaran Raman namespace {
300e78d131aSEugene Zelenko 
301dc707122SEaswaran Raman /// \brief Distributes functions into instantiation sets.
302dc707122SEaswaran Raman ///
303dc707122SEaswaran Raman /// An instantiation set is a collection of functions that have the same source
304dc707122SEaswaran Raman /// code, ie, template functions specializations.
305dc707122SEaswaran Raman class FunctionInstantiationSetCollector {
306dc707122SEaswaran Raman   typedef DenseMap<std::pair<unsigned, unsigned>,
307dc707122SEaswaran Raman                    std::vector<const FunctionRecord *>> MapT;
308dc707122SEaswaran Raman   MapT InstantiatedFunctions;
309dc707122SEaswaran Raman 
310dc707122SEaswaran Raman public:
311dc707122SEaswaran Raman   void insert(const FunctionRecord &Function, unsigned FileID) {
312dc707122SEaswaran Raman     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
313dc707122SEaswaran Raman     while (I != E && I->FileID != FileID)
314dc707122SEaswaran Raman       ++I;
315dc707122SEaswaran Raman     assert(I != E && "function does not cover the given file");
316dc707122SEaswaran Raman     auto &Functions = InstantiatedFunctions[I->startLoc()];
317dc707122SEaswaran Raman     Functions.push_back(&Function);
318dc707122SEaswaran Raman   }
319dc707122SEaswaran Raman 
320dc707122SEaswaran Raman   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
321dc707122SEaswaran Raman 
322dc707122SEaswaran Raman   MapT::iterator end() { return InstantiatedFunctions.end(); }
323dc707122SEaswaran Raman };
324dc707122SEaswaran Raman 
325dc707122SEaswaran Raman class SegmentBuilder {
326dc707122SEaswaran Raman   std::vector<CoverageSegment> &Segments;
327dc707122SEaswaran Raman   SmallVector<const CountedRegion *, 8> ActiveRegions;
328dc707122SEaswaran Raman 
329dc707122SEaswaran Raman   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
330dc707122SEaswaran Raman 
331dc707122SEaswaran Raman   /// Start a segment with no count specified.
332dc707122SEaswaran Raman   void startSegment(unsigned Line, unsigned Col) {
333dc707122SEaswaran Raman     DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
334dc707122SEaswaran Raman     Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
335dc707122SEaswaran Raman   }
336dc707122SEaswaran Raman 
337dc707122SEaswaran Raman   /// Start a segment with the given Region's count.
338dc707122SEaswaran Raman   void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
339dc707122SEaswaran Raman                     const CountedRegion &Region) {
340dc707122SEaswaran Raman     // Avoid creating empty regions.
341dc707122SEaswaran Raman     if (!Segments.empty() && Segments.back().Line == Line &&
342dc707122SEaswaran Raman         Segments.back().Col == Col)
343dc707122SEaswaran Raman       Segments.pop_back();
344dc707122SEaswaran Raman     DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
345dc707122SEaswaran Raman     // Set this region's count.
346e78d131aSEugene Zelenko     if (Region.Kind != CounterMappingRegion::SkippedRegion) {
347dc707122SEaswaran Raman       DEBUG(dbgs() << " with count " << Region.ExecutionCount);
348dc707122SEaswaran Raman       Segments.emplace_back(Line, Col, Region.ExecutionCount, IsRegionEntry);
349dc707122SEaswaran Raman     } else
350dc707122SEaswaran Raman       Segments.emplace_back(Line, Col, IsRegionEntry);
351dc707122SEaswaran Raman     DEBUG(dbgs() << "\n");
352dc707122SEaswaran Raman   }
353dc707122SEaswaran Raman 
354dc707122SEaswaran Raman   /// Start a segment for the given region.
355dc707122SEaswaran Raman   void startSegment(const CountedRegion &Region) {
356dc707122SEaswaran Raman     startSegment(Region.LineStart, Region.ColumnStart, true, Region);
357dc707122SEaswaran Raman   }
358dc707122SEaswaran Raman 
359dc707122SEaswaran Raman   /// Pop the top region off of the active stack, starting a new segment with
360dc707122SEaswaran Raman   /// the containing Region's count.
361dc707122SEaswaran Raman   void popRegion() {
362dc707122SEaswaran Raman     const CountedRegion *Active = ActiveRegions.back();
363dc707122SEaswaran Raman     unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
364dc707122SEaswaran Raman     ActiveRegions.pop_back();
365dc707122SEaswaran Raman     if (ActiveRegions.empty())
366dc707122SEaswaran Raman       startSegment(Line, Col);
367dc707122SEaswaran Raman     else
368dc707122SEaswaran Raman       startSegment(Line, Col, false, *ActiveRegions.back());
369dc707122SEaswaran Raman   }
370dc707122SEaswaran Raman 
371dc707122SEaswaran Raman   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
372dc707122SEaswaran Raman     for (const auto &Region : Regions) {
373dc707122SEaswaran Raman       // Pop any regions that end before this one starts.
374dc707122SEaswaran Raman       while (!ActiveRegions.empty() &&
375dc707122SEaswaran Raman              ActiveRegions.back()->endLoc() <= Region.startLoc())
376dc707122SEaswaran Raman         popRegion();
377dc707122SEaswaran Raman       // Add this region to the stack.
378dc707122SEaswaran Raman       ActiveRegions.push_back(&Region);
379dc707122SEaswaran Raman       startSegment(Region);
380dc707122SEaswaran Raman     }
381dc707122SEaswaran Raman     // Pop any regions that are left in the stack.
382dc707122SEaswaran Raman     while (!ActiveRegions.empty())
383dc707122SEaswaran Raman       popRegion();
384dc707122SEaswaran Raman   }
385dc707122SEaswaran Raman 
386dc707122SEaswaran Raman   /// Sort a nested sequence of regions from a single file.
387dc707122SEaswaran Raman   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
38827d8dd39SIgor Kudrin     std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
38927d8dd39SIgor Kudrin                                                  const CountedRegion &RHS) {
39027d8dd39SIgor Kudrin       if (LHS.startLoc() != RHS.startLoc())
39127d8dd39SIgor Kudrin         return LHS.startLoc() < RHS.startLoc();
39227d8dd39SIgor Kudrin       if (LHS.endLoc() != RHS.endLoc())
393dc707122SEaswaran Raman         // When LHS completely contains RHS, we sort LHS first.
394dc707122SEaswaran Raman         return RHS.endLoc() < LHS.endLoc();
39527d8dd39SIgor Kudrin       // If LHS and RHS cover the same area, we need to sort them according
39627d8dd39SIgor Kudrin       // to their kinds so that the most suitable region will become "active"
39727d8dd39SIgor Kudrin       // in combineRegions(). Because we accumulate counter values only from
39827d8dd39SIgor Kudrin       // regions of the same kind as the first region of the area, prefer
39927d8dd39SIgor Kudrin       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
400e78d131aSEugene Zelenko       static_assert(CounterMappingRegion::CodeRegion <
401e78d131aSEugene Zelenko                             CounterMappingRegion::ExpansionRegion &&
402e78d131aSEugene Zelenko                         CounterMappingRegion::ExpansionRegion <
403e78d131aSEugene Zelenko                             CounterMappingRegion::SkippedRegion,
40427d8dd39SIgor Kudrin                     "Unexpected order of region kind values");
40527d8dd39SIgor Kudrin       return LHS.Kind < RHS.Kind;
406dc707122SEaswaran Raman     });
407dc707122SEaswaran Raman   }
408dc707122SEaswaran Raman 
409dc707122SEaswaran Raman   /// Combine counts of regions which cover the same area.
410dc707122SEaswaran Raman   static ArrayRef<CountedRegion>
411dc707122SEaswaran Raman   combineRegions(MutableArrayRef<CountedRegion> Regions) {
412dc707122SEaswaran Raman     if (Regions.empty())
413dc707122SEaswaran Raman       return Regions;
414dc707122SEaswaran Raman     auto Active = Regions.begin();
415dc707122SEaswaran Raman     auto End = Regions.end();
416dc707122SEaswaran Raman     for (auto I = Regions.begin() + 1; I != End; ++I) {
417dc707122SEaswaran Raman       if (Active->startLoc() != I->startLoc() ||
418dc707122SEaswaran Raman           Active->endLoc() != I->endLoc()) {
419dc707122SEaswaran Raman         // Shift to the next region.
420dc707122SEaswaran Raman         ++Active;
421dc707122SEaswaran Raman         if (Active != I)
422dc707122SEaswaran Raman           *Active = *I;
423dc707122SEaswaran Raman         continue;
424dc707122SEaswaran Raman       }
425dc707122SEaswaran Raman       // Merge duplicate region.
42627d8dd39SIgor Kudrin       // If CodeRegions and ExpansionRegions cover the same area, it's probably
42727d8dd39SIgor Kudrin       // a macro which is fully expanded to another macro. In that case, we need
42827d8dd39SIgor Kudrin       // to accumulate counts only from CodeRegions, or else the area will be
42927d8dd39SIgor Kudrin       // counted twice.
43027d8dd39SIgor Kudrin       // On the other hand, a macro may have a nested macro in its body. If the
43127d8dd39SIgor Kudrin       // outer macro is used several times, the ExpansionRegion for the nested
43227d8dd39SIgor Kudrin       // macro will also be added several times. These ExpansionRegions cover
43327d8dd39SIgor Kudrin       // the same source locations and have to be combined to reach the correct
43427d8dd39SIgor Kudrin       // value for that area.
43527d8dd39SIgor Kudrin       // We add counts of the regions of the same kind as the active region
43627d8dd39SIgor Kudrin       // to handle the both situations.
43727d8dd39SIgor Kudrin       if (I->Kind == Active->Kind)
438dc707122SEaswaran Raman         Active->ExecutionCount += I->ExecutionCount;
439dc707122SEaswaran Raman     }
440dc707122SEaswaran Raman     return Regions.drop_back(std::distance(++Active, End));
441dc707122SEaswaran Raman   }
442dc707122SEaswaran Raman 
443dc707122SEaswaran Raman public:
444dc707122SEaswaran Raman   /// Build a list of CoverageSegments from a list of Regions.
445dc707122SEaswaran Raman   static std::vector<CoverageSegment>
446dc707122SEaswaran Raman   buildSegments(MutableArrayRef<CountedRegion> Regions) {
447dc707122SEaswaran Raman     std::vector<CoverageSegment> Segments;
448dc707122SEaswaran Raman     SegmentBuilder Builder(Segments);
449dc707122SEaswaran Raman 
450dc707122SEaswaran Raman     sortNestedRegions(Regions);
451dc707122SEaswaran Raman     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
452dc707122SEaswaran Raman 
453dc707122SEaswaran Raman     Builder.buildSegmentsImpl(CombinedRegions);
454dc707122SEaswaran Raman     return Segments;
455dc707122SEaswaran Raman   }
456dc707122SEaswaran Raman };
457e78d131aSEugene Zelenko 
458e78d131aSEugene Zelenko } // end anonymous namespace
459dc707122SEaswaran Raman 
460dc707122SEaswaran Raman std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
461dc707122SEaswaran Raman   std::vector<StringRef> Filenames;
462dc707122SEaswaran Raman   for (const auto &Function : getCoveredFunctions())
463dc707122SEaswaran Raman     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
464dc707122SEaswaran Raman                      Function.Filenames.end());
465dc707122SEaswaran Raman   std::sort(Filenames.begin(), Filenames.end());
466dc707122SEaswaran Raman   auto Last = std::unique(Filenames.begin(), Filenames.end());
467dc707122SEaswaran Raman   Filenames.erase(Last, Filenames.end());
468dc707122SEaswaran Raman   return Filenames;
469dc707122SEaswaran Raman }
470dc707122SEaswaran Raman 
471dc707122SEaswaran Raman static SmallBitVector gatherFileIDs(StringRef SourceFile,
472dc707122SEaswaran Raman                                     const FunctionRecord &Function) {
473dc707122SEaswaran Raman   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
474dc707122SEaswaran Raman   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
475dc707122SEaswaran Raman     if (SourceFile == Function.Filenames[I])
476dc707122SEaswaran Raman       FilenameEquivalence[I] = true;
477dc707122SEaswaran Raman   return FilenameEquivalence;
478dc707122SEaswaran Raman }
479dc707122SEaswaran Raman 
480dc707122SEaswaran Raman /// Return the ID of the file where the definition of the function is located.
481dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
482dc707122SEaswaran Raman   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
483dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
484dc707122SEaswaran Raman     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
485dc707122SEaswaran Raman       IsNotExpandedFile[CR.ExpandedFileID] = false;
486dc707122SEaswaran Raman   int I = IsNotExpandedFile.find_first();
487dc707122SEaswaran Raman   if (I == -1)
488dc707122SEaswaran Raman     return None;
489dc707122SEaswaran Raman   return I;
490dc707122SEaswaran Raman }
491dc707122SEaswaran Raman 
492dc707122SEaswaran Raman /// Check if SourceFile is the file that contains the definition of
493dc707122SEaswaran Raman /// the Function. Return the ID of the file in that case or None otherwise.
494dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
495dc707122SEaswaran Raman                                              const FunctionRecord &Function) {
496dc707122SEaswaran Raman   Optional<unsigned> I = findMainViewFileID(Function);
497dc707122SEaswaran Raman   if (I && SourceFile == Function.Filenames[*I])
498dc707122SEaswaran Raman     return I;
499dc707122SEaswaran Raman   return None;
500dc707122SEaswaran Raman }
501dc707122SEaswaran Raman 
502dc707122SEaswaran Raman static bool isExpansion(const CountedRegion &R, unsigned FileID) {
503dc707122SEaswaran Raman   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
504dc707122SEaswaran Raman }
505dc707122SEaswaran Raman 
5067fcc5472SVedant Kumar CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
507dc707122SEaswaran Raman   CoverageData FileCoverage(Filename);
508e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
509dc707122SEaswaran Raman 
510dc707122SEaswaran Raman   for (const auto &Function : Functions) {
511dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
512dc707122SEaswaran Raman     auto FileIDs = gatherFileIDs(Filename, Function);
513dc707122SEaswaran Raman     for (const auto &CR : Function.CountedRegions)
514dc707122SEaswaran Raman       if (FileIDs.test(CR.FileID)) {
515dc707122SEaswaran Raman         Regions.push_back(CR);
516dc707122SEaswaran Raman         if (MainFileID && isExpansion(CR, *MainFileID))
517dc707122SEaswaran Raman           FileCoverage.Expansions.emplace_back(CR, Function);
518dc707122SEaswaran Raman       }
519dc707122SEaswaran Raman   }
520dc707122SEaswaran Raman 
521dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
522dc707122SEaswaran Raman   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
523dc707122SEaswaran Raman 
524dc707122SEaswaran Raman   return FileCoverage;
525dc707122SEaswaran Raman }
526dc707122SEaswaran Raman 
527dc707122SEaswaran Raman std::vector<const FunctionRecord *>
528f681e2e5SVedant Kumar CoverageMapping::getInstantiations(StringRef Filename) const {
529dc707122SEaswaran Raman   FunctionInstantiationSetCollector InstantiationSetCollector;
530dc707122SEaswaran Raman   for (const auto &Function : Functions) {
531dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
532dc707122SEaswaran Raman     if (!MainFileID)
533dc707122SEaswaran Raman       continue;
534dc707122SEaswaran Raman     InstantiationSetCollector.insert(Function, *MainFileID);
535dc707122SEaswaran Raman   }
536dc707122SEaswaran Raman 
537dc707122SEaswaran Raman   std::vector<const FunctionRecord *> Result;
538dc707122SEaswaran Raman   for (const auto &InstantiationSet : InstantiationSetCollector) {
539dc707122SEaswaran Raman     if (InstantiationSet.second.size() < 2)
540dc707122SEaswaran Raman       continue;
541dc707122SEaswaran Raman     Result.insert(Result.end(), InstantiationSet.second.begin(),
542dc707122SEaswaran Raman                   InstantiationSet.second.end());
543dc707122SEaswaran Raman   }
544dc707122SEaswaran Raman   return Result;
545dc707122SEaswaran Raman }
546dc707122SEaswaran Raman 
547dc707122SEaswaran Raman CoverageData
548f681e2e5SVedant Kumar CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
549dc707122SEaswaran Raman   auto MainFileID = findMainViewFileID(Function);
550dc707122SEaswaran Raman   if (!MainFileID)
551dc707122SEaswaran Raman     return CoverageData();
552dc707122SEaswaran Raman 
553dc707122SEaswaran Raman   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
554e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
555dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
556dc707122SEaswaran Raman     if (CR.FileID == *MainFileID) {
557dc707122SEaswaran Raman       Regions.push_back(CR);
558dc707122SEaswaran Raman       if (isExpansion(CR, *MainFileID))
559dc707122SEaswaran Raman         FunctionCoverage.Expansions.emplace_back(CR, Function);
560dc707122SEaswaran Raman     }
561dc707122SEaswaran Raman 
562dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
563dc707122SEaswaran Raman   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
564dc707122SEaswaran Raman 
565dc707122SEaswaran Raman   return FunctionCoverage;
566dc707122SEaswaran Raman }
567dc707122SEaswaran Raman 
568f681e2e5SVedant Kumar CoverageData CoverageMapping::getCoverageForExpansion(
569f681e2e5SVedant Kumar     const ExpansionRecord &Expansion) const {
570dc707122SEaswaran Raman   CoverageData ExpansionCoverage(
571dc707122SEaswaran Raman       Expansion.Function.Filenames[Expansion.FileID]);
572e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
573dc707122SEaswaran Raman   for (const auto &CR : Expansion.Function.CountedRegions)
574dc707122SEaswaran Raman     if (CR.FileID == Expansion.FileID) {
575dc707122SEaswaran Raman       Regions.push_back(CR);
576dc707122SEaswaran Raman       if (isExpansion(CR, Expansion.FileID))
577dc707122SEaswaran Raman         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
578dc707122SEaswaran Raman     }
579dc707122SEaswaran Raman 
580dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
581dc707122SEaswaran Raman                << "\n");
582dc707122SEaswaran Raman   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
583dc707122SEaswaran Raman 
584dc707122SEaswaran Raman   return ExpansionCoverage;
585dc707122SEaswaran Raman }
586dc707122SEaswaran Raman 
587e78d131aSEugene Zelenko static std::string getCoverageMapErrString(coveragemap_error Err) {
5889152fd17SVedant Kumar   switch (Err) {
589dc707122SEaswaran Raman   case coveragemap_error::success:
590dc707122SEaswaran Raman     return "Success";
591dc707122SEaswaran Raman   case coveragemap_error::eof:
592dc707122SEaswaran Raman     return "End of File";
593dc707122SEaswaran Raman   case coveragemap_error::no_data_found:
594dc707122SEaswaran Raman     return "No coverage data found";
595dc707122SEaswaran Raman   case coveragemap_error::unsupported_version:
596dc707122SEaswaran Raman     return "Unsupported coverage format version";
597dc707122SEaswaran Raman   case coveragemap_error::truncated:
598dc707122SEaswaran Raman     return "Truncated coverage data";
599dc707122SEaswaran Raman   case coveragemap_error::malformed:
600dc707122SEaswaran Raman     return "Malformed coverage data";
601dc707122SEaswaran Raman   }
602dc707122SEaswaran Raman   llvm_unreachable("A value of coveragemap_error has no message.");
603dc707122SEaswaran Raman }
6049152fd17SVedant Kumar 
605e78d131aSEugene Zelenko namespace {
606e78d131aSEugene Zelenko 
6074718f8b5SPeter Collingbourne // FIXME: This class is only here to support the transition to llvm::Error. It
6084718f8b5SPeter Collingbourne // will be removed once this transition is complete. Clients should prefer to
6094718f8b5SPeter Collingbourne // deal with the Error value directly, rather than converting to error_code.
6109152fd17SVedant Kumar class CoverageMappingErrorCategoryType : public std::error_category {
611990504e6SReid Kleckner   const char *name() const noexcept override { return "llvm.coveragemap"; }
6129152fd17SVedant Kumar   std::string message(int IE) const override {
6139152fd17SVedant Kumar     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
6149152fd17SVedant Kumar   }
615dc707122SEaswaran Raman };
616e78d131aSEugene Zelenko 
6179152fd17SVedant Kumar } // end anonymous namespace
6189152fd17SVedant Kumar 
6199152fd17SVedant Kumar std::string CoverageMapError::message() const {
6209152fd17SVedant Kumar   return getCoverageMapErrString(Err);
621dc707122SEaswaran Raman }
622dc707122SEaswaran Raman 
623dc707122SEaswaran Raman static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
624dc707122SEaswaran Raman 
625dc707122SEaswaran Raman const std::error_category &llvm::coverage::coveragemap_category() {
626dc707122SEaswaran Raman   return *ErrorCategory;
627dc707122SEaswaran Raman }
6289152fd17SVedant Kumar 
6299152fd17SVedant Kumar char CoverageMapError::ID = 0;
630