1//===-- Coverage.cpp - Debug info coverage metrics ------------------------===//
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#include "llvm-dwarfdump.h"
10#include "llvm/ADT/SetOperations.h"
11#include "llvm/BinaryFormat/Dwarf.h"
12#include "llvm/DebugInfo/DIContext.h"
13#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
14#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
15#include "llvm/DebugInfo/DWARF/DWARFContext.h"
16#include "llvm/IR/CFG.h"
17#include "llvm/IR/DebugInfo.h"
18#include "llvm/IR/DebugInfoMetadata.h"
19#include "llvm/IR/DebugProgramInstruction.h"
20#include "llvm/IR/Instructions.h"
21#include "llvm/IR/Module.h"
22#include "llvm/IRReader/IRReader.h"
23#include "llvm/Object/ObjectFile.h"
24#include "llvm/Support/SourceMgr.h"
25
26using namespace llvm;
27using namespace llvm::dwarf;
28using namespace llvm::object;
29
30/// Pair of file index and line number representing a source location.
31typedef std::pair<uint16_t, size_t> SourceLocation;
32/// Pair of subroutine name and variable name representing a local variable.
33typedef std::pair<std::string, std::string> BitcodeVarKey;
34/// Pair of file name and line number representing a source location.
35typedef std::pair<StringRef, uint32_t> BitcodeSourceLocation;
36/// Maps local variables found in the bitcode to a set of source locations.
37typedef std::map<BitcodeVarKey, std::optional<DenseSet<BitcodeSourceLocation>>>
38 BitcodeLineMap;
39
40/// Adds source locations to the line set that correspond to an address range.
41static void addLines(const DWARFDebugLine::LineTable *LineTable,
42 DenseSet<SourceLocation> &Lines, DWARFAddressRange Range) {
43 std::vector<uint32_t> Rows;
44 if (LineTable->lookupAddressRange(Address: {.Address: Range.LowPC, .SectionIndex: Range.SectionIndex},
45 Size: Range.HighPC - Range.LowPC, Result&: Rows)) {
46 for (const auto &RowI : Rows) {
47 const auto Row = LineTable->Rows[RowI];
48 // Lookup can return addresses below the LowPC - filter these out.
49 if (Row.Address.Address < Range.LowPC)
50 continue;
51
52 if (Row.Line) // Ignore zero lines.
53 Lines.insert(V: {Row.File, Row.Line});
54 }
55 }
56}
57
58/// Converts the file index of each line in the set to use our own internal
59/// file index. This is required for a reliable comparison as the DWARF index
60/// may differ across compilations.
61static DenseSet<SourceLocation>
62convertFileIndices(DenseSet<SourceLocation> Lines,
63 const DWARFDebugLine::LineTable *const LineTable,
64 DenseMap<uint16_t, uint16_t> &FileIndexMap,
65 StringMap<std::optional<uint16_t>> &FileNameMap) {
66 DenseSet<SourceLocation> ResultLines;
67 for (const auto &L : Lines) {
68 uint16_t Index;
69 const auto IndexIt = FileIndexMap.find(Val: L.first);
70 if (IndexIt != FileIndexMap.end()) {
71 Index = IndexIt->second;
72 } else {
73 std::string Name;
74 [[maybe_unused]] bool ValidIndex = LineTable->getFileNameByIndex(
75 FileIndex: L.first, CompDir: "", Kind: DILineInfoSpecifier::FileLineInfoKind::RelativeFilePath,
76 Result&: Name);
77 assert(ValidIndex && "File index was not valid for its own line table");
78
79 auto NameIt = FileNameMap.find(Key: Name);
80 if (NameIt != FileNameMap.end() && NameIt->second) {
81 Index = *NameIt->second;
82 } else {
83 Index = FileNameMap.size();
84 FileNameMap.insert(KV: {Name, Index});
85 }
86
87 FileIndexMap.insert(KV: {L.first, Index});
88 }
89
90 ResultLines.insert(V: {Index, L.second});
91 }
92
93 return ResultLines;
94}
95
96/// Returns the set of source lines covered by a variable's debug information,
97/// computed by intersecting the variable's location ranges and the containing
98/// scope's address ranges.
99static DenseSet<SourceLocation>
100computeVariableCoverage(DWARFDie VariableDIE,
101 const DWARFDebugLine::LineTable *const LineTable,
102 DenseMap<uint16_t, uint16_t> &FileIndexMap,
103 StringMap<std::optional<uint16_t>> &FileNameMap,
104 BitcodeLineMap::value_type *DefinedLines) {
105 // The optionals below will be empty if no address ranges were found, and
106 // present (but containing an empty set) if ranges were found but contained no
107 // source locations, in order to distinguish the two cases.
108
109 auto Locations = VariableDIE.getLocations(Attr: DW_AT_location);
110 std::optional<DenseSet<SourceLocation>> Lines;
111 if (Locations) {
112 for (const auto &L : Locations.get()) {
113 if (L.Range) {
114 if (!Lines)
115 Lines = DenseSet<SourceLocation>();
116 addLines(LineTable, Lines&: *Lines, Range: L.Range.value());
117 }
118 }
119 } else {
120 // If the variable is optimized out and has no DW_AT_location, return an
121 // empty set instead of falling back to the parent scope's address ranges.
122 consumeError(Err: Locations.takeError());
123 return {};
124 }
125
126 // DW_AT_location attribute may contain overly broad address ranges, or none
127 // at all, so we also consider the parent scope's address ranges if present.
128 auto ParentRanges = VariableDIE.getParent().getAddressRanges();
129 std::optional<DenseSet<SourceLocation>> ParentLines;
130 if (ParentRanges) {
131 ParentLines = DenseSet<SourceLocation>();
132 for (const auto &R : ParentRanges.get())
133 addLines(LineTable, Lines&: *ParentLines, Range: R);
134 } else {
135 consumeError(Err: ParentRanges.takeError());
136 }
137
138 if (!Lines && ParentLines)
139 Lines = std::move(ParentLines);
140 else if (ParentLines)
141 set_intersect(S1&: *Lines, S2: *ParentLines);
142
143 auto ResultLines =
144 convertFileIndices(Lines: Lines.value_or(u: DenseSet<SourceLocation>()), LineTable,
145 FileIndexMap, FileNameMap);
146
147 if (DefinedLines) {
148 // Remove any lines where the variable does not have a defined value.
149 auto &DL = DefinedLines->second;
150 if (DL) {
151 DenseSet<SourceLocation> IndexLines;
152 for (const auto &L : *DL) {
153 auto NameIt = FileNameMap.find(Key: L.first);
154 if (NameIt != FileNameMap.end()) {
155 if (NameIt->second)
156 IndexLines.insert(V: {*NameIt->second, L.second});
157 } else {
158 // LineTable::getFileNameByIndex can return absolute paths even when
159 // relative paths are requested, so search for keys that end with this
160 // path as well.
161 SmallVector<std::pair<StringRef, std::optional<uint16_t>>> NewEntries;
162 for (const auto &NameEntry : FileNameMap) {
163 auto Name = NameEntry.first();
164 if (Name.find(Str: L.first, From: Name.size() - L.first.size()) !=
165 std::string_view::npos) {
166 NewEntries.push_back(Elt: {L.first, NameEntry.second});
167 IndexLines.insert(V: {*NameEntry.second, L.second});
168 }
169 }
170 for (const auto &E : NewEntries)
171 FileNameMap.insert(KV: E);
172 if (FileNameMap.find(Key: L.first) == FileNameMap.end()) {
173 assert(0 && "Files found in bitcode but not in DWARF");
174 FileNameMap.insert(KV: {L.first, std::nullopt});
175 }
176 }
177 }
178 if (!Lines)
179 assert(0 && "Source lines found in bitcode but not in DWARF");
180 else
181 set_intersect(S1&: ResultLines, S2: IndexLines);
182 }
183 }
184
185 return ResultLines;
186}
187
188/// Adds source locations to the line set that are within an inlined subroutine.
189static void getInlinedLines(DWARFDie SubroutineDIE,
190 DenseSet<SourceLocation> &Lines,
191 const DWARFDebugLine::LineTable *const LineTable) {
192 for (const auto &ChildDIE : SubroutineDIE.children()) {
193 if (ChildDIE.getTag() == DW_TAG_inlined_subroutine) {
194 auto Ranges = ChildDIE.getAddressRanges();
195 if (Ranges) {
196 for (const auto &R : Ranges.get())
197 addLines(LineTable, Lines, Range: R);
198 } else {
199 consumeError(Err: Ranges.takeError());
200 }
201 } else {
202 getInlinedLines(SubroutineDIE: ChildDIE, Lines, LineTable);
203 }
204 }
205}
206
207/// Returns the set of source lines present in the line table for a subroutine.
208static DenseSet<SourceLocation>
209computeSubroutineCoverage(DWARFDie SubroutineDIE,
210 const DWARFDebugLine::LineTable *const LineTable,
211 DenseMap<uint16_t, uint16_t> &FileIndexMap,
212 StringMap<std::optional<uint16_t>> &FileNameMap) {
213 auto Ranges = SubroutineDIE.getAddressRanges();
214 DenseSet<SourceLocation> Lines;
215 if (Ranges) {
216 for (const auto &R : Ranges.get())
217 addLines(LineTable, Lines, Range: R);
218 } else {
219 consumeError(Err: Ranges.takeError());
220 }
221
222 // Exclude lines from any subroutines inlined into this one.
223 DenseSet<SourceLocation> InlinedLines;
224 getInlinedLines(SubroutineDIE, Lines&: InlinedLines, LineTable);
225 set_subtract(S1&: Lines, S2: InlinedLines);
226
227 return convertFileIndices(Lines, LineTable, FileIndexMap, FileNameMap);
228}
229
230static const SmallVector<DWARFDie> getParentSubroutines(DWARFDie DIE) {
231 SmallVector<DWARFDie> Parents;
232 DWARFDie Parent = DIE;
233 do {
234 if (Parent.getTag() == DW_TAG_subprogram) {
235 Parents.push_back(Elt: Parent);
236 break;
237 }
238 if (Parent.getTag() == DW_TAG_inlined_subroutine)
239 Parents.push_back(Elt: Parent);
240 } while ((Parent = Parent.getParent()));
241 return Parents;
242}
243
244static bool isInScope(MDNode *Scope, const DebugLoc &Loc) {
245 MDNode *Parent = Loc.getScope();
246 while (Parent != Scope) {
247 auto *S = dyn_cast_if_present<DIScope>(Val: Parent);
248 if (!S)
249 return false;
250 Parent = S->getScope();
251 }
252 return true;
253}
254
255/// Determines whether an instruction stores to a location. For the purposes of
256/// this analysis, we consider any call-like instruction with the location as an
257/// argument to be a store to it.
258static bool isStoreToLocation(const DataLayout &DL, Instruction &I,
259 Value *Loc) {
260 std::optional<at::AssignmentInfo> Info;
261 if (StoreInst *SI = dyn_cast<StoreInst>(Val: &I)) {
262 if (SI->getPointerOperand() == Loc)
263 return true;
264 Info = at::getAssignmentInfo(DL, SI);
265 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(Val: &I)) {
266 if (MI->getDest() == Loc)
267 return true;
268 Info = at::getAssignmentInfo(DL, I: MI);
269 } else if (CallBase *CI = dyn_cast<CallBase>(Val: &I)) {
270 return CI->hasArgument(V: Loc);
271 }
272 return Info && Info->Base == Loc;
273}
274
275typedef SmallDenseMap<BasicBlock *, Instruction *, 8> VarDefinitionMap;
276
277struct VarState {
278 DbgVariableRecord &DVR;
279 VarDefinitionMap Definitions;
280};
281
282/// Adds source locations to the line set for instructions in a basic block,
283/// starting with a specific instruction.
284static void addModuleLines(Instruction *I, VarState &Var,
285 DenseSet<std::pair<StringRef, uint32_t>> &Lines) {
286 auto *VarScope = Var.DVR.getVariable()->getScope();
287 do {
288 auto &Loc = I->getDebugLoc();
289 DIScope *Scope;
290 if (Loc && isInScope(Scope: VarScope, Loc) && Loc.getLine() &&
291 (Scope = dyn_cast_if_present<DIScope>(Val: Loc.getScope()))) {
292 Lines.insert(V: {Scope->getFilename(), Loc.getLine()});
293 }
294 } while ((I = I->getNextNode()));
295}
296
297/// Computes the defined lines of all variables in an IR module.
298static BitcodeLineMap processModule(Module *Mod, bool MaybeUndefined) {
299 BitcodeLineMap Result;
300 std::vector<VarState> Vars;
301 for (auto &F : Mod->functions()) {
302 Vars.clear();
303 for (auto &BB : F) {
304 for (auto &I : BB) {
305 for (DbgVariableRecord &DVR : filterDbgVars(R: I.getDbgRecordRange())) {
306 if (DVR.isKillLocation())
307 continue;
308 if (DVR.isDbgDeclare()) {
309 // For #dbg_declare, don't treat the variable as live until we find
310 // a store to it.
311 Vars.push_back(x: VarState{.DVR: DVR, .Definitions: VarDefinitionMap()});
312 } else if (DVR.isDbgValue()) {
313 // For #dbg_value, the variable is live immediately from this point.
314 if (DVR.getDebugLoc().getInlinedAt() != nullptr) {
315 assert(0 && "Variable in bitcode has been inlined");
316 continue;
317 }
318 auto Var = find_if(Range&: Vars, P: [&](auto &Var) {
319 return Var.DVR.getVariable() == DVR.getVariable();
320 });
321 if (Var != Vars.end())
322 // If a basic block contains multiple stores to a variable, use
323 // the earliest one by allowing the insertion to silently fail if
324 // the basic block is already in the map.
325 Var->Definitions.insert(KV: {&BB, &I});
326 else
327 Vars.push_back(x: VarState{.DVR: DVR, .Definitions: {{&BB, &I}}});
328 }
329 }
330 }
331 }
332
333 for (auto &BB : F) {
334 for (auto &I : BB) {
335 for (auto &Var : Vars) {
336 if (isStoreToLocation(DL: Mod->getDataLayout(), I, Loc: Var.DVR.getValue())) {
337 // The variable is live from the instruction after the store. As
338 // above, the earliest store in this basic block will be used.
339 Var.Definitions.insert(KV: {&BB, I.getNextNode()});
340 }
341 }
342 }
343 }
344
345 for (auto &Var : Vars) {
346 SmallPtrSet<BasicBlock *, 8> Visited;
347 DenseSet<std::pair<StringRef, uint32_t>> Lines;
348
349 if (MaybeUndefined) {
350 // Visit all basic blocks that are reachable from a definition.
351 auto B = Var.Definitions.keys();
352 SmallVector<BasicBlock *> BlocksToVisit{B.begin(), B.end()};
353
354 while (!BlocksToVisit.empty()) {
355 BasicBlock *BB = BlocksToVisit.pop_back_val();
356 if (!Visited.insert(Ptr: BB).second)
357 continue;
358
359 auto S = successors(BB);
360 BlocksToVisit.append(in_start: S.begin(), in_end: S.end());
361 // Treat all successor blocks as live throughout.
362 for (auto *BB : S)
363 Var.Definitions.insert_or_assign(Key: BB, Val: &BB->front());
364 }
365
366 // Add lines to the set for all blocks in the definition map.
367 for (auto I : Var.Definitions)
368 if (I.second != nullptr)
369 addModuleLines(I: I.second, Var, Lines);
370 } else {
371 // Visit all basic blocks that are reachable from the entry block
372 // without going through a block that stores to the variable.
373 SmallVector<BasicBlock *> BlocksToVisit{&F.getEntryBlock()};
374
375 while (!BlocksToVisit.empty()) {
376 BasicBlock *BB = BlocksToVisit.pop_back_val();
377 if (!Visited.insert(Ptr: BB).second)
378 continue;
379
380 auto I = Var.Definitions.find(Val: BB);
381 if (I != Var.Definitions.end()) {
382 // Block contains a definition: add all lines after it to the set
383 if (I->second != nullptr)
384 addModuleLines(I: I->second, Var, Lines);
385 } else {
386 // Block does not contain a definition: visit its successors
387 auto S = successors(BB);
388 BlocksToVisit.append(in_start: S.begin(), in_end: S.end());
389 }
390 }
391
392 // All unvisited basic blocks must only be reachable by going through a
393 // block that stores to the variable, so add lines to the set for all of
394 // their instructions.
395 for (auto &BB : F)
396 if (!Visited.count(Ptr: &BB))
397 addModuleLines(I: &BB.front(), Var, Lines);
398 }
399
400 BitcodeVarKey Key(F.getName(), Var.DVR.getVariable()->getName());
401 Result.emplace(args&: Key, args&: Lines);
402 }
403 }
404 return Result;
405}
406
407struct VarKey {
408 const char *const SubprogramName;
409 const char *const Name;
410 std::string DeclFile;
411 uint64_t DeclLine;
412
413 bool operator==(const VarKey &Other) const {
414 return DeclLine == Other.DeclLine &&
415 !strcmp(s1: SubprogramName, s2: Other.SubprogramName) &&
416 !strcmp(s1: Name, s2: Other.Name) && !DeclFile.compare(str: Other.DeclFile);
417 }
418
419 bool operator<(const VarKey &Other) const {
420 int A = strcmp(s1: SubprogramName, s2: Other.SubprogramName);
421 if (A)
422 return A < 0;
423 int B = strcmp(s1: Name, s2: Other.Name);
424 if (B)
425 return B < 0;
426 int C = DeclFile.compare(str: Other.DeclFile);
427 if (C)
428 return C < 0;
429 return DeclLine < Other.DeclLine;
430 }
431};
432
433struct VarCoverage {
434 SmallVector<DWARFDie> Parents;
435 size_t Cov;
436 size_t BaselineCov;
437 size_t LTCov;
438 size_t Missing;
439 size_t Instances;
440 bool MissingBaseline;
441};
442
443typedef std::multimap<VarKey, VarCoverage, std::less<>> VarMap;
444typedef std::map<VarKey, DenseSet<SourceLocation>, std::less<>> BaselineVarMap;
445
446static std::optional<const VarKey> getVarKey(DWARFDie VariableDIE,
447 DWARFDie SubroutineDIE) {
448 const auto *const VariableName = VariableDIE.getName(Kind: DINameKind::LinkageName);
449 const auto DeclFile = VariableDIE.getDeclFile(
450 Kind: DILineInfoSpecifier::FileLineInfoKind::RelativeFilePath);
451 const auto *const SubroutineName =
452 SubroutineDIE.getName(Kind: DINameKind::LinkageName);
453 if (!VariableName || !SubroutineName)
454 return std::nullopt;
455 return VarKey{.SubprogramName: SubroutineName, .Name: VariableName, .DeclFile: DeclFile,
456 .DeclLine: VariableDIE.getDeclLine()};
457}
458
459static void displayParents(SmallVector<DWARFDie> Parents, raw_ostream &OS) {
460 bool First = true;
461 for (const auto Parent : Parents) {
462 if (auto FormValue = Parent.find(Attr: DW_AT_call_file)) {
463 if (auto OptString = FormValue->getAsFile(
464 Kind: DILineInfoSpecifier::FileLineInfoKind::RelativeFilePath)) {
465 if (First)
466 First = false;
467 else
468 OS << ", ";
469 OS << *OptString << ":" << toUnsigned(V: Parent.find(Attr: DW_AT_call_line), Default: 0);
470 }
471 }
472 }
473}
474
475static void displayVariableCoverage(const VarKey &Key, const VarCoverage &Var,
476 bool CombineInstances, raw_ostream &OS) {
477 WithColor(OS, HighlightColor::String) << Key.SubprogramName;
478 OS << "\t";
479 if (CombineInstances)
480 OS << Var.Instances;
481 else if (Var.Parents.size())
482 // FIXME: This may overflow the terminal if the inlining chain is large.
483 displayParents(Parents: Var.Parents, OS);
484 OS << "\t";
485 WithColor(OS, HighlightColor::String) << Key.Name;
486 OS << "\t";
487 if (!Key.DeclFile.empty())
488 OS << Key.DeclFile << ":" << Key.DeclLine;
489 OS << "\t" << format(Fmt: "%.3g", Vals: ((float)Var.Cov / Var.Instances));
490 if (Var.BaselineCov)
491 OS << "\t" << format(Fmt: "%.3g", Vals: ((float)Var.BaselineCov / Var.Instances))
492 << "\t" << format(Fmt: "%.3g", Vals: ((float)Var.Cov / Var.BaselineCov)) << "\t"
493 << format(Fmt: "%.3g", Vals: ((float)Var.LTCov / Var.Instances)) << "\t"
494 << format(Fmt: "%.3g", Vals: ((float)Var.LTCov / Var.BaselineCov));
495 OS << "\n";
496 if (Var.MissingBaseline)
497 WithColor(errs(), HighlightColor::Warning).warning()
498 << "DIE not found in baseline\n";
499 if (Var.Missing)
500 WithColor(errs(), HighlightColor::Warning).warning()
501 << Var.Missing << " lines not found in baseline\n";
502}
503
504bool dwarfdump::showVariableCoverage(ObjectFile &Obj, DWARFContext &DICtx,
505 ObjectFile *BaselineObj,
506 DWARFContext *BaselineCtx,
507 StringRef BitcodeFile, bool MaybeUndefined,
508 bool CombineInstances, raw_ostream &OS) {
509 BitcodeLineMap LM;
510 LLVMContext Context;
511 if (!BitcodeFile.empty()) {
512 SMDiagnostic Err;
513 std::unique_ptr<Module> Mod = parseIRFile(Filename: BitcodeFile, Err, Context);
514 if (!Err.getMessage().empty())
515 Err.print(ProgName: "llvm-dwarfdump", S&: OS);
516 else
517 LM = processModule(Mod: Mod.get(), MaybeUndefined);
518 }
519
520 BaselineVarMap BaselineVars;
521 StringMap<std::optional<uint16_t>> FileNameMap;
522
523 if (BaselineCtx) {
524 for (const auto &U : BaselineCtx->info_section_units()) {
525 const auto *const LT = BaselineCtx->getLineTableForUnit(U: U.get());
526 DenseMap<uint16_t, uint16_t> FileIndexMap;
527 for (const auto &Entry : U->dies()) {
528 DWARFDie VariableDIE = {U.get(), &Entry};
529 if (VariableDIE.getTag() != DW_TAG_variable &&
530 VariableDIE.getTag() != DW_TAG_formal_parameter)
531 continue;
532
533 const auto Parents = getParentSubroutines(DIE: VariableDIE);
534 if (!Parents.size())
535 continue;
536 const auto SubroutineDIE = Parents.front();
537 auto Key = getVarKey(VariableDIE, SubroutineDIE);
538 if (!Key)
539 continue;
540
541 const auto DefinedLines = LM.find(x: {Key->SubprogramName, Key->Name});
542 auto Cov = computeVariableCoverage(
543 VariableDIE, LineTable: LT, FileIndexMap, FileNameMap,
544 DefinedLines: DefinedLines != LM.end() ? &*DefinedLines : nullptr);
545 const auto SubroutineCov = computeSubroutineCoverage(
546 SubroutineDIE, LineTable: LT, FileIndexMap, FileNameMap);
547 set_intersect(S1&: Cov, S2: SubroutineCov);
548
549 auto Result = BaselineVars.insert(x: {*Key, Cov});
550 if (!Result.second)
551 Result.first->second.insert_range(R&: Cov);
552 }
553 }
554 }
555
556 VarMap Vars;
557
558 for (const auto &U : DICtx.info_section_units()) {
559 const auto *const LT = DICtx.getLineTableForUnit(U: U.get());
560 DenseMap<uint16_t, uint16_t> FileIndexMap;
561 for (const auto &Entry : U->dies()) {
562 DWARFDie VariableDIE = {U.get(), &Entry};
563 if (VariableDIE.getTag() != DW_TAG_variable &&
564 VariableDIE.getTag() != DW_TAG_formal_parameter)
565 continue;
566
567 const auto Parents = getParentSubroutines(DIE: VariableDIE);
568 if (!Parents.size())
569 continue;
570 const auto SubroutineDIE = Parents.front();
571 auto Key = getVarKey(VariableDIE, SubroutineDIE);
572 if (!Key)
573 continue;
574
575 const auto DefinedLines = LM.find(x: {Key->SubprogramName, Key->Name});
576 auto Cov = computeVariableCoverage(
577 VariableDIE, LineTable: LT, FileIndexMap, FileNameMap,
578 DefinedLines: DefinedLines != LM.end() ? &*DefinedLines : nullptr);
579 const auto SubroutineCov = computeSubroutineCoverage(
580 SubroutineDIE, LineTable: LT, FileIndexMap, FileNameMap);
581 set_intersect(S1&: Cov, S2: SubroutineCov);
582
583 VarCoverage VarCov = {.Parents: Parents, .Cov: Cov.size(), .BaselineCov: 0, .LTCov: 0, .Missing: 0, .Instances: 1, .MissingBaseline: false};
584
585 if (BaselineCtx) {
586 BaselineVarMap::iterator Var = BaselineVars.find(x: *Key);
587
588 if (Var != BaselineVars.end()) {
589 const auto BCov = Var->second;
590 VarCov.BaselineCov = BCov.size();
591
592 for (const auto &L : Cov)
593 VarCov.Missing += (1 - BCov.count(V: L));
594
595 for (const auto &L : BCov)
596 VarCov.LTCov += SubroutineCov.count(V: L);
597 } else {
598 VarCov.MissingBaseline = true;
599 }
600 }
601
602 Vars.insert(x: {*Key, VarCov});
603 }
604 }
605
606 for (auto V : BaselineVars)
607 if (!Vars.count(x: V.first))
608 Vars.insert(x: {V.first, {.Parents: {}, .Cov: 0, .BaselineCov: V.second.size(), .LTCov: 0, .Missing: 0, .Instances: 1, .MissingBaseline: false}});
609
610 std::pair<VarMap::iterator, VarMap::iterator> Range;
611
612 OS << "\nVariable coverage statistics:\nFunction\t"
613 << (CombineInstances ? "InstanceCount" : "InlChain")
614 << "\tVariable\tDecl\tLinesCovered";
615 if (BaselineCtx)
616 OS << "\tBaseline\tCoveredRatio\tLinesPresent\tLinesPresentRatio";
617 OS << "\n";
618
619 if (CombineInstances) {
620 for (auto FirstVar = Vars.begin(); FirstVar != Vars.end();
621 FirstVar = Range.second) {
622 Range = Vars.equal_range(x: FirstVar->first);
623 VarCoverage CombinedCov = {.Parents: {}, .Cov: 0, .BaselineCov: 0, .LTCov: 0, .Missing: 0, .Instances: 0, .MissingBaseline: false};
624 for (auto Var = Range.first; Var != Range.second; ++Var) {
625 ++CombinedCov.Instances;
626 CombinedCov.Cov += Var->second.Cov;
627 CombinedCov.BaselineCov += Var->second.BaselineCov;
628 CombinedCov.LTCov += Var->second.LTCov;
629 CombinedCov.Missing += Var->second.Missing;
630 CombinedCov.MissingBaseline |= Var->second.MissingBaseline;
631 }
632 displayVariableCoverage(Key: FirstVar->first, Var: CombinedCov, CombineInstances: true, OS);
633 }
634 } else {
635 for (auto Var : Vars)
636 displayVariableCoverage(Key: Var.first, Var: Var.second, CombineInstances: false, OS);
637 }
638
639 return true;
640}
641