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