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