1 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // GCOV implements the interface to read and write coverage files that use
11 // 'gcov' format.
12 //
13 //===----------------------------------------------------------------------===//
14
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 <algorithm>
23 #include <system_error>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // GCOVFile implementation.
28
29 /// readGCNO - Read GCNO buffer.
readGCNO(GCOVBuffer & Buffer)30 bool GCOVFile::readGCNO(GCOVBuffer &Buffer) {
31 if (!Buffer.readGCNOFormat()) return false;
32 if (!Buffer.readGCOVVersion(Version)) return false;
33
34 if (!Buffer.readInt(Checksum)) return false;
35 while (true) {
36 if (!Buffer.readFunctionTag()) break;
37 auto GFun = make_unique<GCOVFunction>(*this);
38 if (!GFun->readGCNO(Buffer, Version))
39 return false;
40 Functions.push_back(std::move(GFun));
41 }
42
43 GCNOInitialized = true;
44 return true;
45 }
46
47 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
48 /// called after readGCNO().
readGCDA(GCOVBuffer & Buffer)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";
56 return false;
57 }
58
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";
64 return false;
65 }
66 for (size_t i = 0, e = Functions.size(); i < e; ++i) {
67 if (!Buffer.readFunctionTag()) {
68 errs() << "Unexpected number of functions.\n";
69 return false;
70 }
71 if (!Functions[i]->readGCDA(Buffer, Version))
72 return false;
73 }
74 if (Buffer.readObjectTag()) {
75 uint32_t Length;
76 uint32_t Dummy;
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);
82 }
83 while (Buffer.readProgramTag()) {
84 uint32_t Length;
85 if (!Buffer.readInt(Length)) return false;
86 Buffer.advanceCursor(Length);
87 ++ProgramCount;
88 }
89
90 return true;
91 }
92
93 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
dump() const94 void GCOVFile::dump() const {
95 for (const auto &FPtr : Functions)
96 FPtr->dump();
97 }
98
99 /// collectLineCounts - Collect line counts. This must be used after
100 /// reading .gcno and .gcda files.
collectLineCounts(FileInfo & FI)101 void GCOVFile::collectLineCounts(FileInfo &FI) {
102 for (const auto &FPtr : Functions)
103 FPtr->collectLineCounts(FI);
104 FI.setRunCount(RunCount);
105 FI.setProgramCount(ProgramCount);
106 }
107
108 //===----------------------------------------------------------------------===//
109 // GCOVFunction implementation.
110
111 /// readGCNO - Read a function from the GCNO buffer. Return false if an error
112 /// occurs.
readGCNO(GCOVBuffer & Buff,GCOV::GCOVVersion Version)113 bool GCOVFunction::readGCNO(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
114 uint32_t Dummy;
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";
124 return false;
125 }
126 }
127 if (!Buff.readString(Name)) return false;
128 if (!Buff.readString(Filename)) return false;
129 if (!Buff.readInt(LineNumber)) return false;
130
131 // read blocks.
132 if (!Buff.readBlockTag()) {
133 errs() << "Block tag not found.\n";
134 return false;
135 }
136 uint32_t BlockCount;
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));
141 }
142
143 // read edges.
144 while (Buff.readEdgeTag()) {
145 uint32_t EdgeCount;
146 if (!Buff.readInt(EdgeCount)) return false;
147 EdgeCount = (EdgeCount - 1) / 2;
148 uint32_t BlockNo;
149 if (!Buff.readInt(BlockNo)) return false;
150 if (BlockNo >= BlockCount) {
151 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
152 << ").\n";
153 return false;
154 }
155 for (uint32_t i = 0, e = EdgeCount; i != e; ++i) {
156 uint32_t Dst;
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
163 }
164 }
165
166 // read line table.
167 while (Buff.readLineTag()) {
168 uint32_t LineTableLength;
169 // Read the length of this line table.
170 if (!Buff.readInt(LineTableLength)) return false;
171 uint32_t EndPos = Buff.getCursor() + LineTableLength*4;
172 uint32_t BlockNo;
173 // Read the block number this table is associated with.
174 if (!Buff.readInt(BlockNo)) return false;
175 if (BlockNo >= BlockCount) {
176 errs() << "Unexpected block number: " << BlockNo << " (in " << Name
177 << ").\n";
178 return false;
179 }
180 GCOVBlock &Block = *Blocks[BlockNo];
181 // Read the word that pads the beginning of the line table. This may be a
182 // flag of some sort, but seems to always be zero.
183 if (!Buff.readInt(Dummy)) return false;
184
185 // Line information starts here and continues up until the last word.
186 if (Buff.getCursor() != (EndPos - sizeof(uint32_t))) {
187 StringRef F;
188 // Read the source file name.
189 if (!Buff.readString(F)) return false;
190 if (Filename != F) {
191 errs() << "Multiple sources for a single basic block: " << Filename
192 << " != " << F << " (in " << Name << ").\n";
193 return false;
194 }
195 // Read lines up to, but not including, the null terminator.
196 while (Buff.getCursor() < (EndPos - 2 * sizeof(uint32_t))) {
197 uint32_t Line;
198 if (!Buff.readInt(Line)) return false;
199 // Line 0 means this instruction was injected by the compiler. Skip it.
200 if (!Line) continue;
201 Block.addLine(Line);
202 }
203 // Read the null terminator.
204 if (!Buff.readInt(Dummy)) return false;
205 }
206 // The last word is either a flag or padding, it isn't clear which. Skip
207 // over it.
208 if (!Buff.readInt(Dummy)) return false;
209 }
210 return true;
211 }
212
213 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
214 /// occurs.
readGCDA(GCOVBuffer & Buff,GCOV::GCOVVersion Version)215 bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
216 uint32_t Dummy;
217 if (!Buff.readInt(Dummy)) return false; // Function header length
218
219 uint32_t GCDAIdent;
220 if (!Buff.readInt(GCDAIdent)) return false;
221 if (Ident != GCDAIdent) {
222 errs() << "Function identifiers do not match: " << Ident << " != "
223 << GCDAIdent << " (in " << Name << ").\n";
224 return false;
225 }
226
227 uint32_t GCDAChecksum;
228 if (!Buff.readInt(GCDAChecksum)) return false;
229 if (Checksum != GCDAChecksum) {
230 errs() << "Function checksums do not match: " << Checksum << " != "
231 << GCDAChecksum << " (in " << Name << ").\n";
232 return false;
233 }
234
235 uint32_t CfgChecksum;
236 if (Version != GCOV::V402) {
237 if (!Buff.readInt(CfgChecksum)) return false;
238 if (Parent.getChecksum() != CfgChecksum) {
239 errs() << "File checksums do not match: " << Parent.getChecksum()
240 << " != " << CfgChecksum << " (in " << Name << ").\n";
241 return false;
242 }
243 }
244
245 StringRef GCDAName;
246 if (!Buff.readString(GCDAName)) return false;
247 if (Name != GCDAName) {
248 errs() << "Function names do not match: " << Name << " != " << GCDAName
249 << ".\n";
250 return false;
251 }
252
253 if (!Buff.readArcTag()) {
254 errs() << "Arc tag not found (in " << Name << ").\n";
255 return false;
256 }
257
258 uint32_t Count;
259 if (!Buff.readInt(Count)) return false;
260 Count /= 2;
261
262 // This for loop adds the counts for each block. A second nested loop is
263 // required to combine the edge counts that are contained in the GCDA file.
264 for (uint32_t BlockNo = 0; Count > 0; ++BlockNo) {
265 // The last block is always reserved for exit block
266 if (BlockNo >= Blocks.size()) {
267 errs() << "Unexpected number of edges (in " << Name << ").\n";
268 return false;
269 }
270 if (BlockNo == Blocks.size() - 1)
271 errs() << "(" << Name << ") has arcs from exit block.\n";
272 GCOVBlock &Block = *Blocks[BlockNo];
273 for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
274 ++EdgeNo) {
275 if (Count == 0) {
276 errs() << "Unexpected number of edges (in " << Name << ").\n";
277 return false;
278 }
279 uint64_t ArcCount;
280 if (!Buff.readInt64(ArcCount)) return false;
281 Block.addCount(EdgeNo, ArcCount);
282 --Count;
283 }
284 Block.sortDstEdges();
285 }
286 return true;
287 }
288
289 /// getEntryCount - Get the number of times the function was called by
290 /// retrieving the entry block's count.
getEntryCount() const291 uint64_t GCOVFunction::getEntryCount() const {
292 return Blocks.front()->getCount();
293 }
294
295 /// getExitCount - Get the number of times the function returned by retrieving
296 /// the exit block's count.
getExitCount() const297 uint64_t GCOVFunction::getExitCount() const {
298 return Blocks.back()->getCount();
299 }
300
301 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
dump() const302 void GCOVFunction::dump() const {
303 dbgs() << "===== " << Name << " (" << Ident << ") @ " << Filename << ":"
304 << LineNumber << "\n";
305 for (const auto &Block : Blocks)
306 Block->dump();
307 }
308
309 /// collectLineCounts - Collect line counts. This must be used after
310 /// reading .gcno and .gcda files.
collectLineCounts(FileInfo & FI)311 void GCOVFunction::collectLineCounts(FileInfo &FI) {
312 // If the line number is zero, this is a function that doesn't actually appear
313 // in the source file, so there isn't anything we can do with it.
314 if (LineNumber == 0)
315 return;
316
317 for (const auto &Block : Blocks)
318 Block->collectLineCounts(FI);
319 FI.addFunctionLine(Filename, LineNumber, this);
320 }
321
322 //===----------------------------------------------------------------------===//
323 // GCOVBlock implementation.
324
325 /// ~GCOVBlock - Delete GCOVBlock and its content.
~GCOVBlock()326 GCOVBlock::~GCOVBlock() {
327 SrcEdges.clear();
328 DstEdges.clear();
329 Lines.clear();
330 }
331
332 /// addCount - Add to block counter while storing the edge count. If the
333 /// destination has no outgoing edges, also update that block's count too.
addCount(size_t DstEdgeNo,uint64_t N)334 void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
335 assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
336 DstEdges[DstEdgeNo]->Count = N;
337 Counter += N;
338 if (!DstEdges[DstEdgeNo]->Dst.getNumDstEdges())
339 DstEdges[DstEdgeNo]->Dst.Counter += N;
340 }
341
342 /// sortDstEdges - Sort destination edges by block number, nop if already
343 /// sorted. This is required for printing branch info in the correct order.
sortDstEdges()344 void GCOVBlock::sortDstEdges() {
345 if (!DstEdgesAreSorted) {
346 SortDstEdgesFunctor SortEdges;
347 std::stable_sort(DstEdges.begin(), DstEdges.end(), SortEdges);
348 }
349 }
350
351 /// collectLineCounts - Collect line counts. This must be used after
352 /// reading .gcno and .gcda files.
collectLineCounts(FileInfo & FI)353 void GCOVBlock::collectLineCounts(FileInfo &FI) {
354 for (SmallVectorImpl<uint32_t>::iterator I = Lines.begin(),
355 E = Lines.end(); I != E; ++I)
356 FI.addBlockLine(Parent.getFilename(), *I, this);
357 }
358
359 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
dump() const360 void GCOVBlock::dump() const {
361 dbgs() << "Block : " << Number << " Counter : " << Counter << "\n";
362 if (!SrcEdges.empty()) {
363 dbgs() << "\tSource Edges : ";
364 for (EdgeIterator I = SrcEdges.begin(), E = SrcEdges.end(); I != E; ++I) {
365 const GCOVEdge *Edge = *I;
366 dbgs() << Edge->Src.Number << " (" << Edge->Count << "), ";
367 }
368 dbgs() << "\n";
369 }
370 if (!DstEdges.empty()) {
371 dbgs() << "\tDestination Edges : ";
372 for (EdgeIterator I = DstEdges.begin(), E = DstEdges.end(); I != E; ++I) {
373 const GCOVEdge *Edge = *I;
374 dbgs() << Edge->Dst.Number << " (" << Edge->Count << "), ";
375 }
376 dbgs() << "\n";
377 }
378 if (!Lines.empty()) {
379 dbgs() << "\tLines : ";
380 for (SmallVectorImpl<uint32_t>::const_iterator I = Lines.begin(),
381 E = Lines.end(); I != E; ++I)
382 dbgs() << (*I) << ",";
383 dbgs() << "\n";
384 }
385 }
386
387 //===----------------------------------------------------------------------===//
388 // FileInfo implementation.
389
390 // Safe integer division, returns 0 if numerator is 0.
safeDiv(uint64_t Numerator,uint64_t Divisor)391 static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
392 if (!Numerator)
393 return 0;
394 return Numerator/Divisor;
395 }
396
397 // This custom division function mimics gcov's branch ouputs:
398 // - Round to closest whole number
399 // - Only output 0% or 100% if it's exactly that value
branchDiv(uint64_t Numerator,uint64_t Divisor)400 static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
401 if (!Numerator)
402 return 0;
403 if (Numerator == Divisor)
404 return 100;
405
406 uint8_t Res = (Numerator*100+Divisor/2) / Divisor;
407 if (Res == 0)
408 return 1;
409 if (Res == 100)
410 return 99;
411 return Res;
412 }
413
414 struct formatBranchInfo {
formatBranchInfoformatBranchInfo415 formatBranchInfo(const GCOVOptions &Options, uint64_t Count,
416 uint64_t Total) :
417 Options(Options), Count(Count), Total(Total) {}
418
printformatBranchInfo419 void print(raw_ostream &OS) const {
420 if (!Total)
421 OS << "never executed";
422 else if (Options.BranchCount)
423 OS << "taken " << Count;
424 else
425 OS << "taken " << branchDiv(Count, Total) << "%";
426 }
427
428 const GCOVOptions &Options;
429 uint64_t Count;
430 uint64_t Total;
431 };
432
operator <<(raw_ostream & OS,const formatBranchInfo & FBI)433 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
434 FBI.print(OS);
435 return OS;
436 }
437
438 namespace {
439 class LineConsumer {
440 std::unique_ptr<MemoryBuffer> Buffer;
441 StringRef Remaining;
442 public:
LineConsumer(StringRef Filename)443 LineConsumer(StringRef Filename) {
444 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
445 MemoryBuffer::getFileOrSTDIN(Filename);
446 if (std::error_code EC = BufferOrErr.getError()) {
447 errs() << Filename << ": " << EC.message() << "\n";
448 Remaining = "";
449 } else {
450 Buffer = std::move(BufferOrErr.get());
451 Remaining = Buffer->getBuffer();
452 }
453 }
empty()454 bool empty() { return Remaining.empty(); }
printNext(raw_ostream & OS,uint32_t LineNum)455 void printNext(raw_ostream &OS, uint32_t LineNum) {
456 StringRef Line;
457 if (empty())
458 Line = "/*EOF*/";
459 else
460 std::tie(Line, Remaining) = Remaining.split("\n");
461 OS << format("%5u:", LineNum) << Line << "\n";
462 }
463 };
464 }
465
466 /// Convert a path to a gcov filename. If PreservePaths is true, this
467 /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
mangleCoveragePath(StringRef Filename,bool PreservePaths)468 static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
469 if (!PreservePaths)
470 return sys::path::filename(Filename).str();
471
472 // This behaviour is defined by gcov in terms of text replacements, so it's
473 // not likely to do anything useful on filesystems with different textual
474 // conventions.
475 llvm::SmallString<256> Result("");
476 StringRef::iterator I, S, E;
477 for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
478 if (*I != '/')
479 continue;
480
481 if (I - S == 1 && *S == '.') {
482 // ".", the current directory, is skipped.
483 } else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
484 // "..", the parent directory, is replaced with "^".
485 Result.append("^#");
486 } else {
487 if (S < I)
488 // Leave other components intact,
489 Result.append(S, I);
490 // And separate with "#".
491 Result.push_back('#');
492 }
493 S = I + 1;
494 }
495
496 if (S < I)
497 Result.append(S, I);
498 return Result.str();
499 }
500
getCoveragePath(StringRef Filename,StringRef MainFilename)501 std::string FileInfo::getCoveragePath(StringRef Filename,
502 StringRef MainFilename) {
503 if (Options.NoOutput)
504 // This is probably a bug in gcov, but when -n is specified, paths aren't
505 // mangled at all, and the -l and -p options are ignored. Here, we do the
506 // same.
507 return Filename;
508
509 std::string CoveragePath;
510 if (Options.LongFileNames && !Filename.equals(MainFilename))
511 CoveragePath =
512 mangleCoveragePath(MainFilename, Options.PreservePaths) + "##";
513 CoveragePath +=
514 mangleCoveragePath(Filename, Options.PreservePaths) + ".gcov";
515 return CoveragePath;
516 }
517
518 std::unique_ptr<raw_ostream>
openCoveragePath(StringRef CoveragePath)519 FileInfo::openCoveragePath(StringRef CoveragePath) {
520 if (Options.NoOutput)
521 return llvm::make_unique<raw_null_ostream>();
522
523 std::error_code EC;
524 auto OS = llvm::make_unique<raw_fd_ostream>(CoveragePath.str(), EC,
525 sys::fs::F_Text);
526 if (EC) {
527 errs() << EC.message() << "\n";
528 return llvm::make_unique<raw_null_ostream>();
529 }
530 return std::move(OS);
531 }
532
533 /// print - Print source files with collected line count information.
print(StringRef MainFilename,StringRef GCNOFile,StringRef GCDAFile)534 void FileInfo::print(StringRef MainFilename, StringRef GCNOFile,
535 StringRef GCDAFile) {
536 for (StringMap<LineData>::const_iterator I = LineInfo.begin(),
537 E = LineInfo.end(); I != E; ++I) {
538 StringRef Filename = I->first();
539 auto AllLines = LineConsumer(Filename);
540
541 std::string CoveragePath = getCoveragePath(Filename, MainFilename);
542 std::unique_ptr<raw_ostream> S = openCoveragePath(CoveragePath);
543 raw_ostream &OS = *S;
544
545 OS << " -: 0:Source:" << Filename << "\n";
546 OS << " -: 0:Graph:" << GCNOFile << "\n";
547 OS << " -: 0:Data:" << GCDAFile << "\n";
548 OS << " -: 0:Runs:" << RunCount << "\n";
549 OS << " -: 0:Programs:" << ProgramCount << "\n";
550
551 const LineData &Line = I->second;
552 GCOVCoverage FileCoverage(Filename);
553 for (uint32_t LineIndex = 0;
554 LineIndex < Line.LastLine || !AllLines.empty(); ++LineIndex) {
555 if (Options.BranchInfo) {
556 FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
557 if (FuncsIt != Line.Functions.end())
558 printFunctionSummary(OS, FuncsIt->second);
559 }
560
561 BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
562 if (BlocksIt == Line.Blocks.end()) {
563 // No basic blocks are on this line. Not an executable line of code.
564 OS << " -:";
565 AllLines.printNext(OS, LineIndex + 1);
566 } else {
567 const BlockVector &Blocks = BlocksIt->second;
568
569 // Add up the block counts to form line counts.
570 DenseMap<const GCOVFunction *, bool> LineExecs;
571 uint64_t LineCount = 0;
572 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
573 I != E; ++I) {
574 const GCOVBlock *Block = *I;
575 if (Options.AllBlocks) {
576 // Only take the highest block count for that line.
577 uint64_t BlockCount = Block->getCount();
578 LineCount = LineCount > BlockCount ? LineCount : BlockCount;
579 } else {
580 // Sum up all of the block counts.
581 LineCount += Block->getCount();
582 }
583
584 if (Options.FuncCoverage) {
585 // This is a slightly convoluted way to most accurately gather line
586 // statistics for functions. Basically what is happening is that we
587 // don't want to count a single line with multiple blocks more than
588 // once. However, we also don't simply want to give the total line
589 // count to every function that starts on the line. Thus, what is
590 // happening here are two things:
591 // 1) Ensure that the number of logical lines is only incremented
592 // once per function.
593 // 2) If there are multiple blocks on the same line, ensure that the
594 // number of lines executed is incremented as long as at least
595 // one of the blocks are executed.
596 const GCOVFunction *Function = &Block->getParent();
597 if (FuncCoverages.find(Function) == FuncCoverages.end()) {
598 std::pair<const GCOVFunction *, GCOVCoverage>
599 KeyValue(Function, GCOVCoverage(Function->getName()));
600 FuncCoverages.insert(KeyValue);
601 }
602 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
603
604 if (LineExecs.find(Function) == LineExecs.end()) {
605 if (Block->getCount()) {
606 ++FuncCoverage.LinesExec;
607 LineExecs[Function] = true;
608 } else {
609 LineExecs[Function] = false;
610 }
611 ++FuncCoverage.LogicalLines;
612 } else if (!LineExecs[Function] && Block->getCount()) {
613 ++FuncCoverage.LinesExec;
614 LineExecs[Function] = true;
615 }
616 }
617 }
618
619 if (LineCount == 0)
620 OS << " #####:";
621 else {
622 OS << format("%9" PRIu64 ":", LineCount);
623 ++FileCoverage.LinesExec;
624 }
625 ++FileCoverage.LogicalLines;
626
627 AllLines.printNext(OS, LineIndex + 1);
628
629 uint32_t BlockNo = 0;
630 uint32_t EdgeNo = 0;
631 for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
632 I != E; ++I) {
633 const GCOVBlock *Block = *I;
634
635 // Only print block and branch information at the end of the block.
636 if (Block->getLastLine() != LineIndex+1)
637 continue;
638 if (Options.AllBlocks)
639 printBlockInfo(OS, *Block, LineIndex, BlockNo);
640 if (Options.BranchInfo) {
641 size_t NumEdges = Block->getNumDstEdges();
642 if (NumEdges > 1)
643 printBranchInfo(OS, *Block, FileCoverage, EdgeNo);
644 else if (Options.UncondBranch && NumEdges == 1)
645 printUncondBranchInfo(OS, EdgeNo, (*Block->dst_begin())->Count);
646 }
647 }
648 }
649 }
650 FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
651 }
652
653 // FIXME: There is no way to detect calls given current instrumentation.
654 if (Options.FuncCoverage)
655 printFuncCoverage();
656 printFileCoverage();
657 return;
658 }
659
660 /// printFunctionSummary - Print function and block summary.
printFunctionSummary(raw_ostream & OS,const FunctionVector & Funcs) const661 void FileInfo::printFunctionSummary(raw_ostream &OS,
662 const FunctionVector &Funcs) const {
663 for (FunctionVector::const_iterator I = Funcs.begin(), E = Funcs.end();
664 I != E; ++I) {
665 const GCOVFunction *Func = *I;
666 uint64_t EntryCount = Func->getEntryCount();
667 uint32_t BlocksExec = 0;
668 for (GCOVFunction::BlockIterator I = Func->block_begin(),
669 E = Func->block_end(); I != E; ++I) {
670 const GCOVBlock &Block = **I;
671 if (Block.getNumDstEdges() && Block.getCount())
672 ++BlocksExec;
673 }
674
675 OS << "function " << Func->getName() << " called " << EntryCount
676 << " returned " << safeDiv(Func->getExitCount()*100, EntryCount)
677 << "% blocks executed "
678 << safeDiv(BlocksExec*100, Func->getNumBlocks()-1) << "%\n";
679 }
680 }
681
682 /// printBlockInfo - Output counts for each block.
printBlockInfo(raw_ostream & OS,const GCOVBlock & Block,uint32_t LineIndex,uint32_t & BlockNo) const683 void FileInfo::printBlockInfo(raw_ostream &OS, const GCOVBlock &Block,
684 uint32_t LineIndex, uint32_t &BlockNo) const {
685 if (Block.getCount() == 0)
686 OS << " $$$$$:";
687 else
688 OS << format("%9" PRIu64 ":", Block.getCount());
689 OS << format("%5u-block %2u\n", LineIndex+1, BlockNo++);
690 }
691
692 /// printBranchInfo - Print conditional branch probabilities.
printBranchInfo(raw_ostream & OS,const GCOVBlock & Block,GCOVCoverage & Coverage,uint32_t & EdgeNo)693 void FileInfo::printBranchInfo(raw_ostream &OS, const GCOVBlock &Block,
694 GCOVCoverage &Coverage, uint32_t &EdgeNo) {
695 SmallVector<uint64_t, 16> BranchCounts;
696 uint64_t TotalCounts = 0;
697 for (GCOVBlock::EdgeIterator I = Block.dst_begin(), E = Block.dst_end();
698 I != E; ++I) {
699 const GCOVEdge *Edge = *I;
700 BranchCounts.push_back(Edge->Count);
701 TotalCounts += Edge->Count;
702 if (Block.getCount()) ++Coverage.BranchesExec;
703 if (Edge->Count) ++Coverage.BranchesTaken;
704 ++Coverage.Branches;
705
706 if (Options.FuncCoverage) {
707 const GCOVFunction *Function = &Block.getParent();
708 GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
709 if (Block.getCount()) ++FuncCoverage.BranchesExec;
710 if (Edge->Count) ++FuncCoverage.BranchesTaken;
711 ++FuncCoverage.Branches;
712 }
713 }
714
715 for (SmallVectorImpl<uint64_t>::const_iterator I = BranchCounts.begin(),
716 E = BranchCounts.end(); I != E; ++I) {
717 OS << format("branch %2u ", EdgeNo++)
718 << formatBranchInfo(Options, *I, TotalCounts) << "\n";
719 }
720 }
721
722 /// printUncondBranchInfo - Print unconditional branch probabilities.
printUncondBranchInfo(raw_ostream & OS,uint32_t & EdgeNo,uint64_t Count) const723 void FileInfo::printUncondBranchInfo(raw_ostream &OS, uint32_t &EdgeNo,
724 uint64_t Count) const {
725 OS << format("unconditional %2u ", EdgeNo++)
726 << formatBranchInfo(Options, Count, Count) << "\n";
727 }
728
729 // printCoverage - Print generic coverage info used by both printFuncCoverage
730 // and printFileCoverage.
printCoverage(const GCOVCoverage & Coverage) const731 void FileInfo::printCoverage(const GCOVCoverage &Coverage) const {
732 outs() << format("Lines executed:%.2f%% of %u\n",
733 double(Coverage.LinesExec)*100/Coverage.LogicalLines,
734 Coverage.LogicalLines);
735 if (Options.BranchInfo) {
736 if (Coverage.Branches) {
737 outs() << format("Branches executed:%.2f%% of %u\n",
738 double(Coverage.BranchesExec)*100/Coverage.Branches,
739 Coverage.Branches);
740 outs() << format("Taken at least once:%.2f%% of %u\n",
741 double(Coverage.BranchesTaken)*100/Coverage.Branches,
742 Coverage.Branches);
743 } else {
744 outs() << "No branches\n";
745 }
746 outs() << "No calls\n"; // to be consistent with gcov
747 }
748 }
749
750 // printFuncCoverage - Print per-function coverage info.
printFuncCoverage() const751 void FileInfo::printFuncCoverage() const {
752 for (FuncCoverageMap::const_iterator I = FuncCoverages.begin(),
753 E = FuncCoverages.end(); I != E; ++I) {
754 const GCOVCoverage &Coverage = I->second;
755 outs() << "Function '" << Coverage.Name << "'\n";
756 printCoverage(Coverage);
757 outs() << "\n";
758 }
759 }
760
761 // printFileCoverage - Print per-file coverage info.
printFileCoverage() const762 void FileInfo::printFileCoverage() const {
763 for (FileCoverageList::const_iterator I = FileCoverages.begin(),
764 E = FileCoverages.end(); I != E; ++I) {
765 const std::string &Filename = I->first;
766 const GCOVCoverage &Coverage = I->second;
767 outs() << "File '" << Coverage.Name << "'\n";
768 printCoverage(Coverage);
769 if (!Options.NoOutput)
770 outs() << Coverage.Name << ":creating '" << Filename << "'\n";
771 outs() << "\n";
772 }
773 }
774