xref: /llvm-project/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp (revision e302fc597afd6d7586c5c5b15cf52f6a34de8a83)
1 //===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains support for clang's and llvm's instrumentation based
11 // code coverage.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/None.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/SmallBitVector.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/ADT/StringRef.h"
23 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
24 #include "llvm/ProfileData/InstrProfReader.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Errc.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cstdint>
35 #include <iterator>
36 #include <map>
37 #include <memory>
38 #include <string>
39 #include <system_error>
40 #include <utility>
41 #include <vector>
42 
43 using namespace llvm;
44 using namespace coverage;
45 
46 #define DEBUG_TYPE "coverage-mapping"
47 
48 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
49   auto It = ExpressionIndices.find(E);
50   if (It != ExpressionIndices.end())
51     return Counter::getExpression(It->second);
52   unsigned I = Expressions.size();
53   Expressions.push_back(E);
54   ExpressionIndices[E] = I;
55   return Counter::getExpression(I);
56 }
57 
58 void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
59                                             SmallVectorImpl<Term> &Terms) {
60   switch (C.getKind()) {
61   case Counter::Zero:
62     break;
63   case Counter::CounterValueReference:
64     Terms.emplace_back(C.getCounterID(), Factor);
65     break;
66   case Counter::Expression:
67     const auto &E = Expressions[C.getExpressionID()];
68     extractTerms(E.LHS, Factor, Terms);
69     extractTerms(
70         E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
71     break;
72   }
73 }
74 
75 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
76   // Gather constant terms.
77   SmallVector<Term, 32> Terms;
78   extractTerms(ExpressionTree, +1, Terms);
79 
80   // If there are no terms, this is just a zero. The algorithm below assumes at
81   // least one term.
82   if (Terms.size() == 0)
83     return Counter::getZero();
84 
85   // Group the terms by counter ID.
86   llvm::sort(Terms.begin(), Terms.end(), [](const Term &LHS, const Term &RHS) {
87     return LHS.CounterID < RHS.CounterID;
88   });
89 
90   // Combine terms by counter ID to eliminate counters that sum to zero.
91   auto Prev = Terms.begin();
92   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
93     if (I->CounterID == Prev->CounterID) {
94       Prev->Factor += I->Factor;
95       continue;
96     }
97     ++Prev;
98     *Prev = *I;
99   }
100   Terms.erase(++Prev, Terms.end());
101 
102   Counter C;
103   // Create additions. We do this before subtractions to avoid constructs like
104   // ((0 - X) + Y), as opposed to (Y - X).
105   for (auto T : Terms) {
106     if (T.Factor <= 0)
107       continue;
108     for (int I = 0; I < T.Factor; ++I)
109       if (C.isZero())
110         C = Counter::getCounter(T.CounterID);
111       else
112         C = get(CounterExpression(CounterExpression::Add, C,
113                                   Counter::getCounter(T.CounterID)));
114   }
115 
116   // Create subtractions.
117   for (auto T : Terms) {
118     if (T.Factor >= 0)
119       continue;
120     for (int I = 0; I < -T.Factor; ++I)
121       C = get(CounterExpression(CounterExpression::Subtract, C,
122                                 Counter::getCounter(T.CounterID)));
123   }
124   return C;
125 }
126 
127 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
128   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
129 }
130 
131 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
132   return simplify(
133       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
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 void FunctionRecordIterator::skipOtherFiles() {
191   while (Current != Records.end() && !Filename.empty() &&
192          Filename != Current->Filenames[0])
193     ++Current;
194   if (Current == Records.end())
195     *this = FunctionRecordIterator();
196 }
197 
198 Error CoverageMapping::loadFunctionRecord(
199     const CoverageMappingRecord &Record,
200     IndexedInstrProfReader &ProfileReader) {
201   StringRef OrigFuncName = Record.FunctionName;
202   if (OrigFuncName.empty())
203     return make_error<CoverageMapError>(coveragemap_error::malformed);
204 
205   if (Record.Filenames.empty())
206     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
207   else
208     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
209 
210   // Don't load records for (filenames, function) pairs we've already seen.
211   auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
212                                           Record.Filenames.end());
213   if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
214     return Error::success();
215 
216   CounterMappingContext Ctx(Record.Expressions);
217 
218   std::vector<uint64_t> Counts;
219   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
220                                                 Record.FunctionHash, Counts)) {
221     instrprof_error IPE = InstrProfError::take(std::move(E));
222     if (IPE == instrprof_error::hash_mismatch) {
223       FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash);
224       return Error::success();
225     } else if (IPE != instrprof_error::unknown_function)
226       return make_error<InstrProfError>(IPE);
227     Counts.assign(Record.MappingRegions.size(), 0);
228   }
229   Ctx.setCounts(Counts);
230 
231   assert(!Record.MappingRegions.empty() && "Function has no regions");
232 
233   FunctionRecord Function(OrigFuncName, Record.Filenames);
234   for (const auto &Region : Record.MappingRegions) {
235     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
236     if (auto E = ExecutionCount.takeError()) {
237       consumeError(std::move(E));
238       return Error::success();
239     }
240     Function.pushRegion(Region, *ExecutionCount);
241   }
242 
243   Functions.push_back(std::move(Function));
244   return Error::success();
245 }
246 
247 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
248     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
249     IndexedInstrProfReader &ProfileReader) {
250   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
251 
252   for (const auto &CoverageReader : CoverageReaders) {
253     for (auto RecordOrErr : *CoverageReader) {
254       if (Error E = RecordOrErr.takeError())
255         return std::move(E);
256       const auto &Record = *RecordOrErr;
257       if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
258         return std::move(E);
259     }
260   }
261 
262   return std::move(Coverage);
263 }
264 
265 Expected<std::unique_ptr<CoverageMapping>>
266 CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
267                       StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
268   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
269   if (Error E = ProfileReaderOrErr.takeError())
270     return std::move(E);
271   auto ProfileReader = std::move(ProfileReaderOrErr.get());
272 
273   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
274   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
275   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
276     auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
277     if (std::error_code EC = CovMappingBufOrErr.getError())
278       return errorCodeToError(EC);
279     StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
280     auto CoverageReaderOrErr =
281         BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
282     if (Error E = CoverageReaderOrErr.takeError())
283       return std::move(E);
284     Readers.push_back(std::move(CoverageReaderOrErr.get()));
285     Buffers.push_back(std::move(CovMappingBufOrErr.get()));
286   }
287   return load(Readers, *ProfileReader);
288 }
289 
290 namespace {
291 
292 /// Distributes functions into instantiation sets.
293 ///
294 /// An instantiation set is a collection of functions that have the same source
295 /// code, ie, template functions specializations.
296 class FunctionInstantiationSetCollector {
297   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
298   MapT InstantiatedFunctions;
299 
300 public:
301   void insert(const FunctionRecord &Function, unsigned FileID) {
302     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
303     while (I != E && I->FileID != FileID)
304       ++I;
305     assert(I != E && "function does not cover the given file");
306     auto &Functions = InstantiatedFunctions[I->startLoc()];
307     Functions.push_back(&Function);
308   }
309 
310   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
311   MapT::iterator end() { return InstantiatedFunctions.end(); }
312 };
313 
314 class SegmentBuilder {
315   std::vector<CoverageSegment> &Segments;
316   SmallVector<const CountedRegion *, 8> ActiveRegions;
317 
318   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
319 
320   /// Emit a segment with the count from \p Region starting at \p StartLoc.
321   //
322   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
323   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
324   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
325                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
326     bool HasCount = !EmitSkippedRegion &&
327                     (Region.Kind != CounterMappingRegion::SkippedRegion);
328 
329     // If the new segment wouldn't affect coverage rendering, skip it.
330     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
331       const auto &Last = Segments.back();
332       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
333           !Last.IsRegionEntry)
334         return;
335     }
336 
337     if (HasCount)
338       Segments.emplace_back(StartLoc.first, StartLoc.second,
339                             Region.ExecutionCount, IsRegionEntry,
340                             Region.Kind == CounterMappingRegion::GapRegion);
341     else
342       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
343 
344     LLVM_DEBUG({
345       const auto &Last = Segments.back();
346       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
347              << " (count = " << Last.Count << ")"
348              << (Last.IsRegionEntry ? ", RegionEntry" : "")
349              << (!Last.HasCount ? ", Skipped" : "")
350              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
351     });
352   }
353 
354   /// Emit segments for active regions which end before \p Loc.
355   ///
356   /// \p Loc: The start location of the next region. If None, all active
357   /// regions are completed.
358   /// \p FirstCompletedRegion: Index of the first completed region.
359   void completeRegionsUntil(Optional<LineColPair> Loc,
360                             unsigned FirstCompletedRegion) {
361     // Sort the completed regions by end location. This makes it simple to
362     // emit closing segments in sorted order.
363     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
364     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
365                       [](const CountedRegion *L, const CountedRegion *R) {
366                         return L->endLoc() < R->endLoc();
367                       });
368 
369     // Emit segments for all completed regions.
370     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
371          ++I) {
372       const auto *CompletedRegion = ActiveRegions[I];
373       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
374              "Completed region ends after start of new region");
375 
376       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
377       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
378 
379       // Don't emit any more segments if they start where the new region begins.
380       if (Loc && CompletedSegmentLoc == *Loc)
381         break;
382 
383       // Don't emit a segment if the next completed region ends at the same
384       // location as this one.
385       if (CompletedSegmentLoc == CompletedRegion->endLoc())
386         continue;
387 
388       // Use the count from the last completed region which ends at this loc.
389       for (unsigned J = I + 1; J < E; ++J)
390         if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
391           CompletedRegion = ActiveRegions[J];
392 
393       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
394     }
395 
396     auto Last = ActiveRegions.back();
397     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
398       // If there's a gap after the end of the last completed region and the
399       // start of the new region, use the last active region to fill the gap.
400       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
401                    false);
402     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
403       // Emit a skipped segment if there are no more active regions. This
404       // ensures that gaps between functions are marked correctly.
405       startSegment(*Last, Last->endLoc(), false, true);
406     }
407 
408     // Pop the completed regions.
409     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
410   }
411 
412   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
413     for (const auto &CR : enumerate(Regions)) {
414       auto CurStartLoc = CR.value().startLoc();
415 
416       // Active regions which end before the current region need to be popped.
417       auto CompletedRegions =
418           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
419                                 [&](const CountedRegion *Region) {
420                                   return !(Region->endLoc() <= CurStartLoc);
421                                 });
422       if (CompletedRegions != ActiveRegions.end()) {
423         unsigned FirstCompletedRegion =
424             std::distance(ActiveRegions.begin(), CompletedRegions);
425         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
426       }
427 
428       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
429 
430       // Try to emit a segment for the current region.
431       if (CurStartLoc == CR.value().endLoc()) {
432         // Avoid making zero-length regions active. If it's the last region,
433         // emit a skipped segment. Otherwise use its predecessor's count.
434         const bool Skipped = (CR.index() + 1) == Regions.size();
435         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
436                      CurStartLoc, !GapRegion, Skipped);
437         continue;
438       }
439       if (CR.index() + 1 == Regions.size() ||
440           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
441         // Emit a segment if the next region doesn't start at the same location
442         // as this one.
443         startSegment(CR.value(), CurStartLoc, !GapRegion);
444       }
445 
446       // This region is active (i.e not completed).
447       ActiveRegions.push_back(&CR.value());
448     }
449 
450     // Complete any remaining active regions.
451     if (!ActiveRegions.empty())
452       completeRegionsUntil(None, 0);
453   }
454 
455   /// Sort a nested sequence of regions from a single file.
456   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
457     llvm::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
458                                                   const CountedRegion &RHS) {
459       if (LHS.startLoc() != RHS.startLoc())
460         return LHS.startLoc() < RHS.startLoc();
461       if (LHS.endLoc() != RHS.endLoc())
462         // When LHS completely contains RHS, we sort LHS first.
463         return RHS.endLoc() < LHS.endLoc();
464       // If LHS and RHS cover the same area, we need to sort them according
465       // to their kinds so that the most suitable region will become "active"
466       // in combineRegions(). Because we accumulate counter values only from
467       // regions of the same kind as the first region of the area, prefer
468       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
469       static_assert(CounterMappingRegion::CodeRegion <
470                             CounterMappingRegion::ExpansionRegion &&
471                         CounterMappingRegion::ExpansionRegion <
472                             CounterMappingRegion::SkippedRegion,
473                     "Unexpected order of region kind values");
474       return LHS.Kind < RHS.Kind;
475     });
476   }
477 
478   /// Combine counts of regions which cover the same area.
479   static ArrayRef<CountedRegion>
480   combineRegions(MutableArrayRef<CountedRegion> Regions) {
481     if (Regions.empty())
482       return Regions;
483     auto Active = Regions.begin();
484     auto End = Regions.end();
485     for (auto I = Regions.begin() + 1; I != End; ++I) {
486       if (Active->startLoc() != I->startLoc() ||
487           Active->endLoc() != I->endLoc()) {
488         // Shift to the next region.
489         ++Active;
490         if (Active != I)
491           *Active = *I;
492         continue;
493       }
494       // Merge duplicate region.
495       // If CodeRegions and ExpansionRegions cover the same area, it's probably
496       // a macro which is fully expanded to another macro. In that case, we need
497       // to accumulate counts only from CodeRegions, or else the area will be
498       // counted twice.
499       // On the other hand, a macro may have a nested macro in its body. If the
500       // outer macro is used several times, the ExpansionRegion for the nested
501       // macro will also be added several times. These ExpansionRegions cover
502       // the same source locations and have to be combined to reach the correct
503       // value for that area.
504       // We add counts of the regions of the same kind as the active region
505       // to handle the both situations.
506       if (I->Kind == Active->Kind)
507         Active->ExecutionCount += I->ExecutionCount;
508     }
509     return Regions.drop_back(std::distance(++Active, End));
510   }
511 
512 public:
513   /// Build a sorted list of CoverageSegments from a list of Regions.
514   static std::vector<CoverageSegment>
515   buildSegments(MutableArrayRef<CountedRegion> Regions) {
516     std::vector<CoverageSegment> Segments;
517     SegmentBuilder Builder(Segments);
518 
519     sortNestedRegions(Regions);
520     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
521 
522     LLVM_DEBUG({
523       dbgs() << "Combined regions:\n";
524       for (const auto &CR : CombinedRegions)
525         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
526                << CR.LineEnd << ":" << CR.ColumnEnd
527                << " (count=" << CR.ExecutionCount << ")\n";
528     });
529 
530     Builder.buildSegmentsImpl(CombinedRegions);
531 
532 #ifndef NDEBUG
533     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
534       const auto &L = Segments[I - 1];
535       const auto &R = Segments[I];
536       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
537         LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
538                           << " followed by " << R.Line << ":" << R.Col << "\n");
539         assert(false && "Coverage segments not unique or sorted");
540       }
541     }
542 #endif
543 
544     return Segments;
545   }
546 };
547 
548 } // end anonymous namespace
549 
550 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
551   std::vector<StringRef> Filenames;
552   for (const auto &Function : getCoveredFunctions())
553     Filenames.insert(Filenames.end(), Function.Filenames.begin(),
554                      Function.Filenames.end());
555   llvm::sort(Filenames.begin(), Filenames.end());
556   auto Last = std::unique(Filenames.begin(), Filenames.end());
557   Filenames.erase(Last, Filenames.end());
558   return Filenames;
559 }
560 
561 static SmallBitVector gatherFileIDs(StringRef SourceFile,
562                                     const FunctionRecord &Function) {
563   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
564   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
565     if (SourceFile == Function.Filenames[I])
566       FilenameEquivalence[I] = true;
567   return FilenameEquivalence;
568 }
569 
570 /// Return the ID of the file where the definition of the function is located.
571 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
572   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
573   for (const auto &CR : Function.CountedRegions)
574     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
575       IsNotExpandedFile[CR.ExpandedFileID] = false;
576   int I = IsNotExpandedFile.find_first();
577   if (I == -1)
578     return None;
579   return I;
580 }
581 
582 /// Check if SourceFile is the file that contains the definition of
583 /// the Function. Return the ID of the file in that case or None otherwise.
584 static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
585                                              const FunctionRecord &Function) {
586   Optional<unsigned> I = findMainViewFileID(Function);
587   if (I && SourceFile == Function.Filenames[*I])
588     return I;
589   return None;
590 }
591 
592 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
593   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
594 }
595 
596 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
597   CoverageData FileCoverage(Filename);
598   std::vector<CountedRegion> Regions;
599 
600   for (const auto &Function : Functions) {
601     auto MainFileID = findMainViewFileID(Filename, Function);
602     auto FileIDs = gatherFileIDs(Filename, Function);
603     for (const auto &CR : Function.CountedRegions)
604       if (FileIDs.test(CR.FileID)) {
605         Regions.push_back(CR);
606         if (MainFileID && isExpansion(CR, *MainFileID))
607           FileCoverage.Expansions.emplace_back(CR, Function);
608       }
609   }
610 
611   LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
612   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
613 
614   return FileCoverage;
615 }
616 
617 std::vector<InstantiationGroup>
618 CoverageMapping::getInstantiationGroups(StringRef Filename) const {
619   FunctionInstantiationSetCollector InstantiationSetCollector;
620   for (const auto &Function : Functions) {
621     auto MainFileID = findMainViewFileID(Filename, Function);
622     if (!MainFileID)
623       continue;
624     InstantiationSetCollector.insert(Function, *MainFileID);
625   }
626 
627   std::vector<InstantiationGroup> Result;
628   for (auto &InstantiationSet : InstantiationSetCollector) {
629     InstantiationGroup IG{InstantiationSet.first.first,
630                           InstantiationSet.first.second,
631                           std::move(InstantiationSet.second)};
632     Result.emplace_back(std::move(IG));
633   }
634   return Result;
635 }
636 
637 CoverageData
638 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
639   auto MainFileID = findMainViewFileID(Function);
640   if (!MainFileID)
641     return CoverageData();
642 
643   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
644   std::vector<CountedRegion> Regions;
645   for (const auto &CR : Function.CountedRegions)
646     if (CR.FileID == *MainFileID) {
647       Regions.push_back(CR);
648       if (isExpansion(CR, *MainFileID))
649         FunctionCoverage.Expansions.emplace_back(CR, Function);
650     }
651 
652   LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
653                     << "\n");
654   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
655 
656   return FunctionCoverage;
657 }
658 
659 CoverageData CoverageMapping::getCoverageForExpansion(
660     const ExpansionRecord &Expansion) const {
661   CoverageData ExpansionCoverage(
662       Expansion.Function.Filenames[Expansion.FileID]);
663   std::vector<CountedRegion> Regions;
664   for (const auto &CR : Expansion.Function.CountedRegions)
665     if (CR.FileID == Expansion.FileID) {
666       Regions.push_back(CR);
667       if (isExpansion(CR, Expansion.FileID))
668         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
669     }
670 
671   LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
672                     << Expansion.FileID << "\n");
673   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
674 
675   return ExpansionCoverage;
676 }
677 
678 LineCoverageStats::LineCoverageStats(
679     ArrayRef<const CoverageSegment *> LineSegments,
680     const CoverageSegment *WrappedSegment, unsigned Line)
681     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
682       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
683   // Find the minimum number of regions which start in this line.
684   unsigned MinRegionCount = 0;
685   auto isStartOfRegion = [](const CoverageSegment *S) {
686     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
687   };
688   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
689     if (isStartOfRegion(LineSegments[I]))
690       ++MinRegionCount;
691 
692   bool StartOfSkippedRegion = !LineSegments.empty() &&
693                               !LineSegments.front()->HasCount &&
694                               LineSegments.front()->IsRegionEntry;
695 
696   HasMultipleRegions = MinRegionCount > 1;
697   Mapped =
698       !StartOfSkippedRegion &&
699       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
700 
701   if (!Mapped)
702     return;
703 
704   // Pick the max count from the non-gap, region entry segments and the
705   // wrapped count.
706   if (WrappedSegment)
707     ExecutionCount = WrappedSegment->Count;
708   if (!MinRegionCount)
709     return;
710   for (const auto *LS : LineSegments)
711     if (isStartOfRegion(LS))
712       ExecutionCount = std::max(ExecutionCount, LS->Count);
713 }
714 
715 LineCoverageIterator &LineCoverageIterator::operator++() {
716   if (Next == CD.end()) {
717     Stats = LineCoverageStats();
718     Ended = true;
719     return *this;
720   }
721   if (Segments.size())
722     WrappedSegment = Segments.back();
723   Segments.clear();
724   while (Next != CD.end() && Next->Line == Line)
725     Segments.push_back(&*Next++);
726   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
727   ++Line;
728   return *this;
729 }
730 
731 static std::string getCoverageMapErrString(coveragemap_error Err) {
732   switch (Err) {
733   case coveragemap_error::success:
734     return "Success";
735   case coveragemap_error::eof:
736     return "End of File";
737   case coveragemap_error::no_data_found:
738     return "No coverage data found";
739   case coveragemap_error::unsupported_version:
740     return "Unsupported coverage format version";
741   case coveragemap_error::truncated:
742     return "Truncated coverage data";
743   case coveragemap_error::malformed:
744     return "Malformed coverage data";
745   }
746   llvm_unreachable("A value of coveragemap_error has no message.");
747 }
748 
749 namespace {
750 
751 // FIXME: This class is only here to support the transition to llvm::Error. It
752 // will be removed once this transition is complete. Clients should prefer to
753 // deal with the Error value directly, rather than converting to error_code.
754 class CoverageMappingErrorCategoryType : public std::error_category {
755   const char *name() const noexcept override { return "llvm.coveragemap"; }
756   std::string message(int IE) const override {
757     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
758   }
759 };
760 
761 } // end anonymous namespace
762 
763 std::string CoverageMapError::message() const {
764   return getCoverageMapErrString(Err);
765 }
766 
767 static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
768 
769 const std::error_category &llvm::coverage::coveragemap_category() {
770   return *ErrorCategory;
771 }
772 
773 char CoverageMapError::ID = 0;
774