llvm-cov: Add support for gcov's --long-file-names option
[oota-llvm.git] / lib / IR / GCOV.cpp
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 "llvm/Support/system_error.h"
23 #include <algorithm>
24 using namespace llvm;
25
26 //===----------------------------------------------------------------------===//
27 // GCOVFile implementation.
28
29 /// readGCNO - Read GCNO 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().
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.
94 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.
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.
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     if (!Buff.readInt(LineTableLength)) return false;
170     uint32_t EndPos = Buff.getCursor() + LineTableLength*4;
171     uint32_t BlockNo;
172     if (!Buff.readInt(BlockNo)) return false;
173     if (BlockNo >= BlockCount) {
174       errs() << "Unexpected block number: " << BlockNo << " (in " << Name
175              << ").\n";
176       return false;
177     }
178     GCOVBlock &Block = *Blocks[BlockNo];
179     if (!Buff.readInt(Dummy)) return false; // flag
180     while (Buff.getCursor() != (EndPos - 4)) {
181       StringRef F;
182       if (!Buff.readString(F)) return false;
183       if (Filename != F) {
184         errs() << "Multiple sources for a single basic block: " << Filename
185                << " != " << F << " (in " << Name << ").\n";
186         return false;
187       }
188       if (Buff.getCursor() == (EndPos - 4)) break;
189       while (true) {
190         uint32_t Line;
191         if (!Buff.readInt(Line)) return false;
192         if (!Line) break;
193         Block.addLine(Line);
194       }
195     }
196     if (!Buff.readInt(Dummy)) return false; // flag
197   }
198   return true;
199 }
200
201 /// readGCDA - Read a function from the GCDA buffer. Return false if an error
202 /// occurs.
203 bool GCOVFunction::readGCDA(GCOVBuffer &Buff, GCOV::GCOVVersion Version) {
204   uint32_t Dummy;
205   if (!Buff.readInt(Dummy)) return false; // Function header length
206
207   uint32_t GCDAIdent;
208   if (!Buff.readInt(GCDAIdent)) return false;
209   if (Ident != GCDAIdent) {
210     errs() << "Function identifiers do not match: " << Ident << " != "
211            << GCDAIdent << " (in " << Name << ").\n";
212     return false;
213   }
214
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";
220     return false;
221   }
222
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";
229       return false;
230     }
231   }
232
233   StringRef GCDAName;
234   if (!Buff.readString(GCDAName)) return false;
235   if (Name != GCDAName) {
236     errs() << "Function names do not match: " << Name << " != " << GCDAName
237            << ".\n";
238     return false;
239   }
240
241   if (!Buff.readArcTag()) {
242     errs() << "Arc tag not found (in " << Name << ").\n";
243     return false;
244   }
245
246   uint32_t Count;
247   if (!Buff.readInt(Count)) return false;
248   Count /= 2;
249
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";
256       return false;
257     }
258     GCOVBlock &Block = *Blocks[BlockNo];
259     for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
260            ++EdgeNo) {
261       if (Count == 0) {
262         errs() << "Unexpected number of edges (in " << Name << ").\n";
263         return false;
264       }
265       uint64_t ArcCount;
266       if (!Buff.readInt64(ArcCount)) return false;
267       Block.addCount(EdgeNo, ArcCount);
268       --Count;
269     }
270     Block.sortDstEdges();
271   }
272   return true;
273 }
274
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();
279 }
280
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();
285 }
286
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)
291     Block->dump();
292 }
293
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.
299   if (LineNumber == 0)
300     return;
301
302   for (const auto &Block : Blocks)
303     Block->collectLineCounts(FI);
304   FI.addFunctionLine(Filename, LineNumber, this);
305 }
306
307 //===----------------------------------------------------------------------===//
308 // GCOVBlock implementation.
309
310 /// ~GCOVBlock - Delete GCOVBlock and its content.
311 GCOVBlock::~GCOVBlock() {
312   SrcEdges.clear();
313   DstEdges.clear();
314   Lines.clear();
315 }
316
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;
322   Counter += N;
323   if (!DstEdges[DstEdgeNo]->Dst.getNumDstEdges())
324     DstEdges[DstEdgeNo]->Dst.Counter += N;
325 }
326
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);
333   }
334 }
335
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);
342 }
343
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 << "), ";
352     }
353     dbgs() << "\n";
354   }
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 << "), ";
360     }
361     dbgs() << "\n";
362   }
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) << ",";
368     dbgs() << "\n";
369   }
370 }
371
372 //===----------------------------------------------------------------------===//
373 // FileInfo implementation.
374
375 // Safe integer division, returns 0 if numerator is 0.
376 static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
377   if (!Numerator)
378     return 0;
379   return Numerator/Divisor;
380 }
381
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) {
386   if (!Numerator)
387     return 0;
388   if (Numerator == Divisor)
389     return 100;
390
391   uint8_t Res = (Numerator*100+Divisor/2) / Divisor;
392   if (Res == 0)
393     return 1;
394   if (Res == 100)
395     return 99;
396   return Res;
397 }
398
399 struct formatBranchInfo {
400   formatBranchInfo(const GCOVOptions &Options, uint64_t Count,
401                    uint64_t Total) :
402     Options(Options), Count(Count), Total(Total) {}
403
404   void print(raw_ostream &OS) const {
405     if (!Total)
406       OS << "never executed";
407     else if (Options.BranchCount)
408       OS << "taken " << Count;
409     else
410       OS << "taken " << branchDiv(Count, Total) << "%";
411   }
412
413   const GCOVOptions &Options;
414   uint64_t Count;
415   uint64_t Total;
416 };
417
418 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
419   FBI.print(OS);
420   return OS;
421 }
422
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) {
426   if (!PreservePaths)
427     return sys::path::filename(Filename).str();
428
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
431   // conventions.
432   llvm::SmallString<256> Result("");
433   StringRef::iterator I, S, E;
434   for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
435     if (*I != '/')
436       continue;
437
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 "^".
442       Result.append("^#");
443     } else {
444       if (S < I)
445         // Leave other components intact,
446         Result.append(S, I);
447       // And separate with "#".
448       Result.push_back('#');
449     }
450     S = I + 1;
451   }
452
453   if (S < I)
454     Result.append(S, I);
455   return Result.str();
456 }
457
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";
467       return;
468     }
469     StringRef AllLines = Buff->getBuffer();
470
471     std::string CoveragePath;
472     if (Options.LongFileNames && !Filename.equals(MainFilename))
473       CoveragePath =
474           mangleCoveragePath(MainFilename, Options.PreservePaths) + "##";
475     CoveragePath +=
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";
481
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";
487
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);
495       }
496
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.
500         OS << "        -:";
501         std::pair<StringRef, StringRef> P = AllLines.split('\n');
502         OS << format("%5u:", LineIndex+1) << P.first << "\n";
503         AllLines = P.second;
504       } else {
505         const BlockVector &Blocks = BlocksIt->second;
506
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();
511                I != E; ++I) {
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;
517           } else {
518             // Sum up all of the block counts.
519             LineCount += Block->getCount();
520           }
521
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);
539             }
540             GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
541
542             if (LineExecs.find(Function) == LineExecs.end()) {
543               if (Block->getCount()) {
544                 ++FuncCoverage.LinesExec;
545                 LineExecs[Function] = true;
546               } else {
547                 LineExecs[Function] = false;
548               }
549               ++FuncCoverage.LogicalLines;
550             } else if (!LineExecs[Function] && Block->getCount()) {
551               ++FuncCoverage.LinesExec;
552               LineExecs[Function] = true;
553             }
554           }
555         }
556
557         if (LineCount == 0)
558           OS << "    #####:";
559         else {
560           OS << format("%9" PRIu64 ":", LineCount);
561           ++FileCoverage.LinesExec;
562         }
563         ++FileCoverage.LogicalLines;
564
565         std::pair<StringRef, StringRef> P = AllLines.split('\n');
566         OS << format("%5u:", LineIndex+1) << P.first << "\n";
567         AllLines = P.second;
568
569         uint32_t BlockNo = 0;
570         uint32_t EdgeNo = 0;
571         for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
572                I != E; ++I) {
573           const GCOVBlock *Block = *I;
574
575           // Only print block and branch information at the end of the block.
576           if (Block->getLastLine() != LineIndex+1)
577             continue;
578           if (Options.AllBlocks)
579             printBlockInfo(OS, *Block, LineIndex, BlockNo);
580           if (Options.BranchInfo) {
581             size_t NumEdges = Block->getNumDstEdges();
582             if (NumEdges > 1)
583               printBranchInfo(OS, *Block, FileCoverage, EdgeNo);
584             else if (Options.UncondBranch && NumEdges == 1)
585               printUncondBranchInfo(OS, EdgeNo, (*Block->dst_begin())->Count);
586           }
587         }
588       }
589     }
590     FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
591   }
592
593   // FIXME: There is no way to detect calls given current instrumentation.
594   if (Options.FuncCoverage)
595     printFuncCoverage();
596   printFileCoverage();
597 }
598
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();
603          I != E; ++I) {
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())
611           ++BlocksExec;
612     }
613
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";
618   }
619 }
620
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)
625     OS << "    $$$$$:";
626   else
627     OS << format("%9" PRIu64 ":", Block.getCount());
628   OS << format("%5u-block %2u\n", LineIndex+1, BlockNo++);
629 }
630
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();
637          I != E; ++I) {
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;
643     ++Coverage.Branches;
644
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;
651     }
652   }
653
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";
658   }
659 }
660
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";
666 }
667
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,
678                        Coverage.Branches);
679       outs() << format("Taken at least once:%.2f%% of %u\n",
680                        double(Coverage.BranchesTaken)*100/Coverage.Branches,
681                        Coverage.Branches);
682     } else {
683       outs() << "No branches\n";
684     }
685     outs() << "No calls\n"; // to be consistent with gcov
686   }
687 }
688
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);
696     outs() << "\n";
697   }
698 }
699
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";
709   }
710 }