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
46using namespace llvm;
47using namespace coverage;
48
49#define DEBUG_TYPE "coverage-mapping"
50
51Counter CounterExpressionBuilder::get(const CounterExpression &E) {
52 auto [It, Inserted] = ExpressionIndices.try_emplace(Key: E, Args: Expressions.size());
53 if (Inserted)
54 Expressions.push_back(x: E);
55 return Counter::getExpression(ExpressionId: It->second);
56}
57
58void 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(Args: C.getCounterID(), Args&: Factor);
65 break;
66 case Counter::Expression:
67 const auto &E = Expressions[C.getExpressionID()];
68 extractTerms(C: E.LHS, Factor, Terms);
69 extractTerms(
70 C: E.RHS, Factor: E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
71 break;
72 }
73}
74
75Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
76 // Gather constant terms.
77 SmallVector<Term, 32> Terms;
78 extractTerms(C: ExpressionTree, Factor: +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(C&: Terms, Comp: [](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(CS: ++Prev, CE: 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(CounterId: T.CounterID);
111 else
112 C = get(E: CounterExpression(CounterExpression::Add, C,
113 Counter::getCounter(CounterId: 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(E: CounterExpression(CounterExpression::Subtract, C,
122 Counter::getCounter(CounterId: T.CounterID)));
123 }
124 return C;
125}
126
127Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS, bool Simplify) {
128 auto Cnt = get(E: CounterExpression(CounterExpression::Add, LHS, RHS));
129 return Simplify ? simplify(ExpressionTree: Cnt) : Cnt;
130}
131
132Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS,
133 bool Simplify) {
134 auto Cnt = get(E: CounterExpression(CounterExpression::Subtract, LHS, RHS));
135 return Simplify ? simplify(ExpressionTree: Cnt) : Cnt;
136}
137
138Counter 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(x: 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(C: CE.LHS, Map);
148 auto NewRHS = subst(C: CE.RHS, Map);
149
150 // Reconstruct Expression with induced subexpressions.
151 switch (CE.Kind) {
152 case CounterExpression::Add:
153 C = add(LHS: NewLHS, RHS: NewRHS);
154 break;
155 case CounterExpression::Subtract:
156 C = subtract(LHS: NewLHS, RHS: NewRHS);
157 break;
158 }
159
160 return C;
161}
162
163void 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(C: E.LHS, OS);
177 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
178 dump(C: 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(Err: std::move(E));
188 return;
189 }
190 OS << '[' << *Value << ']';
191}
192
193Expected<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(x: {.ICounter: 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(EC: 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(EC: errc::argument_out_of_domain);
226 const auto &E = Expressions[Current.ICounter.getExpressionID()];
227 if (Current.VisitCount == StackElem::KNeverVisited) {
228 CounterStack.push(x: StackElem{.ICounter: E.LHS});
229 Current.VisitCount = StackElem::KVisitedOnce;
230 } else if (Current.VisitCount == StackElem::KVisitedOnce) {
231 Current.LHS = LastPoppedValue;
232 CounterStack.push(x: StackElem{.ICounter: 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".
253void 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 first: TV.begin(),
263 last: llvm::find_if(Range&: TV,
264 P: [&](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 KV: {AB.find_first(), std::make_pair(x: J + 1, y: I + 1)});
279 }
280 }
281}
282
283mcdc::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(Elt: 0);
314
315 unsigned Ord = 0;
316 while (!Q.empty()) {
317 auto IID = Q.begin();
318 int ID = *IID;
319 Q.erase(CI: 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(Args: -Node.Width, Args: Ord++, Args&: ID, Args&: 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(Elt: NextID);
351 }
352 }
353
354 llvm::sort(C&: 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
382namespace {
383
384/// Construct this->NextIDs with Branches for TVIdxBuilder to use it
385/// before MCDCRecordProcessor().
386class NextIDsBuilder {
387protected:
388 SmallVector<mcdc::ConditionIDs> NextIDs;
389
390public:
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
405class 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 /// Helper for sorting ExecVectors.
430 struct TVIdxTuple {
431 MCDCRecord::CondState MCDCCond; /// True/False
432 unsigned BIdx; /// Bitmap Index
433 unsigned Ord; /// Last position on ExecVectors
434
435 TVIdxTuple(MCDCRecord::CondState MCDCCond, unsigned BIdx, unsigned Ord)
436 : MCDCCond(MCDCCond), BIdx(BIdx), Ord(Ord) {}
437
438 bool operator<(const TVIdxTuple &RHS) const {
439 return (std::tie(args: this->MCDCCond, args: this->BIdx, args: this->Ord) <
440 std::tie(args: RHS.MCDCCond, args: RHS.BIdx, args: RHS.Ord));
441 }
442 };
443
444 // Indices for sorted TestVectors;
445 std::vector<TVIdxTuple> ExecVectorIdxs;
446
447 /// Actual executed Test Vectors for the boolean expression, based on
448 /// ExecutedTestVectorBitmap.
449 MCDCRecord::TestVectors ExecVectors;
450
451#ifndef NDEBUG
452 DenseSet<unsigned> TVIdxs;
453#endif
454
455 bool IsVersion11;
456
457public:
458 MCDCRecordProcessor(const BitVector &Bitmap,
459 const CounterMappingRegion &Region,
460 ArrayRef<const CounterMappingRegion *> Branches,
461 bool IsVersion11)
462 : NextIDsBuilder(Branches), TVIdxBuilder(this->NextIDs), Bitmap(Bitmap),
463 Region(Region), DecisionParams(Region.getDecisionParams()),
464 Branches(Branches), NumConditions(DecisionParams.NumConditions),
465 Folded{._M_elems: {BitVector(NumConditions), BitVector(NumConditions)}},
466 IndependencePairs(NumConditions), IsVersion11(IsVersion11) {}
467
468private:
469 // Walk the binary decision diagram and try assigning both false and true to
470 // each node. When a terminal node (ID == 0) is reached, fill in the value in
471 // the truth table.
472 void buildTestVector(MCDCRecord::TestVector &TV, mcdc::ConditionID ID,
473 int TVIdx) {
474 for (auto MCDCCond : {MCDCRecord::MCDC_False, MCDCRecord::MCDC_True}) {
475 static_assert(MCDCRecord::MCDC_False == 0);
476 static_assert(MCDCRecord::MCDC_True == 1);
477 TV.set(I: ID, Val: MCDCCond);
478 auto NextID = NextIDs[ID][MCDCCond];
479 auto NextTVIdx = TVIdx + Indices[ID][MCDCCond];
480 assert(NextID == SavedNodes[ID].NextIDs[MCDCCond]);
481 if (NextID >= 0) {
482 buildTestVector(TV, ID: NextID, TVIdx: NextTVIdx);
483 continue;
484 }
485
486 assert(TVIdx < SavedNodes[ID].Width);
487 assert(TVIdxs.insert(NextTVIdx).second && "Duplicate TVIdx");
488
489 if (!Bitmap[IsVersion11
490 ? DecisionParams.BitmapIdx * CHAR_BIT + TV.getIndex()
491 : DecisionParams.BitmapIdx - NumTestVectors + NextTVIdx])
492 continue;
493
494 ExecVectorIdxs.emplace_back(args&: MCDCCond, args&: NextTVIdx, args: ExecVectors.size());
495
496 // Copy the completed test vector to the vector of testvectors.
497 // The final value (T,F) is equal to the last non-dontcare state on the
498 // path (in a short-circuiting system).
499 ExecVectors.push_back(Elt: {TV, MCDCCond});
500 }
501
502 // Reset back to DontCare.
503 TV.set(I: ID, Val: MCDCRecord::MCDC_DontCare);
504 }
505
506 /// Walk the bits in the bitmap. A bit set to '1' indicates that the test
507 /// vector at the corresponding index was executed during a test run.
508 void findExecutedTestVectors() {
509 // Walk the binary decision diagram to enumerate all possible test vectors.
510 // We start at the root node (ID == 0) with all values being DontCare.
511 // `TVIdx` starts with 0 and is in the traversal.
512 // `Index` encodes the bitmask of true values and is initially 0.
513 MCDCRecord::TestVector TV(NumConditions);
514 buildTestVector(TV, ID: 0, TVIdx: 0);
515 assert(TVIdxs.size() == unsigned(NumTestVectors) &&
516 "TVIdxs wasn't fulfilled");
517
518 llvm::sort(C&: ExecVectorIdxs);
519 MCDCRecord::TestVectors NewTestVectors;
520 for (const auto &IdxTuple : ExecVectorIdxs)
521 NewTestVectors.push_back(Elt: std::move(ExecVectors[IdxTuple.Ord]));
522 ExecVectors = std::move(NewTestVectors);
523 }
524
525public:
526 /// Process the MC/DC Record in order to produce a result for a boolean
527 /// expression. This process includes tracking the conditions that comprise
528 /// the decision region, calculating the list of all possible test vectors,
529 /// marking the executed test vectors, and then finding an Independence Pair
530 /// out of the executed test vectors for each condition in the boolean
531 /// expression. A condition is tracked to ensure that its ID can be mapped to
532 /// its ordinal position in the boolean expression. The condition's source
533 /// location is also tracked, as well as whether it is constant folded (in
534 /// which case it is excuded from the metric).
535 MCDCRecord processMCDCRecord() {
536 MCDCRecord::CondIDMap PosToID;
537 MCDCRecord::LineColPairMap CondLoc;
538
539 // Walk the Record's BranchRegions (representing Conditions) in order to:
540 // - Hash the condition based on its corresponding ID. This will be used to
541 // calculate the test vectors.
542 // - Keep a map of the condition's ordinal position (1, 2, 3, 4) to its
543 // actual ID. This will be used to visualize the conditions in the
544 // correct order.
545 // - Keep track of the condition source location. This will be used to
546 // visualize where the condition is.
547 // - Record whether the condition is constant folded so that we exclude it
548 // from being measured.
549 for (auto [I, B] : enumerate(First&: Branches)) {
550 const auto &BranchParams = B->getBranchParams();
551 PosToID[I] = BranchParams.ID;
552 CondLoc[I] = B->startLoc();
553 Folded[false][I] = B->FalseCount.isZero();
554 Folded[true][I] = B->Count.isZero();
555 }
556
557 // Using Profile Bitmap from runtime, mark the executed test vectors.
558 findExecutedTestVectors();
559
560 // Record Test vectors, executed vectors, and independence pairs.
561 return MCDCRecord(Region, std::move(ExecVectors), std::move(Folded),
562 std::move(PosToID), std::move(CondLoc));
563 }
564};
565
566} // namespace
567
568Expected<MCDCRecord> CounterMappingContext::evaluateMCDCRegion(
569 const CounterMappingRegion &Region,
570 ArrayRef<const CounterMappingRegion *> Branches, bool IsVersion11) {
571
572 MCDCRecordProcessor MCDCProcessor(Bitmap, Region, Branches, IsVersion11);
573 return MCDCProcessor.processMCDCRecord();
574}
575
576unsigned CounterMappingContext::getMaxCounterID(const Counter &C) const {
577 struct StackElem {
578 Counter ICounter;
579 int64_t LHS = 0;
580 enum {
581 KNeverVisited = 0,
582 KVisitedOnce = 1,
583 KVisitedTwice = 2,
584 } VisitCount = KNeverVisited;
585 };
586
587 std::stack<StackElem> CounterStack;
588 CounterStack.push(x: {.ICounter: C});
589
590 int64_t LastPoppedValue;
591
592 while (!CounterStack.empty()) {
593 StackElem &Current = CounterStack.top();
594
595 switch (Current.ICounter.getKind()) {
596 case Counter::Zero:
597 LastPoppedValue = 0;
598 CounterStack.pop();
599 break;
600 case Counter::CounterValueReference:
601 LastPoppedValue = Current.ICounter.getCounterID();
602 CounterStack.pop();
603 break;
604 case Counter::Expression: {
605 if (Current.ICounter.getExpressionID() >= Expressions.size()) {
606 LastPoppedValue = 0;
607 CounterStack.pop();
608 } else {
609 const auto &E = Expressions[Current.ICounter.getExpressionID()];
610 if (Current.VisitCount == StackElem::KNeverVisited) {
611 CounterStack.push(x: StackElem{.ICounter: E.LHS});
612 Current.VisitCount = StackElem::KVisitedOnce;
613 } else if (Current.VisitCount == StackElem::KVisitedOnce) {
614 Current.LHS = LastPoppedValue;
615 CounterStack.push(x: StackElem{.ICounter: E.RHS});
616 Current.VisitCount = StackElem::KVisitedTwice;
617 } else {
618 int64_t LHS = Current.LHS;
619 int64_t RHS = LastPoppedValue;
620 LastPoppedValue = std::max(a: LHS, b: RHS);
621 CounterStack.pop();
622 }
623 }
624 break;
625 }
626 }
627 }
628
629 return LastPoppedValue;
630}
631
632void FunctionRecordIterator::skipOtherFiles() {
633 while (Current != Records.end() && !Filename.empty() &&
634 Filename != Current->Filenames[0])
635 advanceOne();
636 if (Current == Records.end())
637 *this = FunctionRecordIterator();
638}
639
640ArrayRef<unsigned> CoverageMapping::getImpreciseRecordIndicesForFilename(
641 StringRef Filename) const {
642 size_t FilenameHash = hash_value(S: Filename);
643 auto RecordIt = FilenameHash2RecordIndices.find(Val: FilenameHash);
644 if (RecordIt == FilenameHash2RecordIndices.end())
645 return {};
646 return RecordIt->second;
647}
648
649static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
650 const CoverageMappingRecord &Record) {
651 unsigned MaxCounterID = 0;
652 for (const auto &Region : Record.MappingRegions) {
653 MaxCounterID = std::max(a: MaxCounterID, b: Ctx.getMaxCounterID(C: Region.Count));
654 if (Region.isBranch())
655 MaxCounterID =
656 std::max(a: MaxCounterID, b: Ctx.getMaxCounterID(C: Region.FalseCount));
657 }
658 return MaxCounterID;
659}
660
661/// Returns the bit count
662static unsigned getMaxBitmapSize(const CoverageMappingRecord &Record,
663 bool IsVersion11) {
664 unsigned MaxBitmapIdx = 0;
665 unsigned NumConditions = 0;
666 // Scan max(BitmapIdx).
667 // Note that `<=` is used insted of `<`, because `BitmapIdx == 0` is valid
668 // and `MaxBitmapIdx is `unsigned`. `BitmapIdx` is unique in the record.
669 for (const auto &Region : reverse(C: Record.MappingRegions)) {
670 if (Region.Kind != CounterMappingRegion::MCDCDecisionRegion)
671 continue;
672 const auto &DecisionParams = Region.getDecisionParams();
673 if (MaxBitmapIdx <= DecisionParams.BitmapIdx) {
674 MaxBitmapIdx = DecisionParams.BitmapIdx;
675 NumConditions = DecisionParams.NumConditions;
676 }
677 }
678
679 if (IsVersion11)
680 MaxBitmapIdx = MaxBitmapIdx * CHAR_BIT +
681 llvm::alignTo(Value: uint64_t(1) << NumConditions, CHAR_BIT);
682
683 return MaxBitmapIdx;
684}
685
686namespace {
687
688/// Walk MappingRegions along Expansions and emit CountedRegions.
689struct CountedRegionEmitter {
690 /// A nestable Decision.
691 struct DecisionRecord {
692 const CounterMappingRegion *DecisionRegion;
693 unsigned NumConditions; ///< Copy of DecisionRegion.NumConditions
694 /// Pushed by traversal order.
695 SmallVector<const CounterMappingRegion *> MCDCBranches;
696#ifndef NDEBUG
697 DenseSet<mcdc::ConditionID> ConditionIDs;
698#endif
699
700 DecisionRecord(const CounterMappingRegion &Decision)
701 : DecisionRegion(&Decision),
702 NumConditions(Decision.getDecisionParams().NumConditions) {
703 assert(Decision.Kind == CounterMappingRegion::MCDCDecisionRegion);
704 }
705
706 bool pushBranch(const CounterMappingRegion &B) {
707 assert(B.Kind == CounterMappingRegion::MCDCBranchRegion);
708 assert(ConditionIDs.insert(B.getBranchParams().ID).second &&
709 "Duplicate CondID");
710 MCDCBranches.push_back(Elt: &B);
711 assert(MCDCBranches.size() <= NumConditions &&
712 "MCDCBranch exceeds NumConds");
713 return (MCDCBranches.size() == NumConditions);
714 }
715 };
716
717 const CoverageMappingRecord &Record;
718 CounterMappingContext &Ctx;
719 FunctionRecord &Function;
720 bool IsVersion11;
721
722 /// Evaluated Counters.
723 std::map<Counter, uint64_t> CounterValues;
724
725 /// Decisions are nestable.
726 SmallVector<DecisionRecord, 1> DecisionStack;
727
728 /// A File pointed by Expansion
729 struct FileInfo {
730 /// The last index(+1) for each FileID in MappingRegions.
731 unsigned LastIndex = 0;
732 /// Mark Files pointed by Expansions.
733 /// Non-marked Files are root Files.
734 bool IsExpanded = false;
735 };
736
737 /// The last element is a sentinel with Index=NumRegions.
738 std::vector<FileInfo> Files;
739#ifndef NDEBUG
740 DenseSet<unsigned> Visited;
741#endif
742
743 CountedRegionEmitter(const CoverageMappingRecord &Record,
744 CounterMappingContext &Ctx, FunctionRecord &Function,
745 bool IsVersion11)
746 : Record(Record), Ctx(Ctx), Function(Function), IsVersion11(IsVersion11),
747 Files(Record.Filenames.size()) {
748 // Scan MappingRegions and mark each last index by FileID.
749 for (auto [I, Region] : enumerate(First: Record.MappingRegions)) {
750 if (Region.FileID >= Files.size()) {
751 // Extend (only possible in CoverageMappingTests)
752 Files.resize(new_size: Region.FileID + 1);
753 }
754 Files[Region.FileID].LastIndex = I + 1;
755 if (Region.Kind == CounterMappingRegion::ExpansionRegion) {
756 if (Region.ExpandedFileID >= Files.size()) {
757 // Extend (only possible in CoverageMappingTests)
758 Files.resize(new_size: Region.ExpandedFileID + 1);
759 }
760 Files[Region.ExpandedFileID].IsExpanded = true;
761 }
762 }
763 }
764
765 /// Evaluate C and store its evaluated Value into CounterValues.
766 Error evaluateAndCacheCounter(Counter C) {
767 if (CounterValues.count(x: C) > 0)
768 return Error::success();
769
770 auto ValueOrErr = Ctx.evaluate(C);
771 if (!ValueOrErr)
772 return ValueOrErr.takeError();
773 CounterValues[C] = *ValueOrErr;
774 return Error::success();
775 }
776
777 Error walk(unsigned Idx) {
778 assert(Idx < Files.size());
779 unsigned B = (Idx == 0 ? 0 : Files[Idx - 1].LastIndex);
780 unsigned E = Files[Idx].LastIndex;
781 assert(B != E && "Empty FileID");
782 assert(Visited.insert(Idx).second && "Duplicate Expansions");
783 for (unsigned I = B; I != E; ++I) {
784 const auto &Region = Record.MappingRegions[I];
785 if (Region.FileID != Idx)
786 break;
787
788 if (Region.Kind == CounterMappingRegion::ExpansionRegion)
789 if (auto E = walk(Idx: Region.ExpandedFileID))
790 return E;
791
792 if (auto E = evaluateAndCacheCounter(C: Region.Count))
793 return E;
794
795 if (Region.Kind == CounterMappingRegion::MCDCDecisionRegion) {
796 // Start the new Decision on the stack.
797 DecisionStack.emplace_back(Args: Region);
798 } else if (Region.Kind == CounterMappingRegion::MCDCBranchRegion) {
799 assert(!DecisionStack.empty() && "Orphan MCDCBranch");
800 auto &D = DecisionStack.back();
801
802 if (D.pushBranch(B: Region)) {
803 // All Branches have been found in the Decision.
804 auto RecordOrErr = Ctx.evaluateMCDCRegion(
805 Region: *D.DecisionRegion, Branches: D.MCDCBranches, IsVersion11);
806 if (!RecordOrErr)
807 return RecordOrErr.takeError();
808
809 // Finish the stack.
810 Function.pushMCDCRecord(Record: std::move(*RecordOrErr));
811 DecisionStack.pop_back();
812 }
813 }
814
815 // Evaluate FalseCount
816 // It may have the Counter in Branches, or Zero.
817 if (auto E = evaluateAndCacheCounter(C: Region.FalseCount))
818 return E;
819 }
820
821 assert((Idx != 0 || DecisionStack.empty()) && "Decision wasn't closed");
822
823 return Error::success();
824 }
825
826 Error emitCountedRegions() {
827 // Walk MappingRegions along Expansions.
828 // - Evaluate Counters
829 // - Emit MCDCRecords
830 for (auto [I, F] : enumerate(First&: Files)) {
831 if (!F.IsExpanded)
832 if (auto E = walk(Idx: I))
833 return E;
834 }
835 assert(Visited.size() == Files.size() && "Dangling FileID");
836
837 // Emit CountedRegions in the same order as MappingRegions.
838 for (const auto &Region : Record.MappingRegions) {
839 if (Region.Kind == CounterMappingRegion::MCDCDecisionRegion)
840 continue; // Don't emit.
841 // Adopt values from the CounterValues.
842 // FalseCount may be Zero unless Branches.
843 Function.pushRegion(Region, Count: CounterValues[Region.Count],
844 FalseCount: CounterValues[Region.FalseCount]);
845 }
846
847 return Error::success();
848 }
849};
850
851} // namespace
852
853Error CoverageMapping::loadFunctionRecord(
854 const CoverageMappingRecord &Record,
855 const std::optional<std::reference_wrapper<IndexedInstrProfReader>>
856 &ProfileReader) {
857 StringRef OrigFuncName = Record.FunctionName;
858 if (OrigFuncName.empty())
859 return make_error<CoverageMapError>(Args: coveragemap_error::malformed,
860 Args: "record function name is empty");
861
862 if (Record.Filenames.empty())
863 OrigFuncName = getFuncNameWithoutPrefix(PGOFuncName: OrigFuncName);
864 else
865 OrigFuncName = getFuncNameWithoutPrefix(PGOFuncName: OrigFuncName, FileName: Record.Filenames[0]);
866
867 CounterMappingContext Ctx(Record.Expressions);
868
869 std::vector<uint64_t> Counts;
870 if (ProfileReader) {
871 if (Error E = ProfileReader.value().get().getFunctionCounts(
872 FuncName: Record.FunctionName, FuncHash: Record.FunctionHash, Counts)) {
873 instrprof_error IPE = std::get<0>(in: InstrProfError::take(E: std::move(E)));
874 if (IPE == instrprof_error::hash_mismatch) {
875 FuncHashMismatches.emplace_back(args: std::string(Record.FunctionName),
876 args: Record.FunctionHash);
877 return Error::success();
878 }
879 if (IPE != instrprof_error::unknown_function)
880 return make_error<InstrProfError>(Args&: IPE);
881 Counts.assign(n: getMaxCounterID(Ctx, Record) + 1, val: 0);
882 }
883 } else {
884 Counts.assign(n: getMaxCounterID(Ctx, Record) + 1, val: 0);
885 }
886 Ctx.setCounts(Counts);
887
888 bool IsVersion11 =
889 ProfileReader && ProfileReader.value().get().getVersion() <
890 IndexedInstrProf::ProfVersion::Version12;
891
892 BitVector Bitmap;
893 if (ProfileReader) {
894 if (Error E = ProfileReader.value().get().getFunctionBitmap(
895 FuncName: Record.FunctionName, FuncHash: Record.FunctionHash, Bitmap)) {
896 instrprof_error IPE = std::get<0>(in: InstrProfError::take(E: std::move(E)));
897 if (IPE == instrprof_error::hash_mismatch) {
898 FuncHashMismatches.emplace_back(args: std::string(Record.FunctionName),
899 args: Record.FunctionHash);
900 return Error::success();
901 }
902 if (IPE != instrprof_error::unknown_function)
903 return make_error<InstrProfError>(Args&: IPE);
904 Bitmap = BitVector(getMaxBitmapSize(Record, IsVersion11));
905 }
906 } else {
907 Bitmap = BitVector(getMaxBitmapSize(Record, IsVersion11: false));
908 }
909 Ctx.setBitmap(std::move(Bitmap));
910
911 assert(!Record.MappingRegions.empty() && "Function has no regions");
912
913 // This coverage record is a zero region for a function that's unused in
914 // some TU, but used in a different TU. Ignore it. The coverage maps from the
915 // the other TU will either be loaded (providing full region counts) or they
916 // won't (in which case we don't unintuitively report functions as uncovered
917 // when they have non-zero counts in the profile).
918 if (Record.MappingRegions.size() == 1 &&
919 Record.MappingRegions[0].Count.isZero() && Counts[0] > 0)
920 return Error::success();
921
922 FunctionRecord Function(OrigFuncName, Record.Filenames);
923
924 // Emit CountedRegions into FunctionRecord.
925 if (auto E = CountedRegionEmitter(Record, Ctx, Function, IsVersion11)
926 .emitCountedRegions()) {
927 errs() << "warning: " << Record.FunctionName << ": ";
928 logAllUnhandledErrors(E: std::move(E), OS&: errs());
929 return Error::success();
930 }
931
932 // Don't create records for (filenames, function) pairs we've already seen.
933 auto FilenamesHash = hash_combine_range(R: Record.Filenames);
934 if (!RecordProvenance[FilenamesHash].insert(V: hash_value(S: OrigFuncName)).second)
935 return Error::success();
936
937 Functions.push_back(x: std::move(Function));
938
939 // Performance optimization: keep track of the indices of the function records
940 // which correspond to each filename. This can be used to substantially speed
941 // up queries for coverage info in a file.
942 unsigned RecordIndex = Functions.size() - 1;
943 for (StringRef Filename : Record.Filenames) {
944 auto &RecordIndices = FilenameHash2RecordIndices[hash_value(S: Filename)];
945 // Note that there may be duplicates in the filename set for a function
946 // record, because of e.g. macro expansions in the function in which both
947 // the macro and the function are defined in the same file.
948 if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
949 RecordIndices.push_back(Elt: RecordIndex);
950 }
951
952 return Error::success();
953}
954
955// This function is for memory optimization by shortening the lifetimes
956// of CoverageMappingReader instances.
957Error CoverageMapping::loadFromReaders(
958 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
959 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
960 &ProfileReader,
961 CoverageMapping &Coverage) {
962 assert(!Coverage.SingleByteCoverage || !ProfileReader ||
963 *Coverage.SingleByteCoverage ==
964 ProfileReader.value().get().hasSingleByteCoverage());
965 Coverage.SingleByteCoverage =
966 !ProfileReader || ProfileReader.value().get().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
979Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
980 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
981 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
982 &ProfileReader) {
983 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
984 if (Error E = loadFromReaders(CoverageReaders, ProfileReader, Coverage&: *Coverage))
985 return std::move(E);
986 return std::move(Coverage);
987}
988
989// If E is a no_data_found error, returns success. Otherwise returns E.
990static Error handleMaybeNoDataFoundError(Error E) {
991 return handleErrors(E: std::move(E), Hs: [](const CoverageMapError &CME) {
992 if (CME.get() == coveragemap_error::no_data_found)
993 return static_cast<Error>(Error::success());
994 return make_error<CoverageMapError>(Args: CME.get(), Args: CME.getMessage());
995 });
996}
997
998Error CoverageMapping::loadFromFile(
999 StringRef Filename, StringRef Arch, StringRef CompilationDir,
1000 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
1001 &ProfileReader,
1002 CoverageMapping &Coverage, bool &DataFound,
1003 SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
1004 auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
1005 Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1006 if (std::error_code EC = CovMappingBufOrErr.getError())
1007 return createFileError(F: Filename, E: errorCodeToError(EC));
1008 MemoryBufferRef CovMappingBufRef =
1009 CovMappingBufOrErr.get()->getMemBufferRef();
1010 SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
1011
1012 SmallVector<object::BuildIDRef> BinaryIDs;
1013 auto CoverageReadersOrErr = BinaryCoverageReader::create(
1014 ObjectBuffer: CovMappingBufRef, Arch, ObjectFileBuffers&: Buffers, CompilationDir,
1015 BinaryIDs: FoundBinaryIDs ? &BinaryIDs : nullptr);
1016 if (Error E = CoverageReadersOrErr.takeError()) {
1017 E = handleMaybeNoDataFoundError(E: std::move(E));
1018 if (E)
1019 return createFileError(F: Filename, E: std::move(E));
1020 return E;
1021 }
1022
1023 SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
1024 for (auto &Reader : CoverageReadersOrErr.get())
1025 Readers.push_back(Elt: std::move(Reader));
1026 if (FoundBinaryIDs && !Readers.empty()) {
1027 llvm::append_range(C&: *FoundBinaryIDs,
1028 R: llvm::map_range(C&: BinaryIDs, F: [](object::BuildIDRef BID) {
1029 return object::BuildID(BID);
1030 }));
1031 }
1032 DataFound |= !Readers.empty();
1033 if (Error E = loadFromReaders(CoverageReaders: Readers, ProfileReader, Coverage))
1034 return createFileError(F: Filename, E: std::move(E));
1035 return Error::success();
1036}
1037
1038Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
1039 ArrayRef<StringRef> ObjectFilenames,
1040 std::optional<StringRef> ProfileFilename, vfs::FileSystem &FS,
1041 ArrayRef<StringRef> Arches, StringRef CompilationDir,
1042 const object::BuildIDFetcher *BIDFetcher, bool CheckBinaryIDs) {
1043 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
1044 if (ProfileFilename) {
1045 auto ProfileReaderOrErr =
1046 IndexedInstrProfReader::create(Path: ProfileFilename.value(), FS);
1047 if (Error E = ProfileReaderOrErr.takeError())
1048 return createFileError(F: ProfileFilename.value(), E: std::move(E));
1049 ProfileReader = std::move(ProfileReaderOrErr.get());
1050 }
1051 auto ProfileReaderRef =
1052 ProfileReader
1053 ? std::optional<std::reference_wrapper<IndexedInstrProfReader>>(
1054 *ProfileReader)
1055 : std::nullopt;
1056 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
1057 bool DataFound = false;
1058
1059 auto GetArch = [&](size_t Idx) {
1060 if (Arches.empty())
1061 return StringRef();
1062 if (Arches.size() == 1)
1063 return Arches.front();
1064 return Arches[Idx];
1065 };
1066
1067 SmallVector<object::BuildID> FoundBinaryIDs;
1068 for (const auto &File : llvm::enumerate(First&: ObjectFilenames)) {
1069 if (Error E = loadFromFile(Filename: File.value(), Arch: GetArch(File.index()),
1070 CompilationDir, ProfileReader&: ProfileReaderRef, Coverage&: *Coverage,
1071 DataFound, FoundBinaryIDs: &FoundBinaryIDs))
1072 return std::move(E);
1073 }
1074
1075 if (BIDFetcher) {
1076 std::vector<object::BuildID> ProfileBinaryIDs;
1077 if (ProfileReader)
1078 if (Error E = ProfileReader->readBinaryIds(BinaryIds&: ProfileBinaryIDs))
1079 return createFileError(F: ProfileFilename.value(), E: std::move(E));
1080
1081 SmallVector<object::BuildIDRef> BinaryIDsToFetch;
1082 if (!ProfileBinaryIDs.empty()) {
1083 const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) {
1084 return std::lexicographical_compare(first1: A.begin(), last1: A.end(), first2: B.begin(),
1085 last2: B.end());
1086 };
1087 llvm::sort(C&: FoundBinaryIDs, Comp: Compare);
1088 std::set_difference(
1089 first1: ProfileBinaryIDs.begin(), last1: ProfileBinaryIDs.end(),
1090 first2: FoundBinaryIDs.begin(), last2: FoundBinaryIDs.end(),
1091 result: std::inserter(x&: BinaryIDsToFetch, i: BinaryIDsToFetch.end()), comp: Compare);
1092 }
1093
1094 for (object::BuildIDRef BinaryID : BinaryIDsToFetch) {
1095 std::optional<std::string> PathOpt = BIDFetcher->fetch(BuildID: BinaryID);
1096 if (PathOpt) {
1097 std::string Path = std::move(*PathOpt);
1098 StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef();
1099 if (Error E = loadFromFile(Filename: Path, Arch, CompilationDir, ProfileReader&: ProfileReaderRef,
1100 Coverage&: *Coverage, DataFound))
1101 return std::move(E);
1102 } else if (CheckBinaryIDs) {
1103 return createFileError(
1104 F: ProfileFilename.value(),
1105 E: createStringError(EC: errc::no_such_file_or_directory,
1106 S: "Missing binary ID: " +
1107 llvm::toHex(Input: BinaryID, /*LowerCase=*/true)));
1108 }
1109 }
1110 }
1111
1112 if (!DataFound)
1113 return createFileError(
1114 F: join(Begin: ObjectFilenames.begin(), End: ObjectFilenames.end(), Separator: ", "),
1115 E: make_error<CoverageMapError>(Args: coveragemap_error::no_data_found));
1116 return std::move(Coverage);
1117}
1118
1119namespace {
1120
1121/// Distributes functions into instantiation sets.
1122///
1123/// An instantiation set is a collection of functions that have the same source
1124/// code, ie, template functions specializations.
1125class FunctionInstantiationSetCollector {
1126 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
1127 MapT InstantiatedFunctions;
1128
1129public:
1130 void insert(const FunctionRecord &Function, unsigned FileID) {
1131 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
1132 while (I != E && I->FileID != FileID)
1133 ++I;
1134 assert(I != E && "function does not cover the given file");
1135 auto &Functions = InstantiatedFunctions[I->startLoc()];
1136 Functions.push_back(x: &Function);
1137 }
1138
1139 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
1140 MapT::iterator end() { return InstantiatedFunctions.end(); }
1141};
1142
1143class SegmentBuilder {
1144 std::vector<CoverageSegment> &Segments;
1145 SmallVector<const CountedRegion *, 8> ActiveRegions;
1146
1147 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
1148
1149 /// Emit a segment with the count from \p Region starting at \p StartLoc.
1150 //
1151 /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
1152 /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
1153 void startSegment(const CountedRegion &Region, LineColPair StartLoc,
1154 bool IsRegionEntry, bool EmitSkippedRegion = false) {
1155 bool HasCount = !EmitSkippedRegion &&
1156 (Region.Kind != CounterMappingRegion::SkippedRegion);
1157
1158 // If the new segment wouldn't affect coverage rendering, skip it.
1159 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
1160 const auto &Last = Segments.back();
1161 if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
1162 !Last.IsRegionEntry)
1163 return;
1164 }
1165
1166 if (HasCount)
1167 Segments.emplace_back(args&: StartLoc.first, args&: StartLoc.second,
1168 args: Region.ExecutionCount, args&: IsRegionEntry,
1169 args: Region.Kind == CounterMappingRegion::GapRegion);
1170 else
1171 Segments.emplace_back(args&: StartLoc.first, args&: StartLoc.second, args&: IsRegionEntry);
1172
1173 LLVM_DEBUG({
1174 const auto &Last = Segments.back();
1175 dbgs() << "Segment at " << Last.Line << ":" << Last.Col
1176 << " (count = " << Last.Count << ")"
1177 << (Last.IsRegionEntry ? ", RegionEntry" : "")
1178 << (!Last.HasCount ? ", Skipped" : "")
1179 << (Last.IsGapRegion ? ", Gap" : "") << "\n";
1180 });
1181 }
1182
1183 /// Emit segments for active regions which end before \p Loc.
1184 ///
1185 /// \p Loc: The start location of the next region. If std::nullopt, all active
1186 /// regions are completed.
1187 /// \p FirstCompletedRegion: Index of the first completed region.
1188 void completeRegionsUntil(std::optional<LineColPair> Loc,
1189 unsigned FirstCompletedRegion) {
1190 // Sort the completed regions by end location. This makes it simple to
1191 // emit closing segments in sorted order.
1192 auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
1193 std::stable_sort(first: CompletedRegionsIt, last: ActiveRegions.end(),
1194 comp: [](const CountedRegion *L, const CountedRegion *R) {
1195 return L->endLoc() < R->endLoc();
1196 });
1197
1198 // Emit segments for all completed regions.
1199 for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
1200 ++I) {
1201 const auto *CompletedRegion = ActiveRegions[I];
1202 assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
1203 "Completed region ends after start of new region");
1204
1205 const auto *PrevCompletedRegion = ActiveRegions[I - 1];
1206 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
1207
1208 // Don't emit any more segments if they start where the new region begins.
1209 if (Loc && CompletedSegmentLoc == *Loc)
1210 break;
1211
1212 // Don't emit a segment if the next completed region ends at the same
1213 // location as this one.
1214 if (CompletedSegmentLoc == CompletedRegion->endLoc())
1215 continue;
1216
1217 // Use the count from the last completed region which ends at this loc.
1218 for (unsigned J = I + 1; J < E; ++J)
1219 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
1220 CompletedRegion = ActiveRegions[J];
1221
1222 startSegment(Region: *CompletedRegion, StartLoc: CompletedSegmentLoc, IsRegionEntry: false);
1223 }
1224
1225 auto Last = ActiveRegions.back();
1226 if (FirstCompletedRegion && Last->endLoc() != *Loc) {
1227 // If there's a gap after the end of the last completed region and the
1228 // start of the new region, use the last active region to fill the gap.
1229 startSegment(Region: *ActiveRegions[FirstCompletedRegion - 1], StartLoc: Last->endLoc(),
1230 IsRegionEntry: false);
1231 } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
1232 // Emit a skipped segment if there are no more active regions. This
1233 // ensures that gaps between functions are marked correctly.
1234 startSegment(Region: *Last, StartLoc: Last->endLoc(), IsRegionEntry: false, EmitSkippedRegion: true);
1235 }
1236
1237 // Pop the completed regions.
1238 ActiveRegions.erase(CS: CompletedRegionsIt, CE: ActiveRegions.end());
1239 }
1240
1241 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
1242 for (const auto &CR : enumerate(First&: Regions)) {
1243 auto CurStartLoc = CR.value().startLoc();
1244
1245 // Active regions which end before the current region need to be popped.
1246 auto CompletedRegions =
1247 std::stable_partition(first: ActiveRegions.begin(), last: ActiveRegions.end(),
1248 pred: [&](const CountedRegion *Region) {
1249 return !(Region->endLoc() <= CurStartLoc);
1250 });
1251 if (CompletedRegions != ActiveRegions.end()) {
1252 unsigned FirstCompletedRegion =
1253 std::distance(first: ActiveRegions.begin(), last: CompletedRegions);
1254 completeRegionsUntil(Loc: CurStartLoc, FirstCompletedRegion);
1255 }
1256
1257 bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
1258
1259 // Try to emit a segment for the current region.
1260 if (CurStartLoc == CR.value().endLoc()) {
1261 // Avoid making zero-length regions active. If it's the last region,
1262 // emit a skipped segment. Otherwise use its predecessor's count.
1263 const bool Skipped =
1264 (CR.index() + 1) == Regions.size() ||
1265 CR.value().Kind == CounterMappingRegion::SkippedRegion;
1266 startSegment(Region: ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
1267 StartLoc: CurStartLoc, IsRegionEntry: !GapRegion, EmitSkippedRegion: Skipped);
1268 // If it is skipped segment, create a segment with last pushed
1269 // regions's count at CurStartLoc.
1270 if (Skipped && !ActiveRegions.empty())
1271 startSegment(Region: *ActiveRegions.back(), StartLoc: CurStartLoc, IsRegionEntry: false);
1272 continue;
1273 }
1274 if (CR.index() + 1 == Regions.size() ||
1275 CurStartLoc != Regions[CR.index() + 1].startLoc()) {
1276 // Emit a segment if the next region doesn't start at the same location
1277 // as this one.
1278 startSegment(Region: CR.value(), StartLoc: CurStartLoc, IsRegionEntry: !GapRegion);
1279 }
1280
1281 // This region is active (i.e not completed).
1282 ActiveRegions.push_back(Elt: &CR.value());
1283 }
1284
1285 // Complete any remaining active regions.
1286 if (!ActiveRegions.empty())
1287 completeRegionsUntil(Loc: std::nullopt, FirstCompletedRegion: 0);
1288 }
1289
1290 /// Sort a nested sequence of regions from a single file.
1291 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
1292 llvm::sort(C&: Regions, Comp: [](const CountedRegion &LHS, const CountedRegion &RHS) {
1293 if (LHS.startLoc() != RHS.startLoc())
1294 return LHS.startLoc() < RHS.startLoc();
1295 if (LHS.endLoc() != RHS.endLoc())
1296 // When LHS completely contains RHS, we sort LHS first.
1297 return RHS.endLoc() < LHS.endLoc();
1298 // If LHS and RHS cover the same area, we need to sort them according
1299 // to their kinds so that the most suitable region will become "active"
1300 // in combineRegions(). Because we accumulate counter values only from
1301 // regions of the same kind as the first region of the area, prefer
1302 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
1303 static_assert(CounterMappingRegion::CodeRegion <
1304 CounterMappingRegion::ExpansionRegion &&
1305 CounterMappingRegion::ExpansionRegion <
1306 CounterMappingRegion::SkippedRegion,
1307 "Unexpected order of region kind values");
1308 return LHS.Kind < RHS.Kind;
1309 });
1310 }
1311
1312 /// Combine counts of regions which cover the same area.
1313 static ArrayRef<CountedRegion>
1314 combineRegions(MutableArrayRef<CountedRegion> Regions) {
1315 if (Regions.empty())
1316 return Regions;
1317 auto Active = Regions.begin();
1318 auto End = Regions.end();
1319 for (auto I = Regions.begin() + 1; I != End; ++I) {
1320 if (Active->startLoc() != I->startLoc() ||
1321 Active->endLoc() != I->endLoc()) {
1322 // Shift to the next region.
1323 ++Active;
1324 if (Active != I)
1325 *Active = *I;
1326 continue;
1327 }
1328 // Merge duplicate region.
1329 // If CodeRegions and ExpansionRegions cover the same area, it's probably
1330 // a macro which is fully expanded to another macro. In that case, we need
1331 // to accumulate counts only from CodeRegions, or else the area will be
1332 // counted twice.
1333 // On the other hand, a macro may have a nested macro in its body. If the
1334 // outer macro is used several times, the ExpansionRegion for the nested
1335 // macro will also be added several times. These ExpansionRegions cover
1336 // the same source locations and have to be combined to reach the correct
1337 // value for that area.
1338 // We add counts of the regions of the same kind as the active region
1339 // to handle the both situations.
1340 if (I->Kind == Active->Kind)
1341 Active->ExecutionCount += I->ExecutionCount;
1342 }
1343 return Regions.drop_back(N: std::distance(first: ++Active, last: End));
1344 }
1345
1346public:
1347 /// Build a sorted list of CoverageSegments from a list of Regions.
1348 static std::vector<CoverageSegment>
1349 buildSegments(MutableArrayRef<CountedRegion> Regions) {
1350 std::vector<CoverageSegment> Segments;
1351 SegmentBuilder Builder(Segments);
1352
1353 sortNestedRegions(Regions);
1354 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
1355
1356 LLVM_DEBUG({
1357 dbgs() << "Combined regions:\n";
1358 for (const auto &CR : CombinedRegions)
1359 dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
1360 << CR.LineEnd << ":" << CR.ColumnEnd
1361 << " (count=" << CR.ExecutionCount << ")\n";
1362 });
1363
1364 Builder.buildSegmentsImpl(Regions: CombinedRegions);
1365
1366#ifndef NDEBUG
1367 for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
1368 const auto &L = Segments[I - 1];
1369 const auto &R = Segments[I];
1370 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
1371 if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
1372 continue;
1373 LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
1374 << " followed by " << R.Line << ":" << R.Col << "\n");
1375 assert(false && "Coverage segments not unique or sorted");
1376 }
1377 }
1378#endif
1379
1380 return Segments;
1381 }
1382};
1383
1384struct MergeableCoverageData : public CoverageData {
1385 std::vector<CountedRegion> CodeRegions;
1386
1387 MergeableCoverageData(bool Single, StringRef Filename)
1388 : CoverageData(Single, Filename) {}
1389
1390 void addFunctionRegions(
1391 const FunctionRecord &Function,
1392 std::function<bool(const CounterMappingRegion &CR)> shouldProcess,
1393 std::function<bool(const CountedRegion &CR)> shouldExpand) {
1394 for (const auto &CR : Function.CountedRegions)
1395 if (shouldProcess(CR)) {
1396 CodeRegions.push_back(x: CR);
1397 if (shouldExpand(CR))
1398 Expansions.emplace_back(args: CR, args: Function);
1399 }
1400 // Capture branch regions specific to the function (excluding expansions).
1401 for (const auto &CR : Function.CountedBranchRegions)
1402 if (shouldProcess(CR))
1403 BranchRegions.push_back(x: CR);
1404 // Capture MCDC records specific to the function.
1405 for (const auto &MR : Function.MCDCRecords)
1406 if (shouldProcess(MR.getDecisionRegion()))
1407 MCDCRecords.push_back(x: MR);
1408 }
1409
1410 CoverageData buildSegments() {
1411 Segments = SegmentBuilder::buildSegments(Regions: CodeRegions);
1412 return CoverageData(std::move(*this));
1413 }
1414};
1415} // end anonymous namespace
1416
1417std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
1418 std::vector<StringRef> Filenames;
1419 for (const auto &Function : getCoveredFunctions())
1420 llvm::append_range(C&: Filenames, R: Function.Filenames);
1421 llvm::sort(C&: Filenames);
1422 auto Last = llvm::unique(R&: Filenames);
1423 Filenames.erase(first: Last, last: Filenames.end());
1424 return Filenames;
1425}
1426
1427static SmallBitVector gatherFileIDs(StringRef SourceFile,
1428 const FunctionRecord &Function) {
1429 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
1430 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
1431 if (SourceFile == Function.Filenames[I])
1432 FilenameEquivalence[I] = true;
1433 return FilenameEquivalence;
1434}
1435
1436/// Return the ID of the file where the definition of the function is located.
1437static std::optional<unsigned>
1438findMainViewFileID(const FunctionRecord &Function) {
1439 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
1440 for (const auto &CR : Function.CountedRegions)
1441 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
1442 IsNotExpandedFile[CR.ExpandedFileID] = false;
1443 int I = IsNotExpandedFile.find_first();
1444 if (I == -1)
1445 return std::nullopt;
1446 return I;
1447}
1448
1449/// Check if SourceFile is the file that contains the definition of
1450/// the Function. Return the ID of the file in that case or std::nullopt
1451/// otherwise.
1452static std::optional<unsigned>
1453findMainViewFileID(StringRef SourceFile, const FunctionRecord &Function) {
1454 std::optional<unsigned> I = findMainViewFileID(Function);
1455 if (I && SourceFile == Function.Filenames[*I])
1456 return I;
1457 return std::nullopt;
1458}
1459
1460static bool isExpansion(const CountedRegion &R, unsigned FileID) {
1461 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
1462}
1463
1464CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
1465 assert(SingleByteCoverage);
1466 MergeableCoverageData FileCoverage(*SingleByteCoverage, Filename);
1467
1468 // Look up the function records in the given file. Due to hash collisions on
1469 // the filename, we may get back some records that are not in the file.
1470 ArrayRef<unsigned> RecordIndices =
1471 getImpreciseRecordIndicesForFilename(Filename);
1472 for (unsigned RecordIndex : RecordIndices) {
1473 const FunctionRecord &Function = Functions[RecordIndex];
1474 auto MainFileID = findMainViewFileID(SourceFile: Filename, Function);
1475 auto FileIDs = gatherFileIDs(SourceFile: Filename, Function);
1476 FileCoverage.addFunctionRegions(
1477 Function, shouldProcess: [&](auto &CR) { return FileIDs.test(CR.FileID); },
1478 shouldExpand: [&](auto &CR) { return (MainFileID && isExpansion(CR, *MainFileID)); });
1479 }
1480
1481 LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
1482
1483 return FileCoverage.buildSegments();
1484}
1485
1486std::vector<InstantiationGroup>
1487CoverageMapping::getInstantiationGroups(StringRef Filename) const {
1488 FunctionInstantiationSetCollector InstantiationSetCollector;
1489 // Look up the function records in the given file. Due to hash collisions on
1490 // the filename, we may get back some records that are not in the file.
1491 ArrayRef<unsigned> RecordIndices =
1492 getImpreciseRecordIndicesForFilename(Filename);
1493 for (unsigned RecordIndex : RecordIndices) {
1494 const FunctionRecord &Function = Functions[RecordIndex];
1495 auto MainFileID = findMainViewFileID(SourceFile: Filename, Function);
1496 if (!MainFileID)
1497 continue;
1498 InstantiationSetCollector.insert(Function, FileID: *MainFileID);
1499 }
1500
1501 std::vector<InstantiationGroup> Result;
1502 for (auto &InstantiationSet : InstantiationSetCollector) {
1503 InstantiationGroup IG{InstantiationSet.first.first,
1504 InstantiationSet.first.second,
1505 std::move(InstantiationSet.second)};
1506 Result.emplace_back(args: std::move(IG));
1507 }
1508 return Result;
1509}
1510
1511CoverageData
1512CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
1513 auto MainFileID = findMainViewFileID(Function);
1514 if (!MainFileID)
1515 return CoverageData();
1516
1517 assert(SingleByteCoverage);
1518 MergeableCoverageData FunctionCoverage(*SingleByteCoverage,
1519 Function.Filenames[*MainFileID]);
1520 FunctionCoverage.addFunctionRegions(
1521 Function, shouldProcess: [&](auto &CR) { return (CR.FileID == *MainFileID); },
1522 shouldExpand: [&](auto &CR) { return isExpansion(CR, *MainFileID); });
1523
1524 LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
1525 << "\n");
1526
1527 return FunctionCoverage.buildSegments();
1528}
1529
1530CoverageData CoverageMapping::getCoverageForExpansion(
1531 const ExpansionRecord &Expansion) const {
1532 assert(SingleByteCoverage);
1533 CoverageData ExpansionCoverage(
1534 *SingleByteCoverage, Expansion.Function.Filenames[Expansion.FileID]);
1535 std::vector<CountedRegion> Regions;
1536 for (const auto &CR : Expansion.Function.CountedRegions)
1537 if (CR.FileID == Expansion.FileID) {
1538 Regions.push_back(x: CR);
1539 if (isExpansion(R: CR, FileID: Expansion.FileID))
1540 ExpansionCoverage.Expansions.emplace_back(args: CR, args: Expansion.Function);
1541 }
1542 for (const auto &CR : Expansion.Function.CountedBranchRegions)
1543 // Capture branch regions that only pertain to the corresponding expansion.
1544 if (CR.FileID == Expansion.FileID)
1545 ExpansionCoverage.BranchRegions.push_back(x: CR);
1546
1547 LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
1548 << Expansion.FileID << "\n");
1549 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1550
1551 return ExpansionCoverage;
1552}
1553
1554LineCoverageStats::LineCoverageStats(
1555 ArrayRef<const CoverageSegment *> LineSegments,
1556 const CoverageSegment *WrappedSegment, unsigned Line)
1557 : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
1558 LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
1559 // Find the minimum number of regions which start in this line.
1560 unsigned MinRegionCount = 0;
1561 auto isStartOfRegion = [](const CoverageSegment *S) {
1562 return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
1563 };
1564 for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
1565 if (isStartOfRegion(LineSegments[I]))
1566 ++MinRegionCount;
1567
1568 bool StartOfSkippedRegion = !LineSegments.empty() &&
1569 !LineSegments.front()->HasCount &&
1570 LineSegments.front()->IsRegionEntry;
1571
1572 HasMultipleRegions = MinRegionCount > 1;
1573 Mapped =
1574 !StartOfSkippedRegion &&
1575 ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
1576
1577 // if there is any starting segment at this line with a counter, it must be
1578 // mapped
1579 Mapped |= any_of(Range&: LineSegments, P: [](const auto *Seq) {
1580 return Seq->IsRegionEntry && Seq->HasCount;
1581 });
1582
1583 if (!Mapped) {
1584 return;
1585 }
1586
1587 // Pick the max count from the non-gap, region entry segments and the
1588 // wrapped count.
1589 if (WrappedSegment)
1590 ExecutionCount = WrappedSegment->Count;
1591 if (!MinRegionCount)
1592 return;
1593 for (const auto *LS : LineSegments)
1594 if (isStartOfRegion(LS))
1595 ExecutionCount = std::max(a: ExecutionCount, b: LS->Count);
1596}
1597
1598LineCoverageIterator &LineCoverageIterator::operator++() {
1599 if (Next == CD.end()) {
1600 Stats = LineCoverageStats();
1601 Ended = true;
1602 return *this;
1603 }
1604 if (Segments.size())
1605 WrappedSegment = Segments.back();
1606 Segments.clear();
1607 while (Next != CD.end() && Next->Line == Line)
1608 Segments.push_back(Elt: &*Next++);
1609 Stats = LineCoverageStats(Segments, WrappedSegment, Line);
1610 ++Line;
1611 return *this;
1612}
1613
1614static std::string getCoverageMapErrString(coveragemap_error Err,
1615 const std::string &ErrMsg = "") {
1616 std::string Msg;
1617 raw_string_ostream OS(Msg);
1618
1619 switch (Err) {
1620 case coveragemap_error::success:
1621 OS << "success";
1622 break;
1623 case coveragemap_error::eof:
1624 OS << "end of File";
1625 break;
1626 case coveragemap_error::no_data_found:
1627 OS << "no coverage data found";
1628 break;
1629 case coveragemap_error::unsupported_version:
1630 OS << "unsupported coverage format version";
1631 break;
1632 case coveragemap_error::truncated:
1633 OS << "truncated coverage data";
1634 break;
1635 case coveragemap_error::malformed:
1636 OS << "malformed coverage data";
1637 break;
1638 case coveragemap_error::decompression_failed:
1639 OS << "failed to decompress coverage data (zlib)";
1640 break;
1641 case coveragemap_error::invalid_or_missing_arch_specifier:
1642 OS << "`-arch` specifier is invalid or missing for universal binary";
1643 break;
1644 }
1645
1646 // If optional error message is not empty, append it to the message.
1647 if (!ErrMsg.empty())
1648 OS << ": " << ErrMsg;
1649
1650 return Msg;
1651}
1652
1653namespace {
1654
1655// FIXME: This class is only here to support the transition to llvm::Error. It
1656// will be removed once this transition is complete. Clients should prefer to
1657// deal with the Error value directly, rather than converting to error_code.
1658class CoverageMappingErrorCategoryType : public std::error_category {
1659 const char *name() const noexcept override { return "llvm.coveragemap"; }
1660 std::string message(int IE) const override {
1661 return getCoverageMapErrString(Err: static_cast<coveragemap_error>(IE));
1662 }
1663};
1664
1665} // end anonymous namespace
1666
1667std::string CoverageMapError::message() const {
1668 return getCoverageMapErrString(Err, ErrMsg: Msg);
1669}
1670
1671const std::error_category &llvm::coverage::coveragemap_category() {
1672 static CoverageMappingErrorCategoryType ErrorCategory;
1673 return ErrorCategory;
1674}
1675
1676char CoverageMapError::ID = 0;
1677