xref: /llvm-project/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp (revision aadaaface2ec96ee30d92bf46faa41dd9e68b64d)
1 //===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains support for clang's and llvm's instrumentation based
10 // code coverage.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
23 #include "llvm/ProfileData/InstrProfReader.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/Errc.h"
26 #include "llvm/Support/Error.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include <algorithm>
31 #include <cassert>
32 #include <cstdint>
33 #include <iterator>
34 #include <map>
35 #include <memory>
36 #include <optional>
37 #include <string>
38 #include <system_error>
39 #include <utility>
40 #include <vector>
41 
42 using namespace llvm;
43 using namespace coverage;
44 
45 #define DEBUG_TYPE "coverage-mapping"
46 
47 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
48   auto It = ExpressionIndices.find(E);
49   if (It != ExpressionIndices.end())
50     return Counter::getExpression(It->second);
51   unsigned I = Expressions.size();
52   Expressions.push_back(E);
53   ExpressionIndices[E] = I;
54   return Counter::getExpression(I);
55 }
56 
57 void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
58                                             SmallVectorImpl<Term> &Terms) {
59   switch (C.getKind()) {
60   case Counter::Zero:
61     break;
62   case Counter::CounterValueReference:
63     Terms.emplace_back(C.getCounterID(), Factor);
64     break;
65   case Counter::Expression:
66     const auto &E = Expressions[C.getExpressionID()];
67     extractTerms(E.LHS, Factor, Terms);
68     extractTerms(
69         E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
70     break;
71   }
72 }
73 
74 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
75   // Gather constant terms.
76   SmallVector<Term, 32> Terms;
77   extractTerms(ExpressionTree, +1, Terms);
78 
79   // If there are no terms, this is just a zero. The algorithm below assumes at
80   // least one term.
81   if (Terms.size() == 0)
82     return Counter::getZero();
83 
84   // Group the terms by counter ID.
85   llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
86     return LHS.CounterID < RHS.CounterID;
87   });
88 
89   // Combine terms by counter ID to eliminate counters that sum to zero.
90   auto Prev = Terms.begin();
91   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
92     if (I->CounterID == Prev->CounterID) {
93       Prev->Factor += I->Factor;
94       continue;
95     }
96     ++Prev;
97     *Prev = *I;
98   }
99   Terms.erase(++Prev, Terms.end());
100 
101   Counter C;
102   // Create additions. We do this before subtractions to avoid constructs like
103   // ((0 - X) + Y), as opposed to (Y - X).
104   for (auto T : Terms) {
105     if (T.Factor <= 0)
106       continue;
107     for (int I = 0; I < T.Factor; ++I)
108       if (C.isZero())
109         C = Counter::getCounter(T.CounterID);
110       else
111         C = get(CounterExpression(CounterExpression::Add, C,
112                                   Counter::getCounter(T.CounterID)));
113   }
114 
115   // Create subtractions.
116   for (auto T : Terms) {
117     if (T.Factor >= 0)
118       continue;
119     for (int I = 0; I < -T.Factor; ++I)
120       C = get(CounterExpression(CounterExpression::Subtract, C,
121                                 Counter::getCounter(T.CounterID)));
122   }
123   return C;
124 }
125 
126 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS, bool Simplify) {
127   auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS));
128   return Simplify ? simplify(Cnt) : Cnt;
129 }
130 
131 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS,
132                                            bool Simplify) {
133   auto Cnt = get(CounterExpression(CounterExpression::Subtract, LHS, RHS));
134   return Simplify ? simplify(Cnt) : Cnt;
135 }
136 
137 void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
138   switch (C.getKind()) {
139   case Counter::Zero:
140     OS << '0';
141     return;
142   case Counter::CounterValueReference:
143     OS << '#' << C.getCounterID();
144     break;
145   case Counter::Expression: {
146     if (C.getExpressionID() >= Expressions.size())
147       return;
148     const auto &E = Expressions[C.getExpressionID()];
149     OS << '(';
150     dump(E.LHS, OS);
151     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
152     dump(E.RHS, OS);
153     OS << ')';
154     break;
155   }
156   }
157   if (CounterValues.empty())
158     return;
159   Expected<int64_t> Value = evaluate(C);
160   if (auto E = Value.takeError()) {
161     consumeError(std::move(E));
162     return;
163   }
164   OS << '[' << *Value << ']';
165 }
166 
167 Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
168   switch (C.getKind()) {
169   case Counter::Zero:
170     return 0;
171   case Counter::CounterValueReference:
172     if (C.getCounterID() >= CounterValues.size())
173       return errorCodeToError(errc::argument_out_of_domain);
174     return CounterValues[C.getCounterID()];
175   case Counter::Expression: {
176     if (C.getExpressionID() >= Expressions.size())
177       return errorCodeToError(errc::argument_out_of_domain);
178     const auto &E = Expressions[C.getExpressionID()];
179     Expected<int64_t> LHS = evaluate(E.LHS);
180     if (!LHS)
181       return LHS;
182     Expected<int64_t> RHS = evaluate(E.RHS);
183     if (!RHS)
184       return RHS;
185     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
186   }
187   }
188   llvm_unreachable("Unhandled CounterKind");
189 }
190 
191 unsigned CounterMappingContext::getMaxCounterID(const Counter &C) const {
192   switch (C.getKind()) {
193   case Counter::Zero:
194     return 0;
195   case Counter::CounterValueReference:
196     return C.getCounterID();
197   case Counter::Expression: {
198     if (C.getExpressionID() >= Expressions.size())
199       return 0;
200     const auto &E = Expressions[C.getExpressionID()];
201     return std::max(getMaxCounterID(E.LHS), getMaxCounterID(E.RHS));
202   }
203   }
204   llvm_unreachable("Unhandled CounterKind");
205 }
206 
207 void FunctionRecordIterator::skipOtherFiles() {
208   while (Current != Records.end() && !Filename.empty() &&
209          Filename != Current->Filenames[0])
210     ++Current;
211   if (Current == Records.end())
212     *this = FunctionRecordIterator();
213 }
214 
215 ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename(
216     StringRef Filename) const {
217   size_t FilenameHash = hash_value(Filename);
218   auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
219   if (RecordIt == FilenameHash2RecordIndices.end())
220     return {};
221   return RecordIt->second;
222 }
223 
224 static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
225                                 const CoverageMappingRecord &Record) {
226   unsigned MaxCounterID = 0;
227   for (const auto &Region : Record.MappingRegions) {
228     MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count));
229   }
230   return MaxCounterID;
231 }
232 
233 Error CoverageMapping::loadFunctionRecord(
234     const CoverageMappingRecord &Record,
235     IndexedInstrProfReader &ProfileReader) {
236   StringRef OrigFuncName = Record.FunctionName;
237   if (OrigFuncName.empty())
238     return make_error<CoverageMapError>(coveragemap_error::malformed);
239 
240   if (Record.Filenames.empty())
241     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
242   else
243     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
244 
245   CounterMappingContext Ctx(Record.Expressions);
246 
247   std::vector<uint64_t> Counts;
248   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
249                                                 Record.FunctionHash, Counts)) {
250     instrprof_error IPE = InstrProfError::take(std::move(E));
251     if (IPE == instrprof_error::hash_mismatch) {
252       FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
253                                       Record.FunctionHash);
254       return Error::success();
255     } else if (IPE != instrprof_error::unknown_function)
256       return make_error<InstrProfError>(IPE);
257     Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
258   }
259   Ctx.setCounts(Counts);
260 
261   assert(!Record.MappingRegions.empty() && "Function has no regions");
262 
263   // This coverage record is a zero region for a function that's unused in
264   // some TU, but used in a different TU. Ignore it. The coverage maps from the
265   // the other TU will either be loaded (providing full region counts) or they
266   // won't (in which case we don't unintuitively report functions as uncovered
267   // when they have non-zero counts in the profile).
268   if (Record.MappingRegions.size() == 1 &&
269       Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
270     return Error::success();
271 
272   FunctionRecord Function(OrigFuncName, Record.Filenames);
273   for (const auto &Region : Record.MappingRegions) {
274     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
275     if (auto E = ExecutionCount.takeError()) {
276       consumeError(std::move(E));
277       return Error::success();
278     }
279     Expected<int64_t> AltExecutionCount = Ctx.evaluate(Region.FalseCount);
280     if (auto E = AltExecutionCount.takeError()) {
281       consumeError(std::move(E));
282       return Error::success();
283     }
284     Function.pushRegion(Region, *ExecutionCount, *AltExecutionCount);
285   }
286 
287   // Don't create records for (filenames, function) pairs we've already seen.
288   auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
289                                           Record.Filenames.end());
290   if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
291     return Error::success();
292 
293   Functions.push_back(std::move(Function));
294 
295   // Performance optimization: keep track of the indices of the function records
296   // which correspond to each filename. This can be used to substantially speed
297   // up queries for coverage info in a file.
298   unsigned RecordIndex = Functions.size() - 1;
299   for (StringRef Filename : Record.Filenames) {
300     auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)];
301     // Note that there may be duplicates in the filename set for a function
302     // record, because of e.g. macro expansions in the function in which both
303     // the macro and the function are defined in the same file.
304     if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
305       RecordIndices.push_back(RecordIndex);
306   }
307 
308   return Error::success();
309 }
310 
311 // This function is for memory optimization by shortening the lifetimes
312 // of CoverageMappingReader instances.
313 Error CoverageMapping::loadFromReaders(
314     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
315     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage) {
316   for (const auto &CoverageReader : CoverageReaders) {
317     for (auto RecordOrErr : *CoverageReader) {
318       if (Error E = RecordOrErr.takeError())
319         return E;
320       const auto &Record = *RecordOrErr;
321       if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader))
322         return E;
323     }
324   }
325   return Error::success();
326 }
327 
328 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
329     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
330     IndexedInstrProfReader &ProfileReader) {
331   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
332   if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
333     return std::move(E);
334   return std::move(Coverage);
335 }
336 
337 // If E is a no_data_found error, returns success. Otherwise returns E.
338 static Error handleMaybeNoDataFoundError(Error E) {
339   return handleErrors(
340       std::move(E), [](const CoverageMapError &CME) {
341         if (CME.get() == coveragemap_error::no_data_found)
342           return static_cast<Error>(Error::success());
343         return make_error<CoverageMapError>(CME.get());
344       });
345 }
346 
347 Expected<std::unique_ptr<CoverageMapping>>
348 CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
349                       StringRef ProfileFilename, ArrayRef<StringRef> Arches,
350                       StringRef CompilationDir) {
351   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
352   if (Error E = ProfileReaderOrErr.takeError())
353     return createFileError(ProfileFilename, std::move(E));
354   auto ProfileReader = std::move(ProfileReaderOrErr.get());
355   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
356   bool DataFound = false;
357 
358   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
359     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
360         File.value(), /*IsText=*/false, /*RequiresNullTerminator=*/false);
361     if (std::error_code EC = CovMappingBufOrErr.getError())
362       return createFileError(File.value(), errorCodeToError(EC));
363     StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
364     MemoryBufferRef CovMappingBufRef =
365         CovMappingBufOrErr.get()->getMemBufferRef();
366     SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
367     auto CoverageReadersOrErr = BinaryCoverageReader::create(
368         CovMappingBufRef, Arch, Buffers, CompilationDir);
369     if (Error E = CoverageReadersOrErr.takeError()) {
370       E = handleMaybeNoDataFoundError(std::move(E));
371       if (E)
372         return createFileError(File.value(), std::move(E));
373       // E == success (originally a no_data_found error).
374       continue;
375     }
376 
377     SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
378     for (auto &Reader : CoverageReadersOrErr.get())
379       Readers.push_back(std::move(Reader));
380     DataFound |= !Readers.empty();
381     if (Error E = loadFromReaders(Readers, *ProfileReader, *Coverage))
382       return createFileError(File.value(), std::move(E));
383   }
384   // If no readers were created, either no objects were provided or none of them
385   // had coverage data. Return an error in the latter case.
386   if (!DataFound && !ObjectFilenames.empty())
387     return createFileError(
388         join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
389         make_error<CoverageMapError>(coveragemap_error::no_data_found));
390   return std::move(Coverage);
391 }
392 
393 namespace {
394 
395 /// Distributes functions into instantiation sets.
396 ///
397 /// An instantiation set is a collection of functions that have the same source
398 /// code, ie, template functions specializations.
399 class FunctionInstantiationSetCollector {
400   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
401   MapT InstantiatedFunctions;
402 
403 public:
404   void insert(const FunctionRecord &Function, unsigned FileID) {
405     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
406     while (I != E && I->FileID != FileID)
407       ++I;
408     assert(I != E && "function does not cover the given file");
409     auto &Functions = InstantiatedFunctions[I->startLoc()];
410     Functions.push_back(&Function);
411   }
412 
413   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
414   MapT::iterator end() { return InstantiatedFunctions.end(); }
415 };
416 
417 class SegmentBuilder {
418   std::vector<CoverageSegment> &Segments;
419   SmallVector<const CountedRegion *, 8> ActiveRegions;
420 
421   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
422 
423   /// Emit a segment with the count from \p Region starting at \p StartLoc.
424   //
425   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
426   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
427   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
428                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
429     bool HasCount = !EmitSkippedRegion &&
430                     (Region.Kind != CounterMappingRegion::SkippedRegion);
431 
432     // If the new segment wouldn't affect coverage rendering, skip it.
433     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
434       const auto &Last = Segments.back();
435       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
436           !Last.IsRegionEntry)
437         return;
438     }
439 
440     if (HasCount)
441       Segments.emplace_back(StartLoc.first, StartLoc.second,
442                             Region.ExecutionCount, IsRegionEntry,
443                             Region.Kind == CounterMappingRegion::GapRegion);
444     else
445       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
446 
447     LLVM_DEBUG({
448       const auto &Last = Segments.back();
449       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
450              << " (count = " << Last.Count << ")"
451              << (Last.IsRegionEntry ? ", RegionEntry" : "")
452              << (!Last.HasCount ? ", Skipped" : "")
453              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
454     });
455   }
456 
457   /// Emit segments for active regions which end before \p Loc.
458   ///
459   /// \p Loc: The start location of the next region. If None, all active
460   /// regions are completed.
461   /// \p FirstCompletedRegion: Index of the first completed region.
462   void completeRegionsUntil(std::optional<LineColPair> Loc,
463                             unsigned FirstCompletedRegion) {
464     // Sort the completed regions by end location. This makes it simple to
465     // emit closing segments in sorted order.
466     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
467     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
468                       [](const CountedRegion *L, const CountedRegion *R) {
469                         return L->endLoc() < R->endLoc();
470                       });
471 
472     // Emit segments for all completed regions.
473     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
474          ++I) {
475       const auto *CompletedRegion = ActiveRegions[I];
476       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
477              "Completed region ends after start of new region");
478 
479       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
480       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
481 
482       // Don't emit any more segments if they start where the new region begins.
483       if (Loc && CompletedSegmentLoc == *Loc)
484         break;
485 
486       // Don't emit a segment if the next completed region ends at the same
487       // location as this one.
488       if (CompletedSegmentLoc == CompletedRegion->endLoc())
489         continue;
490 
491       // Use the count from the last completed region which ends at this loc.
492       for (unsigned J = I + 1; J < E; ++J)
493         if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
494           CompletedRegion = ActiveRegions[J];
495 
496       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
497     }
498 
499     auto Last = ActiveRegions.back();
500     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
501       // If there's a gap after the end of the last completed region and the
502       // start of the new region, use the last active region to fill the gap.
503       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
504                    false);
505     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
506       // Emit a skipped segment if there are no more active regions. This
507       // ensures that gaps between functions are marked correctly.
508       startSegment(*Last, Last->endLoc(), false, true);
509     }
510 
511     // Pop the completed regions.
512     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
513   }
514 
515   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
516     for (const auto &CR : enumerate(Regions)) {
517       auto CurStartLoc = CR.value().startLoc();
518 
519       // Active regions which end before the current region need to be popped.
520       auto CompletedRegions =
521           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
522                                 [&](const CountedRegion *Region) {
523                                   return !(Region->endLoc() <= CurStartLoc);
524                                 });
525       if (CompletedRegions != ActiveRegions.end()) {
526         unsigned FirstCompletedRegion =
527             std::distance(ActiveRegions.begin(), CompletedRegions);
528         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
529       }
530 
531       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
532 
533       // Try to emit a segment for the current region.
534       if (CurStartLoc == CR.value().endLoc()) {
535         // Avoid making zero-length regions active. If it's the last region,
536         // emit a skipped segment. Otherwise use its predecessor's count.
537         const bool Skipped =
538             (CR.index() + 1) == Regions.size() ||
539             CR.value().Kind == CounterMappingRegion::SkippedRegion;
540         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
541                      CurStartLoc, !GapRegion, Skipped);
542         // If it is skipped segment, create a segment with last pushed
543         // regions's count at CurStartLoc.
544         if (Skipped && !ActiveRegions.empty())
545           startSegment(*ActiveRegions.back(), CurStartLoc, false);
546         continue;
547       }
548       if (CR.index() + 1 == Regions.size() ||
549           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
550         // Emit a segment if the next region doesn't start at the same location
551         // as this one.
552         startSegment(CR.value(), CurStartLoc, !GapRegion);
553       }
554 
555       // This region is active (i.e not completed).
556       ActiveRegions.push_back(&CR.value());
557     }
558 
559     // Complete any remaining active regions.
560     if (!ActiveRegions.empty())
561       completeRegionsUntil(std::nullopt, 0);
562   }
563 
564   /// Sort a nested sequence of regions from a single file.
565   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
566     llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
567       if (LHS.startLoc() != RHS.startLoc())
568         return LHS.startLoc() < RHS.startLoc();
569       if (LHS.endLoc() != RHS.endLoc())
570         // When LHS completely contains RHS, we sort LHS first.
571         return RHS.endLoc() < LHS.endLoc();
572       // If LHS and RHS cover the same area, we need to sort them according
573       // to their kinds so that the most suitable region will become "active"
574       // in combineRegions(). Because we accumulate counter values only from
575       // regions of the same kind as the first region of the area, prefer
576       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
577       static_assert(CounterMappingRegion::CodeRegion <
578                             CounterMappingRegion::ExpansionRegion &&
579                         CounterMappingRegion::ExpansionRegion <
580                             CounterMappingRegion::SkippedRegion,
581                     "Unexpected order of region kind values");
582       return LHS.Kind < RHS.Kind;
583     });
584   }
585 
586   /// Combine counts of regions which cover the same area.
587   static ArrayRef<CountedRegion>
588   combineRegions(MutableArrayRef<CountedRegion> Regions) {
589     if (Regions.empty())
590       return Regions;
591     auto Active = Regions.begin();
592     auto End = Regions.end();
593     for (auto I = Regions.begin() + 1; I != End; ++I) {
594       if (Active->startLoc() != I->startLoc() ||
595           Active->endLoc() != I->endLoc()) {
596         // Shift to the next region.
597         ++Active;
598         if (Active != I)
599           *Active = *I;
600         continue;
601       }
602       // Merge duplicate region.
603       // If CodeRegions and ExpansionRegions cover the same area, it's probably
604       // a macro which is fully expanded to another macro. In that case, we need
605       // to accumulate counts only from CodeRegions, or else the area will be
606       // counted twice.
607       // On the other hand, a macro may have a nested macro in its body. If the
608       // outer macro is used several times, the ExpansionRegion for the nested
609       // macro will also be added several times. These ExpansionRegions cover
610       // the same source locations and have to be combined to reach the correct
611       // value for that area.
612       // We add counts of the regions of the same kind as the active region
613       // to handle the both situations.
614       if (I->Kind == Active->Kind)
615         Active->ExecutionCount += I->ExecutionCount;
616     }
617     return Regions.drop_back(std::distance(++Active, End));
618   }
619 
620 public:
621   /// Build a sorted list of CoverageSegments from a list of Regions.
622   static std::vector<CoverageSegment>
623   buildSegments(MutableArrayRef<CountedRegion> Regions) {
624     std::vector<CoverageSegment> Segments;
625     SegmentBuilder Builder(Segments);
626 
627     sortNestedRegions(Regions);
628     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
629 
630     LLVM_DEBUG({
631       dbgs() << "Combined regions:\n";
632       for (const auto &CR : CombinedRegions)
633         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
634                << CR.LineEnd << ":" << CR.ColumnEnd
635                << " (count=" << CR.ExecutionCount << ")\n";
636     });
637 
638     Builder.buildSegmentsImpl(CombinedRegions);
639 
640 #ifndef NDEBUG
641     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
642       const auto &L = Segments[I - 1];
643       const auto &R = Segments[I];
644       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
645         if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
646           continue;
647         LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
648                           << " followed by " << R.Line << ":" << R.Col << "\n");
649         assert(false && "Coverage segments not unique or sorted");
650       }
651     }
652 #endif
653 
654     return Segments;
655   }
656 };
657 
658 } // end anonymous namespace
659 
660 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
661   std::vector<StringRef> Filenames;
662   for (const auto &Function : getCoveredFunctions())
663     llvm::append_range(Filenames, Function.Filenames);
664   llvm::sort(Filenames);
665   auto Last = std::unique(Filenames.begin(), Filenames.end());
666   Filenames.erase(Last, Filenames.end());
667   return Filenames;
668 }
669 
670 static SmallBitVector gatherFileIDs(StringRef SourceFile,
671                                     const FunctionRecord &Function) {
672   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
673   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
674     if (SourceFile == Function.Filenames[I])
675       FilenameEquivalence[I] = true;
676   return FilenameEquivalence;
677 }
678 
679 /// Return the ID of the file where the definition of the function is located.
680 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
681   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
682   for (const auto &CR : Function.CountedRegions)
683     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
684       IsNotExpandedFile[CR.ExpandedFileID] = false;
685   int I = IsNotExpandedFile.find_first();
686   if (I == -1)
687     return std::nullopt;
688   return I;
689 }
690 
691 /// Check if SourceFile is the file that contains the definition of
692 /// the Function. Return the ID of the file in that case or None otherwise.
693 static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
694                                              const FunctionRecord &Function) {
695   Optional<unsigned> I = findMainViewFileID(Function);
696   if (I && SourceFile == Function.Filenames[*I])
697     return I;
698   return std::nullopt;
699 }
700 
701 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
702   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
703 }
704 
705 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
706   CoverageData FileCoverage(Filename);
707   std::vector<CountedRegion> Regions;
708 
709   // Look up the function records in the given file. Due to hash collisions on
710   // the filename, we may get back some records that are not in the file.
711   ArrayRef<unsigned> RecordIndices =
712       getImpreciseRecordIndicesForFilename(Filename);
713   for (unsigned RecordIndex : RecordIndices) {
714     const FunctionRecord &Function = Functions[RecordIndex];
715     auto MainFileID = findMainViewFileID(Filename, Function);
716     auto FileIDs = gatherFileIDs(Filename, Function);
717     for (const auto &CR : Function.CountedRegions)
718       if (FileIDs.test(CR.FileID)) {
719         Regions.push_back(CR);
720         if (MainFileID && isExpansion(CR, *MainFileID))
721           FileCoverage.Expansions.emplace_back(CR, Function);
722       }
723     // Capture branch regions specific to the function (excluding expansions).
724     for (const auto &CR : Function.CountedBranchRegions)
725       if (FileIDs.test(CR.FileID) && (CR.FileID == CR.ExpandedFileID))
726         FileCoverage.BranchRegions.push_back(CR);
727   }
728 
729   LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
730   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
731 
732   return FileCoverage;
733 }
734 
735 std::vector<InstantiationGroup>
736 CoverageMapping::getInstantiationGroups(StringRef Filename) const {
737   FunctionInstantiationSetCollector InstantiationSetCollector;
738   // Look up the function records in the given file. Due to hash collisions on
739   // the filename, we may get back some records that are not in the file.
740   ArrayRef<unsigned> RecordIndices =
741       getImpreciseRecordIndicesForFilename(Filename);
742   for (unsigned RecordIndex : RecordIndices) {
743     const FunctionRecord &Function = Functions[RecordIndex];
744     auto MainFileID = findMainViewFileID(Filename, Function);
745     if (!MainFileID)
746       continue;
747     InstantiationSetCollector.insert(Function, *MainFileID);
748   }
749 
750   std::vector<InstantiationGroup> Result;
751   for (auto &InstantiationSet : InstantiationSetCollector) {
752     InstantiationGroup IG{InstantiationSet.first.first,
753                           InstantiationSet.first.second,
754                           std::move(InstantiationSet.second)};
755     Result.emplace_back(std::move(IG));
756   }
757   return Result;
758 }
759 
760 CoverageData
761 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
762   auto MainFileID = findMainViewFileID(Function);
763   if (!MainFileID)
764     return CoverageData();
765 
766   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
767   std::vector<CountedRegion> Regions;
768   for (const auto &CR : Function.CountedRegions)
769     if (CR.FileID == *MainFileID) {
770       Regions.push_back(CR);
771       if (isExpansion(CR, *MainFileID))
772         FunctionCoverage.Expansions.emplace_back(CR, Function);
773     }
774   // Capture branch regions specific to the function (excluding expansions).
775   for (const auto &CR : Function.CountedBranchRegions)
776     if (CR.FileID == *MainFileID)
777       FunctionCoverage.BranchRegions.push_back(CR);
778 
779   LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
780                     << "\n");
781   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
782 
783   return FunctionCoverage;
784 }
785 
786 CoverageData CoverageMapping::getCoverageForExpansion(
787     const ExpansionRecord &Expansion) const {
788   CoverageData ExpansionCoverage(
789       Expansion.Function.Filenames[Expansion.FileID]);
790   std::vector<CountedRegion> Regions;
791   for (const auto &CR : Expansion.Function.CountedRegions)
792     if (CR.FileID == Expansion.FileID) {
793       Regions.push_back(CR);
794       if (isExpansion(CR, Expansion.FileID))
795         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
796     }
797   for (const auto &CR : Expansion.Function.CountedBranchRegions)
798     // Capture branch regions that only pertain to the corresponding expansion.
799     if (CR.FileID == Expansion.FileID)
800       ExpansionCoverage.BranchRegions.push_back(CR);
801 
802   LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
803                     << Expansion.FileID << "\n");
804   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
805 
806   return ExpansionCoverage;
807 }
808 
809 LineCoverageStats::LineCoverageStats(
810     ArrayRef<const CoverageSegment *> LineSegments,
811     const CoverageSegment *WrappedSegment, unsigned Line)
812     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
813       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
814   // Find the minimum number of regions which start in this line.
815   unsigned MinRegionCount = 0;
816   auto isStartOfRegion = [](const CoverageSegment *S) {
817     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
818   };
819   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
820     if (isStartOfRegion(LineSegments[I]))
821       ++MinRegionCount;
822 
823   bool StartOfSkippedRegion = !LineSegments.empty() &&
824                               !LineSegments.front()->HasCount &&
825                               LineSegments.front()->IsRegionEntry;
826 
827   HasMultipleRegions = MinRegionCount > 1;
828   Mapped =
829       !StartOfSkippedRegion &&
830       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
831 
832   if (!Mapped)
833     return;
834 
835   // Pick the max count from the non-gap, region entry segments and the
836   // wrapped count.
837   if (WrappedSegment)
838     ExecutionCount = WrappedSegment->Count;
839   if (!MinRegionCount)
840     return;
841   for (const auto *LS : LineSegments)
842     if (isStartOfRegion(LS))
843       ExecutionCount = std::max(ExecutionCount, LS->Count);
844 }
845 
846 LineCoverageIterator &LineCoverageIterator::operator++() {
847   if (Next == CD.end()) {
848     Stats = LineCoverageStats();
849     Ended = true;
850     return *this;
851   }
852   if (Segments.size())
853     WrappedSegment = Segments.back();
854   Segments.clear();
855   while (Next != CD.end() && Next->Line == Line)
856     Segments.push_back(&*Next++);
857   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
858   ++Line;
859   return *this;
860 }
861 
862 static std::string getCoverageMapErrString(coveragemap_error Err) {
863   switch (Err) {
864   case coveragemap_error::success:
865     return "Success";
866   case coveragemap_error::eof:
867     return "End of File";
868   case coveragemap_error::no_data_found:
869     return "No coverage data found";
870   case coveragemap_error::unsupported_version:
871     return "Unsupported coverage format version";
872   case coveragemap_error::truncated:
873     return "Truncated coverage data";
874   case coveragemap_error::malformed:
875     return "Malformed coverage data";
876   case coveragemap_error::decompression_failed:
877     return "Failed to decompress coverage data (zlib)";
878   case coveragemap_error::invalid_or_missing_arch_specifier:
879     return "`-arch` specifier is invalid or missing for universal binary";
880   }
881   llvm_unreachable("A value of coveragemap_error has no message.");
882 }
883 
884 namespace {
885 
886 // FIXME: This class is only here to support the transition to llvm::Error. It
887 // will be removed once this transition is complete. Clients should prefer to
888 // deal with the Error value directly, rather than converting to error_code.
889 class CoverageMappingErrorCategoryType : public std::error_category {
890   const char *name() const noexcept override { return "llvm.coveragemap"; }
891   std::string message(int IE) const override {
892     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
893   }
894 };
895 
896 } // end anonymous namespace
897 
898 std::string CoverageMapError::message() const {
899   return getCoverageMapErrString(Err);
900 }
901 
902 const std::error_category &llvm::coverage::coveragemap_category() {
903   static CoverageMappingErrorCategoryType ErrorCategory;
904   return ErrorCategory;
905 }
906 
907 char CoverageMapError::ID = 0;
908