xref: /llvm-project/llvm/lib/ProfileData/Coverage/CoverageMapping.cpp (revision 1f6a347c8abf8868fb4630c404480226c2efc2c2)
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/STLExtras.h"
18 #include "llvm/ADT/SmallBitVector.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/StringExtras.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Object/BuildID.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/MemoryBuffer.h"
30 #include "llvm/Support/VirtualFileSystem.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm>
33 #include <cassert>
34 #include <cmath>
35 #include <cstdint>
36 #include <iterator>
37 #include <map>
38 #include <memory>
39 #include <optional>
40 #include <string>
41 #include <system_error>
42 #include <utility>
43 #include <vector>
44 
45 using namespace llvm;
46 using namespace coverage;
47 
48 #define DEBUG_TYPE "coverage-mapping"
49 
50 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
51   auto It = ExpressionIndices.find(E);
52   if (It != ExpressionIndices.end())
53     return Counter::getExpression(It->second);
54   unsigned I = Expressions.size();
55   Expressions.push_back(E);
56   ExpressionIndices[E] = I;
57   return Counter::getExpression(I);
58 }
59 
60 void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
61                                             SmallVectorImpl<Term> &Terms) {
62   switch (C.getKind()) {
63   case Counter::Zero:
64     break;
65   case Counter::CounterValueReference:
66     Terms.emplace_back(C.getCounterID(), Factor);
67     break;
68   case Counter::Expression:
69     const auto &E = Expressions[C.getExpressionID()];
70     extractTerms(E.LHS, Factor, Terms);
71     extractTerms(
72         E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
73     break;
74   }
75 }
76 
77 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
78   // Gather constant terms.
79   SmallVector<Term, 32> Terms;
80   extractTerms(ExpressionTree, +1, Terms);
81 
82   // If there are no terms, this is just a zero. The algorithm below assumes at
83   // least one term.
84   if (Terms.size() == 0)
85     return Counter::getZero();
86 
87   // Group the terms by counter ID.
88   llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
89     return LHS.CounterID < RHS.CounterID;
90   });
91 
92   // Combine terms by counter ID to eliminate counters that sum to zero.
93   auto Prev = Terms.begin();
94   for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
95     if (I->CounterID == Prev->CounterID) {
96       Prev->Factor += I->Factor;
97       continue;
98     }
99     ++Prev;
100     *Prev = *I;
101   }
102   Terms.erase(++Prev, Terms.end());
103 
104   Counter C;
105   // Create additions. We do this before subtractions to avoid constructs like
106   // ((0 - X) + Y), as opposed to (Y - X).
107   for (auto T : Terms) {
108     if (T.Factor <= 0)
109       continue;
110     for (int I = 0; I < T.Factor; ++I)
111       if (C.isZero())
112         C = Counter::getCounter(T.CounterID);
113       else
114         C = get(CounterExpression(CounterExpression::Add, C,
115                                   Counter::getCounter(T.CounterID)));
116   }
117 
118   // Create subtractions.
119   for (auto T : Terms) {
120     if (T.Factor >= 0)
121       continue;
122     for (int I = 0; I < -T.Factor; ++I)
123       C = get(CounterExpression(CounterExpression::Subtract, C,
124                                 Counter::getCounter(T.CounterID)));
125   }
126   return C;
127 }
128 
129 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS, bool Simplify) {
130   auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS));
131   return Simplify ? simplify(Cnt) : Cnt;
132 }
133 
134 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS,
135                                            bool Simplify) {
136   auto Cnt = get(CounterExpression(CounterExpression::Subtract, LHS, RHS));
137   return Simplify ? simplify(Cnt) : Cnt;
138 }
139 
140 void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
141   switch (C.getKind()) {
142   case Counter::Zero:
143     OS << '0';
144     return;
145   case Counter::CounterValueReference:
146     OS << '#' << C.getCounterID();
147     break;
148   case Counter::Expression: {
149     if (C.getExpressionID() >= Expressions.size())
150       return;
151     const auto &E = Expressions[C.getExpressionID()];
152     OS << '(';
153     dump(E.LHS, OS);
154     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
155     dump(E.RHS, OS);
156     OS << ')';
157     break;
158   }
159   }
160   if (CounterValues.empty())
161     return;
162   Expected<int64_t> Value = evaluate(C);
163   if (auto E = Value.takeError()) {
164     consumeError(std::move(E));
165     return;
166   }
167   OS << '[' << *Value << ']';
168 }
169 
170 Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
171   struct StackElem {
172     Counter ICounter;
173     int64_t LHS = 0;
174     enum {
175       KNeverVisited = 0,
176       KVisitedOnce = 1,
177       KVisitedTwice = 2,
178     } VisitCount = KNeverVisited;
179   };
180 
181   std::stack<StackElem> CounterStack;
182   CounterStack.push({C});
183 
184   int64_t LastPoppedValue;
185 
186   while (!CounterStack.empty()) {
187     StackElem &Current = CounterStack.top();
188 
189     switch (Current.ICounter.getKind()) {
190     case Counter::Zero:
191       LastPoppedValue = 0;
192       CounterStack.pop();
193       break;
194     case Counter::CounterValueReference:
195       if (Current.ICounter.getCounterID() >= CounterValues.size())
196         return errorCodeToError(errc::argument_out_of_domain);
197       LastPoppedValue = CounterValues[Current.ICounter.getCounterID()];
198       CounterStack.pop();
199       break;
200     case Counter::Expression: {
201       if (Current.ICounter.getExpressionID() >= Expressions.size())
202         return errorCodeToError(errc::argument_out_of_domain);
203       const auto &E = Expressions[Current.ICounter.getExpressionID()];
204       if (Current.VisitCount == StackElem::KNeverVisited) {
205         CounterStack.push(StackElem{E.LHS});
206         Current.VisitCount = StackElem::KVisitedOnce;
207       } else if (Current.VisitCount == StackElem::KVisitedOnce) {
208         Current.LHS = LastPoppedValue;
209         CounterStack.push(StackElem{E.RHS});
210         Current.VisitCount = StackElem::KVisitedTwice;
211       } else {
212         int64_t LHS = Current.LHS;
213         int64_t RHS = LastPoppedValue;
214         LastPoppedValue =
215             E.Kind == CounterExpression::Subtract ? LHS - RHS : LHS + RHS;
216         CounterStack.pop();
217       }
218       break;
219     }
220     }
221   }
222 
223   return LastPoppedValue;
224 }
225 
226 namespace {
227 
228 class MCDCRecordProcessor {
229   /// A bitmap representing the executed test vectors for a boolean expression.
230   /// Each index of the bitmap corresponds to a possible test vector. An index
231   /// with a bit value of '1' indicates that the corresponding Test Vector
232   /// identified by that index was executed.
233   const BitVector &Bitmap;
234 
235   /// Decision Region to which the ExecutedTestVectorBitmap applies.
236   const CounterMappingRegion &Region;
237   const mcdc::DecisionParameters &DecisionParams;
238 
239   /// Array of branch regions corresponding each conditions in the boolean
240   /// expression.
241   ArrayRef<const CounterMappingRegion *> Branches;
242 
243   /// Total number of conditions in the boolean expression.
244   unsigned NumConditions;
245 
246   /// Mapping of a condition ID to its corresponding branch params.
247   llvm::DenseMap<unsigned, mcdc::ConditionIDs> CondsMap;
248 
249   /// Vector used to track whether a condition is constant folded.
250   MCDCRecord::BoolVector Folded;
251 
252   /// Mapping of calculated MC/DC Independence Pairs for each condition.
253   MCDCRecord::TVPairMap IndependencePairs;
254 
255   /// Actual executed Test Vectors for the boolean expression, based on
256   /// ExecutedTestVectorBitmap.
257   MCDCRecord::TestVectors ExecVectors;
258 
259 public:
260   MCDCRecordProcessor(const BitVector &Bitmap,
261                       const CounterMappingRegion &Region,
262                       ArrayRef<const CounterMappingRegion *> Branches)
263       : Bitmap(Bitmap), Region(Region),
264         DecisionParams(Region.getDecisionParams()), Branches(Branches),
265         NumConditions(DecisionParams.NumConditions),
266         Folded(NumConditions, false), IndependencePairs(NumConditions) {}
267 
268 private:
269   // Walk the binary decision diagram and try assigning both false and true to
270   // each node. When a terminal node (ID == 0) is reached, fill in the value in
271   // the truth table.
272   void buildTestVector(MCDCRecord::TestVector &TV, mcdc::ConditionID ID,
273                        unsigned Index) {
274     assert((Index & (1 << ID)) == 0);
275 
276     for (auto MCDCCond : {MCDCRecord::MCDC_False, MCDCRecord::MCDC_True}) {
277       static_assert(MCDCRecord::MCDC_False == 0);
278       static_assert(MCDCRecord::MCDC_True == 1);
279       Index |= MCDCCond << ID;
280       TV[ID] = MCDCCond;
281       auto NextID = CondsMap[ID][MCDCCond];
282       if (NextID >= 0) {
283         buildTestVector(TV, NextID, Index);
284         continue;
285       }
286 
287       if (!Bitmap[DecisionParams.BitmapIdx * CHAR_BIT + Index])
288         continue;
289 
290       // Copy the completed test vector to the vector of testvectors.
291       ExecVectors.push_back(TV);
292 
293       // The final value (T,F) is equal to the last non-dontcare state on the
294       // path (in a short-circuiting system).
295       ExecVectors.back().push_back(MCDCCond);
296     }
297 
298     // Reset back to DontCare.
299     TV[ID] = MCDCRecord::MCDC_DontCare;
300   }
301 
302   /// Walk the bits in the bitmap.  A bit set to '1' indicates that the test
303   /// vector at the corresponding index was executed during a test run.
304   void findExecutedTestVectors() {
305     // Walk the binary decision diagram to enumerate all possible test vectors.
306     // We start at the root node (ID == 0) with all values being DontCare.
307     // `Index` encodes the bitmask of true values and is initially 0.
308     MCDCRecord::TestVector TV(NumConditions, MCDCRecord::MCDC_DontCare);
309     buildTestVector(TV, 0, 0);
310   }
311 
312   // Find an independence pair for each condition:
313   // - The condition is true in one test and false in the other.
314   // - The decision outcome is true one test and false in the other.
315   // - All other conditions' values must be equal or marked as "don't care".
316   void findIndependencePairs() {
317     unsigned NumTVs = ExecVectors.size();
318     for (unsigned I = 1; I < NumTVs; ++I) {
319       const MCDCRecord::TestVector &A = ExecVectors[I];
320       for (unsigned J = 0; J < I; ++J) {
321         const MCDCRecord::TestVector &B = ExecVectors[J];
322         // Enumerate two execution vectors whose outcomes are different.
323         if (A[NumConditions] == B[NumConditions])
324           continue;
325         unsigned Flip = NumConditions, Idx;
326         for (Idx = 0; Idx < NumConditions; ++Idx) {
327           MCDCRecord::CondState ACond = A[Idx], BCond = B[Idx];
328           if (ACond == BCond || ACond == MCDCRecord::MCDC_DontCare ||
329               BCond == MCDCRecord::MCDC_DontCare)
330             continue;
331           if (Flip != NumConditions)
332             break;
333           Flip = Idx;
334         }
335         // If the two vectors differ in exactly one condition, ignoring DontCare
336         // conditions, we have found an independence pair.
337         if (Idx == NumConditions && Flip != NumConditions)
338           IndependencePairs.insert({Flip, std::make_pair(J + 1, I + 1)});
339       }
340     }
341   }
342 
343 public:
344   /// Process the MC/DC Record in order to produce a result for a boolean
345   /// expression. This process includes tracking the conditions that comprise
346   /// the decision region, calculating the list of all possible test vectors,
347   /// marking the executed test vectors, and then finding an Independence Pair
348   /// out of the executed test vectors for each condition in the boolean
349   /// expression. A condition is tracked to ensure that its ID can be mapped to
350   /// its ordinal position in the boolean expression. The condition's source
351   /// location is also tracked, as well as whether it is constant folded (in
352   /// which case it is excuded from the metric).
353   MCDCRecord processMCDCRecord() {
354     unsigned I = 0;
355     MCDCRecord::CondIDMap PosToID;
356     MCDCRecord::LineColPairMap CondLoc;
357 
358     // Walk the Record's BranchRegions (representing Conditions) in order to:
359     // - Hash the condition based on its corresponding ID. This will be used to
360     //   calculate the test vectors.
361     // - Keep a map of the condition's ordinal position (1, 2, 3, 4) to its
362     //   actual ID.  This will be used to visualize the conditions in the
363     //   correct order.
364     // - Keep track of the condition source location. This will be used to
365     //   visualize where the condition is.
366     // - Record whether the condition is constant folded so that we exclude it
367     //   from being measured.
368     for (const auto *B : Branches) {
369       const auto &BranchParams = B->getBranchParams();
370       CondsMap[BranchParams.ID] = BranchParams.Conds;
371       PosToID[I] = BranchParams.ID;
372       CondLoc[I] = B->startLoc();
373       Folded[I++] = (B->Count.isZero() && B->FalseCount.isZero());
374     }
375 
376     // Using Profile Bitmap from runtime, mark the executed test vectors.
377     findExecutedTestVectors();
378 
379     // Compare executed test vectors against each other to find an independence
380     // pairs for each condition.  This processing takes the most time.
381     findIndependencePairs();
382 
383     // Record Test vectors, executed vectors, and independence pairs.
384     return MCDCRecord(Region, std::move(ExecVectors),
385                       std::move(IndependencePairs), std::move(Folded),
386                       std::move(PosToID), std::move(CondLoc));
387   }
388 };
389 
390 } // namespace
391 
392 Expected<MCDCRecord> CounterMappingContext::evaluateMCDCRegion(
393     const CounterMappingRegion &Region,
394     ArrayRef<const CounterMappingRegion *> Branches) {
395 
396   MCDCRecordProcessor MCDCProcessor(Bitmap, Region, Branches);
397   return MCDCProcessor.processMCDCRecord();
398 }
399 
400 unsigned CounterMappingContext::getMaxCounterID(const Counter &C) const {
401   struct StackElem {
402     Counter ICounter;
403     int64_t LHS = 0;
404     enum {
405       KNeverVisited = 0,
406       KVisitedOnce = 1,
407       KVisitedTwice = 2,
408     } VisitCount = KNeverVisited;
409   };
410 
411   std::stack<StackElem> CounterStack;
412   CounterStack.push({C});
413 
414   int64_t LastPoppedValue;
415 
416   while (!CounterStack.empty()) {
417     StackElem &Current = CounterStack.top();
418 
419     switch (Current.ICounter.getKind()) {
420     case Counter::Zero:
421       LastPoppedValue = 0;
422       CounterStack.pop();
423       break;
424     case Counter::CounterValueReference:
425       LastPoppedValue = Current.ICounter.getCounterID();
426       CounterStack.pop();
427       break;
428     case Counter::Expression: {
429       if (Current.ICounter.getExpressionID() >= Expressions.size()) {
430         LastPoppedValue = 0;
431         CounterStack.pop();
432       } else {
433         const auto &E = Expressions[Current.ICounter.getExpressionID()];
434         if (Current.VisitCount == StackElem::KNeverVisited) {
435           CounterStack.push(StackElem{E.LHS});
436           Current.VisitCount = StackElem::KVisitedOnce;
437         } else if (Current.VisitCount == StackElem::KVisitedOnce) {
438           Current.LHS = LastPoppedValue;
439           CounterStack.push(StackElem{E.RHS});
440           Current.VisitCount = StackElem::KVisitedTwice;
441         } else {
442           int64_t LHS = Current.LHS;
443           int64_t RHS = LastPoppedValue;
444           LastPoppedValue = std::max(LHS, RHS);
445           CounterStack.pop();
446         }
447       }
448       break;
449     }
450     }
451   }
452 
453   return LastPoppedValue;
454 }
455 
456 void FunctionRecordIterator::skipOtherFiles() {
457   while (Current != Records.end() && !Filename.empty() &&
458          Filename != Current->Filenames[0])
459     ++Current;
460   if (Current == Records.end())
461     *this = FunctionRecordIterator();
462 }
463 
464 ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename(
465     StringRef Filename) const {
466   size_t FilenameHash = hash_value(Filename);
467   auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
468   if (RecordIt == FilenameHash2RecordIndices.end())
469     return {};
470   return RecordIt->second;
471 }
472 
473 static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
474                                 const CoverageMappingRecord &Record) {
475   unsigned MaxCounterID = 0;
476   for (const auto &Region : Record.MappingRegions) {
477     MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count));
478   }
479   return MaxCounterID;
480 }
481 
482 /// Returns the bit count
483 static unsigned getMaxBitmapSize(const CounterMappingContext &Ctx,
484                                  const CoverageMappingRecord &Record) {
485   unsigned MaxBitmapIdx = 0;
486   unsigned NumConditions = 0;
487   // Scan max(BitmapIdx).
488   // Note that `<=` is used insted of `<`, because `BitmapIdx == 0` is valid
489   // and `MaxBitmapIdx is `unsigned`. `BitmapIdx` is unique in the record.
490   for (const auto &Region : reverse(Record.MappingRegions)) {
491     if (Region.Kind != CounterMappingRegion::MCDCDecisionRegion)
492       continue;
493     const auto &DecisionParams = Region.getDecisionParams();
494     if (MaxBitmapIdx <= DecisionParams.BitmapIdx) {
495       MaxBitmapIdx = DecisionParams.BitmapIdx;
496       NumConditions = DecisionParams.NumConditions;
497     }
498   }
499   unsigned SizeInBits = llvm::alignTo(uint64_t(1) << NumConditions, CHAR_BIT);
500   return MaxBitmapIdx * CHAR_BIT + SizeInBits;
501 }
502 
503 namespace {
504 
505 /// Collect Decisions, Branchs, and Expansions and associate them.
506 class MCDCDecisionRecorder {
507 private:
508   /// This holds the DecisionRegion and MCDCBranches under it.
509   /// Also traverses Expansion(s).
510   /// The Decision has the number of MCDCBranches and will complete
511   /// when it is filled with unique ConditionID of MCDCBranches.
512   struct DecisionRecord {
513     const CounterMappingRegion *DecisionRegion;
514 
515     /// They are reflected from DecisionRegion for convenience.
516     mcdc::DecisionParameters DecisionParams;
517     LineColPair DecisionStartLoc;
518     LineColPair DecisionEndLoc;
519 
520     /// This is passed to `MCDCRecordProcessor`, so this should be compatible
521     /// to`ArrayRef<const CounterMappingRegion *>`.
522     SmallVector<const CounterMappingRegion *> MCDCBranches;
523 
524     /// IDs that are stored in MCDCBranches
525     /// Complete when all IDs (1 to NumConditions) are met.
526     DenseSet<mcdc::ConditionID> ConditionIDs;
527 
528     /// Set of IDs of Expansion(s) that are relevant to DecisionRegion
529     /// and its children (via expansions).
530     /// FileID  pointed by ExpandedFileID is dedicated to the expansion, so
531     /// the location in the expansion doesn't matter.
532     DenseSet<unsigned> ExpandedFileIDs;
533 
534     DecisionRecord(const CounterMappingRegion &Decision)
535         : DecisionRegion(&Decision),
536           DecisionParams(Decision.getDecisionParams()),
537           DecisionStartLoc(Decision.startLoc()),
538           DecisionEndLoc(Decision.endLoc()) {
539       assert(Decision.Kind == CounterMappingRegion::MCDCDecisionRegion);
540     }
541 
542     /// Determine whether DecisionRecord dominates `R`.
543     bool dominates(const CounterMappingRegion &R) const {
544       // Determine whether `R` is included in `DecisionRegion`.
545       if (R.FileID == DecisionRegion->FileID &&
546           R.startLoc() >= DecisionStartLoc && R.endLoc() <= DecisionEndLoc)
547         return true;
548 
549       // Determine whether `R` is pointed by any of Expansions.
550       return ExpandedFileIDs.contains(R.FileID);
551     }
552 
553     enum Result {
554       NotProcessed = 0, /// Irrelevant to this Decision
555       Processed,        /// Added to this Decision
556       Completed,        /// Added and filled this Decision
557     };
558 
559     /// Add Branch into the Decision
560     /// \param Branch expects MCDCBranchRegion
561     /// \returns NotProcessed/Processed/Completed
562     Result addBranch(const CounterMappingRegion &Branch) {
563       assert(Branch.Kind == CounterMappingRegion::MCDCBranchRegion);
564 
565       auto ConditionID = Branch.getBranchParams().ID;
566       assert(ConditionID >= 0 && "ConditionID should be positive");
567 
568       if (ConditionIDs.contains(ConditionID) ||
569           ConditionID >= DecisionParams.NumConditions)
570         return NotProcessed;
571 
572       if (!this->dominates(Branch))
573         return NotProcessed;
574 
575       assert(MCDCBranches.size() < DecisionParams.NumConditions);
576 
577       // Put `ID=0` in front of `MCDCBranches` for convenience
578       // even if `MCDCBranches` is not topological.
579       if (ConditionID == 0)
580         MCDCBranches.insert(MCDCBranches.begin(), &Branch);
581       else
582         MCDCBranches.push_back(&Branch);
583 
584       // Mark `ID` as `assigned`.
585       ConditionIDs.insert(ConditionID);
586 
587       // `Completed` when `MCDCBranches` is full
588       return (MCDCBranches.size() == DecisionParams.NumConditions ? Completed
589                                                                   : Processed);
590     }
591 
592     /// Record Expansion if it is relevant to this Decision.
593     /// Each `Expansion` may nest.
594     /// \returns true if recorded.
595     bool recordExpansion(const CounterMappingRegion &Expansion) {
596       if (!this->dominates(Expansion))
597         return false;
598 
599       ExpandedFileIDs.insert(Expansion.ExpandedFileID);
600       return true;
601     }
602   };
603 
604 private:
605   /// Decisions in progress
606   /// DecisionRecord is added for each MCDCDecisionRegion.
607   /// DecisionRecord is removed when Decision is completed.
608   SmallVector<DecisionRecord> Decisions;
609 
610 public:
611   ~MCDCDecisionRecorder() {
612     assert(Decisions.empty() && "All Decisions have not been resolved");
613   }
614 
615   /// Register Region and start recording.
616   void registerDecision(const CounterMappingRegion &Decision) {
617     Decisions.emplace_back(Decision);
618   }
619 
620   void recordExpansion(const CounterMappingRegion &Expansion) {
621     any_of(Decisions, [&Expansion](auto &Decision) {
622       return Decision.recordExpansion(Expansion);
623     });
624   }
625 
626   using DecisionAndBranches =
627       std::pair<const CounterMappingRegion *,             /// Decision
628                 SmallVector<const CounterMappingRegion *> /// Branches
629                 >;
630 
631   /// Add MCDCBranchRegion to DecisionRecord.
632   /// \param Branch to be processed
633   /// \returns DecisionsAndBranches if DecisionRecord completed.
634   ///     Or returns nullopt.
635   std::optional<DecisionAndBranches>
636   processBranch(const CounterMappingRegion &Branch) {
637     // Seek each Decision and apply Region to it.
638     for (auto DecisionIter = Decisions.begin(), DecisionEnd = Decisions.end();
639          DecisionIter != DecisionEnd; ++DecisionIter)
640       switch (DecisionIter->addBranch(Branch)) {
641       case DecisionRecord::NotProcessed:
642         continue;
643       case DecisionRecord::Processed:
644         return std::nullopt;
645       case DecisionRecord::Completed:
646         DecisionAndBranches Result =
647             std::make_pair(DecisionIter->DecisionRegion,
648                            std::move(DecisionIter->MCDCBranches));
649         Decisions.erase(DecisionIter); // No longer used.
650         return Result;
651       }
652 
653     llvm_unreachable("Branch not found in Decisions");
654   }
655 };
656 
657 } // namespace
658 
659 Error CoverageMapping::loadFunctionRecord(
660     const CoverageMappingRecord &Record,
661     IndexedInstrProfReader &ProfileReader) {
662   StringRef OrigFuncName = Record.FunctionName;
663   if (OrigFuncName.empty())
664     return make_error<CoverageMapError>(coveragemap_error::malformed,
665                                         "record function name is empty");
666 
667   if (Record.Filenames.empty())
668     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
669   else
670     OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
671 
672   CounterMappingContext Ctx(Record.Expressions);
673 
674   std::vector<uint64_t> Counts;
675   if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
676                                                 Record.FunctionHash, Counts)) {
677     instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
678     if (IPE == instrprof_error::hash_mismatch) {
679       FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
680                                       Record.FunctionHash);
681       return Error::success();
682     }
683     if (IPE != instrprof_error::unknown_function)
684       return make_error<InstrProfError>(IPE);
685     Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
686   }
687   Ctx.setCounts(Counts);
688 
689   BitVector Bitmap;
690   if (Error E = ProfileReader.getFunctionBitmap(Record.FunctionName,
691                                                 Record.FunctionHash, Bitmap)) {
692     instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
693     if (IPE == instrprof_error::hash_mismatch) {
694       FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
695                                       Record.FunctionHash);
696       return Error::success();
697     }
698     if (IPE != instrprof_error::unknown_function)
699       return make_error<InstrProfError>(IPE);
700     Bitmap = BitVector(getMaxBitmapSize(Ctx, Record));
701   }
702   Ctx.setBitmap(std::move(Bitmap));
703 
704   assert(!Record.MappingRegions.empty() && "Function has no regions");
705 
706   // This coverage record is a zero region for a function that's unused in
707   // some TU, but used in a different TU. Ignore it. The coverage maps from the
708   // the other TU will either be loaded (providing full region counts) or they
709   // won't (in which case we don't unintuitively report functions as uncovered
710   // when they have non-zero counts in the profile).
711   if (Record.MappingRegions.size() == 1 &&
712       Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
713     return Error::success();
714 
715   MCDCDecisionRecorder MCDCDecisions;
716   FunctionRecord Function(OrigFuncName, Record.Filenames);
717   for (const auto &Region : Record.MappingRegions) {
718     // MCDCDecisionRegion should be handled first since it overlaps with
719     // others inside.
720     if (Region.Kind == CounterMappingRegion::MCDCDecisionRegion) {
721       MCDCDecisions.registerDecision(Region);
722       continue;
723     }
724     Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
725     if (auto E = ExecutionCount.takeError()) {
726       consumeError(std::move(E));
727       return Error::success();
728     }
729     Expected<int64_t> AltExecutionCount = Ctx.evaluate(Region.FalseCount);
730     if (auto E = AltExecutionCount.takeError()) {
731       consumeError(std::move(E));
732       return Error::success();
733     }
734     Function.pushRegion(Region, *ExecutionCount, *AltExecutionCount);
735 
736     // Record ExpansionRegion.
737     if (Region.Kind == CounterMappingRegion::ExpansionRegion) {
738       MCDCDecisions.recordExpansion(Region);
739       continue;
740     }
741 
742     // Do nothing unless MCDCBranchRegion.
743     if (Region.Kind != CounterMappingRegion::MCDCBranchRegion)
744       continue;
745 
746     auto Result = MCDCDecisions.processBranch(Region);
747     if (!Result) // Any Decision doesn't complete.
748       continue;
749 
750     auto MCDCDecision = Result->first;
751     auto &MCDCBranches = Result->second;
752 
753     // Since the bitmap identifies the executed test vectors for an MC/DC
754     // DecisionRegion, all of the information is now available to process.
755     // This is where the bulk of the MC/DC progressing takes place.
756     Expected<MCDCRecord> Record =
757         Ctx.evaluateMCDCRegion(*MCDCDecision, MCDCBranches);
758     if (auto E = Record.takeError()) {
759       consumeError(std::move(E));
760       return Error::success();
761     }
762 
763     // Save the MC/DC Record so that it can be visualized later.
764     Function.pushMCDCRecord(std::move(*Record));
765   }
766 
767   // Don't create records for (filenames, function) pairs we've already seen.
768   auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
769                                           Record.Filenames.end());
770   if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
771     return Error::success();
772 
773   Functions.push_back(std::move(Function));
774 
775   // Performance optimization: keep track of the indices of the function records
776   // which correspond to each filename. This can be used to substantially speed
777   // up queries for coverage info in a file.
778   unsigned RecordIndex = Functions.size() - 1;
779   for (StringRef Filename : Record.Filenames) {
780     auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)];
781     // Note that there may be duplicates in the filename set for a function
782     // record, because of e.g. macro expansions in the function in which both
783     // the macro and the function are defined in the same file.
784     if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
785       RecordIndices.push_back(RecordIndex);
786   }
787 
788   return Error::success();
789 }
790 
791 // This function is for memory optimization by shortening the lifetimes
792 // of CoverageMappingReader instances.
793 Error CoverageMapping::loadFromReaders(
794     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
795     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage) {
796   for (const auto &CoverageReader : CoverageReaders) {
797     for (auto RecordOrErr : *CoverageReader) {
798       if (Error E = RecordOrErr.takeError())
799         return E;
800       const auto &Record = *RecordOrErr;
801       if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader))
802         return E;
803     }
804   }
805   return Error::success();
806 }
807 
808 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
809     ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
810     IndexedInstrProfReader &ProfileReader) {
811   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
812   if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
813     return std::move(E);
814   return std::move(Coverage);
815 }
816 
817 // If E is a no_data_found error, returns success. Otherwise returns E.
818 static Error handleMaybeNoDataFoundError(Error E) {
819   return handleErrors(
820       std::move(E), [](const CoverageMapError &CME) {
821         if (CME.get() == coveragemap_error::no_data_found)
822           return static_cast<Error>(Error::success());
823         return make_error<CoverageMapError>(CME.get(), CME.getMessage());
824       });
825 }
826 
827 Error CoverageMapping::loadFromFile(
828     StringRef Filename, StringRef Arch, StringRef CompilationDir,
829     IndexedInstrProfReader &ProfileReader, CoverageMapping &Coverage,
830     bool &DataFound, SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
831   auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
832       Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false);
833   if (std::error_code EC = CovMappingBufOrErr.getError())
834     return createFileError(Filename, errorCodeToError(EC));
835   MemoryBufferRef CovMappingBufRef =
836       CovMappingBufOrErr.get()->getMemBufferRef();
837   SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
838 
839   SmallVector<object::BuildIDRef> BinaryIDs;
840   auto CoverageReadersOrErr = BinaryCoverageReader::create(
841       CovMappingBufRef, Arch, Buffers, CompilationDir,
842       FoundBinaryIDs ? &BinaryIDs : nullptr);
843   if (Error E = CoverageReadersOrErr.takeError()) {
844     E = handleMaybeNoDataFoundError(std::move(E));
845     if (E)
846       return createFileError(Filename, std::move(E));
847     return E;
848   }
849 
850   SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
851   for (auto &Reader : CoverageReadersOrErr.get())
852     Readers.push_back(std::move(Reader));
853   if (FoundBinaryIDs && !Readers.empty()) {
854     llvm::append_range(*FoundBinaryIDs,
855                        llvm::map_range(BinaryIDs, [](object::BuildIDRef BID) {
856                          return object::BuildID(BID);
857                        }));
858   }
859   DataFound |= !Readers.empty();
860   if (Error E = loadFromReaders(Readers, ProfileReader, Coverage))
861     return createFileError(Filename, std::move(E));
862   return Error::success();
863 }
864 
865 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
866     ArrayRef<StringRef> ObjectFilenames, StringRef ProfileFilename,
867     vfs::FileSystem &FS, ArrayRef<StringRef> Arches, StringRef CompilationDir,
868     const object::BuildIDFetcher *BIDFetcher, bool CheckBinaryIDs) {
869   auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename, FS);
870   if (Error E = ProfileReaderOrErr.takeError())
871     return createFileError(ProfileFilename, std::move(E));
872   auto ProfileReader = std::move(ProfileReaderOrErr.get());
873   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
874   bool DataFound = false;
875 
876   auto GetArch = [&](size_t Idx) {
877     if (Arches.empty())
878       return StringRef();
879     if (Arches.size() == 1)
880       return Arches.front();
881     return Arches[Idx];
882   };
883 
884   SmallVector<object::BuildID> FoundBinaryIDs;
885   for (const auto &File : llvm::enumerate(ObjectFilenames)) {
886     if (Error E =
887             loadFromFile(File.value(), GetArch(File.index()), CompilationDir,
888                          *ProfileReader, *Coverage, DataFound, &FoundBinaryIDs))
889       return std::move(E);
890   }
891 
892   if (BIDFetcher) {
893     std::vector<object::BuildID> ProfileBinaryIDs;
894     if (Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs))
895       return createFileError(ProfileFilename, std::move(E));
896 
897     SmallVector<object::BuildIDRef> BinaryIDsToFetch;
898     if (!ProfileBinaryIDs.empty()) {
899       const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) {
900         return std::lexicographical_compare(A.begin(), A.end(), B.begin(),
901                                             B.end());
902       };
903       llvm::sort(FoundBinaryIDs, Compare);
904       std::set_difference(
905           ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(),
906           FoundBinaryIDs.begin(), FoundBinaryIDs.end(),
907           std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.end()), Compare);
908     }
909 
910     for (object::BuildIDRef BinaryID : BinaryIDsToFetch) {
911       std::optional<std::string> PathOpt = BIDFetcher->fetch(BinaryID);
912       if (PathOpt) {
913         std::string Path = std::move(*PathOpt);
914         StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef();
915         if (Error E = loadFromFile(Path, Arch, CompilationDir, *ProfileReader,
916                                   *Coverage, DataFound))
917           return std::move(E);
918       } else if (CheckBinaryIDs) {
919         return createFileError(
920             ProfileFilename,
921             createStringError(errc::no_such_file_or_directory,
922                               "Missing binary ID: " +
923                                   llvm::toHex(BinaryID, /*LowerCase=*/true)));
924       }
925     }
926   }
927 
928   if (!DataFound)
929     return createFileError(
930         join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
931         make_error<CoverageMapError>(coveragemap_error::no_data_found));
932   return std::move(Coverage);
933 }
934 
935 namespace {
936 
937 /// Distributes functions into instantiation sets.
938 ///
939 /// An instantiation set is a collection of functions that have the same source
940 /// code, ie, template functions specializations.
941 class FunctionInstantiationSetCollector {
942   using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
943   MapT InstantiatedFunctions;
944 
945 public:
946   void insert(const FunctionRecord &Function, unsigned FileID) {
947     auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
948     while (I != E && I->FileID != FileID)
949       ++I;
950     assert(I != E && "function does not cover the given file");
951     auto &Functions = InstantiatedFunctions[I->startLoc()];
952     Functions.push_back(&Function);
953   }
954 
955   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
956   MapT::iterator end() { return InstantiatedFunctions.end(); }
957 };
958 
959 class SegmentBuilder {
960   std::vector<CoverageSegment> &Segments;
961   SmallVector<const CountedRegion *, 8> ActiveRegions;
962 
963   SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
964 
965   /// Emit a segment with the count from \p Region starting at \p StartLoc.
966   //
967   /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
968   /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
969   void startSegment(const CountedRegion &Region, LineColPair StartLoc,
970                     bool IsRegionEntry, bool EmitSkippedRegion = false) {
971     bool HasCount = !EmitSkippedRegion &&
972                     (Region.Kind != CounterMappingRegion::SkippedRegion);
973 
974     // If the new segment wouldn't affect coverage rendering, skip it.
975     if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
976       const auto &Last = Segments.back();
977       if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
978           !Last.IsRegionEntry)
979         return;
980     }
981 
982     if (HasCount)
983       Segments.emplace_back(StartLoc.first, StartLoc.second,
984                             Region.ExecutionCount, IsRegionEntry,
985                             Region.Kind == CounterMappingRegion::GapRegion);
986     else
987       Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
988 
989     LLVM_DEBUG({
990       const auto &Last = Segments.back();
991       dbgs() << "Segment at " << Last.Line << ":" << Last.Col
992              << " (count = " << Last.Count << ")"
993              << (Last.IsRegionEntry ? ", RegionEntry" : "")
994              << (!Last.HasCount ? ", Skipped" : "")
995              << (Last.IsGapRegion ? ", Gap" : "") << "\n";
996     });
997   }
998 
999   /// Emit segments for active regions which end before \p Loc.
1000   ///
1001   /// \p Loc: The start location of the next region. If std::nullopt, all active
1002   /// regions are completed.
1003   /// \p FirstCompletedRegion: Index of the first completed region.
1004   void completeRegionsUntil(std::optional<LineColPair> Loc,
1005                             unsigned FirstCompletedRegion) {
1006     // Sort the completed regions by end location. This makes it simple to
1007     // emit closing segments in sorted order.
1008     auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
1009     std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
1010                       [](const CountedRegion *L, const CountedRegion *R) {
1011                         return L->endLoc() < R->endLoc();
1012                       });
1013 
1014     // Emit segments for all completed regions.
1015     for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
1016          ++I) {
1017       const auto *CompletedRegion = ActiveRegions[I];
1018       assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
1019              "Completed region ends after start of new region");
1020 
1021       const auto *PrevCompletedRegion = ActiveRegions[I - 1];
1022       auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
1023 
1024       // Don't emit any more segments if they start where the new region begins.
1025       if (Loc && CompletedSegmentLoc == *Loc)
1026         break;
1027 
1028       // Don't emit a segment if the next completed region ends at the same
1029       // location as this one.
1030       if (CompletedSegmentLoc == CompletedRegion->endLoc())
1031         continue;
1032 
1033       // Use the count from the last completed region which ends at this loc.
1034       for (unsigned J = I + 1; J < E; ++J)
1035         if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
1036           CompletedRegion = ActiveRegions[J];
1037 
1038       startSegment(*CompletedRegion, CompletedSegmentLoc, false);
1039     }
1040 
1041     auto Last = ActiveRegions.back();
1042     if (FirstCompletedRegion && Last->endLoc() != *Loc) {
1043       // If there's a gap after the end of the last completed region and the
1044       // start of the new region, use the last active region to fill the gap.
1045       startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
1046                    false);
1047     } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
1048       // Emit a skipped segment if there are no more active regions. This
1049       // ensures that gaps between functions are marked correctly.
1050       startSegment(*Last, Last->endLoc(), false, true);
1051     }
1052 
1053     // Pop the completed regions.
1054     ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
1055   }
1056 
1057   void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
1058     for (const auto &CR : enumerate(Regions)) {
1059       auto CurStartLoc = CR.value().startLoc();
1060 
1061       // Active regions which end before the current region need to be popped.
1062       auto CompletedRegions =
1063           std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
1064                                 [&](const CountedRegion *Region) {
1065                                   return !(Region->endLoc() <= CurStartLoc);
1066                                 });
1067       if (CompletedRegions != ActiveRegions.end()) {
1068         unsigned FirstCompletedRegion =
1069             std::distance(ActiveRegions.begin(), CompletedRegions);
1070         completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
1071       }
1072 
1073       bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
1074 
1075       // Try to emit a segment for the current region.
1076       if (CurStartLoc == CR.value().endLoc()) {
1077         // Avoid making zero-length regions active. If it's the last region,
1078         // emit a skipped segment. Otherwise use its predecessor's count.
1079         const bool Skipped =
1080             (CR.index() + 1) == Regions.size() ||
1081             CR.value().Kind == CounterMappingRegion::SkippedRegion;
1082         startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
1083                      CurStartLoc, !GapRegion, Skipped);
1084         // If it is skipped segment, create a segment with last pushed
1085         // regions's count at CurStartLoc.
1086         if (Skipped && !ActiveRegions.empty())
1087           startSegment(*ActiveRegions.back(), CurStartLoc, false);
1088         continue;
1089       }
1090       if (CR.index() + 1 == Regions.size() ||
1091           CurStartLoc != Regions[CR.index() + 1].startLoc()) {
1092         // Emit a segment if the next region doesn't start at the same location
1093         // as this one.
1094         startSegment(CR.value(), CurStartLoc, !GapRegion);
1095       }
1096 
1097       // This region is active (i.e not completed).
1098       ActiveRegions.push_back(&CR.value());
1099     }
1100 
1101     // Complete any remaining active regions.
1102     if (!ActiveRegions.empty())
1103       completeRegionsUntil(std::nullopt, 0);
1104   }
1105 
1106   /// Sort a nested sequence of regions from a single file.
1107   static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
1108     llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
1109       if (LHS.startLoc() != RHS.startLoc())
1110         return LHS.startLoc() < RHS.startLoc();
1111       if (LHS.endLoc() != RHS.endLoc())
1112         // When LHS completely contains RHS, we sort LHS first.
1113         return RHS.endLoc() < LHS.endLoc();
1114       // If LHS and RHS cover the same area, we need to sort them according
1115       // to their kinds so that the most suitable region will become "active"
1116       // in combineRegions(). Because we accumulate counter values only from
1117       // regions of the same kind as the first region of the area, prefer
1118       // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
1119       static_assert(CounterMappingRegion::CodeRegion <
1120                             CounterMappingRegion::ExpansionRegion &&
1121                         CounterMappingRegion::ExpansionRegion <
1122                             CounterMappingRegion::SkippedRegion,
1123                     "Unexpected order of region kind values");
1124       return LHS.Kind < RHS.Kind;
1125     });
1126   }
1127 
1128   /// Combine counts of regions which cover the same area.
1129   static ArrayRef<CountedRegion>
1130   combineRegions(MutableArrayRef<CountedRegion> Regions) {
1131     if (Regions.empty())
1132       return Regions;
1133     auto Active = Regions.begin();
1134     auto End = Regions.end();
1135     for (auto I = Regions.begin() + 1; I != End; ++I) {
1136       if (Active->startLoc() != I->startLoc() ||
1137           Active->endLoc() != I->endLoc()) {
1138         // Shift to the next region.
1139         ++Active;
1140         if (Active != I)
1141           *Active = *I;
1142         continue;
1143       }
1144       // Merge duplicate region.
1145       // If CodeRegions and ExpansionRegions cover the same area, it's probably
1146       // a macro which is fully expanded to another macro. In that case, we need
1147       // to accumulate counts only from CodeRegions, or else the area will be
1148       // counted twice.
1149       // On the other hand, a macro may have a nested macro in its body. If the
1150       // outer macro is used several times, the ExpansionRegion for the nested
1151       // macro will also be added several times. These ExpansionRegions cover
1152       // the same source locations and have to be combined to reach the correct
1153       // value for that area.
1154       // We add counts of the regions of the same kind as the active region
1155       // to handle the both situations.
1156       if (I->Kind == Active->Kind)
1157         Active->ExecutionCount += I->ExecutionCount;
1158     }
1159     return Regions.drop_back(std::distance(++Active, End));
1160   }
1161 
1162 public:
1163   /// Build a sorted list of CoverageSegments from a list of Regions.
1164   static std::vector<CoverageSegment>
1165   buildSegments(MutableArrayRef<CountedRegion> Regions) {
1166     std::vector<CoverageSegment> Segments;
1167     SegmentBuilder Builder(Segments);
1168 
1169     sortNestedRegions(Regions);
1170     ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
1171 
1172     LLVM_DEBUG({
1173       dbgs() << "Combined regions:\n";
1174       for (const auto &CR : CombinedRegions)
1175         dbgs() << "  " << CR.LineStart << ":" << CR.ColumnStart << " -> "
1176                << CR.LineEnd << ":" << CR.ColumnEnd
1177                << " (count=" << CR.ExecutionCount << ")\n";
1178     });
1179 
1180     Builder.buildSegmentsImpl(CombinedRegions);
1181 
1182 #ifndef NDEBUG
1183     for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
1184       const auto &L = Segments[I - 1];
1185       const auto &R = Segments[I];
1186       if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
1187         if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
1188           continue;
1189         LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
1190                           << " followed by " << R.Line << ":" << R.Col << "\n");
1191         assert(false && "Coverage segments not unique or sorted");
1192       }
1193     }
1194 #endif
1195 
1196     return Segments;
1197   }
1198 };
1199 
1200 } // end anonymous namespace
1201 
1202 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
1203   std::vector<StringRef> Filenames;
1204   for (const auto &Function : getCoveredFunctions())
1205     llvm::append_range(Filenames, Function.Filenames);
1206   llvm::sort(Filenames);
1207   auto Last = std::unique(Filenames.begin(), Filenames.end());
1208   Filenames.erase(Last, Filenames.end());
1209   return Filenames;
1210 }
1211 
1212 static SmallBitVector gatherFileIDs(StringRef SourceFile,
1213                                     const FunctionRecord &Function) {
1214   SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
1215   for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
1216     if (SourceFile == Function.Filenames[I])
1217       FilenameEquivalence[I] = true;
1218   return FilenameEquivalence;
1219 }
1220 
1221 /// Return the ID of the file where the definition of the function is located.
1222 static std::optional<unsigned>
1223 findMainViewFileID(const FunctionRecord &Function) {
1224   SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
1225   for (const auto &CR : Function.CountedRegions)
1226     if (CR.Kind == CounterMappingRegion::ExpansionRegion)
1227       IsNotExpandedFile[CR.ExpandedFileID] = false;
1228   int I = IsNotExpandedFile.find_first();
1229   if (I == -1)
1230     return std::nullopt;
1231   return I;
1232 }
1233 
1234 /// Check if SourceFile is the file that contains the definition of
1235 /// the Function. Return the ID of the file in that case or std::nullopt
1236 /// otherwise.
1237 static std::optional<unsigned>
1238 findMainViewFileID(StringRef SourceFile, const FunctionRecord &Function) {
1239   std::optional<unsigned> I = findMainViewFileID(Function);
1240   if (I && SourceFile == Function.Filenames[*I])
1241     return I;
1242   return std::nullopt;
1243 }
1244 
1245 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
1246   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
1247 }
1248 
1249 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
1250   CoverageData FileCoverage(Filename);
1251   std::vector<CountedRegion> Regions;
1252 
1253   // Look up the function records in the given file. Due to hash collisions on
1254   // the filename, we may get back some records that are not in the file.
1255   ArrayRef<unsigned> RecordIndices =
1256       getImpreciseRecordIndicesForFilename(Filename);
1257   for (unsigned RecordIndex : RecordIndices) {
1258     const FunctionRecord &Function = Functions[RecordIndex];
1259     auto MainFileID = findMainViewFileID(Filename, Function);
1260     auto FileIDs = gatherFileIDs(Filename, Function);
1261     for (const auto &CR : Function.CountedRegions)
1262       if (FileIDs.test(CR.FileID)) {
1263         Regions.push_back(CR);
1264         if (MainFileID && isExpansion(CR, *MainFileID))
1265           FileCoverage.Expansions.emplace_back(CR, Function);
1266       }
1267     // Capture branch regions specific to the function (excluding expansions).
1268     for (const auto &CR : Function.CountedBranchRegions)
1269       if (FileIDs.test(CR.FileID) && (CR.FileID == CR.ExpandedFileID))
1270         FileCoverage.BranchRegions.push_back(CR);
1271     // Capture MCDC records specific to the function.
1272     for (const auto &MR : Function.MCDCRecords)
1273       if (FileIDs.test(MR.getDecisionRegion().FileID))
1274         FileCoverage.MCDCRecords.push_back(MR);
1275   }
1276 
1277   LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
1278   FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1279 
1280   return FileCoverage;
1281 }
1282 
1283 std::vector<InstantiationGroup>
1284 CoverageMapping::getInstantiationGroups(StringRef Filename) const {
1285   FunctionInstantiationSetCollector InstantiationSetCollector;
1286   // Look up the function records in the given file. Due to hash collisions on
1287   // the filename, we may get back some records that are not in the file.
1288   ArrayRef<unsigned> RecordIndices =
1289       getImpreciseRecordIndicesForFilename(Filename);
1290   for (unsigned RecordIndex : RecordIndices) {
1291     const FunctionRecord &Function = Functions[RecordIndex];
1292     auto MainFileID = findMainViewFileID(Filename, Function);
1293     if (!MainFileID)
1294       continue;
1295     InstantiationSetCollector.insert(Function, *MainFileID);
1296   }
1297 
1298   std::vector<InstantiationGroup> Result;
1299   for (auto &InstantiationSet : InstantiationSetCollector) {
1300     InstantiationGroup IG{InstantiationSet.first.first,
1301                           InstantiationSet.first.second,
1302                           std::move(InstantiationSet.second)};
1303     Result.emplace_back(std::move(IG));
1304   }
1305   return Result;
1306 }
1307 
1308 CoverageData
1309 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
1310   auto MainFileID = findMainViewFileID(Function);
1311   if (!MainFileID)
1312     return CoverageData();
1313 
1314   CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
1315   std::vector<CountedRegion> Regions;
1316   for (const auto &CR : Function.CountedRegions)
1317     if (CR.FileID == *MainFileID) {
1318       Regions.push_back(CR);
1319       if (isExpansion(CR, *MainFileID))
1320         FunctionCoverage.Expansions.emplace_back(CR, Function);
1321     }
1322   // Capture branch regions specific to the function (excluding expansions).
1323   for (const auto &CR : Function.CountedBranchRegions)
1324     if (CR.FileID == *MainFileID)
1325       FunctionCoverage.BranchRegions.push_back(CR);
1326 
1327   // Capture MCDC records specific to the function.
1328   for (const auto &MR : Function.MCDCRecords)
1329     if (MR.getDecisionRegion().FileID == *MainFileID)
1330       FunctionCoverage.MCDCRecords.push_back(MR);
1331 
1332   LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
1333                     << "\n");
1334   FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1335 
1336   return FunctionCoverage;
1337 }
1338 
1339 CoverageData CoverageMapping::getCoverageForExpansion(
1340     const ExpansionRecord &Expansion) const {
1341   CoverageData ExpansionCoverage(
1342       Expansion.Function.Filenames[Expansion.FileID]);
1343   std::vector<CountedRegion> Regions;
1344   for (const auto &CR : Expansion.Function.CountedRegions)
1345     if (CR.FileID == Expansion.FileID) {
1346       Regions.push_back(CR);
1347       if (isExpansion(CR, Expansion.FileID))
1348         ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
1349     }
1350   for (const auto &CR : Expansion.Function.CountedBranchRegions)
1351     // Capture branch regions that only pertain to the corresponding expansion.
1352     if (CR.FileID == Expansion.FileID)
1353       ExpansionCoverage.BranchRegions.push_back(CR);
1354 
1355   LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
1356                     << Expansion.FileID << "\n");
1357   ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1358 
1359   return ExpansionCoverage;
1360 }
1361 
1362 LineCoverageStats::LineCoverageStats(
1363     ArrayRef<const CoverageSegment *> LineSegments,
1364     const CoverageSegment *WrappedSegment, unsigned Line)
1365     : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
1366       LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
1367   // Find the minimum number of regions which start in this line.
1368   unsigned MinRegionCount = 0;
1369   auto isStartOfRegion = [](const CoverageSegment *S) {
1370     return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
1371   };
1372   for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
1373     if (isStartOfRegion(LineSegments[I]))
1374       ++MinRegionCount;
1375 
1376   bool StartOfSkippedRegion = !LineSegments.empty() &&
1377                               !LineSegments.front()->HasCount &&
1378                               LineSegments.front()->IsRegionEntry;
1379 
1380   HasMultipleRegions = MinRegionCount > 1;
1381   Mapped =
1382       !StartOfSkippedRegion &&
1383       ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
1384 
1385   // if there is any starting segment at this line with a counter, it must be
1386   // mapped
1387   Mapped |= std::any_of(
1388       LineSegments.begin(), LineSegments.end(),
1389       [](const auto *Seq) { return Seq->IsRegionEntry && Seq->HasCount; });
1390 
1391   if (!Mapped) {
1392     return;
1393   }
1394 
1395   // Pick the max count from the non-gap, region entry segments and the
1396   // wrapped count.
1397   if (WrappedSegment)
1398     ExecutionCount = WrappedSegment->Count;
1399   if (!MinRegionCount)
1400     return;
1401   for (const auto *LS : LineSegments)
1402     if (isStartOfRegion(LS))
1403       ExecutionCount = std::max(ExecutionCount, LS->Count);
1404 }
1405 
1406 LineCoverageIterator &LineCoverageIterator::operator++() {
1407   if (Next == CD.end()) {
1408     Stats = LineCoverageStats();
1409     Ended = true;
1410     return *this;
1411   }
1412   if (Segments.size())
1413     WrappedSegment = Segments.back();
1414   Segments.clear();
1415   while (Next != CD.end() && Next->Line == Line)
1416     Segments.push_back(&*Next++);
1417   Stats = LineCoverageStats(Segments, WrappedSegment, Line);
1418   ++Line;
1419   return *this;
1420 }
1421 
1422 static std::string getCoverageMapErrString(coveragemap_error Err,
1423                                            const std::string &ErrMsg = "") {
1424   std::string Msg;
1425   raw_string_ostream OS(Msg);
1426 
1427   switch (Err) {
1428   case coveragemap_error::success:
1429     OS << "success";
1430     break;
1431   case coveragemap_error::eof:
1432     OS << "end of File";
1433     break;
1434   case coveragemap_error::no_data_found:
1435     OS << "no coverage data found";
1436     break;
1437   case coveragemap_error::unsupported_version:
1438     OS << "unsupported coverage format version";
1439     break;
1440   case coveragemap_error::truncated:
1441     OS << "truncated coverage data";
1442     break;
1443   case coveragemap_error::malformed:
1444     OS << "malformed coverage data";
1445     break;
1446   case coveragemap_error::decompression_failed:
1447     OS << "failed to decompress coverage data (zlib)";
1448     break;
1449   case coveragemap_error::invalid_or_missing_arch_specifier:
1450     OS << "`-arch` specifier is invalid or missing for universal binary";
1451     break;
1452   }
1453 
1454   // If optional error message is not empty, append it to the message.
1455   if (!ErrMsg.empty())
1456     OS << ": " << ErrMsg;
1457 
1458   return Msg;
1459 }
1460 
1461 namespace {
1462 
1463 // FIXME: This class is only here to support the transition to llvm::Error. It
1464 // will be removed once this transition is complete. Clients should prefer to
1465 // deal with the Error value directly, rather than converting to error_code.
1466 class CoverageMappingErrorCategoryType : public std::error_category {
1467   const char *name() const noexcept override { return "llvm.coveragemap"; }
1468   std::string message(int IE) const override {
1469     return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
1470   }
1471 };
1472 
1473 } // end anonymous namespace
1474 
1475 std::string CoverageMapError::message() const {
1476   return getCoverageMapErrString(Err, Msg);
1477 }
1478 
1479 const std::error_category &llvm::coverage::coveragemap_category() {
1480   static CoverageMappingErrorCategoryType ErrorCategory;
1481   return ErrorCategory;
1482 }
1483 
1484 char CoverageMapError::ID = 0;
1485