1 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // GCOV implements the interface to read and write coverage files that use
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Support/GCOV.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/Support/MemoryObject.h"
21 #include "llvm/Support/Path.h"
22 #include "llvm/Support/system_error.h"
26 //===----------------------------------------------------------------------===//
27 // GCOVFile implementation.
29 /// readGCNO - Read GCNO buffer.
30 bool GCOVFile::readGCNO(GCOVBuffer &Buffer) {
31 if (!Buffer.readGCNOFormat()) return false;
32 if (!Buffer.readGCOVVersion(Version)) return false;
34 if (!Buffer.readInt(Checksum)) return false;
36 if (!Buffer.readFunctionTag()) break;
37 auto GFun = make_unique<GCOVFunction>(*this);
38 if (!GFun->readGCNO(Buffer, Version))
40 Functions.push_back(std::move(GFun));
43 GCNOInitialized = true;
47 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
48 /// called after readGCNO().
49 bool GCOVFile::readGCDA(GCOVBuffer &Buffer) {
50 assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
51 if (!Buffer.readGCDAFormat()) return false;
52 GCOV::GCOVVersion GCDAVersion;
53 if (!Buffer.readGCOVVersion(GCDAVersion)) return false;
54 if (Version != GCDAVersion) {
55 errs() << "GCOV versions do not match.\n";
59 uint32_t GCDAChecksum;
60 if (!Buffer.readInt(GCDAChecksum)) return false;
61 if (Checksum != GCDAChecksum) {
62 errs() << "File checksums do not match: " << Checksum << " != "
63 << GCDAChecksum << ".\n";
66 for (size_t i = 0, e = Functions.size(); i < e; ++i) {
67 if (!Buffer.readFunctionTag()) {
68 errs() << "Unexpected number of functions.\n";
71 if (!Functions[i]->readGCDA(Buffer, Version))
74 if (Buffer.readObjectTag()) {
77 if (!Buffer.readInt(Length)) return false;
78 if (!Buffer.readInt(Dummy)) return false; // checksum
79 if (!Buffer.readInt(Dummy)) return false; // num
80 if (!Buffer.readInt(RunCount)) return false;
81 Buffer.advanceCursor(Length-3);
83 while (Buffer.readProgramTag()) {
85 if (!Buffer.readInt(Length)) return false;
86 Buffer.advanceCursor(Length);
93 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
94 void GCOVFile::dump() const {
95 for (const auto &FPtr : Functions)
99 /// collectLineCounts - Collect line counts. This must be used after
100 /// reading .gcno and .gcda files.
101 void GCOVFile::collectLineCounts(FileInfo &FI) {
102 for (const auto &FPtr : Functions)
103 FPtr->collectLineCounts(FI);
104 FI.setRunCount(RunCount);
105 FI.setProgramCount(ProgramCount);
108 //===----------------------------------------------------------------------===//
109 // GCOVFunction implementation.
111 /// readGCNO - Read a function from the GCNO buffer. Return false if an error
113 bool GCOVFunction::readGCNO(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
115 if (!Buff.readInt(Dummy)) return false; // Function header length
116 if (!Buff.readInt(Ident)) return false;
117 if (!Buff.readInt(Checksum)) return false;
118 if (Version != GCOV::V402) {
119 uint32_t CfgChecksum;
120 if (!Buff.readInt(CfgChecksum)) return false;
121 if (Parent.getChecksum() != CfgChecksum) {
122 errs() << "File checksums do not match: " << Parent.getChecksum()
123 << " != " << CfgChecksum << " in (" << Name << ").\n";
127 if (!Buff.readString(Name)) return false;
128 if (!Buff.readString(Filename)) return false;
129 if (!Buff.readInt(LineNumber)) return false;
132 if (!Buff.readBlockTag()) {
133 errs() << "Block tag not found.\n";
137 if (!Buff.readInt(BlockCount)) return false;
138 for (uint32_t i = 0, e = BlockCount; i != e; ++i) {
139 if (!Buff.readInt(Dummy)) return false; // Block flags;
140 Blocks.push_back(make_unique<GCOVBlock>(*this, i));
144 while (Buff.readEdgeTag()) {
146 if (!Buff.readInt(EdgeCount)) return false;
147 EdgeCount = (EdgeCount - 1) / 2;
149 if (!Buff.readInt(BlockNo)) return false;
150 if (BlockNo >= BlockCount) {
151 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
155 for (uint32_t i = 0, e = EdgeCount; i != e; ++i) {
157 if (!Buff.readInt(Dst)) return false;
158 Edges.push_back(make_unique<GCOVEdge>(*Blocks[BlockNo], *Blocks[Dst]));
159 GCOVEdge *Edge = Edges.back().get();
160 Blocks[BlockNo]->addDstEdge(Edge);
161 Blocks[Dst]->addSrcEdge(Edge);
162 if (!Buff.readInt(Dummy)) return false; // Edge flag
167 while (Buff.readLineTag()) {
168 uint32_t LineTableLength;
169 if (!Buff.readInt(LineTableLength)) return false;
170 uint32_t EndPos = Buff.getCursor() + LineTableLength*4;
172 if (!Buff.readInt(BlockNo)) return false;
173 if (BlockNo >= BlockCount) {
174 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
178 GCOVBlock &Block = *Blocks[BlockNo];
179 if (!Buff.readInt(Dummy)) return false; // flag
180 while (Buff.getCursor() != (EndPos - 4)) {
182 if (!Buff.readString(F)) return false;
184 errs() << "Multiple sources for a single basic block: " << Filename
185 << " != " << F << " (in " << Name << ").\n";
188 if (Buff.getCursor() == (EndPos - 4)) break;
191 if (!Buff.readInt(Line)) return false;
196 if (!Buff.readInt(Dummy)) return false; // flag
201 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
203 bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
205 if (!Buff.readInt(Dummy)) return false; // Function header length
208 if (!Buff.readInt(GCDAIdent)) return false;
209 if (Ident != GCDAIdent) {
210 errs() << "Function identifiers do not match: " << Ident << " != "
211 << GCDAIdent << " (in " << Name << ").\n";
215 uint32_t GCDAChecksum;
216 if (!Buff.readInt(GCDAChecksum)) return false;
217 if (Checksum != GCDAChecksum) {
218 errs() << "Function checksums do not match: " << Checksum << " != "
219 << GCDAChecksum << " (in " << Name << ").\n";
223 uint32_t CfgChecksum;
224 if (Version != GCOV::V402) {
225 if (!Buff.readInt(CfgChecksum)) return false;
226 if (Parent.getChecksum() != CfgChecksum) {
227 errs() << "File checksums do not match: " << Parent.getChecksum()
228 << " != " << CfgChecksum << " (in " << Name << ").\n";
234 if (!Buff.readString(GCDAName)) return false;
235 if (Name != GCDAName) {
236 errs() << "Function names do not match: " << Name << " != " << GCDAName
241 if (!Buff.readArcTag()) {
242 errs() << "Arc tag not found (in " << Name << ").\n";
247 if (!Buff.readInt(Count)) return false;
250 // This for loop adds the counts for each block. A second nested loop is
251 // required to combine the edge counts that are contained in the GCDA file.
252 for (uint32_t BlockNo = 0; Count > 0; ++BlockNo) {
253 // The last block is always reserved for exit block
254 if (BlockNo >= Blocks.size()-1) {
255 errs() << "Unexpected number of edges (in " << Name << ").\n";
258 GCOVBlock &Block = *Blocks[BlockNo];
259 for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
262 errs() << "Unexpected number of edges (in " << Name << ").\n";
266 if (!Buff.readInt64(ArcCount)) return false;
267 Block.addCount(EdgeNo, ArcCount);
270 Block.sortDstEdges();
275 /// getEntryCount - Get the number of times the function was called by
276 /// retrieving the entry block's count.
277 uint64_t GCOVFunction::getEntryCount() const {
278 return Blocks.front()->getCount();
281 /// getExitCount - Get the number of times the function returned by retrieving
282 /// the exit block's count.
283 uint64_t GCOVFunction::getExitCount() const {
284 return Blocks.back()->getCount();
287 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
288 void GCOVFunction::dump() const {
289 dbgs() << "===== " << Name << " @ " << Filename << ":" << LineNumber << "\n";
290 for (const auto &Block : Blocks)
294 /// collectLineCounts - Collect line counts. This must be used after
295 /// reading .gcno and .gcda files.
296 void GCOVFunction::collectLineCounts(FileInfo &FI) {
297 // If the line number is zero, this is a function that doesn't actually appear
298 // in the source file, so there isn't anything we can do with it.
302 for (const auto &Block : Blocks)
303 Block->collectLineCounts(FI);
304 FI.addFunctionLine(Filename, LineNumber, this);
307 //===----------------------------------------------------------------------===//
308 // GCOVBlock implementation.
310 /// ~GCOVBlock - Delete GCOVBlock and its content.
311 GCOVBlock::~GCOVBlock() {
317 /// addCount - Add to block counter while storing the edge count. If the
318 /// destination has no outgoing edges, also update that block's count too.
319 void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
320 assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
321 DstEdges[DstEdgeNo]->Count = N;
323 if (!DstEdges[DstEdgeNo]->Dst.getNumDstEdges())
324 DstEdges[DstEdgeNo]->Dst.Counter += N;
327 /// sortDstEdges - Sort destination edges by block number, nop if already
328 /// sorted. This is required for printing branch info in the correct order.
329 void GCOVBlock::sortDstEdges() {
330 if (!DstEdgesAreSorted) {
331 SortDstEdgesFunctor SortEdges;
332 std::stable_sort(DstEdges.begin(), DstEdges.end(), SortEdges);
336 /// collectLineCounts - Collect line counts. This must be used after
337 /// reading .gcno and .gcda files.
338 void GCOVBlock::collectLineCounts(FileInfo &FI) {
339 for (SmallVectorImpl<uint32_t>::iterator I = Lines.begin(),
340 E = Lines.end(); I != E; ++I)
341 FI.addBlockLine(Parent.getFilename(), *I, this);
344 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
345 void GCOVBlock::dump() const {
346 dbgs() << "Block : " << Number << " Counter : " << Counter << "\n";
347 if (!SrcEdges.empty()) {
348 dbgs() << "\tSource Edges : ";
349 for (EdgeIterator I = SrcEdges.begin(), E = SrcEdges.end(); I != E; ++I) {
350 const GCOVEdge *Edge = *I;
351 dbgs() << Edge->Src.Number << " (" << Edge->Count << "), ";
355 if (!DstEdges.empty()) {
356 dbgs() << "\tDestination Edges : ";
357 for (EdgeIterator I = DstEdges.begin(), E = DstEdges.end(); I != E; ++I) {
358 const GCOVEdge *Edge = *I;
359 dbgs() << Edge->Dst.Number << " (" << Edge->Count << "), ";
363 if (!Lines.empty()) {
364 dbgs() << "\tLines : ";
365 for (SmallVectorImpl<uint32_t>::const_iterator I = Lines.begin(),
366 E = Lines.end(); I != E; ++I)
367 dbgs() << (*I) << ",";
372 //===----------------------------------------------------------------------===//
373 // FileInfo implementation.
375 // Safe integer division, returns 0 if numerator is 0.
376 static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
379 return Numerator/Divisor;
382 // This custom division function mimics gcov's branch ouputs:
383 // - Round to closest whole number
384 // - Only output 0% or 100% if it's exactly that value
385 static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
388 if (Numerator == Divisor)
391 uint8_t Res = (Numerator*100+Divisor/2) / Divisor;
399 struct formatBranchInfo {
400 formatBranchInfo(const GCOVOptions &Options, uint64_t Count,
402 Options(Options), Count(Count), Total(Total) {}
404 void print(raw_ostream &OS) const {
406 OS << "never executed";
407 else if (Options.BranchCount)
408 OS << "taken " << Count;
410 OS << "taken " << branchDiv(Count, Total) << "%";
413 const GCOVOptions &Options;
418 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
423 /// Convert a path to a gcov filename. If PreservePaths is true, this
424 /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
425 static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
427 return (sys::path::filename(Filename) + ".gcov").str();
429 // This behaviour is defined by gcov in terms of text replacements, so it's
430 // not likely to do anything useful on filesystems with different textual
432 llvm::SmallString<256> Result("");
433 StringRef::iterator I, S, E;
434 for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
438 if (I - S == 1 && *S == '.') {
439 // ".", the current directory, is skipped.
440 } else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
441 // "..", the parent directory, is replaced with "^".
445 // Leave other components intact,
447 // And separate with "#".
448 Result.push_back('#');
455 Result.append(".gcov");
459 /// print - Print source files with collected line count information.
460 void FileInfo::print(StringRef GCNOFile, StringRef GCDAFile) {
461 for (StringMap<LineData>::const_iterator I = LineInfo.begin(),
462 E = LineInfo.end(); I != E; ++I) {
463 StringRef Filename = I->first();
464 std::unique_ptr<MemoryBuffer> Buff;
465 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
466 errs() << Filename << ": " << ec.message() << "\n";
469 StringRef AllLines = Buff->getBuffer();
471 std::string CoveragePath = mangleCoveragePath(Filename,
472 Options.PreservePaths);
473 std::string ErrorInfo;
474 raw_fd_ostream OS(CoveragePath.c_str(), ErrorInfo, sys::fs::F_Text);
475 if (!ErrorInfo.empty())
476 errs() << ErrorInfo << "\n";
478 OS << " -: 0:Source:" << Filename << "\n";
479 OS << " -: 0:Graph:" << GCNOFile << "\n";
480 OS << " -: 0:Data:" << GCDAFile << "\n";
481 OS << " -: 0:Runs:" << RunCount << "\n";
482 OS << " -: 0:Programs:" << ProgramCount << "\n";
484 const LineData &Line = I->second;
485 GCOVCoverage FileCoverage(Filename);
486 for (uint32_t LineIndex = 0; !AllLines.empty(); ++LineIndex) {
487 if (Options.BranchInfo) {
488 FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
489 if (FuncsIt != Line.Functions.end())
490 printFunctionSummary(OS, FuncsIt->second);
493 BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
494 if (BlocksIt == Line.Blocks.end()) {
495 // No basic blocks are on this line. Not an executable line of code.
497 std::pair<StringRef, StringRef> P = AllLines.split('\n');
498 OS << format("%5u:", LineIndex+1) << P.first << "\n";
501 const BlockVector &Blocks = BlocksIt->second;
503 // Add up the block counts to form line counts.
504 DenseMap<const GCOVFunction *, bool> LineExecs;
505 uint64_t LineCount = 0;
506 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
508 const GCOVBlock *Block = *I;
509 if (Options.AllBlocks) {
510 // Only take the highest block count for that line.
511 uint64_t BlockCount = Block->getCount();
512 LineCount = LineCount > BlockCount ? LineCount : BlockCount;
514 // Sum up all of the block counts.
515 LineCount += Block->getCount();
518 if (Options.FuncCoverage) {
519 // This is a slightly convoluted way to most accurately gather line
520 // statistics for functions. Basically what is happening is that we
521 // don't want to count a single line with multiple blocks more than
522 // once. However, we also don't simply want to give the total line
523 // count to every function that starts on the line. Thus, what is
524 // happening here are two things:
525 // 1) Ensure that the number of logical lines is only incremented
526 // once per function.
527 // 2) If there are multiple blocks on the same line, ensure that the
528 // number of lines executed is incremented as long as at least
529 // one of the blocks are executed.
530 const GCOVFunction *Function = &Block->getParent();
531 if (FuncCoverages.find(Function) == FuncCoverages.end()) {
532 std::pair<const GCOVFunction *, GCOVCoverage>
533 KeyValue(Function, GCOVCoverage(Function->getName()));
534 FuncCoverages.insert(KeyValue);
536 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
538 if (LineExecs.find(Function) == LineExecs.end()) {
539 if (Block->getCount()) {
540 ++FuncCoverage.LinesExec;
541 LineExecs[Function] = true;
543 LineExecs[Function] = false;
545 ++FuncCoverage.LogicalLines;
546 } else if (!LineExecs[Function] && Block->getCount()) {
547 ++FuncCoverage.LinesExec;
548 LineExecs[Function] = true;
556 OS << format("%9" PRIu64 ":", LineCount);
557 ++FileCoverage.LinesExec;
559 ++FileCoverage.LogicalLines;
561 std::pair<StringRef, StringRef> P = AllLines.split('\n');
562 OS << format("%5u:", LineIndex+1) << P.first << "\n";
565 uint32_t BlockNo = 0;
567 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
569 const GCOVBlock *Block = *I;
571 // Only print block and branch information at the end of the block.
572 if (Block->getLastLine() != LineIndex+1)
574 if (Options.AllBlocks)
575 printBlockInfo(OS, *Block, LineIndex, BlockNo);
576 if (Options.BranchInfo) {
577 size_t NumEdges = Block->getNumDstEdges();
579 printBranchInfo(OS, *Block, FileCoverage, EdgeNo);
580 else if (Options.UncondBranch && NumEdges == 1)
581 printUncondBranchInfo(OS, EdgeNo, (*Block->dst_begin())->Count);
586 FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
589 // FIXME: There is no way to detect calls given current instrumentation.
590 if (Options.FuncCoverage)
595 /// printFunctionSummary - Print function and block summary.
596 void FileInfo::printFunctionSummary(raw_fd_ostream &OS,
597 const FunctionVector &Funcs) const {
598 for (FunctionVector::const_iterator I = Funcs.begin(), E = Funcs.end();
600 const GCOVFunction *Func = *I;
601 uint64_t EntryCount = Func->getEntryCount();
602 uint32_t BlocksExec = 0;
603 for (GCOVFunction::BlockIterator I = Func->block_begin(),
604 E = Func->block_end(); I != E; ++I) {
605 const GCOVBlock &Block = **I;
606 if (Block.getNumDstEdges() && Block.getCount())
610 OS << "function " << Func->getName() << " called " << EntryCount
611 << " returned " << safeDiv(Func->getExitCount()*100, EntryCount)
612 << "% blocks executed "
613 << safeDiv(BlocksExec*100, Func->getNumBlocks()-1) << "%\n";
617 /// printBlockInfo - Output counts for each block.
618 void FileInfo::printBlockInfo(raw_fd_ostream &OS, const GCOVBlock &Block,
619 uint32_t LineIndex, uint32_t &BlockNo) const {
620 if (Block.getCount() == 0)
623 OS << format("%9" PRIu64 ":", Block.getCount());
624 OS << format("%5u-block %2u\n", LineIndex+1, BlockNo++);
627 /// printBranchInfo - Print conditional branch probabilities.
628 void FileInfo::printBranchInfo(raw_fd_ostream &OS, const GCOVBlock &Block,
629 GCOVCoverage &Coverage, uint32_t &EdgeNo) {
630 SmallVector<uint64_t, 16> BranchCounts;
631 uint64_t TotalCounts = 0;
632 for (GCOVBlock::EdgeIterator I = Block.dst_begin(), E = Block.dst_end();
634 const GCOVEdge *Edge = *I;
635 BranchCounts.push_back(Edge->Count);
636 TotalCounts += Edge->Count;
637 if (Block.getCount()) ++Coverage.BranchesExec;
638 if (Edge->Count) ++Coverage.BranchesTaken;
641 if (Options.FuncCoverage) {
642 const GCOVFunction *Function = &Block.getParent();
643 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
644 if (Block.getCount()) ++FuncCoverage.BranchesExec;
645 if (Edge->Count) ++FuncCoverage.BranchesTaken;
646 ++FuncCoverage.Branches;
650 for (SmallVectorImpl<uint64_t>::const_iterator I = BranchCounts.begin(),
651 E = BranchCounts.end(); I != E; ++I) {
652 OS << format("branch %2u ", EdgeNo++)
653 << formatBranchInfo(Options, *I, TotalCounts) << "\n";
657 /// printUncondBranchInfo - Print unconditional branch probabilities.
658 void FileInfo::printUncondBranchInfo(raw_fd_ostream &OS, uint32_t &EdgeNo,
659 uint64_t Count) const {
660 OS << format("unconditional %2u ", EdgeNo++)
661 << formatBranchInfo(Options, Count, Count) << "\n";
664 // printCoverage - Print generic coverage info used by both printFuncCoverage
665 // and printFileCoverage.
666 void FileInfo::printCoverage(const GCOVCoverage &Coverage) const {
667 outs() << format("Lines executed:%.2f%% of %u\n",
668 double(Coverage.LinesExec)*100/Coverage.LogicalLines,
669 Coverage.LogicalLines);
670 if (Options.BranchInfo) {
671 if (Coverage.Branches) {
672 outs() << format("Branches executed:%.2f%% of %u\n",
673 double(Coverage.BranchesExec)*100/Coverage.Branches,
675 outs() << format("Taken at least once:%.2f%% of %u\n",
676 double(Coverage.BranchesTaken)*100/Coverage.Branches,
679 outs() << "No branches\n";
681 outs() << "No calls\n"; // to be consistent with gcov
685 // printFuncCoverage - Print per-function coverage info.
686 void FileInfo::printFuncCoverage() const {
687 for (FuncCoverageMap::const_iterator I = FuncCoverages.begin(),
688 E = FuncCoverages.end(); I != E; ++I) {
689 const GCOVCoverage &Coverage = I->second;
690 outs() << "Function '" << Coverage.Name << "'\n";
691 printCoverage(Coverage);
696 // printFileCoverage - Print per-file coverage info.
697 void FileInfo::printFileCoverage() const {
698 for (FileCoverageList::const_iterator I = FileCoverages.begin(),
699 E = FileCoverages.end(); I != E; ++I) {
700 const std::string &Filename = I->first;
701 const GCOVCoverage &Coverage = I->second;
702 outs() << "File '" << Coverage.Name << "'\n";
703 printCoverage(Coverage);
704 outs() << Coverage.Name << ":creating '" << Filename << "'\n\n";