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