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