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