llvm-cov: Implement --no-output
[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     // 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.
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()-1) {
267       errs() << "Unexpected number of edges (in " << Name << ").\n";
268       return false;
269     }
270     GCOVBlock &Block = *Blocks[BlockNo];
271     for (size_t EdgeNo = 0, End = Block.getNumDstEdges(); EdgeNo < End;
272            ++EdgeNo) {
273       if (Count == 0) {
274         errs() << "Unexpected number of edges (in " << Name << ").\n";
275         return false;
276       }
277       uint64_t ArcCount;
278       if (!Buff.readInt64(ArcCount)) return false;
279       Block.addCount(EdgeNo, ArcCount);
280       --Count;
281     }
282     Block.sortDstEdges();
283   }
284   return true;
285 }
286
287 /// getEntryCount - Get the number of times the function was called by
288 /// retrieving the entry block's count.
289 uint64_t GCOVFunction::getEntryCount() const {
290   return Blocks.front()->getCount();
291 }
292
293 /// getExitCount - Get the number of times the function returned by retrieving
294 /// the exit block's count.
295 uint64_t GCOVFunction::getExitCount() const {
296   return Blocks.back()->getCount();
297 }
298
299 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
300 void GCOVFunction::dump() const {
301   dbgs() <<  "===== " << Name << " @ " << Filename << ":" << LineNumber << "\n";
302   for (const auto &Block : Blocks)
303     Block->dump();
304 }
305
306 /// collectLineCounts - Collect line counts. This must be used after
307 /// reading .gcno and .gcda files.
308 void GCOVFunction::collectLineCounts(FileInfo &FI) {
309   // If the line number is zero, this is a function that doesn't actually appear
310   // in the source file, so there isn't anything we can do with it.
311   if (LineNumber == 0)
312     return;
313
314   for (const auto &Block : Blocks)
315     Block->collectLineCounts(FI);
316   FI.addFunctionLine(Filename, LineNumber, this);
317 }
318
319 //===----------------------------------------------------------------------===//
320 // GCOVBlock implementation.
321
322 /// ~GCOVBlock - Delete GCOVBlock and its content.
323 GCOVBlock::~GCOVBlock() {
324   SrcEdges.clear();
325   DstEdges.clear();
326   Lines.clear();
327 }
328
329 /// addCount - Add to block counter while storing the edge count. If the
330 /// destination has no outgoing edges, also update that block's count too.
331 void GCOVBlock::addCount(size_t DstEdgeNo, uint64_t N) {
332   assert(DstEdgeNo < DstEdges.size()); // up to caller to ensure EdgeNo is valid
333   DstEdges[DstEdgeNo]->Count = N;
334   Counter += N;
335   if (!DstEdges[DstEdgeNo]->Dst.getNumDstEdges())
336     DstEdges[DstEdgeNo]->Dst.Counter += N;
337 }
338
339 /// sortDstEdges - Sort destination edges by block number, nop if already
340 /// sorted. This is required for printing branch info in the correct order.
341 void GCOVBlock::sortDstEdges() {
342   if (!DstEdgesAreSorted) {
343     SortDstEdgesFunctor SortEdges;
344     std::stable_sort(DstEdges.begin(), DstEdges.end(), SortEdges);
345   }
346 }
347
348 /// collectLineCounts - Collect line counts. This must be used after
349 /// reading .gcno and .gcda files.
350 void GCOVBlock::collectLineCounts(FileInfo &FI) {
351   for (SmallVectorImpl<uint32_t>::iterator I = Lines.begin(),
352          E = Lines.end(); I != E; ++I)
353     FI.addBlockLine(Parent.getFilename(), *I, this);
354 }
355
356 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
357 void GCOVBlock::dump() const {
358   dbgs() << "Block : " << Number << " Counter : " << Counter << "\n";
359   if (!SrcEdges.empty()) {
360     dbgs() << "\tSource Edges : ";
361     for (EdgeIterator I = SrcEdges.begin(), E = SrcEdges.end(); I != E; ++I) {
362       const GCOVEdge *Edge = *I;
363       dbgs() << Edge->Src.Number << " (" << Edge->Count << "), ";
364     }
365     dbgs() << "\n";
366   }
367   if (!DstEdges.empty()) {
368     dbgs() << "\tDestination Edges : ";
369     for (EdgeIterator I = DstEdges.begin(), E = DstEdges.end(); I != E; ++I) {
370       const GCOVEdge *Edge = *I;
371       dbgs() << Edge->Dst.Number << " (" << Edge->Count << "), ";
372     }
373     dbgs() << "\n";
374   }
375   if (!Lines.empty()) {
376     dbgs() << "\tLines : ";
377     for (SmallVectorImpl<uint32_t>::const_iterator I = Lines.begin(),
378            E = Lines.end(); I != E; ++I)
379       dbgs() << (*I) << ",";
380     dbgs() << "\n";
381   }
382 }
383
384 //===----------------------------------------------------------------------===//
385 // FileInfo implementation.
386
387 // Safe integer division, returns 0 if numerator is 0.
388 static uint32_t safeDiv(uint64_t Numerator, uint64_t Divisor) {
389   if (!Numerator)
390     return 0;
391   return Numerator/Divisor;
392 }
393
394 // This custom division function mimics gcov's branch ouputs:
395 //   - Round to closest whole number
396 //   - Only output 0% or 100% if it's exactly that value
397 static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
398   if (!Numerator)
399     return 0;
400   if (Numerator == Divisor)
401     return 100;
402
403   uint8_t Res = (Numerator*100+Divisor/2) / Divisor;
404   if (Res == 0)
405     return 1;
406   if (Res == 100)
407     return 99;
408   return Res;
409 }
410
411 struct formatBranchInfo {
412   formatBranchInfo(const GCOVOptions &Options, uint64_t Count,
413                    uint64_t Total) :
414     Options(Options), Count(Count), Total(Total) {}
415
416   void print(raw_ostream &OS) const {
417     if (!Total)
418       OS << "never executed";
419     else if (Options.BranchCount)
420       OS << "taken " << Count;
421     else
422       OS << "taken " << branchDiv(Count, Total) << "%";
423   }
424
425   const GCOVOptions &Options;
426   uint64_t Count;
427   uint64_t Total;
428 };
429
430 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
431   FBI.print(OS);
432   return OS;
433 }
434
435 /// Convert a path to a gcov filename. If PreservePaths is true, this
436 /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
437 static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
438   if (!PreservePaths)
439     return sys::path::filename(Filename).str();
440
441   // This behaviour is defined by gcov in terms of text replacements, so it's
442   // not likely to do anything useful on filesystems with different textual
443   // conventions.
444   llvm::SmallString<256> Result("");
445   StringRef::iterator I, S, E;
446   for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
447     if (*I != '/')
448       continue;
449
450     if (I - S == 1 && *S == '.') {
451       // ".", the current directory, is skipped.
452     } else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
453       // "..", the parent directory, is replaced with "^".
454       Result.append("^#");
455     } else {
456       if (S < I)
457         // Leave other components intact,
458         Result.append(S, I);
459       // And separate with "#".
460       Result.push_back('#');
461     }
462     S = I + 1;
463   }
464
465   if (S < I)
466     Result.append(S, I);
467   return Result.str();
468 }
469
470 std::string FileInfo::getCoveragePath(StringRef Filename,
471                                       StringRef MainFilename) {
472   if (Options.NoOutput)
473     // This is probably a bug in gcov, but when -n is specified, paths aren't
474     // mangled at all, and the -l and -p options are ignored. Here, we do the
475     // same.
476     return Filename;
477
478   std::string CoveragePath;
479   if (Options.LongFileNames && !Filename.equals(MainFilename))
480     CoveragePath =
481         mangleCoveragePath(MainFilename, Options.PreservePaths) + "##";
482   CoveragePath +=
483       mangleCoveragePath(Filename, Options.PreservePaths) + ".gcov";
484   return CoveragePath;
485 }
486
487 std::unique_ptr<raw_ostream>
488 FileInfo::openCoveragePath(StringRef CoveragePath) {
489   if (Options.NoOutput)
490     return make_unique<raw_null_ostream>();
491
492   std::string ErrorInfo;
493   auto OS = make_unique<raw_fd_ostream>(CoveragePath.str().c_str(), ErrorInfo,
494                                         sys::fs::F_Text);
495   if (!ErrorInfo.empty()) {
496     errs() << ErrorInfo << "\n";
497     return make_unique<raw_null_ostream>();
498   }
499   return std::move(OS);
500 }
501
502 /// print -  Print source files with collected line count information.
503 void FileInfo::print(StringRef MainFilename, StringRef GCNOFile,
504                      StringRef GCDAFile) {
505   for (StringMap<LineData>::const_iterator I = LineInfo.begin(),
506          E = LineInfo.end(); I != E; ++I) {
507     StringRef Filename = I->first();
508     std::unique_ptr<MemoryBuffer> Buff;
509     if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
510       errs() << Filename << ": " << ec.message() << "\n";
511       return;
512     }
513     StringRef AllLines = Buff->getBuffer();
514
515     std::string CoveragePath = getCoveragePath(Filename, MainFilename);
516     std::unique_ptr<raw_ostream> S = openCoveragePath(CoveragePath);
517     raw_ostream &OS = *S;
518
519     OS << "        -:    0:Source:" << Filename << "\n";
520     OS << "        -:    0:Graph:" << GCNOFile << "\n";
521     OS << "        -:    0:Data:" << GCDAFile << "\n";
522     OS << "        -:    0:Runs:" << RunCount << "\n";
523     OS << "        -:    0:Programs:" << ProgramCount << "\n";
524
525     const LineData &Line = I->second;
526     GCOVCoverage FileCoverage(Filename);
527     for (uint32_t LineIndex = 0; !AllLines.empty(); ++LineIndex) {
528       if (Options.BranchInfo) {
529         FunctionLines::const_iterator FuncsIt = Line.Functions.find(LineIndex);
530         if (FuncsIt != Line.Functions.end())
531           printFunctionSummary(OS, FuncsIt->second);
532       }
533
534       BlockLines::const_iterator BlocksIt = Line.Blocks.find(LineIndex);
535       if (BlocksIt == Line.Blocks.end()) {
536         // No basic blocks are on this line. Not an executable line of code.
537         OS << "        -:";
538         std::pair<StringRef, StringRef> P = AllLines.split('\n');
539         OS << format("%5u:", LineIndex+1) << P.first << "\n";
540         AllLines = P.second;
541       } else {
542         const BlockVector &Blocks = BlocksIt->second;
543
544         // Add up the block counts to form line counts.
545         DenseMap<const GCOVFunction *, bool> LineExecs;
546         uint64_t LineCount = 0;
547         for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
548                I != E; ++I) {
549           const GCOVBlock *Block = *I;
550           if (Options.AllBlocks) {
551             // Only take the highest block count for that line.
552             uint64_t BlockCount = Block->getCount();
553             LineCount = LineCount > BlockCount ? LineCount : BlockCount;
554           } else {
555             // Sum up all of the block counts.
556             LineCount += Block->getCount();
557           }
558
559           if (Options.FuncCoverage) {
560             // This is a slightly convoluted way to most accurately gather line
561             // statistics for functions. Basically what is happening is that we
562             // don't want to count a single line with multiple blocks more than
563             // once. However, we also don't simply want to give the total line
564             // count to every function that starts on the line. Thus, what is
565             // happening here are two things:
566             // 1) Ensure that the number of logical lines is only incremented
567             //    once per function.
568             // 2) If there are multiple blocks on the same line, ensure that the
569             //    number of lines executed is incremented as long as at least
570             //    one of the blocks are executed.
571             const GCOVFunction *Function = &Block->getParent();
572             if (FuncCoverages.find(Function) == FuncCoverages.end()) {
573               std::pair<const GCOVFunction *, GCOVCoverage>
574                 KeyValue(Function, GCOVCoverage(Function->getName()));
575               FuncCoverages.insert(KeyValue);
576             }
577             GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
578
579             if (LineExecs.find(Function) == LineExecs.end()) {
580               if (Block->getCount()) {
581                 ++FuncCoverage.LinesExec;
582                 LineExecs[Function] = true;
583               } else {
584                 LineExecs[Function] = false;
585               }
586               ++FuncCoverage.LogicalLines;
587             } else if (!LineExecs[Function] && Block->getCount()) {
588               ++FuncCoverage.LinesExec;
589               LineExecs[Function] = true;
590             }
591           }
592         }
593
594         if (LineCount == 0)
595           OS << "    #####:";
596         else {
597           OS << format("%9" PRIu64 ":", LineCount);
598           ++FileCoverage.LinesExec;
599         }
600         ++FileCoverage.LogicalLines;
601
602         std::pair<StringRef, StringRef> P = AllLines.split('\n');
603         OS << format("%5u:", LineIndex+1) << P.first << "\n";
604         AllLines = P.second;
605
606         uint32_t BlockNo = 0;
607         uint32_t EdgeNo = 0;
608         for (BlockVector::const_iterator I = Blocks.begin(), E = Blocks.end();
609                I != E; ++I) {
610           const GCOVBlock *Block = *I;
611
612           // Only print block and branch information at the end of the block.
613           if (Block->getLastLine() != LineIndex+1)
614             continue;
615           if (Options.AllBlocks)
616             printBlockInfo(OS, *Block, LineIndex, BlockNo);
617           if (Options.BranchInfo) {
618             size_t NumEdges = Block->getNumDstEdges();
619             if (NumEdges > 1)
620               printBranchInfo(OS, *Block, FileCoverage, EdgeNo);
621             else if (Options.UncondBranch && NumEdges == 1)
622               printUncondBranchInfo(OS, EdgeNo, (*Block->dst_begin())->Count);
623           }
624         }
625       }
626     }
627     FileCoverages.push_back(std::make_pair(CoveragePath, FileCoverage));
628   }
629
630   // FIXME: There is no way to detect calls given current instrumentation.
631   if (Options.FuncCoverage)
632     printFuncCoverage();
633   printFileCoverage();
634   return;
635 }
636
637 /// printFunctionSummary - Print function and block summary.
638 void FileInfo::printFunctionSummary(raw_ostream &OS,
639                                     const FunctionVector &Funcs) const {
640   for (FunctionVector::const_iterator I = Funcs.begin(), E = Funcs.end();
641          I != E; ++I) {
642     const GCOVFunction *Func = *I;
643     uint64_t EntryCount = Func->getEntryCount();
644     uint32_t BlocksExec = 0;
645     for (GCOVFunction::BlockIterator I = Func->block_begin(),
646            E = Func->block_end(); I != E; ++I) {
647       const GCOVBlock &Block = **I;
648       if (Block.getNumDstEdges() && Block.getCount())
649           ++BlocksExec;
650     }
651
652     OS << "function " << Func->getName() << " called " << EntryCount
653        << " returned " << safeDiv(Func->getExitCount()*100, EntryCount)
654        << "% blocks executed "
655        << safeDiv(BlocksExec*100, Func->getNumBlocks()-1) << "%\n";
656   }
657 }
658
659 /// printBlockInfo - Output counts for each block.
660 void FileInfo::printBlockInfo(raw_ostream &OS, const GCOVBlock &Block,
661                               uint32_t LineIndex, uint32_t &BlockNo) const {
662   if (Block.getCount() == 0)
663     OS << "    $$$$$:";
664   else
665     OS << format("%9" PRIu64 ":", Block.getCount());
666   OS << format("%5u-block %2u\n", LineIndex+1, BlockNo++);
667 }
668
669 /// printBranchInfo - Print conditional branch probabilities.
670 void FileInfo::printBranchInfo(raw_ostream &OS, const GCOVBlock &Block,
671                                GCOVCoverage &Coverage, uint32_t &EdgeNo) {
672   SmallVector<uint64_t, 16> BranchCounts;
673   uint64_t TotalCounts = 0;
674   for (GCOVBlock::EdgeIterator I = Block.dst_begin(), E = Block.dst_end();
675          I != E; ++I) {
676     const GCOVEdge *Edge = *I;
677     BranchCounts.push_back(Edge->Count);
678     TotalCounts += Edge->Count;
679     if (Block.getCount()) ++Coverage.BranchesExec;
680     if (Edge->Count) ++Coverage.BranchesTaken;
681     ++Coverage.Branches;
682
683     if (Options.FuncCoverage) {
684       const GCOVFunction *Function = &Block.getParent();
685       GCOVCoverage &FuncCoverage = FuncCoverages.find(Function)->second;
686       if (Block.getCount()) ++FuncCoverage.BranchesExec;
687       if (Edge->Count) ++FuncCoverage.BranchesTaken;
688       ++FuncCoverage.Branches;
689     }
690   }
691
692   for (SmallVectorImpl<uint64_t>::const_iterator I = BranchCounts.begin(),
693          E = BranchCounts.end(); I != E; ++I) {
694     OS << format("branch %2u ", EdgeNo++)
695        << formatBranchInfo(Options, *I, TotalCounts) << "\n";
696   }
697 }
698
699 /// printUncondBranchInfo - Print unconditional branch probabilities.
700 void FileInfo::printUncondBranchInfo(raw_ostream &OS, uint32_t &EdgeNo,
701                                      uint64_t Count) const {
702   OS << format("unconditional %2u ", EdgeNo++)
703      << formatBranchInfo(Options, Count, Count) << "\n";
704 }
705
706 // printCoverage - Print generic coverage info used by both printFuncCoverage
707 // and printFileCoverage.
708 void FileInfo::printCoverage(const GCOVCoverage &Coverage) const {
709   outs() << format("Lines executed:%.2f%% of %u\n",
710                    double(Coverage.LinesExec)*100/Coverage.LogicalLines,
711                    Coverage.LogicalLines);
712   if (Options.BranchInfo) {
713     if (Coverage.Branches) {
714       outs() << format("Branches executed:%.2f%% of %u\n",
715                        double(Coverage.BranchesExec)*100/Coverage.Branches,
716                        Coverage.Branches);
717       outs() << format("Taken at least once:%.2f%% of %u\n",
718                        double(Coverage.BranchesTaken)*100/Coverage.Branches,
719                        Coverage.Branches);
720     } else {
721       outs() << "No branches\n";
722     }
723     outs() << "No calls\n"; // to be consistent with gcov
724   }
725 }
726
727 // printFuncCoverage - Print per-function coverage info.
728 void FileInfo::printFuncCoverage() const {
729   for (FuncCoverageMap::const_iterator I = FuncCoverages.begin(),
730                                        E = FuncCoverages.end(); I != E; ++I) {
731     const GCOVCoverage &Coverage = I->second;
732     outs() << "Function '" << Coverage.Name << "'\n";
733     printCoverage(Coverage);
734     outs() << "\n";
735   }
736 }
737
738 // printFileCoverage - Print per-file coverage info.
739 void FileInfo::printFileCoverage() const {
740   for (FileCoverageList::const_iterator I = FileCoverages.begin(),
741                                         E = FileCoverages.end(); I != E; ++I) {
742     const std::string &Filename = I->first;
743     const GCOVCoverage &Coverage = I->second;
744     outs() << "File '" << Coverage.Name << "'\n";
745     printCoverage(Coverage);
746     if (!Options.NoOutput)
747       outs() << Coverage.Name << ":creating '" << Filename << "'\n";
748     outs() << "\n";
749   }
750 }