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