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