Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / lib / ProfileData / GCOV.cpp
blob41ea7555b9f096c4cc7d14bc1f4ebdb55790c560
1 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
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 // GCOV implements the interface to read and write coverage files that use
10 // 'gcov' format.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ProfileData/GCOV.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/llvm-config.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <algorithm>
23 #include <system_error>
25 using namespace llvm;
27 //===----------------------------------------------------------------------===//
28 // GCOVFile implementation.
30 /// readGCNO - Read GCNO buffer.
31 bool GCOVFile::readGCNO(GCOVBuffer &Buffer) {
32 if (!Buffer.readGCNOFormat())
33 return false;
34 if (!Buffer.readGCOVVersion(Version))
35 return false;
37 if (!Buffer.readInt(Checksum))
38 return false;
39 while (true) {
40 if (!Buffer.readFunctionTag())
41 break;
42 auto GFun = make_unique<GCOVFunction>(*this);
43 if (!GFun->readGCNO(Buffer, Version))
44 return false;
45 Functions.push_back(std::move(GFun));
48 GCNOInitialized = true;
49 return true;
52 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
53 /// called after readGCNO().
54 bool GCOVFile::readGCDA(GCOVBuffer &Buffer) {
55 assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
56 if (!Buffer.readGCDAFormat())
57 return false;
58 GCOV::GCOVVersion GCDAVersion;
59 if (!Buffer.readGCOVVersion(GCDAVersion))
60 return false;
61 if (Version != GCDAVersion) {
62 errs() << "GCOV versions do not match.\n";
63 return false;
66 uint32_t GCDAChecksum;
67 if (!Buffer.readInt(GCDAChecksum))
68 return false;
69 if (Checksum != GCDAChecksum) {
70 errs() << "File checksums do not match: " << Checksum
71 << " != " << GCDAChecksum << ".\n";
72 return false;
74 for (size_t i = 0, e = Functions.size(); i < e; ++i) {
75 if (!Buffer.readFunctionTag()) {
76 errs() << "Unexpected number of functions.\n";
77 return false;
79 if (!Functions[i]->readGCDA(Buffer, Version))
80 return false;
82 if (Buffer.readObjectTag()) {
83 uint32_t Length;
84 uint32_t Dummy;
85 if (!Buffer.readInt(Length))
86 return false;
87 if (!Buffer.readInt(Dummy))
88 return false; // checksum
89 if (!Buffer.readInt(Dummy))
90 return false; // num
91 if (!Buffer.readInt(RunCount))
92 return false;
93 Buffer.advanceCursor(Length - 3);
95 while (Buffer.readProgramTag()) {
96 uint32_t Length;
97 if (!Buffer.readInt(Length))
98 return false;
99 Buffer.advanceCursor(Length);
100 ++ProgramCount;
103 return true;
106 void GCOVFile::print(raw_ostream &OS) const {
107 for (const auto &FPtr : Functions)
108 FPtr->print(OS);
111 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
112 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
113 LLVM_DUMP_METHOD void GCOVFile::dump() const { print(dbgs()); }
114 #endif
116 /// collectLineCounts - Collect line counts. This must be used after
117 /// reading .gcno and .gcda files.
118 void GCOVFile::collectLineCounts(FileInfo &FI) {
119 for (const auto &FPtr : Functions)
120 FPtr->collectLineCounts(FI);
121 FI.setRunCount(RunCount);
122 FI.setProgramCount(ProgramCount);
125 //===----------------------------------------------------------------------===//
126 // GCOVFunction implementation.
128 /// readGCNO - Read a function from the GCNO buffer. Return false if an error
129 /// occurs.
130 bool GCOVFunction::readGCNO(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
131 uint32_t Dummy;
132 if (!Buff.readInt(Dummy))
133 return false; // Function header length
134 if (!Buff.readInt(Ident))
135 return false;
136 if (!Buff.readInt(Checksum))
137 return false;
138 if (Version != GCOV::V402) {
139 uint32_t CfgChecksum;
140 if (!Buff.readInt(CfgChecksum))
141 return false;
142 if (Parent.getChecksum() != CfgChecksum) {
143 errs() << "File checksums do not match: " << Parent.getChecksum()
144 << " != " << CfgChecksum << " in (" << Name << ").\n";
145 return false;
148 if (!Buff.readString(Name))
149 return false;
150 if (!Buff.readString(Filename))
151 return false;
152 if (!Buff.readInt(LineNumber))
153 return false;
155 // read blocks.
156 if (!Buff.readBlockTag()) {
157 errs() << "Block tag not found.\n";
158 return false;
160 uint32_t BlockCount;
161 if (!Buff.readInt(BlockCount))
162 return false;
163 for (uint32_t i = 0, e = BlockCount; i != e; ++i) {
164 if (!Buff.readInt(Dummy))
165 return false; // Block flags;
166 Blocks.push_back(make_unique<GCOVBlock>(*this, i));
169 // read edges.
170 while (Buff.readEdgeTag()) {
171 uint32_t EdgeCount;
172 if (!Buff.readInt(EdgeCount))
173 return false;
174 EdgeCount = (EdgeCount - 1) / 2;
175 uint32_t BlockNo;
176 if (!Buff.readInt(BlockNo))
177 return false;
178 if (BlockNo >= BlockCount) {
179 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
180 << ").\n";
181 return false;
183 for (uint32_t i = 0, e = EdgeCount; i != e; ++i) {
184 uint32_t Dst;
185 if (!Buff.readInt(Dst))
186 return false;
187 Edges.push_back(make_unique<GCOVEdge>(*Blocks[BlockNo], *Blocks[Dst]));
188 GCOVEdge *Edge = Edges.back().get();
189 Blocks[BlockNo]->addDstEdge(Edge);
190 Blocks[Dst]->addSrcEdge(Edge);
191 if (!Buff.readInt(Dummy))
192 return false; // Edge flag
196 // read line table.
197 while (Buff.readLineTag()) {
198 uint32_t LineTableLength;
199 // Read the length of this line table.
200 if (!Buff.readInt(LineTableLength))
201 return false;
202 uint32_t EndPos = Buff.getCursor() + LineTableLength * 4;
203 uint32_t BlockNo;
204 // Read the block number this table is associated with.
205 if (!Buff.readInt(BlockNo))
206 return false;
207 if (BlockNo >= BlockCount) {
208 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
209 << ").\n";
210 return false;
212 GCOVBlock &Block = *Blocks[BlockNo];
213 // Read the word that pads the beginning of the line table. This may be a
214 // flag of some sort, but seems to always be zero.
215 if (!Buff.readInt(Dummy))
216 return false;
218 // Line information starts here and continues up until the last word.
219 if (Buff.getCursor() != (EndPos - sizeof(uint32_t))) {
220 StringRef F;
221 // Read the source file name.
222 if (!Buff.readString(F))
223 return false;
224 if (Filename != F) {
225 errs() << "Multiple sources for a single basic block: " << Filename
226 << " != " << F << " (in " << Name << ").\n";
227 return false;
229 // Read lines up to, but not including, the null terminator.
230 while (Buff.getCursor() < (EndPos - 2 * sizeof(uint32_t))) {
231 uint32_t Line;
232 if (!Buff.readInt(Line))
233 return false;
234 // Line 0 means this instruction was injected by the compiler. Skip it.
235 if (!Line)
236 continue;
237 Block.addLine(Line);
239 // Read the null terminator.
240 if (!Buff.readInt(Dummy))
241 return false;
243 // The last word is either a flag or padding, it isn't clear which. Skip
244 // over it.
245 if (!Buff.readInt(Dummy))
246 return false;
248 return true;
251 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
252 /// occurs.
253 bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
254 uint32_t HeaderLength;
255 if (!Buff.readInt(HeaderLength))
256 return false; // Function header length
258 uint64_t EndPos = Buff.getCursor() + HeaderLength * sizeof(uint32_t);
260 uint32_t GCDAIdent;
261 if (!Buff.readInt(GCDAIdent))
262 return false;
263 if (Ident != GCDAIdent) {
264 errs() << "Function identifiers do not match: " << Ident
265 << " != " << GCDAIdent << " (in " << Name << ").\n";
266 return false;
269 uint32_t GCDAChecksum;
270 if (!Buff.readInt(GCDAChecksum))
271 return false;
272 if (Checksum != GCDAChecksum) {
273 errs() << "Function checksums do not match: " << Checksum
274 << " != " << GCDAChecksum << " (in " << Name << ").\n";
275 return false;
278 uint32_t CfgChecksum;
279 if (Version != GCOV::V402) {
280 if (!Buff.readInt(CfgChecksum))
281 return false;
282 if (Parent.getChecksum() != CfgChecksum) {
283 errs() << "File checksums do not match: " << Parent.getChecksum()
284 << " != " << CfgChecksum << " (in " << Name << ").\n";
285 return false;
289 if (Buff.getCursor() < EndPos) {
290 StringRef GCDAName;
291 if (!Buff.readString(GCDAName))
292 return false;
293 if (Name != GCDAName) {
294 errs() << "Function names do not match: " << Name << " != " << GCDAName
295 << ".\n";
296 return false;
300 if (!Buff.readArcTag()) {
301 errs() << "Arc tag not found (in " << Name << ").\n";
302 return false;
305 uint32_t Count;
306 if (!Buff.readInt(Count))
307 return false;
308 Count /= 2;
310 // This for loop adds the counts for each block. A second nested loop is
311 // required to combine the edge counts that are contained in the GCDA file.
312 for (uint32_t BlockNo = 0; Count > 0; ++BlockNo) {
313 // The last block is always reserved for exit block
314 if (BlockNo >= Blocks.size()) {
315 errs() << "Unexpected number of edges (in " << Name << ").\n";
316 return false;
318 if (BlockNo == Blocks.size() - 1)
319 errs() << "(" << Name << ") has arcs from exit block.\n";
320 GCOVBlock &Block = *Blocks[BlockNo];
321 for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
322 ++EdgeNo) {
323 if (Count == 0) {
324 errs() << "Unexpected number of edges (in " << Name << ").\n";
325 return false;
327 uint64_t ArcCount;
328 if (!Buff.readInt64(ArcCount))
329 return false;
330 Block.addCount(EdgeNo, ArcCount);
331 --Count;
333 Block.sortDstEdges();
335 return true;
338 /// getEntryCount - Get the number of times the function was called by
339 /// retrieving the entry block's count.
340 uint64_t GCOVFunction::getEntryCount() const {
341 return Blocks.front()->getCount();
344 /// getExitCount - Get the number of times the function returned by retrieving
345 /// the exit block's count.
346 uint64_t GCOVFunction::getExitCount() const {
347 return Blocks.back()->getCount();
350 void GCOVFunction::print(raw_ostream &OS) const {
351 OS << "===== " << Name << " (" << Ident << ") @ " << Filename << ":"
352 << LineNumber << "\n";
353 for (const auto &Block : Blocks)
354 Block->print(OS);
357 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
358 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
359 LLVM_DUMP_METHOD void GCOVFunction::dump() const { print(dbgs()); }
360 #endif
362 /// collectLineCounts - Collect line counts. This must be used after
363 /// reading .gcno and .gcda files.
364 void GCOVFunction::collectLineCounts(FileInfo &FI) {
365 // If the line number is zero, this is a function that doesn't actually appear
366 // in the source file, so there isn't anything we can do with it.
367 if (LineNumber == 0)
368 return;
370 for (const auto &Block : Blocks)
371 Block->collectLineCounts(FI);
372 FI.addFunctionLine(Filename, LineNumber, this);
375 //===----------------------------------------------------------------------===//
376 // GCOVBlock implementation.
378 /// ~GCOVBlock - Delete GCOVBlock and its content.
379 GCOVBlock::~GCOVBlock() {
380 SrcEdges.clear();
381 DstEdges.clear();
382 Lines.clear();
385 /// addCount - Add to block counter while storing the edge count. If the
386 /// destination has no outgoing edges, also update that block's count too.
387 void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
388 assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
389 DstEdges[DstEdgeNo]->Count = N;
390 Counter += N;
391 if (!DstEdges[DstEdgeNo]->Dst.getNumDstEdges())
392 DstEdges[DstEdgeNo]->Dst.Counter += N;
395 /// sortDstEdges - Sort destination edges by block number, nop if already
396 /// sorted. This is required for printing branch info in the correct order.
397 void GCOVBlock::sortDstEdges() {
398 if (!DstEdgesAreSorted) {
399 SortDstEdgesFunctor SortEdges;
400 std::stable_sort(DstEdges.begin(), DstEdges.end(), SortEdges);
404 /// collectLineCounts - Collect line counts. This must be used after
405 /// reading .gcno and .gcda files.
406 void GCOVBlock::collectLineCounts(FileInfo &FI) {
407 for (uint32_t N : Lines)
408 FI.addBlockLine(Parent.getFilename(), N, this);
411 void GCOVBlock::print(raw_ostream &OS) const {
412 OS << "Block : " << Number << " Counter : " << Counter << "\n";
413 if (!SrcEdges.empty()) {
414 OS << "\tSource Edges : ";
415 for (const GCOVEdge *Edge : SrcEdges)
416 OS << Edge->Src.Number << " (" << Edge->Count << "), ";
417 OS << "\n";
419 if (!DstEdges.empty()) {
420 OS << "\tDestination Edges : ";
421 for (const GCOVEdge *Edge : DstEdges)
422 OS << Edge->Dst.Number << " (" << Edge->Count << "), ";
423 OS << "\n";
425 if (!Lines.empty()) {
426 OS << "\tLines : ";
427 for (uint32_t N : Lines)
428 OS << (N) << ",";
429 OS << "\n";
433 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
434 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
435 LLVM_DUMP_METHOD void GCOVBlock::dump() const { print(dbgs()); }
436 #endif
438 //===----------------------------------------------------------------------===//
439 // Cycles detection
441 // The algorithm in GCC is based on the algorihtm by Hawick & James:
442 // "Enumerating Circuits and Loops in Graphs with Self-Arcs and Multiple-Arcs"
443 // http://complexity.massey.ac.nz/cstn/013/cstn-013.pdf.
445 /// Get the count for the detected cycle.
446 uint64_t GCOVBlock::getCycleCount(const Edges &Path) {
447 uint64_t CycleCount = std::numeric_limits<uint64_t>::max();
448 for (auto E : Path) {
449 CycleCount = std::min(E->CyclesCount, CycleCount);
451 for (auto E : Path) {
452 E->CyclesCount -= CycleCount;
454 return CycleCount;
457 /// Unblock a vertex previously marked as blocked.
458 void GCOVBlock::unblock(const GCOVBlock *U, BlockVector &Blocked,
459 BlockVectorLists &BlockLists) {
460 auto it = find(Blocked, U);
461 if (it == Blocked.end()) {
462 return;
465 const size_t index = it - Blocked.begin();
466 Blocked.erase(it);
468 const BlockVector ToUnblock(BlockLists[index]);
469 BlockLists.erase(BlockLists.begin() + index);
470 for (auto GB : ToUnblock) {
471 GCOVBlock::unblock(GB, Blocked, BlockLists);
475 bool GCOVBlock::lookForCircuit(const GCOVBlock *V, const GCOVBlock *Start,
476 Edges &Path, BlockVector &Blocked,
477 BlockVectorLists &BlockLists,
478 const BlockVector &Blocks, uint64_t &Count) {
479 Blocked.push_back(V);
480 BlockLists.emplace_back(BlockVector());
481 bool FoundCircuit = false;
483 for (auto E : V->dsts()) {
484 const GCOVBlock *W = &E->Dst;
485 if (W < Start || find(Blocks, W) == Blocks.end()) {
486 continue;
489 Path.push_back(E);
491 if (W == Start) {
492 // We've a cycle.
493 Count += GCOVBlock::getCycleCount(Path);
494 FoundCircuit = true;
495 } else if (find(Blocked, W) == Blocked.end() && // W is not blocked.
496 GCOVBlock::lookForCircuit(W, Start, Path, Blocked, BlockLists,
497 Blocks, Count)) {
498 FoundCircuit = true;
501 Path.pop_back();
504 if (FoundCircuit) {
505 GCOVBlock::unblock(V, Blocked, BlockLists);
506 } else {
507 for (auto E : V->dsts()) {
508 const GCOVBlock *W = &E->Dst;
509 if (W < Start || find(Blocks, W) == Blocks.end()) {
510 continue;
512 const size_t index = find(Blocked, W) - Blocked.begin();
513 BlockVector &List = BlockLists[index];
514 if (find(List, V) == List.end()) {
515 List.push_back(V);
520 return FoundCircuit;
523 /// Get the count for the list of blocks which lie on the same line.
524 void GCOVBlock::getCyclesCount(const BlockVector &Blocks, uint64_t &Count) {
525 for (auto Block : Blocks) {
526 Edges Path;
527 BlockVector Blocked;
528 BlockVectorLists BlockLists;
530 GCOVBlock::lookForCircuit(Block, Block, Path, Blocked, BlockLists, Blocks,
531 Count);
535 /// Get the count for the list of blocks which lie on the same line.
536 uint64_t GCOVBlock::getLineCount(const BlockVector &Blocks) {
537 uint64_t Count = 0;
539 for (auto Block : Blocks) {
540 if (Block->getNumSrcEdges() == 0) {
541 // The block has no predecessors and a non-null counter
542 // (can be the case with entry block in functions).
543 Count += Block->getCount();
544 } else {
545 // Add counts from predecessors that are not on the same line.
546 for (auto E : Block->srcs()) {
547 const GCOVBlock *W = &E->Src;
548 if (find(Blocks, W) == Blocks.end()) {
549 Count += E->Count;
553 for (auto E : Block->dsts()) {
554 E->CyclesCount = E->Count;
558 GCOVBlock::getCyclesCount(Blocks, Count);
560 return Count;
563 //===----------------------------------------------------------------------===//
564 // FileInfo implementation.
566 // Safe integer division, returns 0 if numerator is 0.
567 static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
568 if (!Numerator)
569 return 0;
570 return Numerator / Divisor;
573 // This custom division function mimics gcov's branch ouputs:
574 // - Round to closest whole number
575 // - Only output 0% or 100% if it's exactly that value
576 static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
577 if (!Numerator)
578 return 0;
579 if (Numerator == Divisor)
580 return 100;
582 uint8_t Res = (Numerator * 100 + Divisor / 2) / Divisor;
583 if (Res == 0)
584 return 1;
585 if (Res == 100)
586 return 99;
587 return Res;
590 namespace {
591 struct formatBranchInfo {
592 formatBranchInfo(const GCOV::Options &Options, uint64_t Count, uint64_t Total)
593 : Options(Options), Count(Count), Total(Total) {}
595 void print(raw_ostream &OS) const {
596 if (!Total)
597 OS << "never executed";
598 else if (Options.BranchCount)
599 OS << "taken " << Count;
600 else
601 OS << "taken " << branchDiv(Count, Total) << "%";
604 const GCOV::Options &Options;
605 uint64_t Count;
606 uint64_t Total;
609 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
610 FBI.print(OS);
611 return OS;
614 class LineConsumer {
615 std::unique_ptr<MemoryBuffer> Buffer;
616 StringRef Remaining;
618 public:
619 LineConsumer(StringRef Filename) {
620 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
621 MemoryBuffer::getFileOrSTDIN(Filename);
622 if (std::error_code EC = BufferOrErr.getError()) {
623 errs() << Filename << ": " << EC.message() << "\n";
624 Remaining = "";
625 } else {
626 Buffer = std::move(BufferOrErr.get());
627 Remaining = Buffer->getBuffer();
630 bool empty() { return Remaining.empty(); }
631 void printNext(raw_ostream &OS, uint32_t LineNum) {
632 StringRef Line;
633 if (empty())
634 Line = "/*EOF*/";
635 else
636 std::tie(Line, Remaining) = Remaining.split("\n");
637 OS << format("%5u:", LineNum) << Line << "\n";
640 } // end anonymous namespace
642 /// Convert a path to a gcov filename. If PreservePaths is true, this
643 /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
644 static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
645 if (!PreservePaths)
646 return sys::path::filename(Filename).str();
648 // This behaviour is defined by gcov in terms of text replacements, so it's
649 // not likely to do anything useful on filesystems with different textual
650 // conventions.
651 llvm::SmallString<256> Result("");
652 StringRef::iterator I, S, E;
653 for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
654 if (*I != '/')
655 continue;
657 if (I - S == 1 && *S == '.') {
658 // ".", the current directory, is skipped.
659 } else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
660 // "..", the parent directory, is replaced with "^".
661 Result.append("^#");
662 } else {
663 if (S < I)
664 // Leave other components intact,
665 Result.append(S, I);
666 // And separate with "#".
667 Result.push_back('#');
669 S = I + 1;
672 if (S < I)
673 Result.append(S, I);
674 return Result.str();
677 std::string FileInfo::getCoveragePath(StringRef Filename,
678 StringRef MainFilename) {
679 if (Options.NoOutput)
680 // This is probably a bug in gcov, but when -n is specified, paths aren't
681 // mangled at all, and the -l and -p options are ignored. Here, we do the
682 // same.
683 return Filename;
685 std::string CoveragePath;
686 if (Options.LongFileNames && !Filename.equals(MainFilename))
687 CoveragePath =
688 mangleCoveragePath(MainFilename, Options.PreservePaths) + "##";
689 CoveragePath += mangleCoveragePath(Filename, Options.PreservePaths) + ".gcov";
690 return CoveragePath;
693 std::unique_ptr<raw_ostream>
694 FileInfo::openCoveragePath(StringRef CoveragePath) {
695 if (Options.NoOutput)
696 return llvm::make_unique<raw_null_ostream>();
698 std::error_code EC;
699 auto OS =
700 llvm::make_unique<raw_fd_ostream>(CoveragePath, EC, sys::fs::F_Text);
701 if (EC) {
702 errs() << EC.message() << "\n";
703 return llvm::make_unique<raw_null_ostream>();
705 return std::move(OS);
708 /// print - Print source files with collected line count information.
709 void FileInfo::print(raw_ostream &InfoOS, StringRef MainFilename,
710 StringRef GCNOFile, StringRef GCDAFile) {
711 SmallVector<StringRef, 4> Filenames;
712 for (const auto &LI : LineInfo)
713 Filenames.push_back(LI.first());
714 llvm::sort(Filenames);
716 for (StringRef Filename : Filenames) {
717 auto AllLines = LineConsumer(Filename);
719 std::string CoveragePath = getCoveragePath(Filename, MainFilename);
720 std::unique_ptr<raw_ostream> CovStream = openCoveragePath(CoveragePath);
721 raw_ostream &CovOS = *CovStream;
723 CovOS << " -: 0:Source:" << Filename << "\n";
724 CovOS << " -: 0:Graph:" << GCNOFile << "\n";
725 CovOS << " -: 0:Data:" << GCDAFile << "\n";
726 CovOS << " -: 0:Runs:" << RunCount << "\n";
727 CovOS << " -: 0:Programs:" << ProgramCount << "\n";
729 const LineData &Line = LineInfo[Filename];
730 GCOVCoverage FileCoverage(Filename);
731 for (uint32_t LineIndex = 0; LineIndex < Line.LastLine || !AllLines.empty();
732 ++LineIndex) {
733 if (Options.BranchInfo) {
734 FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
735 if (FuncsIt != Line.Functions.end())
736 printFunctionSummary(CovOS, FuncsIt->second);
739 BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
740 if (BlocksIt == Line.Blocks.end()) {
741 // No basic blocks are on this line. Not an executable line of code.
742 CovOS << " -:";
743 AllLines.printNext(CovOS, LineIndex + 1);
744 } else {
745 const BlockVector &Blocks = BlocksIt->second;
747 // Add up the block counts to form line counts.
748 DenseMap<const GCOVFunction *, bool> LineExecs;
749 for (const GCOVBlock *Block : Blocks) {
750 if (Options.FuncCoverage) {
751 // This is a slightly convoluted way to most accurately gather line
752 // statistics for functions. Basically what is happening is that we
753 // don't want to count a single line with multiple blocks more than
754 // once. However, we also don't simply want to give the total line
755 // count to every function that starts on the line. Thus, what is
756 // happening here are two things:
757 // 1) Ensure that the number of logical lines is only incremented
758 // once per function.
759 // 2) If there are multiple blocks on the same line, ensure that the
760 // number of lines executed is incremented as long as at least
761 // one of the blocks are executed.
762 const GCOVFunction *Function = &Block->getParent();
763 if (FuncCoverages.find(Function) == FuncCoverages.end()) {
764 std::pair<const GCOVFunction *, GCOVCoverage> KeyValue(
765 Function, GCOVCoverage(Function->getName()));
766 FuncCoverages.insert(KeyValue);
768 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
770 if (LineExecs.find(Function) == LineExecs.end()) {
771 if (Block->getCount()) {
772 ++FuncCoverage.LinesExec;
773 LineExecs[Function] = true;
774 } else {
775 LineExecs[Function] = false;
777 ++FuncCoverage.LogicalLines;
778 } else if (!LineExecs[Function] && Block->getCount()) {
779 ++FuncCoverage.LinesExec;
780 LineExecs[Function] = true;
785 const uint64_t LineCount = GCOVBlock::getLineCount(Blocks);
786 if (LineCount == 0)
787 CovOS << " #####:";
788 else {
789 CovOS << format("%9" PRIu64 ":", LineCount);
790 ++FileCoverage.LinesExec;
792 ++FileCoverage.LogicalLines;
794 AllLines.printNext(CovOS, LineIndex + 1);
796 uint32_t BlockNo = 0;
797 uint32_t EdgeNo = 0;
798 for (const GCOVBlock *Block : Blocks) {
799 // Only print block and branch information at the end of the block.
800 if (Block->getLastLine() != LineIndex + 1)
801 continue;
802 if (Options.AllBlocks)
803 printBlockInfo(CovOS, *Block, LineIndex, BlockNo);
804 if (Options.BranchInfo) {
805 size_t NumEdges = Block->getNumDstEdges();
806 if (NumEdges > 1)
807 printBranchInfo(CovOS, *Block, FileCoverage, EdgeNo);
808 else if (Options.UncondBranch && NumEdges == 1)
809 printUncondBranchInfo(CovOS, EdgeNo,
810 (*Block->dst_begin())->Count);
815 FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
818 // FIXME: There is no way to detect calls given current instrumentation.
819 if (Options.FuncCoverage)
820 printFuncCoverage(InfoOS);
821 printFileCoverage(InfoOS);
824 /// printFunctionSummary - Print function and block summary.
825 void FileInfo::printFunctionSummary(raw_ostream &OS,
826 const FunctionVector &Funcs) const {
827 for (const GCOVFunction *Func : Funcs) {
828 uint64_t EntryCount = Func->getEntryCount();
829 uint32_t BlocksExec = 0;
830 for (const GCOVBlock &Block : Func->blocks())
831 if (Block.getNumDstEdges() && Block.getCount())
832 ++BlocksExec;
834 OS << "function " << Func->getName() << " called " << EntryCount
835 << " returned " << safeDiv(Func->getExitCount() * 100, EntryCount)
836 << "% blocks executed "
837 << safeDiv(BlocksExec * 100, Func->getNumBlocks() - 1) << "%\n";
841 /// printBlockInfo - Output counts for each block.
842 void FileInfo::printBlockInfo(raw_ostream &OS, const GCOVBlock &Block,
843 uint32_t LineIndex, uint32_t &BlockNo) const {
844 if (Block.getCount() == 0)
845 OS << " $$$$$:";
846 else
847 OS << format("%9" PRIu64 ":", Block.getCount());
848 OS << format("%5u-block %2u\n", LineIndex + 1, BlockNo++);
851 /// printBranchInfo - Print conditional branch probabilities.
852 void FileInfo::printBranchInfo(raw_ostream &OS, const GCOVBlock &Block,
853 GCOVCoverage &Coverage, uint32_t &EdgeNo) {
854 SmallVector<uint64_t, 16> BranchCounts;
855 uint64_t TotalCounts = 0;
856 for (const GCOVEdge *Edge : Block.dsts()) {
857 BranchCounts.push_back(Edge->Count);
858 TotalCounts += Edge->Count;
859 if (Block.getCount())
860 ++Coverage.BranchesExec;
861 if (Edge->Count)
862 ++Coverage.BranchesTaken;
863 ++Coverage.Branches;
865 if (Options.FuncCoverage) {
866 const GCOVFunction *Function = &Block.getParent();
867 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
868 if (Block.getCount())
869 ++FuncCoverage.BranchesExec;
870 if (Edge->Count)
871 ++FuncCoverage.BranchesTaken;
872 ++FuncCoverage.Branches;
876 for (uint64_t N : BranchCounts)
877 OS << format("branch %2u ", EdgeNo++)
878 << formatBranchInfo(Options, N, TotalCounts) << "\n";
881 /// printUncondBranchInfo - Print unconditional branch probabilities.
882 void FileInfo::printUncondBranchInfo(raw_ostream &OS, uint32_t &EdgeNo,
883 uint64_t Count) const {
884 OS << format("unconditional %2u ", EdgeNo++)
885 << formatBranchInfo(Options, Count, Count) << "\n";
888 // printCoverage - Print generic coverage info used by both printFuncCoverage
889 // and printFileCoverage.
890 void FileInfo::printCoverage(raw_ostream &OS,
891 const GCOVCoverage &Coverage) const {
892 OS << format("Lines executed:%.2f%% of %u\n",
893 double(Coverage.LinesExec) * 100 / Coverage.LogicalLines,
894 Coverage.LogicalLines);
895 if (Options.BranchInfo) {
896 if (Coverage.Branches) {
897 OS << format("Branches executed:%.2f%% of %u\n",
898 double(Coverage.BranchesExec) * 100 / Coverage.Branches,
899 Coverage.Branches);
900 OS << format("Taken at least once:%.2f%% of %u\n",
901 double(Coverage.BranchesTaken) * 100 / Coverage.Branches,
902 Coverage.Branches);
903 } else {
904 OS << "No branches\n";
906 OS << "No calls\n"; // to be consistent with gcov
910 // printFuncCoverage - Print per-function coverage info.
911 void FileInfo::printFuncCoverage(raw_ostream &OS) const {
912 for (const auto &FC : FuncCoverages) {
913 const GCOVCoverage &Coverage = FC.second;
914 OS << "Function '" << Coverage.Name << "'\n";
915 printCoverage(OS, Coverage);
916 OS << "\n";
920 // printFileCoverage - Print per-file coverage info.
921 void FileInfo::printFileCoverage(raw_ostream &OS) const {
922 for (const auto &FC : FileCoverages) {
923 const std::string &Filename = FC.first;
924 const GCOVCoverage &Coverage = FC.second;
925 OS << "File '" << Coverage.Name << "'\n";
926 printCoverage(OS, Coverage);
927 if (!Options.NoOutput)
928 OS << Coverage.Name << ":creating '" << Filename << "'\n";
929 OS << "\n";