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