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