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