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).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('#');
458 /// print - Print source files with collected line count information.
459 void FileInfo::print(StringRef MainFilename, StringRef GCNOFile,
460 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;
472 if (Options.LongFileNames && !Filename.equals(MainFilename))
474 mangleCoveragePath(MainFilename, Options.PreservePaths) + "##";
476 mangleCoveragePath(Filename, Options.PreservePaths) + ".gcov";
477 std::string ErrorInfo;
478 raw_fd_ostream OS(CoveragePath.c_str(), ErrorInfo, sys::fs::F_Text);
479 if (!ErrorInfo.empty())
480 errs() << ErrorInfo << "\n";
482 OS << " -: 0:Source:" << Filename << "\n";
483 OS << " -: 0:Graph:" << GCNOFile << "\n";
484 OS << " -: 0:Data:" << GCDAFile << "\n";
485 OS << " -: 0:Runs:" << RunCount << "\n";
486 OS << " -: 0:Programs:" << ProgramCount << "\n";
488 const LineData &Line = I->second;
489 GCOVCoverage FileCoverage(Filename);
490 for (uint32_t LineIndex = 0; !AllLines.empty(); ++LineIndex) {
491 if (Options.BranchInfo) {
492 FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
493 if (FuncsIt != Line.Functions.end())
494 printFunctionSummary(OS, FuncsIt->second);
497 BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
498 if (BlocksIt == Line.Blocks.end()) {
499 // No basic blocks are on this line. Not an executable line of code.
501 std::pair<StringRef, StringRef> P = AllLines.split('\n');
502 OS << format("%5u:", LineIndex+1) << P.first << "\n";
505 const BlockVector &Blocks = BlocksIt->second;
507 // Add up the block counts to form line counts.
508 DenseMap<const GCOVFunction *, bool> LineExecs;
509 uint64_t LineCount = 0;
510 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
512 const GCOVBlock *Block = *I;
513 if (Options.AllBlocks) {
514 // Only take the highest block count for that line.
515 uint64_t BlockCount = Block->getCount();
516 LineCount = LineCount > BlockCount ? LineCount : BlockCount;
518 // Sum up all of the block counts.
519 LineCount += Block->getCount();
522 if (Options.FuncCoverage) {
523 // This is a slightly convoluted way to most accurately gather line
524 // statistics for functions. Basically what is happening is that we
525 // don't want to count a single line with multiple blocks more than
526 // once. However, we also don't simply want to give the total line
527 // count to every function that starts on the line. Thus, what is
528 // happening here are two things:
529 // 1) Ensure that the number of logical lines is only incremented
530 // once per function.
531 // 2) If there are multiple blocks on the same line, ensure that the
532 // number of lines executed is incremented as long as at least
533 // one of the blocks are executed.
534 const GCOVFunction *Function = &Block->getParent();
535 if (FuncCoverages.find(Function) == FuncCoverages.end()) {
536 std::pair<const GCOVFunction *, GCOVCoverage>
537 KeyValue(Function, GCOVCoverage(Function->getName()));
538 FuncCoverages.insert(KeyValue);
540 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
542 if (LineExecs.find(Function) == LineExecs.end()) {
543 if (Block->getCount()) {
544 ++FuncCoverage.LinesExec;
545 LineExecs[Function] = true;
547 LineExecs[Function] = false;
549 ++FuncCoverage.LogicalLines;
550 } else if (!LineExecs[Function] && Block->getCount()) {
551 ++FuncCoverage.LinesExec;
552 LineExecs[Function] = true;
560 OS << format("%9" PRIu64 ":", LineCount);
561 ++FileCoverage.LinesExec;
563 ++FileCoverage.LogicalLines;
565 std::pair<StringRef, StringRef> P = AllLines.split('\n');
566 OS << format("%5u:", LineIndex+1) << P.first << "\n";
569 uint32_t BlockNo = 0;
571 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
573 const GCOVBlock *Block = *I;
575 // Only print block and branch information at the end of the block.
576 if (Block->getLastLine() != LineIndex+1)
578 if (Options.AllBlocks)
579 printBlockInfo(OS, *Block, LineIndex, BlockNo);
580 if (Options.BranchInfo) {
581 size_t NumEdges = Block->getNumDstEdges();
583 printBranchInfo(OS, *Block, FileCoverage, EdgeNo);
584 else if (Options.UncondBranch && NumEdges == 1)
585 printUncondBranchInfo(OS, EdgeNo, (*Block->dst_begin())->Count);
590 FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
593 // FIXME: There is no way to detect calls given current instrumentation.
594 if (Options.FuncCoverage)
599 /// printFunctionSummary - Print function and block summary.
600 void FileInfo::printFunctionSummary(raw_fd_ostream &OS,
601 const FunctionVector &Funcs) const {
602 for (FunctionVector::const_iterator I = Funcs.begin(), E = Funcs.end();
604 const GCOVFunction *Func = *I;
605 uint64_t EntryCount = Func->getEntryCount();
606 uint32_t BlocksExec = 0;
607 for (GCOVFunction::BlockIterator I = Func->block_begin(),
608 E = Func->block_end(); I != E; ++I) {
609 const GCOVBlock &Block = **I;
610 if (Block.getNumDstEdges() && Block.getCount())
614 OS << "function " << Func->getName() << " called " << EntryCount
615 << " returned " << safeDiv(Func->getExitCount()*100, EntryCount)
616 << "% blocks executed "
617 << safeDiv(BlocksExec*100, Func->getNumBlocks()-1) << "%\n";
621 /// printBlockInfo - Output counts for each block.
622 void FileInfo::printBlockInfo(raw_fd_ostream &OS, const GCOVBlock &Block,
623 uint32_t LineIndex, uint32_t &BlockNo) const {
624 if (Block.getCount() == 0)
627 OS << format("%9" PRIu64 ":", Block.getCount());
628 OS << format("%5u-block %2u\n", LineIndex+1, BlockNo++);
631 /// printBranchInfo - Print conditional branch probabilities.
632 void FileInfo::printBranchInfo(raw_fd_ostream &OS, const GCOVBlock &Block,
633 GCOVCoverage &Coverage, uint32_t &EdgeNo) {
634 SmallVector<uint64_t, 16> BranchCounts;
635 uint64_t TotalCounts = 0;
636 for (GCOVBlock::EdgeIterator I = Block.dst_begin(), E = Block.dst_end();
638 const GCOVEdge *Edge = *I;
639 BranchCounts.push_back(Edge->Count);
640 TotalCounts += Edge->Count;
641 if (Block.getCount()) ++Coverage.BranchesExec;
642 if (Edge->Count) ++Coverage.BranchesTaken;
645 if (Options.FuncCoverage) {
646 const GCOVFunction *Function = &Block.getParent();
647 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
648 if (Block.getCount()) ++FuncCoverage.BranchesExec;
649 if (Edge->Count) ++FuncCoverage.BranchesTaken;
650 ++FuncCoverage.Branches;
654 for (SmallVectorImpl<uint64_t>::const_iterator I = BranchCounts.begin(),
655 E = BranchCounts.end(); I != E; ++I) {
656 OS << format("branch %2u ", EdgeNo++)
657 << formatBranchInfo(Options, *I, TotalCounts) << "\n";
661 /// printUncondBranchInfo - Print unconditional branch probabilities.
662 void FileInfo::printUncondBranchInfo(raw_fd_ostream &OS, uint32_t &EdgeNo,
663 uint64_t Count) const {
664 OS << format("unconditional %2u ", EdgeNo++)
665 << formatBranchInfo(Options, Count, Count) << "\n";
668 // printCoverage - Print generic coverage info used by both printFuncCoverage
669 // and printFileCoverage.
670 void FileInfo::printCoverage(const GCOVCoverage &Coverage) const {
671 outs() << format("Lines executed:%.2f%% of %u\n",
672 double(Coverage.LinesExec)*100/Coverage.LogicalLines,
673 Coverage.LogicalLines);
674 if (Options.BranchInfo) {
675 if (Coverage.Branches) {
676 outs() << format("Branches executed:%.2f%% of %u\n",
677 double(Coverage.BranchesExec)*100/Coverage.Branches,
679 outs() << format("Taken at least once:%.2f%% of %u\n",
680 double(Coverage.BranchesTaken)*100/Coverage.Branches,
683 outs() << "No branches\n";
685 outs() << "No calls\n"; // to be consistent with gcov
689 // printFuncCoverage - Print per-function coverage info.
690 void FileInfo::printFuncCoverage() const {
691 for (FuncCoverageMap::const_iterator I = FuncCoverages.begin(),
692 E = FuncCoverages.end(); I != E; ++I) {
693 const GCOVCoverage &Coverage = I->second;
694 outs() << "Function '" << Coverage.Name << "'\n";
695 printCoverage(Coverage);
700 // printFileCoverage - Print per-file coverage info.
701 void FileInfo::printFileCoverage() const {
702 for (FileCoverageList::const_iterator I = FileCoverages.begin(),
703 E = FileCoverages.end(); I != E; ++I) {
704 const std::string &Filename = I->first;
705 const GCOVCoverage &Coverage = I->second;
706 outs() << "File '" << Coverage.Name << "'\n";
707 printCoverage(Coverage);
708 outs() << Coverage.Name << ":creating '" << Filename << "'\n\n";