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>
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 
5771b3d721SVedant Kumar void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
5871b3d721SVedant Kumar                                             SmallVectorImpl<Term> &Terms) {
59dc707122SEaswaran Raman   switch (C.getKind()) {
60dc707122SEaswaran Raman   case Counter::Zero:
61dc707122SEaswaran Raman     break;
62dc707122SEaswaran Raman   case Counter::CounterValueReference:
6371b3d721SVedant Kumar     Terms.emplace_back(C.getCounterID(), Factor);
64dc707122SEaswaran Raman     break;
65dc707122SEaswaran Raman   case Counter::Expression:
66dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
6771b3d721SVedant Kumar     extractTerms(E.LHS, Factor, Terms);
6871b3d721SVedant Kumar     extractTerms(
6971b3d721SVedant Kumar         E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
70dc707122SEaswaran Raman     break;
71dc707122SEaswaran Raman   }
72dc707122SEaswaran Raman }
73dc707122SEaswaran Raman 
74dc707122SEaswaran Raman Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
75dc707122SEaswaran Raman   // Gather constant terms.
7671b3d721SVedant Kumar   SmallVector<Term, 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.
8571b3d721SVedant Kumar   std::sort(Terms.begin(), Terms.end(), [](const Term &LHS, const Term &RHS) {
8671b3d721SVedant Kumar     return LHS.CounterID < RHS.CounterID;
87dc707122SEaswaran Raman   });
88dc707122SEaswaran Raman 
89dc707122SEaswaran Raman   // Combine terms by counter ID to eliminate counters that sum to zero.
90dc707122SEaswaran Raman   auto Prev = Terms.begin();
91dc707122SEaswaran Raman   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
9271b3d721SVedant Kumar     if (I->CounterID == Prev->CounterID) {
9371b3d721SVedant Kumar       Prev->Factor += I->Factor;
94dc707122SEaswaran Raman       continue;
95dc707122SEaswaran Raman     }
96dc707122SEaswaran Raman     ++Prev;
97dc707122SEaswaran Raman     *Prev = *I;
98dc707122SEaswaran Raman   }
99dc707122SEaswaran Raman   Terms.erase(++Prev, Terms.end());
100dc707122SEaswaran Raman 
101dc707122SEaswaran Raman   Counter C;
102dc707122SEaswaran Raman   // Create additions. We do this before subtractions to avoid constructs like
103dc707122SEaswaran Raman   // ((0 - X) + Y), as opposed to (Y - X).
10471b3d721SVedant Kumar   for (auto T : Terms) {
10571b3d721SVedant Kumar     if (T.Factor <= 0)
106dc707122SEaswaran Raman       continue;
10771b3d721SVedant Kumar     for (int I = 0; I < T.Factor; ++I)
108dc707122SEaswaran Raman       if (C.isZero())
10971b3d721SVedant Kumar         C = Counter::getCounter(T.CounterID);
110dc707122SEaswaran Raman       else
111dc707122SEaswaran Raman         C = get(CounterExpression(CounterExpression::Add, C,
11271b3d721SVedant Kumar                                   Counter::getCounter(T.CounterID)));
113dc707122SEaswaran Raman   }
114dc707122SEaswaran Raman 
115dc707122SEaswaran Raman   // Create subtractions.
11671b3d721SVedant Kumar   for (auto T : Terms) {
11771b3d721SVedant Kumar     if (T.Factor >= 0)
118dc707122SEaswaran Raman       continue;
11971b3d721SVedant Kumar     for (int I = 0; I < -T.Factor; ++I)
120dc707122SEaswaran Raman       C = get(CounterExpression(CounterExpression::Subtract, C,
12171b3d721SVedant Kumar                                 Counter::getCounter(T.CounterID)));
122dc707122SEaswaran Raman   }
123dc707122SEaswaran Raman   return C;
124dc707122SEaswaran Raman }
125dc707122SEaswaran Raman 
126dc707122SEaswaran Raman Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
127dc707122SEaswaran Raman   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
128dc707122SEaswaran Raman }
129dc707122SEaswaran Raman 
130dc707122SEaswaran Raman Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
131dc707122SEaswaran Raman   return simplify(
132dc707122SEaswaran Raman       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
133dc707122SEaswaran Raman }
134dc707122SEaswaran Raman 
135e78d131aSEugene Zelenko void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
136dc707122SEaswaran Raman   switch (C.getKind()) {
137dc707122SEaswaran Raman   case Counter::Zero:
138dc707122SEaswaran Raman     OS << '0';
139dc707122SEaswaran Raman     return;
140dc707122SEaswaran Raman   case Counter::CounterValueReference:
141dc707122SEaswaran Raman     OS << '#' << C.getCounterID();
142dc707122SEaswaran Raman     break;
143dc707122SEaswaran Raman   case Counter::Expression: {
144dc707122SEaswaran Raman     if (C.getExpressionID() >= Expressions.size())
145dc707122SEaswaran Raman       return;
146dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
147dc707122SEaswaran Raman     OS << '(';
148dc707122SEaswaran Raman     dump(E.LHS, OS);
149dc707122SEaswaran Raman     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
150dc707122SEaswaran Raman     dump(E.RHS, OS);
151dc707122SEaswaran Raman     OS << ')';
152dc707122SEaswaran Raman     break;
153dc707122SEaswaran Raman   }
154dc707122SEaswaran Raman   }
155dc707122SEaswaran Raman   if (CounterValues.empty())
156dc707122SEaswaran Raman     return;
1579152fd17SVedant Kumar   Expected<int64_t> Value = evaluate(C);
1589152fd17SVedant Kumar   if (auto E = Value.takeError()) {
159e78d131aSEugene Zelenko     consumeError(std::move(E));
160dc707122SEaswaran Raman     return;
1619152fd17SVedant Kumar   }
162dc707122SEaswaran Raman   OS << '[' << *Value << ']';
163dc707122SEaswaran Raman }
164dc707122SEaswaran Raman 
1659152fd17SVedant Kumar Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
166dc707122SEaswaran Raman   switch (C.getKind()) {
167dc707122SEaswaran Raman   case Counter::Zero:
168dc707122SEaswaran Raman     return 0;
169dc707122SEaswaran Raman   case Counter::CounterValueReference:
170dc707122SEaswaran Raman     if (C.getCounterID() >= CounterValues.size())
1719152fd17SVedant Kumar       return errorCodeToError(errc::argument_out_of_domain);
172dc707122SEaswaran Raman     return CounterValues[C.getCounterID()];
173dc707122SEaswaran Raman   case Counter::Expression: {
174dc707122SEaswaran Raman     if (C.getExpressionID() >= Expressions.size())
1759152fd17SVedant Kumar       return errorCodeToError(errc::argument_out_of_domain);
176dc707122SEaswaran Raman     const auto &E = Expressions[C.getExpressionID()];
1779152fd17SVedant Kumar     Expected<int64_t> LHS = evaluate(E.LHS);
178dc707122SEaswaran Raman     if (!LHS)
179dc707122SEaswaran Raman       return LHS;
1809152fd17SVedant Kumar     Expected<int64_t> RHS = evaluate(E.RHS);
181dc707122SEaswaran Raman     if (!RHS)
182dc707122SEaswaran Raman       return RHS;
183dc707122SEaswaran Raman     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
184dc707122SEaswaran Raman   }
185dc707122SEaswaran Raman   }
186dc707122SEaswaran Raman   llvm_unreachable("Unhandled CounterKind");
187dc707122SEaswaran Raman }
188dc707122SEaswaran Raman 
189dc707122SEaswaran Raman void FunctionRecordIterator::skipOtherFiles() {
190dc707122SEaswaran Raman   while (Current != Records.end() && !Filename.empty() &&
191dc707122SEaswaran Raman          Filename != Current->Filenames[0])
192dc707122SEaswaran Raman     ++Current;
193dc707122SEaswaran Raman   if (Current == Records.end())
194dc707122SEaswaran Raman     *this = FunctionRecordIterator();
195dc707122SEaswaran Raman }
196dc707122SEaswaran Raman 
19768216d7bSVedant Kumar Error CoverageMapping::loadFunctionRecord(
19868216d7bSVedant Kumar     const CoverageMappingRecord &Record,
199dc707122SEaswaran Raman     IndexedInstrProfReader &ProfileReader) {
200743574b8SVedant Kumar   StringRef OrigFuncName = Record.FunctionName;
201b1d331a3SVedant Kumar   if (OrigFuncName.empty())
202b1d331a3SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
203b1d331a3SVedant Kumar 
204743574b8SVedant Kumar   if (Record.Filenames.empty())
205743574b8SVedant Kumar     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
206743574b8SVedant Kumar   else
207743574b8SVedant Kumar     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
208743574b8SVedant Kumar 
209743574b8SVedant Kumar   // Don't load records for functions we've already seen.
210743574b8SVedant Kumar   if (!FunctionNames.insert(OrigFuncName).second)
211743574b8SVedant Kumar     return Error::success();
212743574b8SVedant Kumar 
213dc707122SEaswaran Raman   CounterMappingContext Ctx(Record.Expressions);
214dc707122SEaswaran Raman 
21568216d7bSVedant Kumar   std::vector<uint64_t> Counts;
21668216d7bSVedant Kumar   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
21768216d7bSVedant Kumar                                                 Record.FunctionHash, Counts)) {
2189152fd17SVedant Kumar     instrprof_error IPE = InstrProfError::take(std::move(E));
2199152fd17SVedant Kumar     if (IPE == instrprof_error::hash_mismatch) {
22068216d7bSVedant Kumar       MismatchedFunctionCount++;
22168216d7bSVedant Kumar       return Error::success();
2229152fd17SVedant Kumar     } else if (IPE != instrprof_error::unknown_function)
2239152fd17SVedant Kumar       return make_error<InstrProfError>(IPE);
224dc707122SEaswaran Raman     Counts.assign(Record.MappingRegions.size(), 0);
225dc707122SEaswaran Raman   }
226dc707122SEaswaran Raman   Ctx.setCounts(Counts);
227dc707122SEaswaran Raman 
228dc707122SEaswaran Raman   assert(!Record.MappingRegions.empty() && "Function has no regions");
229dc707122SEaswaran Raman 
230dc707122SEaswaran Raman   FunctionRecord Function(OrigFuncName, Record.Filenames);
231dc707122SEaswaran Raman   for (const auto &Region : Record.MappingRegions) {
2329152fd17SVedant Kumar     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
2339152fd17SVedant Kumar     if (auto E = ExecutionCount.takeError()) {
234e78d131aSEugene Zelenko       consumeError(std::move(E));
23568216d7bSVedant Kumar       return Error::success();
2369152fd17SVedant Kumar     }
237dc707122SEaswaran Raman     Function.pushRegion(Region, *ExecutionCount);
238dc707122SEaswaran Raman   }
239dc707122SEaswaran Raman   if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
24068216d7bSVedant Kumar     MismatchedFunctionCount++;
24168216d7bSVedant Kumar     return Error::success();
242dc707122SEaswaran Raman   }
243dc707122SEaswaran Raman 
24468216d7bSVedant Kumar   Functions.push_back(std::move(Function));
24568216d7bSVedant Kumar   return Error::success();
246dc707122SEaswaran Raman }
247dc707122SEaswaran Raman 
248743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
249743574b8SVedant Kumar     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
250743574b8SVedant Kumar     IndexedInstrProfReader &ProfileReader) {
251743574b8SVedant Kumar   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
252743574b8SVedant Kumar 
253*bae83970SVedant Kumar   for (const auto &CoverageReader : CoverageReaders) {
254*bae83970SVedant Kumar     for (auto RecordOrErr : *CoverageReader) {
255*bae83970SVedant Kumar       if (Error E = RecordOrErr.takeError())
256*bae83970SVedant Kumar         return std::move(E);
257*bae83970SVedant Kumar       const auto &Record = *RecordOrErr;
258743574b8SVedant Kumar       if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
2599152fd17SVedant Kumar         return std::move(E);
260*bae83970SVedant Kumar     }
261*bae83970SVedant Kumar   }
262743574b8SVedant Kumar 
263743574b8SVedant Kumar   return std::move(Coverage);
264743574b8SVedant Kumar }
265743574b8SVedant Kumar 
266743574b8SVedant Kumar Expected<std::unique_ptr<CoverageMapping>>
267743574b8SVedant Kumar CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
2684b102c3dSVedant Kumar                       StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
269dc707122SEaswaran Raman   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
2709152fd17SVedant Kumar   if (Error E = ProfileReaderOrErr.takeError())
2719152fd17SVedant Kumar     return std::move(E);
272dc707122SEaswaran Raman   auto ProfileReader = std::move(ProfileReaderOrErr.get());
273743574b8SVedant Kumar 
274743574b8SVedant Kumar   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
275743574b8SVedant Kumar   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
2764b102c3dSVedant Kumar   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
2774b102c3dSVedant Kumar     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
278743574b8SVedant Kumar     if (std::error_code EC = CovMappingBufOrErr.getError())
279743574b8SVedant Kumar       return errorCodeToError(EC);
2804b102c3dSVedant Kumar     StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
281743574b8SVedant Kumar     auto CoverageReaderOrErr =
282743574b8SVedant Kumar         BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
283743574b8SVedant Kumar     if (Error E = CoverageReaderOrErr.takeError())
284743574b8SVedant Kumar       return std::move(E);
285743574b8SVedant Kumar     Readers.push_back(std::move(CoverageReaderOrErr.get()));
286743574b8SVedant Kumar     Buffers.push_back(std::move(CovMappingBufOrErr.get()));
287743574b8SVedant Kumar   }
288743574b8SVedant Kumar   return load(Readers, *ProfileReader);
289dc707122SEaswaran Raman }
290dc707122SEaswaran Raman 
291dc707122SEaswaran Raman namespace {
292e78d131aSEugene Zelenko 
293dc707122SEaswaran Raman /// \brief Distributes functions into instantiation sets.
294dc707122SEaswaran Raman ///
295dc707122SEaswaran Raman /// An instantiation set is a collection of functions that have the same source
296dc707122SEaswaran Raman /// code, ie, template functions specializations.
297dc707122SEaswaran Raman class FunctionInstantiationSetCollector {
29872208a82SEugene Zelenko   using MapT = DenseMap<std::pair<unsigned, unsigned>,
29972208a82SEugene Zelenko                         std::vector<const FunctionRecord *>>;
300dc707122SEaswaran Raman   MapT InstantiatedFunctions;
301dc707122SEaswaran Raman 
302dc707122SEaswaran Raman public:
303dc707122SEaswaran Raman   void insert(const FunctionRecord &Function, unsigned FileID) {
304dc707122SEaswaran Raman     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
305dc707122SEaswaran Raman     while (I != E && I->FileID != FileID)
306dc707122SEaswaran Raman       ++I;
307dc707122SEaswaran Raman     assert(I != E && "function does not cover the given file");
308dc707122SEaswaran Raman     auto &Functions = InstantiatedFunctions[I->startLoc()];
309dc707122SEaswaran Raman     Functions.push_back(&Function);
310dc707122SEaswaran Raman   }
311dc707122SEaswaran Raman 
312dc707122SEaswaran Raman   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
313dc707122SEaswaran Raman   MapT::iterator end() { return InstantiatedFunctions.end(); }
314dc707122SEaswaran Raman };
315dc707122SEaswaran Raman 
316dc707122SEaswaran Raman class SegmentBuilder {
317dc707122SEaswaran Raman   std::vector<CoverageSegment> &Segments;
318dc707122SEaswaran Raman   SmallVector<const CountedRegion *, 8> ActiveRegions;
319dc707122SEaswaran Raman 
320dc707122SEaswaran Raman   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
321dc707122SEaswaran Raman 
322dc707122SEaswaran Raman   /// Start a segment with no count specified.
323dc707122SEaswaran Raman   void startSegment(unsigned Line, unsigned Col) {
324dc707122SEaswaran Raman     DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
325dc707122SEaswaran Raman     Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
326dc707122SEaswaran Raman   }
327dc707122SEaswaran Raman 
328dc707122SEaswaran Raman   /// Start a segment with the given Region's count.
329dc707122SEaswaran Raman   void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
330dc707122SEaswaran Raman                     const CountedRegion &Region) {
331dc707122SEaswaran Raman     // Avoid creating empty regions.
332dc707122SEaswaran Raman     if (!Segments.empty() && Segments.back().Line == Line &&
333dc707122SEaswaran Raman         Segments.back().Col == Col)
334dc707122SEaswaran Raman       Segments.pop_back();
335dc707122SEaswaran Raman     DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
336dc707122SEaswaran Raman     // Set this region's count.
337e78d131aSEugene Zelenko     if (Region.Kind != CounterMappingRegion::SkippedRegion) {
338dc707122SEaswaran Raman       DEBUG(dbgs() << " with count " << Region.ExecutionCount);
339dc707122SEaswaran Raman       Segments.emplace_back(Line, Col, Region.ExecutionCount, IsRegionEntry);
340dc707122SEaswaran Raman     } else
341dc707122SEaswaran Raman       Segments.emplace_back(Line, Col, IsRegionEntry);
342dc707122SEaswaran Raman     DEBUG(dbgs() << "\n");
343dc707122SEaswaran Raman   }
344dc707122SEaswaran Raman 
345dc707122SEaswaran Raman   /// Start a segment for the given region.
346dc707122SEaswaran Raman   void startSegment(const CountedRegion &Region) {
347dc707122SEaswaran Raman     startSegment(Region.LineStart, Region.ColumnStart, true, Region);
348dc707122SEaswaran Raman   }
349dc707122SEaswaran Raman 
350dc707122SEaswaran Raman   /// Pop the top region off of the active stack, starting a new segment with
351dc707122SEaswaran Raman   /// the containing Region's count.
352dc707122SEaswaran Raman   void popRegion() {
353dc707122SEaswaran Raman     const CountedRegion *Active = ActiveRegions.back();
354dc707122SEaswaran Raman     unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
355dc707122SEaswaran Raman     ActiveRegions.pop_back();
356dc707122SEaswaran Raman     if (ActiveRegions.empty())
357dc707122SEaswaran Raman       startSegment(Line, Col);
358dc707122SEaswaran Raman     else
359dc707122SEaswaran Raman       startSegment(Line, Col, false, *ActiveRegions.back());
360dc707122SEaswaran Raman   }
361dc707122SEaswaran Raman 
362dc707122SEaswaran Raman   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
363dc707122SEaswaran Raman     for (const auto &Region : Regions) {
364dc707122SEaswaran Raman       // Pop any regions that end before this one starts.
365dc707122SEaswaran Raman       while (!ActiveRegions.empty() &&
366dc707122SEaswaran Raman              ActiveRegions.back()->endLoc() <= Region.startLoc())
367dc707122SEaswaran Raman         popRegion();
368dc707122SEaswaran Raman       // Add this region to the stack.
369dc707122SEaswaran Raman       ActiveRegions.push_back(&Region);
370dc707122SEaswaran Raman       startSegment(Region);
371dc707122SEaswaran Raman     }
372dc707122SEaswaran Raman     // Pop any regions that are left in the stack.
373dc707122SEaswaran Raman     while (!ActiveRegions.empty())
374dc707122SEaswaran Raman       popRegion();
375dc707122SEaswaran Raman   }
376dc707122SEaswaran Raman 
377dc707122SEaswaran Raman   /// Sort a nested sequence of regions from a single file.
378dc707122SEaswaran Raman   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
37927d8dd39SIgor Kudrin     std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
38027d8dd39SIgor Kudrin                                                  const CountedRegion &RHS) {
38127d8dd39SIgor Kudrin       if (LHS.startLoc() != RHS.startLoc())
38227d8dd39SIgor Kudrin         return LHS.startLoc() < RHS.startLoc();
38327d8dd39SIgor Kudrin       if (LHS.endLoc() != RHS.endLoc())
384dc707122SEaswaran Raman         // When LHS completely contains RHS, we sort LHS first.
385dc707122SEaswaran Raman         return RHS.endLoc() < LHS.endLoc();
38627d8dd39SIgor Kudrin       // If LHS and RHS cover the same area, we need to sort them according
38727d8dd39SIgor Kudrin       // to their kinds so that the most suitable region will become "active"
38827d8dd39SIgor Kudrin       // in combineRegions(). Because we accumulate counter values only from
38927d8dd39SIgor Kudrin       // regions of the same kind as the first region of the area, prefer
39027d8dd39SIgor Kudrin       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
391e78d131aSEugene Zelenko       static_assert(CounterMappingRegion::CodeRegion <
392e78d131aSEugene Zelenko                             CounterMappingRegion::ExpansionRegion &&
393e78d131aSEugene Zelenko                         CounterMappingRegion::ExpansionRegion <
394e78d131aSEugene Zelenko                             CounterMappingRegion::SkippedRegion,
39527d8dd39SIgor Kudrin                     "Unexpected order of region kind values");
39627d8dd39SIgor Kudrin       return LHS.Kind < RHS.Kind;
397dc707122SEaswaran Raman     });
398dc707122SEaswaran Raman   }
399dc707122SEaswaran Raman 
400dc707122SEaswaran Raman   /// Combine counts of regions which cover the same area.
401dc707122SEaswaran Raman   static ArrayRef<CountedRegion>
402dc707122SEaswaran Raman   combineRegions(MutableArrayRef<CountedRegion> Regions) {
403dc707122SEaswaran Raman     if (Regions.empty())
404dc707122SEaswaran Raman       return Regions;
405dc707122SEaswaran Raman     auto Active = Regions.begin();
406dc707122SEaswaran Raman     auto End = Regions.end();
407dc707122SEaswaran Raman     for (auto I = Regions.begin() + 1; I != End; ++I) {
408dc707122SEaswaran Raman       if (Active->startLoc() != I->startLoc() ||
409dc707122SEaswaran Raman           Active->endLoc() != I->endLoc()) {
410dc707122SEaswaran Raman         // Shift to the next region.
411dc707122SEaswaran Raman         ++Active;
412dc707122SEaswaran Raman         if (Active != I)
413dc707122SEaswaran Raman           *Active = *I;
414dc707122SEaswaran Raman         continue;
415dc707122SEaswaran Raman       }
416dc707122SEaswaran Raman       // Merge duplicate region.
41727d8dd39SIgor Kudrin       // If CodeRegions and ExpansionRegions cover the same area, it's probably
41827d8dd39SIgor Kudrin       // a macro which is fully expanded to another macro. In that case, we need
41927d8dd39SIgor Kudrin       // to accumulate counts only from CodeRegions, or else the area will be
42027d8dd39SIgor Kudrin       // counted twice.
42127d8dd39SIgor Kudrin       // On the other hand, a macro may have a nested macro in its body. If the
42227d8dd39SIgor Kudrin       // outer macro is used several times, the ExpansionRegion for the nested
42327d8dd39SIgor Kudrin       // macro will also be added several times. These ExpansionRegions cover
42427d8dd39SIgor Kudrin       // the same source locations and have to be combined to reach the correct
42527d8dd39SIgor Kudrin       // value for that area.
42627d8dd39SIgor Kudrin       // We add counts of the regions of the same kind as the active region
42727d8dd39SIgor Kudrin       // to handle the both situations.
42827d8dd39SIgor Kudrin       if (I->Kind == Active->Kind)
429dc707122SEaswaran Raman         Active->ExecutionCount += I->ExecutionCount;
430dc707122SEaswaran Raman     }
431dc707122SEaswaran Raman     return Regions.drop_back(std::distance(++Active, End));
432dc707122SEaswaran Raman   }
433dc707122SEaswaran Raman 
434dc707122SEaswaran Raman public:
435dc707122SEaswaran Raman   /// Build a list of CoverageSegments from a list of Regions.
436dc707122SEaswaran Raman   static std::vector<CoverageSegment>
437dc707122SEaswaran Raman   buildSegments(MutableArrayRef<CountedRegion> Regions) {
438dc707122SEaswaran Raman     std::vector<CoverageSegment> Segments;
439dc707122SEaswaran Raman     SegmentBuilder Builder(Segments);
440dc707122SEaswaran Raman 
441dc707122SEaswaran Raman     sortNestedRegions(Regions);
442dc707122SEaswaran Raman     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
443dc707122SEaswaran Raman 
444dc707122SEaswaran Raman     Builder.buildSegmentsImpl(CombinedRegions);
445dc707122SEaswaran Raman     return Segments;
446dc707122SEaswaran Raman   }
447dc707122SEaswaran Raman };
448e78d131aSEugene Zelenko 
449e78d131aSEugene Zelenko } // end anonymous namespace
450dc707122SEaswaran Raman 
451dc707122SEaswaran Raman std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
452dc707122SEaswaran Raman   std::vector<StringRef> Filenames;
453dc707122SEaswaran Raman   for (const auto &Function : getCoveredFunctions())
454dc707122SEaswaran Raman     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
455dc707122SEaswaran Raman                      Function.Filenames.end());
456dc707122SEaswaran Raman   std::sort(Filenames.begin(), Filenames.end());
457dc707122SEaswaran Raman   auto Last = std::unique(Filenames.begin(), Filenames.end());
458dc707122SEaswaran Raman   Filenames.erase(Last, Filenames.end());
459dc707122SEaswaran Raman   return Filenames;
460dc707122SEaswaran Raman }
461dc707122SEaswaran Raman 
462dc707122SEaswaran Raman static SmallBitVector gatherFileIDs(StringRef SourceFile,
463dc707122SEaswaran Raman                                     const FunctionRecord &Function) {
464dc707122SEaswaran Raman   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
465dc707122SEaswaran Raman   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
466dc707122SEaswaran Raman     if (SourceFile == Function.Filenames[I])
467dc707122SEaswaran Raman       FilenameEquivalence[I] = true;
468dc707122SEaswaran Raman   return FilenameEquivalence;
469dc707122SEaswaran Raman }
470dc707122SEaswaran Raman 
471dc707122SEaswaran Raman /// Return the ID of the file where the definition of the function is located.
472dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
473dc707122SEaswaran Raman   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
474dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
475dc707122SEaswaran Raman     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
476dc707122SEaswaran Raman       IsNotExpandedFile[CR.ExpandedFileID] = false;
477dc707122SEaswaran Raman   int I = IsNotExpandedFile.find_first();
478dc707122SEaswaran Raman   if (I == -1)
479dc707122SEaswaran Raman     return None;
480dc707122SEaswaran Raman   return I;
481dc707122SEaswaran Raman }
482dc707122SEaswaran Raman 
483dc707122SEaswaran Raman /// Check if SourceFile is the file that contains the definition of
484dc707122SEaswaran Raman /// the Function. Return the ID of the file in that case or None otherwise.
485dc707122SEaswaran Raman static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
486dc707122SEaswaran Raman                                              const FunctionRecord &Function) {
487dc707122SEaswaran Raman   Optional<unsigned> I = findMainViewFileID(Function);
488dc707122SEaswaran Raman   if (I && SourceFile == Function.Filenames[*I])
489dc707122SEaswaran Raman     return I;
490dc707122SEaswaran Raman   return None;
491dc707122SEaswaran Raman }
492dc707122SEaswaran Raman 
493dc707122SEaswaran Raman static bool isExpansion(const CountedRegion &R, unsigned FileID) {
494dc707122SEaswaran Raman   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
495dc707122SEaswaran Raman }
496dc707122SEaswaran Raman 
4977fcc5472SVedant Kumar CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
498dc707122SEaswaran Raman   CoverageData FileCoverage(Filename);
499e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
500dc707122SEaswaran Raman 
501dc707122SEaswaran Raman   for (const auto &Function : Functions) {
502dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
503dc707122SEaswaran Raman     auto FileIDs = gatherFileIDs(Filename, Function);
504dc707122SEaswaran Raman     for (const auto &CR : Function.CountedRegions)
505dc707122SEaswaran Raman       if (FileIDs.test(CR.FileID)) {
506dc707122SEaswaran Raman         Regions.push_back(CR);
507dc707122SEaswaran Raman         if (MainFileID && isExpansion(CR, *MainFileID))
508dc707122SEaswaran Raman           FileCoverage.Expansions.emplace_back(CR, Function);
509dc707122SEaswaran Raman       }
510dc707122SEaswaran Raman   }
511dc707122SEaswaran Raman 
512dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
513dc707122SEaswaran Raman   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
514dc707122SEaswaran Raman 
515dc707122SEaswaran Raman   return FileCoverage;
516dc707122SEaswaran Raman }
517dc707122SEaswaran Raman 
518dde19c5aSVedant Kumar std::vector<InstantiationGroup>
519dde19c5aSVedant Kumar CoverageMapping::getInstantiationGroups(StringRef Filename) const {
520dc707122SEaswaran Raman   FunctionInstantiationSetCollector InstantiationSetCollector;
521dc707122SEaswaran Raman   for (const auto &Function : Functions) {
522dc707122SEaswaran Raman     auto MainFileID = findMainViewFileID(Filename, Function);
523dc707122SEaswaran Raman     if (!MainFileID)
524dc707122SEaswaran Raman       continue;
525dc707122SEaswaran Raman     InstantiationSetCollector.insert(Function, *MainFileID);
526dc707122SEaswaran Raman   }
527dc707122SEaswaran Raman 
528dde19c5aSVedant Kumar   std::vector<InstantiationGroup> Result;
529dc707122SEaswaran Raman   for (const auto &InstantiationSet : InstantiationSetCollector) {
530dde19c5aSVedant Kumar     InstantiationGroup IG{InstantiationSet.first.first,
531dde19c5aSVedant Kumar                           InstantiationSet.first.second,
532dde19c5aSVedant Kumar                           std::move(InstantiationSet.second)};
533dde19c5aSVedant Kumar     Result.emplace_back(std::move(IG));
534dc707122SEaswaran Raman   }
535dc707122SEaswaran Raman   return Result;
536dc707122SEaswaran Raman }
537dc707122SEaswaran Raman 
538dc707122SEaswaran Raman CoverageData
539f681e2e5SVedant Kumar CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
540dc707122SEaswaran Raman   auto MainFileID = findMainViewFileID(Function);
541dc707122SEaswaran Raman   if (!MainFileID)
542dc707122SEaswaran Raman     return CoverageData();
543dc707122SEaswaran Raman 
544dc707122SEaswaran Raman   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
545e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
546dc707122SEaswaran Raman   for (const auto &CR : Function.CountedRegions)
547dc707122SEaswaran Raman     if (CR.FileID == *MainFileID) {
548dc707122SEaswaran Raman       Regions.push_back(CR);
549dc707122SEaswaran Raman       if (isExpansion(CR, *MainFileID))
550dc707122SEaswaran Raman         FunctionCoverage.Expansions.emplace_back(CR, Function);
551dc707122SEaswaran Raman     }
552dc707122SEaswaran Raman 
553dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
554dc707122SEaswaran Raman   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
555dc707122SEaswaran Raman 
556dc707122SEaswaran Raman   return FunctionCoverage;
557dc707122SEaswaran Raman }
558dc707122SEaswaran Raman 
559f681e2e5SVedant Kumar CoverageData CoverageMapping::getCoverageForExpansion(
560f681e2e5SVedant Kumar     const ExpansionRecord &Expansion) const {
561dc707122SEaswaran Raman   CoverageData ExpansionCoverage(
562dc707122SEaswaran Raman       Expansion.Function.Filenames[Expansion.FileID]);
563e78d131aSEugene Zelenko   std::vector<CountedRegion> Regions;
564dc707122SEaswaran Raman   for (const auto &CR : Expansion.Function.CountedRegions)
565dc707122SEaswaran Raman     if (CR.FileID == Expansion.FileID) {
566dc707122SEaswaran Raman       Regions.push_back(CR);
567dc707122SEaswaran Raman       if (isExpansion(CR, Expansion.FileID))
568dc707122SEaswaran Raman         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
569dc707122SEaswaran Raman     }
570dc707122SEaswaran Raman 
571dc707122SEaswaran Raman   DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
572dc707122SEaswaran Raman                << "\n");
573dc707122SEaswaran Raman   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
574dc707122SEaswaran Raman 
575dc707122SEaswaran Raman   return ExpansionCoverage;
576dc707122SEaswaran Raman }
577dc707122SEaswaran Raman 
578e78d131aSEugene Zelenko static std::string getCoverageMapErrString(coveragemap_error Err) {
5799152fd17SVedant Kumar   switch (Err) {
580dc707122SEaswaran Raman   case coveragemap_error::success:
581dc707122SEaswaran Raman     return "Success";
582dc707122SEaswaran Raman   case coveragemap_error::eof:
583dc707122SEaswaran Raman     return "End of File";
584dc707122SEaswaran Raman   case coveragemap_error::no_data_found:
585dc707122SEaswaran Raman     return "No coverage data found";
586dc707122SEaswaran Raman   case coveragemap_error::unsupported_version:
587dc707122SEaswaran Raman     return "Unsupported coverage format version";
588dc707122SEaswaran Raman   case coveragemap_error::truncated:
589dc707122SEaswaran Raman     return "Truncated coverage data";
590dc707122SEaswaran Raman   case coveragemap_error::malformed:
591dc707122SEaswaran Raman     return "Malformed coverage data";
592dc707122SEaswaran Raman   }
593dc707122SEaswaran Raman   llvm_unreachable("A value of coveragemap_error has no message.");
594dc707122SEaswaran Raman }
5959152fd17SVedant Kumar 
596e78d131aSEugene Zelenko namespace {
597e78d131aSEugene Zelenko 
5984718f8b5SPeter Collingbourne // FIXME: This class is only here to support the transition to llvm::Error. It
5994718f8b5SPeter Collingbourne // will be removed once this transition is complete. Clients should prefer to
6004718f8b5SPeter Collingbourne // deal with the Error value directly, rather than converting to error_code.
6019152fd17SVedant Kumar class CoverageMappingErrorCategoryType : public std::error_category {
602990504e6SReid Kleckner   const char *name() const noexcept override { return "llvm.coveragemap"; }
6039152fd17SVedant Kumar   std::string message(int IE) const override {
6049152fd17SVedant Kumar     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
6059152fd17SVedant Kumar   }
606dc707122SEaswaran Raman };
607e78d131aSEugene Zelenko 
6089152fd17SVedant Kumar } // end anonymous namespace
6099152fd17SVedant Kumar 
6109152fd17SVedant Kumar std::string CoverageMapError::message() const {
6119152fd17SVedant Kumar   return getCoverageMapErrString(Err);
612dc707122SEaswaran Raman }
613dc707122SEaswaran Raman 
614dc707122SEaswaran Raman static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
615dc707122SEaswaran Raman 
616dc707122SEaswaran Raman const std::error_category &llvm::coverage::coveragemap_category() {
617dc707122SEaswaran Raman   return *ErrorCategory;
618dc707122SEaswaran Raman }
6199152fd17SVedant Kumar 
6209152fd17SVedant Kumar char CoverageMapError::ID = 0;
621