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