LLVM 23.0.0git
CoverageMapping.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/Object/BuildID.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Errc.h"
27#include "llvm/Support/Error.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(E, Expressions.size());
53 if (Inserted)
54 Expressions.push_back(E);
55 return Counter::getExpression(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;
64 Terms.emplace_back(C.getCounterID(), Factor);
65 break;
67 const auto &E = Expressions[C.getExpressionID()];
68 extractTerms(E.LHS, Factor, Terms);
69 extractTerms(
70 E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
71 break;
72 }
73}
74
75Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
76 // Gather constant terms.
78 extractTerms(ExpressionTree, +1, Terms);
79
80 // If there are no terms, this is just a zero. The algorithm below assumes at
81 // least one term.
82 if (Terms.size() == 0)
83 return Counter::getZero();
84
85 // Group the terms by counter ID.
86 llvm::sort(Terms, [](const Term &LHS, const Term &RHS) {
87 return LHS.CounterID < RHS.CounterID;
88 });
89
90 // Combine terms by counter ID to eliminate counters that sum to zero.
91 auto Prev = Terms.begin();
92 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
93 if (I->CounterID == Prev->CounterID) {
94 Prev->Factor += I->Factor;
95 continue;
96 }
97 ++Prev;
98 *Prev = *I;
99 }
100 Terms.erase(++Prev, Terms.end());
101
102 Counter C;
103 // Create additions. We do this before subtractions to avoid constructs like
104 // ((0 - X) + Y), as opposed to (Y - X).
105 for (auto T : Terms) {
106 if (T.Factor <= 0)
107 continue;
108 for (int I = 0; I < T.Factor; ++I)
109 if (C.isZero())
110 C = Counter::getCounter(T.CounterID);
111 else
112 C = get(CounterExpression(CounterExpression::Add, C,
113 Counter::getCounter(T.CounterID)));
114 }
115
116 // Create subtractions.
117 for (auto T : Terms) {
118 if (T.Factor >= 0)
119 continue;
120 for (int I = 0; I < -T.Factor; ++I)
121 C = get(CounterExpression(CounterExpression::Subtract, C,
122 Counter::getCounter(T.CounterID)));
123 }
124 return C;
125}
126
128 auto Cnt = get(CounterExpression(CounterExpression::Add, LHS, RHS));
129 return Simplify ? simplify(Cnt) : Cnt;
130}
131
133 bool Simplify) {
134 auto Cnt = get(CounterExpression(CounterExpression::Subtract, LHS, RHS));
135 return Simplify ? simplify(Cnt) : Cnt;
136}
137
139 // Replace C with the value found in Map even if C is Expression.
140 if (auto I = Map.find(C); I != Map.end())
141 return I->second;
142
143 if (!C.isExpression())
144 return C;
145
146 auto CE = Expressions[C.getExpressionID()];
147 auto NewLHS = subst(CE.LHS, Map);
148 auto NewRHS = subst(CE.RHS, Map);
149
150 // Reconstruct Expression with induced subexpressions.
151 switch (CE.Kind) {
153 C = add(NewLHS, NewRHS);
154 break;
156 C = subtract(NewLHS, NewRHS);
157 break;
158 }
159
160 return C;
161}
162
164 switch (C.getKind()) {
165 case Counter::Zero:
166 OS << '0';
167 return;
169 OS << '#' << C.getCounterID();
170 break;
171 case Counter::Expression: {
172 if (C.getExpressionID() >= Expressions.size())
173 return;
174 const auto &E = Expressions[C.getExpressionID()];
175 OS << '(';
176 dump(E.LHS, OS);
177 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
178 dump(E.RHS, OS);
179 OS << ')';
180 break;
181 }
182 }
183 if (CounterValues.empty())
184 return;
186 if (auto E = Value.takeError()) {
187 consumeError(std::move(E));
188 return;
189 }
190 OS << '[' << *Value << ']';
191}
192
194 struct StackElem {
195 Counter ICounter;
196 int64_t LHS = 0;
197 enum {
198 KNeverVisited = 0,
199 KVisitedOnce = 1,
200 KVisitedTwice = 2,
201 } VisitCount = KNeverVisited;
202 };
203
204 std::stack<StackElem> CounterStack;
205 CounterStack.push({C});
206
207 int64_t LastPoppedValue;
208
209 while (!CounterStack.empty()) {
210 StackElem &Current = CounterStack.top();
211
212 switch (Current.ICounter.getKind()) {
213 case Counter::Zero:
214 LastPoppedValue = 0;
215 CounterStack.pop();
216 break;
218 if (Current.ICounter.getCounterID() >= CounterValues.size())
220 LastPoppedValue = CounterValues[Current.ICounter.getCounterID()];
221 CounterStack.pop();
222 break;
223 case Counter::Expression: {
224 if (Current.ICounter.getExpressionID() >= Expressions.size())
226 const auto &E = Expressions[Current.ICounter.getExpressionID()];
227 if (Current.VisitCount == StackElem::KNeverVisited) {
228 CounterStack.push(StackElem{E.LHS});
229 Current.VisitCount = StackElem::KVisitedOnce;
230 } else if (Current.VisitCount == StackElem::KVisitedOnce) {
231 Current.LHS = LastPoppedValue;
232 CounterStack.push(StackElem{E.RHS});
233 Current.VisitCount = StackElem::KVisitedTwice;
234 } else {
235 int64_t LHS = Current.LHS;
236 int64_t RHS = LastPoppedValue;
237 LastPoppedValue =
238 E.Kind == CounterExpression::Subtract ? LHS - RHS : LHS + RHS;
239 CounterStack.pop();
240 }
241 break;
242 }
243 }
244 }
245
246 return LastPoppedValue;
247}
248
249// Find an independence pair for each condition:
250// - The condition is true in one test and false in the other.
251// - The decision outcome is true one test and false in the other.
252// - All other conditions' values must be equal or marked as "don't care".
254 if (IndependencePairs)
255 return;
256
257 IndependencePairs.emplace();
258
259 unsigned NumTVs = TV.size();
260 // Will be replaced to shorter expr.
261 unsigned TVTrueIdx = std::distance(
262 TV.begin(),
263 llvm::find_if(TV,
264 [&](auto I) { return (I.second == MCDCRecord::MCDC_True); })
265
266 );
267 for (unsigned I = TVTrueIdx; I < NumTVs; ++I) {
268 const auto &[A, ACond] = TV[I];
270 for (unsigned J = 0; J < TVTrueIdx; ++J) {
271 const auto &[B, BCond] = TV[J];
273 // If the two vectors differ in exactly one condition, ignoring DontCare
274 // conditions, we have found an independence pair.
275 auto AB = A.getDifferences(B);
276 if (AB.count() == 1)
277 IndependencePairs->insert(
278 {AB.find_first(), std::make_pair(J + 1, I + 1)});
279 }
280 }
281}
282
284 int Offset)
285 : Indices(NextIDs.size()) {
286 // Construct Nodes and set up each InCount
287 auto N = NextIDs.size();
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
311 assert(Nodes[0].InCount == 0);
312 Nodes[0].Width = 1;
313 Q.push_back(0);
314
315 unsigned Ord = 0;
316 while (!Q.empty()) {
317 auto IID = Q.begin();
318 int ID = *IID;
319 Q.erase(IID);
320 auto &Node = Nodes[ID];
321 assert(Node.Width > 0);
322
323 for (unsigned I = 0; I < 2; ++I) {
324 auto NextID = Node.NextIDs[I];
325 assert(NextID != 0 && "NextID should not point to the top");
326 if (NextID < 0) {
327 // Decision
328 Decisions.emplace_back(-Node.Width, Ord++, ID, I);
329 assert(Ord == Decisions.size());
330 continue;
331 }
332
333 // Inter Node
334 auto &NextNode = Nodes[NextID];
335 assert(NextNode.InCount > 0);
336
337 // Assign Idx
338 assert(Indices[ID][I] == INT_MIN);
339 Indices[ID][I] = NextNode.Width;
340 auto NextWidth = int64_t(NextNode.Width) + Node.Width;
341 if (NextWidth > HardMaxTVs) {
342 NumTestVectors = HardMaxTVs; // Overflow
343 return;
344 }
345 NextNode.Width = NextWidth;
346
347 // Ready if all incomings are processed.
348 // Or NextNode.Width hasn't been confirmed yet.
349 if (--NextNode.InCount == 0)
350 Q.push_back(NextID);
351 }
352 }
353
354 llvm::sort(Decisions);
355
356 // Assign TestVector Indices in Decision Nodes
357 int64_t CurIdx = 0;
358 for (auto [NegWidth, Ord, ID, C] : Decisions) {
359 int Width = -NegWidth;
360 assert(Nodes[ID].Width == Width);
361 assert(Nodes[ID].NextIDs[C] < 0);
362 assert(Indices[ID][C] == INT_MIN);
363 Indices[ID][C] = Offset + CurIdx;
364 CurIdx += Width;
365 if (CurIdx > HardMaxTVs) {
366 NumTestVectors = HardMaxTVs; // Overflow
367 return;
368 }
369 }
370
371 assert(CurIdx < HardMaxTVs);
372 NumTestVectors = CurIdx;
373
374#ifndef NDEBUG
375 for (const auto &Idxs : Indices)
376 for (auto Idx : Idxs)
377 assert(Idx != INT_MIN);
378 SavedNodes = std::move(Nodes);
379#endif
380}
381
382namespace {
383
384/// Construct this->NextIDs with Branches for TVIdxBuilder to use it
385/// before MCDCRecordProcessor().
386class NextIDsBuilder {
387protected:
389
390public:
391 NextIDsBuilder(const ArrayRef<const CounterMappingRegion *> Branches)
392 : NextIDs(Branches.size()) {
393#ifndef NDEBUG
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.
414 const mcdc::DecisionParameters &DecisionParams;
415
416 /// Array of branch regions corresponding each conditions in the boolean
417 /// expression.
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.
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(this->MCDCCond, this->BIdx, this->Ord) <
440 std::tie(RHS.MCDCCond, RHS.BIdx, 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,
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{{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(ID, 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, NextID, 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(MCDCCond, NextTVIdx, 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({TV, MCDCCond});
500 }
501
502 // Reset back to 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, 0, 0);
515 assert(TVIdxs.size() == unsigned(NumTestVectors) &&
516 "TVIdxs wasn't fulfilled");
517
518 llvm::sort(ExecVectorIdxs);
519 MCDCRecord::TestVectors NewTestVectors;
520 for (const auto &IdxTuple : ExecVectorIdxs)
521 NewTestVectors.push_back(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;
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(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
570 ArrayRef<const CounterMappingRegion *> Branches, bool IsVersion11) {
571
572 MCDCRecordProcessor MCDCProcessor(Bitmap, Region, Branches, IsVersion11);
573 return MCDCProcessor.processMCDCRecord();
574}
575
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({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;
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(StackElem{E.LHS});
612 Current.VisitCount = StackElem::KVisitedOnce;
613 } else if (Current.VisitCount == StackElem::KVisitedOnce) {
614 Current.LHS = LastPoppedValue;
615 CounterStack.push(StackElem{E.RHS});
616 Current.VisitCount = StackElem::KVisitedTwice;
617 } else {
618 int64_t LHS = Current.LHS;
619 int64_t RHS = LastPoppedValue;
620 LastPoppedValue = std::max(LHS, 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(Filename);
643 auto RecordIt = FilenameHash2RecordIndices.find(FilenameHash);
644 if (RecordIt == FilenameHash2RecordIndices.end())
645 return {};
646 return RecordIt->second;
647}
648
649static unsigned getMaxCounterID(const CounterMappingContext &Ctx,
651 unsigned MaxCounterID = 0;
652 for (const auto &Region : Record.MappingRegions) {
653 MaxCounterID = std::max(MaxCounterID, Ctx.getMaxCounterID(Region.Count));
654 if (Region.isBranch())
655 MaxCounterID =
656 std::max(MaxCounterID, Ctx.getMaxCounterID(Region.FalseCount));
657 }
658 return MaxCounterID;
659}
660
661/// Returns the bit count
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(Record.MappingRegions)) {
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(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.
696#ifndef NDEBUG
697 DenseSet<mcdc::ConditionID> ConditionIDs;
698#endif
699
700 DecisionRecord(const CounterMappingRegion &Decision)
701 : DecisionRegion(&Decision),
702 NumConditions(Decision.getDecisionParams().NumConditions) {
704 }
705
706 bool pushBranch(const CounterMappingRegion &B) {
708 assert(ConditionIDs.insert(B.getBranchParams().ID).second &&
709 "Duplicate CondID");
710 MCDCBranches.push_back(&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(Record.MappingRegions)) {
750 if (Region.FileID >= Files.size()) {
751 // Extend (only possible in CoverageMappingTests)
752 Files.resize(Region.FileID + 1);
753 }
754 Files[Region.FileID].LastIndex = I + 1;
756 if (Region.ExpandedFileID >= Files.size()) {
757 // Extend (only possible in CoverageMappingTests)
758 Files.resize(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(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
789 if (auto E = walk(Region.ExpandedFileID))
790 return E;
791
792 if (auto E = evaluateAndCacheCounter(Region.Count))
793 return E;
794
796 // Start the new Decision on the stack.
797 DecisionStack.emplace_back(Region);
799 assert(!DecisionStack.empty() && "Orphan MCDCBranch");
800 auto &D = DecisionStack.back();
801
802 if (D.pushBranch(Region)) {
803 // All Branches have been found in the Decision.
804 auto RecordOrErr = Ctx.evaluateMCDCRegion(
805 *D.DecisionRegion, D.MCDCBranches, IsVersion11);
806 if (!RecordOrErr)
807 return RecordOrErr.takeError();
808
809 // Finish the stack.
810 Function.pushMCDCRecord(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(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(Files)) {
831 if (!F.IsExpanded)
832 if (auto E = walk(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) {
840 continue; // Don't emit.
841 // Adopt values from the CounterValues.
842 // FalseCount may be Zero unless Branches.
843 Function.pushRegion(Region, CounterValues[Region.Count],
844 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())
860 "record function name is empty");
861
862 if (Record.Filenames.empty())
863 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
864 else
865 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, 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 Record.FunctionName, Record.FunctionHash, Counts)) {
873 instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
875 FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
876 Record.FunctionHash);
877 return Error::success();
878 }
880 return make_error<InstrProfError>(IPE);
881 Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
882 }
883 } else {
884 Counts.assign(getMaxCounterID(Ctx, Record) + 1, 0);
885 }
886 Ctx.setCounts(Counts);
887
888 bool IsVersion11 =
889 ProfileReader && ProfileReader.value().get().getVersion() <
891
892 BitVector Bitmap;
893 if (ProfileReader) {
894 if (Error E = ProfileReader.value().get().getFunctionBitmap(
895 Record.FunctionName, Record.FunctionHash, Bitmap)) {
896 instrprof_error IPE = std::get<0>(InstrProfError::take(std::move(E)));
898 FuncHashMismatches.emplace_back(std::string(Record.FunctionName),
899 Record.FunctionHash);
900 return Error::success();
901 }
903 return make_error<InstrProfError>(IPE);
904 Bitmap = BitVector(getMaxBitmapSize(Record, IsVersion11));
905 }
906 } else {
907 Bitmap = BitVector(getMaxBitmapSize(Record, 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 return E;
928
929 // Don't create records for (filenames, function) pairs we've already seen.
930 auto FilenamesHash = hash_combine_range(Record.Filenames);
931 if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
932 return Error::success();
933
934 Functions.push_back(std::move(Function));
935
936 // Performance optimization: keep track of the indices of the function records
937 // which correspond to each filename. This can be used to substantially speed
938 // up queries for coverage info in a file.
939 unsigned RecordIndex = Functions.size() - 1;
940 for (StringRef Filename : Record.Filenames) {
941 auto &RecordIndices = FilenameHash2RecordIndices[hash_value(Filename)];
942 // Note that there may be duplicates in the filename set for a function
943 // record, because of e.g. macro expansions in the function in which both
944 // the macro and the function are defined in the same file.
945 if (RecordIndices.empty() || RecordIndices.back() != RecordIndex)
946 RecordIndices.push_back(RecordIndex);
947 }
948
949 return Error::success();
950}
951
952// This function is for memory optimization by shortening the lifetimes
953// of CoverageMappingReader instances.
954Error CoverageMapping::loadFromReaders(
955 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
956 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
957 &ProfileReader,
958 CoverageMapping &Coverage) {
959 assert(!Coverage.SingleByteCoverage || !ProfileReader ||
960 *Coverage.SingleByteCoverage ==
961 ProfileReader.value().get().hasSingleByteCoverage());
962 Coverage.SingleByteCoverage =
963 !ProfileReader || ProfileReader.value().get().hasSingleByteCoverage();
964 for (const auto &CoverageReader : CoverageReaders) {
965 for (auto RecordOrErr : *CoverageReader) {
966 if (Error E = RecordOrErr.takeError())
967 return E;
968 const auto &Record = *RecordOrErr;
969 if (Error E = Coverage.loadFunctionRecord(Record, ProfileReader))
970 return E;
971 }
972 }
973 return Error::success();
974}
975
977 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
978 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
979 &ProfileReader) {
980 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
981 if (Error E = loadFromReaders(CoverageReaders, ProfileReader, *Coverage))
982 return std::move(E);
983 return std::move(Coverage);
984}
985
986// If E is a no_data_found error, returns success. Otherwise returns E.
988 return handleErrors(std::move(E), [](const CoverageMapError &CME) {
990 return static_cast<Error>(Error::success());
991 return make_error<CoverageMapError>(CME.get(), CME.getMessage());
992 });
993}
994
995Error CoverageMapping::loadFromFile(
996 StringRef Filename, StringRef Arch, StringRef CompilationDir,
997 std::optional<std::reference_wrapper<IndexedInstrProfReader>>
998 &ProfileReader,
999 CoverageMapping &Coverage, bool &DataFound,
1000 SmallVectorImpl<object::BuildID> *FoundBinaryIDs) {
1001 auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(
1002 Filename, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1003 if (std::error_code EC = CovMappingBufOrErr.getError())
1005 MemoryBufferRef CovMappingBufRef =
1006 CovMappingBufOrErr.get()->getMemBufferRef();
1008
1010 auto CoverageReadersOrErr = BinaryCoverageReader::create(
1011 CovMappingBufRef, Arch, Buffers, CompilationDir,
1012 FoundBinaryIDs ? &BinaryIDs : nullptr);
1013 if (Error E = CoverageReadersOrErr.takeError()) {
1014 E = handleMaybeNoDataFoundError(std::move(E));
1015 if (E)
1016 return createFileError(Filename, std::move(E));
1017 return E;
1018 }
1019
1021 for (auto &Reader : CoverageReadersOrErr.get())
1022 Readers.push_back(std::move(Reader));
1023 if (FoundBinaryIDs && !Readers.empty()) {
1024 llvm::append_range(*FoundBinaryIDs,
1025 llvm::map_range(BinaryIDs, [](object::BuildIDRef BID) {
1026 return object::BuildID(BID);
1027 }));
1028 }
1029 DataFound |= !Readers.empty();
1030 if (Error E = loadFromReaders(Readers, ProfileReader, Coverage))
1031 return createFileError(Filename, std::move(E));
1032 return Error::success();
1033}
1034
1036 ArrayRef<StringRef> ObjectFilenames,
1037 std::optional<StringRef> ProfileFilename, vfs::FileSystem &FS,
1038 ArrayRef<StringRef> Arches, StringRef CompilationDir,
1039 const object::BuildIDFetcher *BIDFetcher, bool CheckBinaryIDs) {
1040 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
1041 if (ProfileFilename) {
1042 auto ProfileReaderOrErr =
1043 IndexedInstrProfReader::create(ProfileFilename.value(), FS);
1044 if (Error E = ProfileReaderOrErr.takeError())
1045 return createFileError(ProfileFilename.value(), std::move(E));
1046 ProfileReader = std::move(ProfileReaderOrErr.get());
1047 }
1048 auto ProfileReaderRef =
1049 ProfileReader
1050 ? std::optional<std::reference_wrapper<IndexedInstrProfReader>>(
1051 *ProfileReader)
1052 : std::nullopt;
1053 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
1054 bool DataFound = false;
1055
1056 auto GetArch = [&](size_t Idx) {
1057 if (Arches.empty())
1058 return StringRef();
1059 if (Arches.size() == 1)
1060 return Arches.front();
1061 return Arches[Idx];
1062 };
1063
1064 SmallVector<object::BuildID> FoundBinaryIDs;
1065 for (const auto &File : llvm::enumerate(ObjectFilenames)) {
1066 if (Error E = loadFromFile(File.value(), GetArch(File.index()),
1067 CompilationDir, ProfileReaderRef, *Coverage,
1068 DataFound, &FoundBinaryIDs))
1069 return std::move(E);
1070 }
1071
1072 if (BIDFetcher) {
1073 std::vector<object::BuildID> ProfileBinaryIDs;
1074 if (ProfileReader)
1075 if (Error E = ProfileReader->readBinaryIds(ProfileBinaryIDs))
1076 return createFileError(ProfileFilename.value(), std::move(E));
1077
1078 SmallVector<object::BuildIDRef> BinaryIDsToFetch;
1079 if (!ProfileBinaryIDs.empty()) {
1080 const auto &Compare = [](object::BuildIDRef A, object::BuildIDRef B) {
1081 return std::lexicographical_compare(A.begin(), A.end(), B.begin(),
1082 B.end());
1083 };
1084 llvm::sort(FoundBinaryIDs, Compare);
1085 std::set_difference(
1086 ProfileBinaryIDs.begin(), ProfileBinaryIDs.end(),
1087 FoundBinaryIDs.begin(), FoundBinaryIDs.end(),
1088 std::inserter(BinaryIDsToFetch, BinaryIDsToFetch.end()), Compare);
1089 }
1090
1091 for (object::BuildIDRef BinaryID : BinaryIDsToFetch) {
1092 std::optional<std::string> PathOpt = BIDFetcher->fetch(BinaryID);
1093 if (PathOpt) {
1094 std::string Path = std::move(*PathOpt);
1095 StringRef Arch = Arches.size() == 1 ? Arches.front() : StringRef();
1096 if (Error E = loadFromFile(Path, Arch, CompilationDir, ProfileReaderRef,
1097 *Coverage, DataFound))
1098 return std::move(E);
1099 } else if (CheckBinaryIDs) {
1100 return createFileError(
1101 ProfileFilename.value(),
1103 "Missing binary ID: " +
1104 llvm::toHex(BinaryID, /*LowerCase=*/true)));
1105 }
1106 }
1107 }
1108
1109 if (!DataFound)
1110 return createFileError(
1111 join(ObjectFilenames.begin(), ObjectFilenames.end(), ", "),
1113 return std::move(Coverage);
1114}
1115
1116namespace {
1117
1118/// Distributes functions into instantiation sets.
1119///
1120/// An instantiation set is a collection of functions that have the same source
1121/// code, ie, template functions specializations.
1122class FunctionInstantiationSetCollector {
1123 using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
1124 MapT InstantiatedFunctions;
1125
1126public:
1127 void insert(const FunctionRecord &Function, unsigned FileID) {
1128 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
1129 while (I != E && I->FileID != FileID)
1130 ++I;
1131 assert(I != E && "function does not cover the given file");
1132 auto &Functions = InstantiatedFunctions[I->startLoc()];
1133 Functions.push_back(&Function);
1134 }
1135
1136 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
1137 MapT::iterator end() { return InstantiatedFunctions.end(); }
1138};
1139
1140class SegmentBuilder {
1141 std::vector<CoverageSegment> &Segments;
1143
1144 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
1145
1146 /// Emit a segment with the count from \p Region starting at \p StartLoc.
1147 //
1148 /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
1149 /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
1150 void startSegment(const CountedRegion &Region, LineColPair StartLoc,
1151 bool IsRegionEntry, bool EmitSkippedRegion = false) {
1152 bool HasCount = !EmitSkippedRegion &&
1154
1155 // If the new segment wouldn't affect coverage rendering, skip it.
1156 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
1157 const auto &Last = Segments.back();
1158 if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
1159 !Last.IsRegionEntry)
1160 return;
1161 }
1162
1163 if (HasCount)
1164 Segments.emplace_back(StartLoc.first, StartLoc.second,
1165 Region.ExecutionCount, IsRegionEntry,
1167 else
1168 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
1169
1170 LLVM_DEBUG({
1171 const auto &Last = Segments.back();
1172 dbgs() << "Segment at " << Last.Line << ":" << Last.Col
1173 << " (count = " << Last.Count << ")"
1174 << (Last.IsRegionEntry ? ", RegionEntry" : "")
1175 << (!Last.HasCount ? ", Skipped" : "")
1176 << (Last.IsGapRegion ? ", Gap" : "") << "\n";
1177 });
1178 }
1179
1180 /// Emit segments for active regions which end before \p Loc.
1181 ///
1182 /// \p Loc: The start location of the next region. If std::nullopt, all active
1183 /// regions are completed.
1184 /// \p FirstCompletedRegion: Index of the first completed region.
1185 void completeRegionsUntil(std::optional<LineColPair> Loc,
1186 unsigned FirstCompletedRegion) {
1187 // Sort the completed regions by end location. This makes it simple to
1188 // emit closing segments in sorted order.
1189 auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
1190 std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
1191 [](const CountedRegion *L, const CountedRegion *R) {
1192 return L->endLoc() < R->endLoc();
1193 });
1194
1195 // Emit segments for all completed regions.
1196 for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
1197 ++I) {
1198 const auto *CompletedRegion = ActiveRegions[I];
1199 assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
1200 "Completed region ends after start of new region");
1201
1202 const auto *PrevCompletedRegion = ActiveRegions[I - 1];
1203 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
1204
1205 // Don't emit any more segments if they start where the new region begins.
1206 if (Loc && CompletedSegmentLoc == *Loc)
1207 break;
1208
1209 // Don't emit a segment if the next completed region ends at the same
1210 // location as this one.
1211 if (CompletedSegmentLoc == CompletedRegion->endLoc())
1212 continue;
1213
1214 // Use the count from the last completed region which ends at this loc.
1215 for (unsigned J = I + 1; J < E; ++J)
1216 if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
1217 CompletedRegion = ActiveRegions[J];
1218
1219 startSegment(*CompletedRegion, CompletedSegmentLoc, false);
1220 }
1221
1222 auto Last = ActiveRegions.back();
1223 if (FirstCompletedRegion && Last->endLoc() != *Loc) {
1224 // If there's a gap after the end of the last completed region and the
1225 // start of the new region, use the last active region to fill the gap.
1226 startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
1227 false);
1228 } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
1229 // Emit a skipped segment if there are no more active regions. This
1230 // ensures that gaps between functions are marked correctly.
1231 startSegment(*Last, Last->endLoc(), false, true);
1232 }
1233
1234 // Pop the completed regions.
1235 ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
1236 }
1237
1238 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
1239 for (const auto &CR : enumerate(Regions)) {
1240 auto CurStartLoc = CR.value().startLoc();
1241
1242 // Active regions which end before the current region need to be popped.
1243 auto CompletedRegions =
1244 std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
1245 [&](const CountedRegion *Region) {
1246 return !(Region->endLoc() <= CurStartLoc);
1247 });
1248 if (CompletedRegions != ActiveRegions.end()) {
1249 unsigned FirstCompletedRegion =
1250 std::distance(ActiveRegions.begin(), CompletedRegions);
1251 completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
1252 }
1253
1254 bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
1255
1256 // Try to emit a segment for the current region.
1257 if (CurStartLoc == CR.value().endLoc()) {
1258 // Avoid making zero-length regions active. If it's the last region,
1259 // emit a skipped segment. Otherwise use its predecessor's count.
1260 const bool Skipped =
1261 (CR.index() + 1) == Regions.size() ||
1262 CR.value().Kind == CounterMappingRegion::SkippedRegion;
1263 startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
1264 CurStartLoc, !GapRegion, Skipped);
1265 // If it is skipped segment, create a segment with last pushed
1266 // regions's count at CurStartLoc.
1267 if (Skipped && !ActiveRegions.empty())
1268 startSegment(*ActiveRegions.back(), CurStartLoc, false);
1269 continue;
1270 }
1271 if (CR.index() + 1 == Regions.size() ||
1272 CurStartLoc != Regions[CR.index() + 1].startLoc()) {
1273 // Emit a segment if the next region doesn't start at the same location
1274 // as this one.
1275 startSegment(CR.value(), CurStartLoc, !GapRegion);
1276 }
1277
1278 // This region is active (i.e not completed).
1279 ActiveRegions.push_back(&CR.value());
1280 }
1281
1282 // Complete any remaining active regions.
1283 if (!ActiveRegions.empty())
1284 completeRegionsUntil(std::nullopt, 0);
1285 }
1286
1287 /// Sort a nested sequence of regions from a single file.
1288 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
1289 llvm::sort(Regions, [](const CountedRegion &LHS, const CountedRegion &RHS) {
1290 if (LHS.startLoc() != RHS.startLoc())
1291 return LHS.startLoc() < RHS.startLoc();
1292 if (LHS.endLoc() != RHS.endLoc())
1293 // When LHS completely contains RHS, we sort LHS first.
1294 return RHS.endLoc() < LHS.endLoc();
1295 // If LHS and RHS cover the same area, we need to sort them according
1296 // to their kinds so that the most suitable region will become "active"
1297 // in combineRegions(). Because we accumulate counter values only from
1298 // regions of the same kind as the first region of the area, prefer
1299 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
1300 static_assert(CounterMappingRegion::CodeRegion <
1304 "Unexpected order of region kind values");
1305 return LHS.Kind < RHS.Kind;
1306 });
1307 }
1308
1309 /// Combine counts of regions which cover the same area.
1311 combineRegions(MutableArrayRef<CountedRegion> Regions) {
1312 if (Regions.empty())
1313 return Regions;
1314 auto Active = Regions.begin();
1315 auto End = Regions.end();
1316 for (auto I = Regions.begin() + 1; I != End; ++I) {
1317 if (Active->startLoc() != I->startLoc() ||
1318 Active->endLoc() != I->endLoc()) {
1319 // Shift to the next region.
1320 ++Active;
1321 if (Active != I)
1322 *Active = *I;
1323 continue;
1324 }
1325 // Merge duplicate region.
1326 // If CodeRegions and ExpansionRegions cover the same area, it's probably
1327 // a macro which is fully expanded to another macro. In that case, we need
1328 // to accumulate counts only from CodeRegions, or else the area will be
1329 // counted twice.
1330 // On the other hand, a macro may have a nested macro in its body. If the
1331 // outer macro is used several times, the ExpansionRegion for the nested
1332 // macro will also be added several times. These ExpansionRegions cover
1333 // the same source locations and have to be combined to reach the correct
1334 // value for that area.
1335 // We add counts of the regions of the same kind as the active region
1336 // to handle the both situations.
1337 if (I->Kind == Active->Kind)
1338 Active->ExecutionCount += I->ExecutionCount;
1339 }
1340 return Regions.drop_back(std::distance(++Active, End));
1341 }
1342
1343public:
1344 /// Build a sorted list of CoverageSegments from a list of Regions.
1345 static std::vector<CoverageSegment>
1346 buildSegments(MutableArrayRef<CountedRegion> Regions) {
1347 std::vector<CoverageSegment> Segments;
1348 SegmentBuilder Builder(Segments);
1349
1350 sortNestedRegions(Regions);
1351 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
1352
1353 LLVM_DEBUG({
1354 dbgs() << "Combined regions:\n";
1355 for (const auto &CR : CombinedRegions)
1356 dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
1357 << CR.LineEnd << ":" << CR.ColumnEnd
1358 << " (count=" << CR.ExecutionCount << ")\n";
1359 });
1360
1361 Builder.buildSegmentsImpl(CombinedRegions);
1362
1363#ifndef NDEBUG
1364 for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
1365 const auto &L = Segments[I - 1];
1366 const auto &R = Segments[I];
1367 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
1368 if (L.Line == R.Line && L.Col == R.Col && !L.HasCount)
1369 continue;
1370 LLVM_DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
1371 << " followed by " << R.Line << ":" << R.Col << "\n");
1372 assert(false && "Coverage segments not unique or sorted");
1373 }
1374 }
1375#endif
1376
1377 return Segments;
1378 }
1379};
1380
1381struct MergeableCoverageData : public CoverageData {
1382 std::vector<CountedRegion> CodeRegions;
1383
1384 MergeableCoverageData(bool Single, StringRef Filename)
1385 : CoverageData(Single, Filename) {}
1386
1387 void addFunctionRegions(
1388 const FunctionRecord &Function,
1389 std::function<bool(const CounterMappingRegion &CR)> shouldProcess,
1390 std::function<bool(const CountedRegion &CR)> shouldExpand) {
1391 for (const auto &CR : Function.CountedRegions)
1392 if (shouldProcess(CR)) {
1393 CodeRegions.push_back(CR);
1394 if (shouldExpand(CR))
1395 Expansions.emplace_back(CR, Function);
1396 }
1397 // Capture branch regions specific to the function (excluding expansions).
1398 for (const auto &CR : Function.CountedBranchRegions)
1399 if (shouldProcess(CR))
1400 BranchRegions.push_back(CR);
1401 // Capture MCDC records specific to the function.
1402 for (const auto &MR : Function.MCDCRecords)
1403 if (shouldProcess(MR.getDecisionRegion()))
1404 MCDCRecords.push_back(MR);
1405 }
1406
1407 CoverageData buildSegments() {
1408 Segments = SegmentBuilder::buildSegments(CodeRegions);
1409 return CoverageData(std::move(*this));
1410 }
1411};
1412} // end anonymous namespace
1413
1414std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
1415 std::vector<StringRef> Filenames;
1416 for (const auto &Function : getCoveredFunctions())
1417 llvm::append_range(Filenames, Function.Filenames);
1418 llvm::sort(Filenames);
1419 auto Last = llvm::unique(Filenames);
1420 Filenames.erase(Last, Filenames.end());
1421 return Filenames;
1422}
1423
1425 const FunctionRecord &Function) {
1426 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
1427 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
1428 if (SourceFile == Function.Filenames[I])
1429 FilenameEquivalence[I] = true;
1430 return FilenameEquivalence;
1431}
1432
1433/// Return the ID of the file where the definition of the function is located.
1434static std::optional<unsigned>
1436 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
1437 for (const auto &CR : Function.CountedRegions)
1439 IsNotExpandedFile[CR.ExpandedFileID] = false;
1440 int I = IsNotExpandedFile.find_first();
1441 if (I == -1)
1442 return std::nullopt;
1443 return I;
1444}
1445
1446/// Check if SourceFile is the file that contains the definition of
1447/// the Function. Return the ID of the file in that case or std::nullopt
1448/// otherwise.
1449static std::optional<unsigned>
1451 std::optional<unsigned> I = findMainViewFileID(Function);
1452 if (I && SourceFile == Function.Filenames[*I])
1453 return I;
1454 return std::nullopt;
1455}
1456
1457static bool isExpansion(const CountedRegion &R, unsigned FileID) {
1458 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
1459}
1460
1462 assert(SingleByteCoverage);
1463 MergeableCoverageData FileCoverage(*SingleByteCoverage, Filename);
1464
1465 // Look up the function records in the given file. Due to hash collisions on
1466 // the filename, we may get back some records that are not in the file.
1467 ArrayRef<unsigned> RecordIndices =
1468 getImpreciseRecordIndicesForFilename(Filename);
1469 for (unsigned RecordIndex : RecordIndices) {
1470 const FunctionRecord &Function = Functions[RecordIndex];
1471 auto MainFileID = findMainViewFileID(Filename, Function);
1472 auto FileIDs = gatherFileIDs(Filename, Function);
1473 FileCoverage.addFunctionRegions(
1474 Function, [&](auto &CR) { return FileIDs.test(CR.FileID); },
1475 [&](auto &CR) { return (MainFileID && isExpansion(CR, *MainFileID)); });
1476 }
1477
1478 LLVM_DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
1479
1480 return FileCoverage.buildSegments();
1481}
1482
1483std::vector<InstantiationGroup>
1485 FunctionInstantiationSetCollector InstantiationSetCollector;
1486 // Look up the function records in the given file. Due to hash collisions on
1487 // the filename, we may get back some records that are not in the file.
1488 ArrayRef<unsigned> RecordIndices =
1489 getImpreciseRecordIndicesForFilename(Filename);
1490 for (unsigned RecordIndex : RecordIndices) {
1491 const FunctionRecord &Function = Functions[RecordIndex];
1492 auto MainFileID = findMainViewFileID(Filename, Function);
1493 if (!MainFileID)
1494 continue;
1495 InstantiationSetCollector.insert(Function, *MainFileID);
1496 }
1497
1498 std::vector<InstantiationGroup> Result;
1499 for (auto &InstantiationSet : InstantiationSetCollector) {
1500 InstantiationGroup IG{InstantiationSet.first.first,
1501 InstantiationSet.first.second,
1502 std::move(InstantiationSet.second)};
1503 Result.emplace_back(std::move(IG));
1504 }
1505 return Result;
1506}
1507
1510 auto MainFileID = findMainViewFileID(Function);
1511 if (!MainFileID)
1512 return CoverageData();
1513
1514 assert(SingleByteCoverage);
1515 MergeableCoverageData FunctionCoverage(*SingleByteCoverage,
1516 Function.Filenames[*MainFileID]);
1517 FunctionCoverage.addFunctionRegions(
1518 Function, [&](auto &CR) { return (CR.FileID == *MainFileID); },
1519 [&](auto &CR) { return isExpansion(CR, *MainFileID); });
1520
1521 LLVM_DEBUG(dbgs() << "Emitting segments for function: " << Function.Name
1522 << "\n");
1523
1524 return FunctionCoverage.buildSegments();
1525}
1526
1528 const ExpansionRecord &Expansion) const {
1529 assert(SingleByteCoverage);
1530 CoverageData ExpansionCoverage(
1531 *SingleByteCoverage, Expansion.Function.Filenames[Expansion.FileID]);
1532 std::vector<CountedRegion> Regions;
1533 for (const auto &CR : Expansion.Function.CountedRegions)
1534 if (CR.FileID == Expansion.FileID) {
1535 Regions.push_back(CR);
1536 if (isExpansion(CR, Expansion.FileID))
1537 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
1538 }
1539 for (const auto &CR : Expansion.Function.CountedBranchRegions)
1540 // Capture branch regions that only pertain to the corresponding expansion.
1541 if (CR.FileID == Expansion.FileID)
1542 ExpansionCoverage.BranchRegions.push_back(CR);
1543
1544 LLVM_DEBUG(dbgs() << "Emitting segments for expansion of file "
1545 << Expansion.FileID << "\n");
1546 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
1547
1548 return ExpansionCoverage;
1549}
1550
1551LineCoverageStats::LineCoverageStats(
1553 const CoverageSegment *WrappedSegment, unsigned Line)
1554 : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
1555 LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
1556 // Find the minimum number of regions which start in this line.
1557 unsigned MinRegionCount = 0;
1558 auto isStartOfRegion = [](const CoverageSegment *S) {
1559 return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
1560 };
1561 for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
1562 if (isStartOfRegion(LineSegments[I]))
1563 ++MinRegionCount;
1564
1565 bool StartOfSkippedRegion = !LineSegments.empty() &&
1566 !LineSegments.front()->HasCount &&
1567 LineSegments.front()->IsRegionEntry;
1568
1569 HasMultipleRegions = MinRegionCount > 1;
1570 Mapped =
1571 !StartOfSkippedRegion &&
1572 ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
1573
1574 // if there is any starting segment at this line with a counter, it must be
1575 // mapped
1576 Mapped |= any_of(LineSegments, [](const auto *Seq) {
1577 return Seq->IsRegionEntry && Seq->HasCount;
1578 });
1579
1580 if (!Mapped) {
1581 return;
1582 }
1583
1584 // Pick the max count from the non-gap, region entry segments and the
1585 // wrapped count.
1586 if (WrappedSegment)
1587 ExecutionCount = WrappedSegment->Count;
1588 if (!MinRegionCount)
1589 return;
1590 for (const auto *LS : LineSegments)
1591 if (isStartOfRegion(LS))
1592 ExecutionCount = std::max(ExecutionCount, LS->Count);
1593}
1594
1596 if (Next == CD.end()) {
1597 Stats = LineCoverageStats();
1598 Ended = true;
1599 return *this;
1600 }
1601 if (Segments.size())
1602 WrappedSegment = Segments.back();
1603 Segments.clear();
1604 while (Next != CD.end() && Next->Line == Line)
1605 Segments.push_back(&*Next++);
1606 Stats = LineCoverageStats(Segments, WrappedSegment, Line);
1607 ++Line;
1608 return *this;
1609}
1610
1612 const std::string &ErrMsg = "") {
1613 std::string Msg;
1614 raw_string_ostream OS(Msg);
1615
1616 switch (Err) {
1618 OS << "success";
1619 break;
1621 OS << "end of File";
1622 break;
1624 OS << "no coverage data found";
1625 break;
1627 OS << "unsupported coverage format version";
1628 break;
1630 OS << "truncated coverage data";
1631 break;
1633 OS << "malformed coverage data";
1634 break;
1636 OS << "failed to decompress coverage data (zlib)";
1637 break;
1639 OS << "`-arch` specifier is invalid or missing for universal binary";
1640 break;
1641 }
1642
1643 // If optional error message is not empty, append it to the message.
1644 if (!ErrMsg.empty())
1645 OS << ": " << ErrMsg;
1646
1647 return Msg;
1648}
1649
1650namespace {
1651
1652// FIXME: This class is only here to support the transition to llvm::Error. It
1653// will be removed once this transition is complete. Clients should prefer to
1654// deal with the Error value directly, rather than converting to error_code.
1655class CoverageMappingErrorCategoryType : public std::error_category {
1656 const char *name() const noexcept override { return "llvm.coveragemap"; }
1657 std::string message(int IE) const override {
1658 return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
1659 }
1660};
1661
1662} // end anonymous namespace
1663
1664std::string CoverageMapError::message() const {
1665 return getCoverageMapErrString(Err, Msg);
1666}
1667
1668const std::error_category &llvm::coverage::coveragemap_category() {
1669 static CoverageMappingErrorCategoryType ErrorCategory;
1670 return ErrorCategory;
1671}
1672
1673char CoverageMapError::ID = 0;
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
aarch64 promote const
This file declares a library for handling Build IDs and using them to find debug info.
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static SmallBitVector gatherFileIDs(StringRef SourceFile, const FunctionRecord &Function)
static std::optional< unsigned > findMainViewFileID(const FunctionRecord &Function)
Return the ID of the file where the definition of the function is located.
static bool isExpansion(const CountedRegion &R, unsigned FileID)
static Error handleMaybeNoDataFoundError(Error E)
static unsigned getMaxBitmapSize(const CoverageMappingRecord &Record, bool IsVersion11)
Returns the bit count.
static std::string getCoverageMapErrString(coveragemap_error Err, const std::string &ErrMsg="")
static unsigned getMaxCounterID(const CounterMappingContext &Ctx, const CoverageMappingRecord &Record)
DXIL Intrinsic Expansion
This file defines the DenseMap class.
hexagon bit simplify
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
static constexpr StringLiteral Filename
if(PassOpts->AAPipeline)
static const char * name
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:114
Defines the virtual file system interface vfs::FileSystem.
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
front - Get the first element.
Definition ArrayRef.h:145
iterator end() const
Definition ArrayRef.h:131
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
iterator begin() const
Definition ArrayRef.h:130
bool empty() const
empty - Check if the array is empty.
Definition ArrayRef.h:137
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
iterator begin()
Definition Function.h:857
size_t size() const
Definition Function.h:862
iterator end()
Definition Function.h:859
static Expected< std::unique_ptr< IndexedInstrProfReader > > create(const Twine &Path, vfs::FileSystem &FS, const Twine &RemappingPath="")
Factory method to create an indexed reader.
static std::pair< instrprof_error, std::string > take(Error E)
Consume an Error and return the raw enum value contained within it, and the optional error message.
Definition InstrProf.h:470
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
iterator end() const
Definition ArrayRef.h:343
iterator begin() const
Definition ArrayRef.h:342
MutableArrayRef< T > drop_back(size_t N=1) const
Definition ArrayRef.h:392
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
iterator erase(const_iterator CI)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
constexpr bool empty() const
empty - Check if the string is empty.
Definition StringRef.h:143
LLVM Value Representation.
Definition Value.h:75
static Expected< std::vector< std::unique_ptr< BinaryCoverageReader > > > create(MemoryBufferRef ObjectBuffer, StringRef Arch, SmallVectorImpl< std::unique_ptr< MemoryBuffer > > &ObjectFileBuffers, StringRef CompilationDir="", SmallVectorImpl< object::BuildIDRef > *BinaryIDs=nullptr)
LLVM_ABI Counter subtract(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that subtracts RHS from LHS.
LLVM_ABI Counter add(Counter LHS, Counter RHS, bool Simplify=true)
Return a counter that represents the expression that adds LHS and RHS.
LLVM_ABI Counter subst(Counter C, const SubstMap &Map)
std::map< Counter, Counter > SubstMap
K to V map.
A Counter mapping context is used to connect the counters, expressions and the obtained counter value...
LLVM_ABI Expected< MCDCRecord > evaluateMCDCRegion(const CounterMappingRegion &Region, ArrayRef< const CounterMappingRegion * > Branches, bool IsVersion11)
Return an MCDC record that indicates executed test vectors and condition pairs.
void setCounts(ArrayRef< uint64_t > Counts)
LLVM_ABI Expected< int64_t > evaluate(const Counter &C) const
Return the number of times that a region of code associated with this counter was executed.
void setBitmap(BitVector &&Bitmap_)
LLVM_ABI unsigned getMaxCounterID(const Counter &C) const
LLVM_ABI void dump(const Counter &C, raw_ostream &OS) const
Coverage information to be processed or displayed.
std::vector< CountedRegion > BranchRegions
std::vector< CoverageSegment > Segments
std::vector< ExpansionRecord > Expansions
std::string message() const override
Return the error message as a string.
coveragemap_error get() const
const std::string & getMessage() const
static LLVM_ABI Expected< std::unique_ptr< CoverageMapping > > load(ArrayRef< std::unique_ptr< CoverageMappingReader > > CoverageReaders, std::optional< std::reference_wrapper< IndexedInstrProfReader > > &ProfileReader)
Load the coverage mapping using the given readers.
LLVM_ABI std::vector< StringRef > getUniqueSourceFiles() const
Returns a lexicographically sorted, unique list of files that are covered.
LLVM_ABI CoverageData getCoverageForExpansion(const ExpansionRecord &Expansion) const
Get the coverage for an expansion within a coverage set.
iterator_range< FunctionRecordIterator > getCoveredFunctions() const
Gets all of the functions covered by this profile.
LLVM_ABI CoverageData getCoverageForFunction(const FunctionRecord &Function) const
Get the coverage for a particular function.
LLVM_ABI std::vector< InstantiationGroup > getInstantiationGroups(StringRef Filename) const
Get the list of function instantiation groups in a particular file.
LLVM_ABI CoverageData getCoverageForFile(StringRef Filename) const
Get the coverage for a particular file.
Iterator over Functions, optionally filtered to a single file.
An instantiation group contains a FunctionRecord list, such that each record corresponds to a distinc...
LineCoverageIterator(const CoverageData &CD)
LLVM_ABI LineCoverageIterator & operator++()
Coverage statistics for a single line.
auto getIndex() const
Equivalent to buildTestVector's Index.
void set(int I, CondState Val)
Set the condition Val at position I.
Compute TestVector Indices "TVIdx" from the Conds graph.
static constexpr auto HardMaxTVs
Hard limit of test vectors.
LLVM_ABI TVIdxBuilder(const SmallVectorImpl< ConditionIDs > &NextIDs, int Offset=0)
Calculate and assign Indices.
SmallVector< std::array< int, 2 > > Indices
Output: Index for TestVectors bitmap (These are not CondIDs)
int NumTestVectors
Output: The number of test vectors.
SmallVector< MCDCNode > SavedNodes
This is no longer needed after the assignment.
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:202
size_type size() const
Definition DenseSet.h:87
BuildIDFetcher searches local cache directories for debug info.
Definition BuildID.h:40
virtual std::optional< std::string > fetch(BuildIDRef BuildID) const
Returns the path to the debug file with the given build ID.
Definition BuildID.cpp:82
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
A raw_ostream that writes to an std::string.
The virtual file system interface.
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ Skipped
Validation was skipped, as it was not needed.
int16_t ConditionID
The ID for MCDCBranch.
Definition MCDCTypes.h:25
std::array< ConditionID, 2 > ConditionIDs
Definition MCDCTypes.h:26
LLVM_ABI const std::error_category & coveragemap_category()
std::pair< unsigned, unsigned > LineColPair
SmallVector< uint8_t, 10 > BuildID
A build ID in binary form.
Definition BuildID.h:26
ArrayRef< uint8_t > BuildIDRef
A reference to a BuildID in binary form.
Definition BuildID.h:29
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
@ Offset
Definition DWP.cpp:532
bool operator<(int64_t V1, const APSInt &V2)
Definition APSInt.h:362
hash_code hash_value(const FixedPointSemantics &Val)
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1399
auto size(R &&Range, std::enable_if_t< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits< decltype(Range.begin())>::iterator_category >::value, void > *=nullptr)
Get the size of a range.
Definition STLExtras.h:1667
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2544
LLVM_ABI StringRef getFuncNameWithoutPrefix(StringRef PGOFuncName, StringRef FileName="<unknown>")
Given a PGO function name, remove the filename prefix and return the original (static) function name.
Error handleErrors(Error E, HandlerTs &&... Hs)
Pass the ErrorInfo(s) contained in E to their respective handlers.
Definition Error.h:967
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2198
auto unique(Range &&R, Predicate P)
Definition STLExtras.h:2124
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1305
auto map_range(ContainerTy &&C, FuncTy F)
Definition STLExtras.h:364
@ no_such_file_or_directory
Definition Errc.h:65
@ argument_out_of_domain
Definition Errc.h:37
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1744
auto reverse(ContainerTy &&C)
Definition STLExtras.h:406
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1634
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
instrprof_error
Definition InstrProf.h:398
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
ArrayRef(const T &OneElt) -> ArrayRef< T >
void toHex(ArrayRef< uint8_t > Input, bool LowerCase, SmallVectorImpl< char > &Output)
Convert buffer Input to its hexadecimal representation. The returned string is double the size of Inp...
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1770
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
void consumeError(Error Err)
Consume a Error without doing anything.
Definition Error.h:1083
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition Hashing.h:466
#define N
Associates a source range with an execution count.
A Counter expression is a value that represents an arithmetic operation with two counters.
A Counter mapping region associates a source range with a specific counter.
@ ExpansionRegion
An ExpansionRegion represents a file expansion region that associates a source range with the expansi...
@ MCDCDecisionRegion
A DecisionRegion represents a top-level boolean expression and is associated with a variable length b...
@ MCDCBranchRegion
A Branch Region can be extended to include IDs to facilitate MC/DC.
@ SkippedRegion
A SkippedRegion represents a source range with code that was skipped by a preprocessor or similar mea...
@ GapRegion
A GapRegion is like a CodeRegion, but its count is only set as the line execution count when its the ...
@ CodeRegion
A CodeRegion associates some code with a counter.
A Counter is an abstract value that describes how to compute the execution count for a region of code...
static Counter getZero()
Return the counter that represents the number zero.
static Counter getCounter(unsigned CounterId)
Return the counter that corresponds to a specific profile counter.
static Counter getExpression(unsigned ExpressionId)
Return the counter that corresponds to a specific addition counter expression.
Coverage mapping information for a single function.
The execution count information starting at a point in a file.
Coverage information for a macro expansion or included file.
Code coverage information for a single function.
llvm::SmallVector< std::pair< TestVector, CondState > > TestVectors
LLVM_ABI void findIndependencePairs()
llvm::DenseMap< unsigned, unsigned > CondIDMap
llvm::DenseMap< unsigned, LineColPair > LineColPairMap
CondState
CondState represents the evaluation of a condition in an executed test vector, which can be True or F...
std::array< BitVector, 2 > BoolVector
llvm::DenseMap< unsigned, TVRowPair > TVPairMap
unsigned BitmapIdx
Byte Index of Bitmap Coverage Object for a Decision Region.
Definition MCDCTypes.h:30
uint16_t NumConditions
Number of Conditions used for a Decision Region.
Definition MCDCTypes.h:33