1 //===- GCOV.cpp - LLVM coverage tool --------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // GCOV implements the interface to read and write coverage files that use
10 // 'gcov' format.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/ProfileData/GCOV.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/Config/llvm-config.h"
17 #include "llvm/Demangle/Demangle.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/MD5.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include <algorithm>
25 #include <system_error>
26 
27 using namespace llvm;
28 
29 enum : uint32_t {
30   GCOV_ARC_ON_TREE = 1 << 0,
31   GCOV_ARC_FALLTHROUGH = 1 << 2,
32 
33   GCOV_TAG_FUNCTION = 0x01000000,
34   GCOV_TAG_BLOCKS = 0x01410000,
35   GCOV_TAG_ARCS = 0x01430000,
36   GCOV_TAG_LINES = 0x01450000,
37   GCOV_TAG_COUNTER_ARCS = 0x01a10000,
38   // GCOV_TAG_OBJECT_SUMMARY superseded GCOV_TAG_PROGRAM_SUMMARY in GCC 9.
39   GCOV_TAG_OBJECT_SUMMARY = 0xa1000000,
40   GCOV_TAG_PROGRAM_SUMMARY = 0xa3000000,
41 };
42 
43 namespace {
44 struct Summary {
45   Summary(StringRef Name) : Name(Name) {}
46 
47   StringRef Name;
48   uint64_t lines = 0;
49   uint64_t linesExec = 0;
50   uint64_t branches = 0;
51   uint64_t branchesExec = 0;
52   uint64_t branchesTaken = 0;
53 };
54 
55 struct LineInfo {
56   SmallVector<const GCOVBlock *, 1> blocks;
57   uint64_t count = 0;
58   bool exists = false;
59 };
60 
61 struct SourceInfo {
62   StringRef filename;
63   SmallString<0> displayName;
64   std::vector<std::vector<const GCOVFunction *>> startLineToFunctions;
65   std::vector<LineInfo> lines;
66   bool ignored = false;
67   SourceInfo(StringRef filename) : filename(filename) {}
68 };
69 
70 class Context {
71 public:
72   Context(const GCOV::Options &Options) : options(Options) {}
73   void print(StringRef filename, StringRef gcno, StringRef gcda,
74              GCOVFile &file);
75 
76 private:
77   std::string getCoveragePath(StringRef filename, StringRef mainFilename) const;
78   void printFunctionDetails(const GCOVFunction &f, raw_ostream &os) const;
79   void printBranchInfo(const GCOVBlock &Block, uint32_t &edgeIdx,
80                        raw_ostream &OS) const;
81   void printSummary(const Summary &summary, raw_ostream &os) const;
82 
83   void collectFunction(GCOVFunction &f, Summary &summary);
84   void collectSourceLine(SourceInfo &si, Summary *summary, LineInfo &line,
85                          size_t lineNum) const;
86   void collectSource(SourceInfo &si, Summary &summary) const;
87   void annotateSource(SourceInfo &si, const GCOVFile &file, StringRef gcno,
88                       StringRef gcda, raw_ostream &os) const;
89   void printSourceToIntermediate(const SourceInfo &si, raw_ostream &os) const;
90 
91   const GCOV::Options &options;
92   std::vector<SourceInfo> sources;
93 };
94 } // namespace
95 
96 //===----------------------------------------------------------------------===//
97 // GCOVFile implementation.
98 
99 /// readGCNO - Read GCNO buffer.
100 bool GCOVFile::readGCNO(GCOVBuffer &buf) {
101   if (!buf.readGCNOFormat())
102     return false;
103   if (!buf.readGCOVVersion(version))
104     return false;
105 
106   checksum = buf.getWord();
107   if (version >= GCOV::V900 && !buf.readString(cwd))
108     return false;
109   if (version >= GCOV::V800)
110     buf.getWord(); // hasUnexecutedBlocks
111 
112   uint32_t tag, length;
113   GCOVFunction *fn = nullptr;
114   while ((tag = buf.getWord())) {
115     if (!buf.readInt(length))
116       return false;
117     uint32_t pos = buf.cursor.tell();
118     if (tag == GCOV_TAG_FUNCTION) {
119       functions.push_back(std::make_unique<GCOVFunction>(*this));
120       fn = functions.back().get();
121       fn->ident = buf.getWord();
122       fn->linenoChecksum = buf.getWord();
123       if (version >= GCOV::V407)
124         fn->cfgChecksum = buf.getWord();
125       buf.readString(fn->Name);
126       StringRef filename;
127       if (version < GCOV::V800) {
128         if (!buf.readString(filename))
129           return false;
130         fn->startLine = buf.getWord();
131       } else {
132         fn->artificial = buf.getWord();
133         if (!buf.readString(filename))
134           return false;
135         fn->startLine = buf.getWord();
136         fn->startColumn = buf.getWord();
137         fn->endLine = buf.getWord();
138         if (version >= GCOV::V900)
139           fn->endColumn = buf.getWord();
140       }
141       auto r = filenameToIdx.try_emplace(filename, filenameToIdx.size());
142       if (r.second)
143         filenames.emplace_back(filename);
144       fn->srcIdx = r.first->second;
145       identToFunction[fn->ident] = fn;
146     } else if (tag == GCOV_TAG_BLOCKS && fn) {
147       if (version < GCOV::V800) {
148         for (uint32_t i = 0; i != length; ++i) {
149           buf.getWord(); // Ignored block flags
150           fn->blocks.push_back(std::make_unique<GCOVBlock>(i));
151         }
152       } else {
153         uint32_t num = buf.getWord();
154         for (uint32_t i = 0; i != num; ++i)
155           fn->blocks.push_back(std::make_unique<GCOVBlock>(i));
156       }
157     } else if (tag == GCOV_TAG_ARCS && fn) {
158       uint32_t srcNo = buf.getWord();
159       if (srcNo >= fn->blocks.size()) {
160         errs() << "unexpected block number: " << srcNo << " (in "
161                << fn->blocks.size() << ")\n";
162         return false;
163       }
164       GCOVBlock *src = fn->blocks[srcNo].get();
165       const uint32_t e =
166           version >= GCOV::V1200 ? (length / 4 - 1) / 2 : (length - 1) / 2;
167       for (uint32_t i = 0; i != e; ++i) {
168         uint32_t dstNo = buf.getWord(), flags = buf.getWord();
169         GCOVBlock *dst = fn->blocks[dstNo].get();
170         auto arc = std::make_unique<GCOVArc>(*src, *dst, flags);
171         src->addDstEdge(arc.get());
172         dst->addSrcEdge(arc.get());
173         if (arc->onTree())
174           fn->treeArcs.push_back(std::move(arc));
175         else
176           fn->arcs.push_back(std::move(arc));
177       }
178     } else if (tag == GCOV_TAG_LINES && fn) {
179       uint32_t srcNo = buf.getWord();
180       if (srcNo >= fn->blocks.size()) {
181         errs() << "unexpected block number: " << srcNo << " (in "
182                << fn->blocks.size() << ")\n";
183         return false;
184       }
185       GCOVBlock &Block = *fn->blocks[srcNo];
186       for (;;) {
187         uint32_t line = buf.getWord();
188         if (line)
189           Block.addLine(line);
190         else {
191           StringRef filename;
192           buf.readString(filename);
193           if (filename.empty())
194             break;
195           // TODO Unhandled
196         }
197       }
198     }
199     pos += version >= GCOV::V1200 ? length : 4 * length;
200     if (pos < buf.cursor.tell())
201       return false;
202     buf.de.skip(buf.cursor, pos - buf.cursor.tell());
203   }
204 
205   GCNOInitialized = true;
206   return true;
207 }
208 
209 /// readGCDA - Read GCDA buffer. It is required that readGCDA() can only be
210 /// called after readGCNO().
211 bool GCOVFile::readGCDA(GCOVBuffer &buf) {
212   assert(GCNOInitialized && "readGCDA() can only be called after readGCNO()");
213   if (!buf.readGCDAFormat())
214     return false;
215   GCOV::GCOVVersion GCDAVersion;
216   if (!buf.readGCOVVersion(GCDAVersion))
217     return false;
218   if (version != GCDAVersion) {
219     errs() << "GCOV versions do not match.\n";
220     return false;
221   }
222 
223   uint32_t GCDAChecksum;
224   if (!buf.readInt(GCDAChecksum))
225     return false;
226   if (checksum != GCDAChecksum) {
227     errs() << "file checksums do not match: " << checksum
228            << " != " << GCDAChecksum << "\n";
229     return false;
230   }
231   uint32_t dummy, tag, length;
232   uint32_t ident;
233   GCOVFunction *fn = nullptr;
234   while ((tag = buf.getWord())) {
235     if (!buf.readInt(length))
236       return false;
237     uint32_t pos = buf.cursor.tell();
238     if (tag == GCOV_TAG_OBJECT_SUMMARY) {
239       buf.readInt(runCount);
240       buf.readInt(dummy);
241       // clang<11 uses a fake 4.2 format which sets length to 9.
242       if (length == 9)
243         buf.readInt(runCount);
244     } else if (tag == GCOV_TAG_PROGRAM_SUMMARY) {
245       // clang<11 uses a fake 4.2 format which sets length to 0.
246       if (length > 0) {
247         buf.readInt(dummy);
248         buf.readInt(dummy);
249         buf.readInt(runCount);
250       }
251       ++programCount;
252     } else if (tag == GCOV_TAG_FUNCTION) {
253       if (length == 0) // Placeholder
254         continue;
255       // As of GCC 10, GCOV_TAG_FUNCTION_LENGTH has never been larger than 3.
256       // However, clang<11 uses a fake 4.2 format which may set length larger
257       // than 3.
258       if (length < 2 || !buf.readInt(ident))
259         return false;
260       auto It = identToFunction.find(ident);
261       uint32_t linenoChecksum, cfgChecksum = 0;
262       buf.readInt(linenoChecksum);
263       if (version >= GCOV::V407)
264         buf.readInt(cfgChecksum);
265       if (It != identToFunction.end()) {
266         fn = It->second;
267         if (linenoChecksum != fn->linenoChecksum ||
268             cfgChecksum != fn->cfgChecksum) {
269           errs() << fn->Name
270                  << format(": checksum mismatch, (%u, %u) != (%u, %u)\n",
271                            linenoChecksum, cfgChecksum, fn->linenoChecksum,
272                            fn->cfgChecksum);
273           return false;
274         }
275       }
276     } else if (tag == GCOV_TAG_COUNTER_ARCS && fn) {
277       uint32_t expected = 2 * fn->arcs.size();
278       if (version >= GCOV::V1200)
279         expected *= 4;
280       if (length != expected) {
281         errs() << fn->Name
282                << format(
283                       ": GCOV_TAG_COUNTER_ARCS mismatch, got %u, expected %u\n",
284                       length, expected);
285         return false;
286       }
287       for (std::unique_ptr<GCOVArc> &arc : fn->arcs) {
288         if (!buf.readInt64(arc->count))
289           return false;
290         arc->src.count += arc->count;
291       }
292 
293       if (fn->blocks.size() >= 2) {
294         GCOVBlock &src = *fn->blocks[0];
295         GCOVBlock &sink =
296             version < GCOV::V408 ? *fn->blocks.back() : *fn->blocks[1];
297         auto arc = std::make_unique<GCOVArc>(sink, src, GCOV_ARC_ON_TREE);
298         sink.addDstEdge(arc.get());
299         src.addSrcEdge(arc.get());
300         fn->treeArcs.push_back(std::move(arc));
301 
302         for (GCOVBlock &block : fn->blocksRange())
303           fn->propagateCounts(block, nullptr);
304         for (size_t i = fn->treeArcs.size() - 1; i; --i)
305           fn->treeArcs[i - 1]->src.count += fn->treeArcs[i - 1]->count;
306       }
307     }
308     pos += version >= GCOV::V1200 ? length : 4 * length;
309     if (pos < buf.cursor.tell())
310       return false;
311     buf.de.skip(buf.cursor, pos - buf.cursor.tell());
312   }
313 
314   return true;
315 }
316 
317 void GCOVFile::print(raw_ostream &OS) const {
318   for (const GCOVFunction &f : *this)
319     f.print(OS);
320 }
321 
322 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
323 /// dump - Dump GCOVFile content to dbgs() for debugging purposes.
324 LLVM_DUMP_METHOD void GCOVFile::dump() const { print(dbgs()); }
325 #endif
326 
327 bool GCOVArc::onTree() const { return flags & GCOV_ARC_ON_TREE; }
328 
329 //===----------------------------------------------------------------------===//
330 // GCOVFunction implementation.
331 
332 StringRef GCOVFunction::getName(bool demangle) const {
333   if (!demangle)
334     return Name;
335   if (demangled.empty()) {
336     do {
337       if (Name.startswith("_Z")) {
338         int status = 0;
339         // Name is guaranteed to be NUL-terminated.
340         char *res = itaniumDemangle(Name.data(), nullptr, nullptr, &status);
341         if (status == 0) {
342           demangled = res;
343           free(res);
344           break;
345         }
346       }
347       demangled = Name;
348     } while (false);
349   }
350   return demangled;
351 }
352 StringRef GCOVFunction::getFilename() const { return file.filenames[srcIdx]; }
353 
354 /// getEntryCount - Get the number of times the function was called by
355 /// retrieving the entry block's count.
356 uint64_t GCOVFunction::getEntryCount() const {
357   return blocks.front()->getCount();
358 }
359 
360 GCOVBlock &GCOVFunction::getExitBlock() const {
361   return file.getVersion() < GCOV::V408 ? *blocks.back() : *blocks[1];
362 }
363 
364 // For each basic block, the sum of incoming edge counts equals the sum of
365 // outgoing edge counts by Kirchoff's circuit law. If the unmeasured arcs form a
366 // spanning tree, the count for each unmeasured arc (GCOV_ARC_ON_TREE) can be
367 // uniquely identified.
368 uint64_t GCOVFunction::propagateCounts(const GCOVBlock &v, GCOVArc *pred) {
369   // If GCOV_ARC_ON_TREE edges do form a tree, visited is not needed; otherwise
370   // this prevents infinite recursion.
371   if (!visited.insert(&v).second)
372     return 0;
373 
374   uint64_t excess = 0;
375   for (GCOVArc *e : v.srcs())
376     if (e != pred)
377       excess += e->onTree() ? propagateCounts(e->src, e) : e->count;
378   for (GCOVArc *e : v.dsts())
379     if (e != pred)
380       excess -= e->onTree() ? propagateCounts(e->dst, e) : e->count;
381   if (int64_t(excess) < 0)
382     excess = -excess;
383   if (pred)
384     pred->count = excess;
385   return excess;
386 }
387 
388 void GCOVFunction::print(raw_ostream &OS) const {
389   OS << "===== " << Name << " (" << ident << ") @ " << getFilename() << ":"
390      << startLine << "\n";
391   for (const auto &Block : blocks)
392     Block->print(OS);
393 }
394 
395 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
396 /// dump - Dump GCOVFunction content to dbgs() for debugging purposes.
397 LLVM_DUMP_METHOD void GCOVFunction::dump() const { print(dbgs()); }
398 #endif
399 
400 /// collectLineCounts - Collect line counts. This must be used after
401 /// reading .gcno and .gcda files.
402 
403 //===----------------------------------------------------------------------===//
404 // GCOVBlock implementation.
405 
406 void GCOVBlock::print(raw_ostream &OS) const {
407   OS << "Block : " << number << " Counter : " << count << "\n";
408   if (!pred.empty()) {
409     OS << "\tSource Edges : ";
410     for (const GCOVArc *Edge : pred)
411       OS << Edge->src.number << " (" << Edge->count << "), ";
412     OS << "\n";
413   }
414   if (!succ.empty()) {
415     OS << "\tDestination Edges : ";
416     for (const GCOVArc *Edge : succ) {
417       if (Edge->flags & GCOV_ARC_ON_TREE)
418         OS << '*';
419       OS << Edge->dst.number << " (" << Edge->count << "), ";
420     }
421     OS << "\n";
422   }
423   if (!lines.empty()) {
424     OS << "\tLines : ";
425     for (uint32_t N : lines)
426       OS << (N) << ",";
427     OS << "\n";
428   }
429 }
430 
431 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
432 /// dump - Dump GCOVBlock content to dbgs() for debugging purposes.
433 LLVM_DUMP_METHOD void GCOVBlock::dump() const { print(dbgs()); }
434 #endif
435 
436 uint64_t
437 GCOVBlock::augmentOneCycle(GCOVBlock *src,
438                            std::vector<std::pair<GCOVBlock *, size_t>> &stack) {
439   GCOVBlock *u;
440   size_t i;
441   stack.clear();
442   stack.emplace_back(src, 0);
443   src->incoming = (GCOVArc *)1; // Mark u available for cycle detection
444   for (;;) {
445     std::tie(u, i) = stack.back();
446     if (i == u->succ.size()) {
447       u->traversable = false;
448       stack.pop_back();
449       if (stack.empty())
450         break;
451       continue;
452     }
453     ++stack.back().second;
454     GCOVArc *succ = u->succ[i];
455     // Ignore saturated arcs (cycleCount has been reduced to 0) and visited
456     // blocks. Ignore self arcs to guard against bad input (.gcno has no
457     // self arcs).
458     if (succ->cycleCount == 0 || !succ->dst.traversable || &succ->dst == u)
459       continue;
460     if (succ->dst.incoming == nullptr) {
461       succ->dst.incoming = succ;
462       stack.emplace_back(&succ->dst, 0);
463       continue;
464     }
465     uint64_t minCount = succ->cycleCount;
466     for (GCOVBlock *v = u;;) {
467       minCount = std::min(minCount, v->incoming->cycleCount);
468       v = &v->incoming->src;
469       if (v == &succ->dst)
470         break;
471     }
472     succ->cycleCount -= minCount;
473     for (GCOVBlock *v = u;;) {
474       v->incoming->cycleCount -= minCount;
475       v = &v->incoming->src;
476       if (v == &succ->dst)
477         break;
478     }
479     return minCount;
480   }
481   return 0;
482 }
483 
484 // Get the total execution count of loops among blocks on the same line.
485 // Assuming a reducible flow graph, the count is the sum of back edge counts.
486 // Identifying loops is complex, so we simply find cycles and perform cycle
487 // cancelling iteratively.
488 uint64_t GCOVBlock::getCyclesCount(const BlockVector &blocks) {
489   std::vector<std::pair<GCOVBlock *, size_t>> stack;
490   uint64_t count = 0, d;
491   for (;;) {
492     // Make blocks on the line traversable and try finding a cycle.
493     for (auto b : blocks) {
494       const_cast<GCOVBlock *>(b)->traversable = true;
495       const_cast<GCOVBlock *>(b)->incoming = nullptr;
496     }
497     d = 0;
498     for (auto block : blocks) {
499       auto *b = const_cast<GCOVBlock *>(block);
500       if (b->traversable && (d = augmentOneCycle(b, stack)) > 0)
501         break;
502     }
503     if (d == 0)
504       break;
505     count += d;
506   }
507   // If there is no more loop, all traversable bits should have been cleared.
508   // This property is needed by subsequent calls.
509   for (auto b : blocks) {
510     assert(!b->traversable);
511     (void)b;
512   }
513   return count;
514 }
515 
516 //===----------------------------------------------------------------------===//
517 // FileInfo implementation.
518 
519 // Format dividend/divisor as a percentage. Return 1 if the result is greater
520 // than 0% and less than 1%.
521 static uint32_t formatPercentage(uint64_t dividend, uint64_t divisor) {
522   if (!dividend || !divisor)
523     return 0;
524   dividend *= 100;
525   return dividend < divisor ? 1 : dividend / divisor;
526 }
527 
528 // This custom division function mimics gcov's branch ouputs:
529 //   - Round to closest whole number
530 //   - Only output 0% or 100% if it's exactly that value
531 static uint32_t branchDiv(uint64_t Numerator, uint64_t Divisor) {
532   if (!Numerator)
533     return 0;
534   if (Numerator == Divisor)
535     return 100;
536 
537   uint8_t Res = (Numerator * 100 + Divisor / 2) / Divisor;
538   if (Res == 0)
539     return 1;
540   if (Res == 100)
541     return 99;
542   return Res;
543 }
544 
545 namespace {
546 struct formatBranchInfo {
547   formatBranchInfo(const GCOV::Options &Options, uint64_t Count, uint64_t Total)
548       : Options(Options), Count(Count), Total(Total) {}
549 
550   void print(raw_ostream &OS) const {
551     if (!Total)
552       OS << "never executed";
553     else if (Options.BranchCount)
554       OS << "taken " << Count;
555     else
556       OS << "taken " << branchDiv(Count, Total) << "%";
557   }
558 
559   const GCOV::Options &Options;
560   uint64_t Count;
561   uint64_t Total;
562 };
563 
564 static raw_ostream &operator<<(raw_ostream &OS, const formatBranchInfo &FBI) {
565   FBI.print(OS);
566   return OS;
567 }
568 
569 class LineConsumer {
570   std::unique_ptr<MemoryBuffer> Buffer;
571   StringRef Remaining;
572 
573 public:
574   LineConsumer() = default;
575   LineConsumer(StringRef Filename) {
576     // Open source files without requiring a NUL terminator. The concurrent
577     // modification may nullify the NUL terminator condition.
578     ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
579         MemoryBuffer::getFileOrSTDIN(Filename, /*IsText=*/false,
580                                      /*RequiresNullTerminator=*/false);
581     if (std::error_code EC = BufferOrErr.getError()) {
582       errs() << Filename << ": " << EC.message() << "\n";
583       Remaining = "";
584     } else {
585       Buffer = std::move(BufferOrErr.get());
586       Remaining = Buffer->getBuffer();
587     }
588   }
589   bool empty() { return Remaining.empty(); }
590   void printNext(raw_ostream &OS, uint32_t LineNum) {
591     StringRef Line;
592     if (empty())
593       Line = "/*EOF*/";
594     else
595       std::tie(Line, Remaining) = Remaining.split("\n");
596     OS << format("%5u:", LineNum) << Line << "\n";
597   }
598 };
599 } // end anonymous namespace
600 
601 /// Convert a path to a gcov filename. If PreservePaths is true, this
602 /// translates "/" to "#", ".." to "^", and drops ".", to match gcov.
603 static std::string mangleCoveragePath(StringRef Filename, bool PreservePaths) {
604   if (!PreservePaths)
605     return sys::path::filename(Filename).str();
606 
607   // This behaviour is defined by gcov in terms of text replacements, so it's
608   // not likely to do anything useful on filesystems with different textual
609   // conventions.
610   llvm::SmallString<256> Result("");
611   StringRef::iterator I, S, E;
612   for (I = S = Filename.begin(), E = Filename.end(); I != E; ++I) {
613     if (*I != '/')
614       continue;
615 
616     if (I - S == 1 && *S == '.') {
617       // ".", the current directory, is skipped.
618     } else if (I - S == 2 && *S == '.' && *(S + 1) == '.') {
619       // "..", the parent directory, is replaced with "^".
620       Result.append("^#");
621     } else {
622       if (S < I)
623         // Leave other components intact,
624         Result.append(S, I);
625       // And separate with "#".
626       Result.push_back('#');
627     }
628     S = I + 1;
629   }
630 
631   if (S < I)
632     Result.append(S, I);
633   return std::string(Result.str());
634 }
635 
636 std::string Context::getCoveragePath(StringRef filename,
637                                      StringRef mainFilename) const {
638   if (options.NoOutput)
639     // This is probably a bug in gcov, but when -n is specified, paths aren't
640     // mangled at all, and the -l and -p options are ignored. Here, we do the
641     // same.
642     return std::string(filename);
643 
644   std::string CoveragePath;
645   if (options.LongFileNames && !filename.equals(mainFilename))
646     CoveragePath =
647         mangleCoveragePath(mainFilename, options.PreservePaths) + "##";
648   CoveragePath += mangleCoveragePath(filename, options.PreservePaths);
649   if (options.HashFilenames) {
650     MD5 Hasher;
651     MD5::MD5Result Result;
652     Hasher.update(filename.str());
653     Hasher.final(Result);
654     CoveragePath += "##" + std::string(Result.digest());
655   }
656   CoveragePath += ".gcov";
657   return CoveragePath;
658 }
659 
660 void Context::collectFunction(GCOVFunction &f, Summary &summary) {
661   SourceInfo &si = sources[f.srcIdx];
662   if (f.startLine >= si.startLineToFunctions.size())
663     si.startLineToFunctions.resize(f.startLine + 1);
664   si.startLineToFunctions[f.startLine].push_back(&f);
665   for (const GCOVBlock &b : f.blocksRange()) {
666     if (b.lines.empty())
667       continue;
668     uint32_t maxLineNum = *std::max_element(b.lines.begin(), b.lines.end());
669     if (maxLineNum >= si.lines.size())
670       si.lines.resize(maxLineNum + 1);
671     for (uint32_t lineNum : b.lines) {
672       LineInfo &line = si.lines[lineNum];
673       if (!line.exists)
674         ++summary.lines;
675       if (line.count == 0 && b.count)
676         ++summary.linesExec;
677       line.exists = true;
678       line.count += b.count;
679       line.blocks.push_back(&b);
680     }
681   }
682 }
683 
684 void Context::collectSourceLine(SourceInfo &si, Summary *summary,
685                                 LineInfo &line, size_t lineNum) const {
686   uint64_t count = 0;
687   for (const GCOVBlock *b : line.blocks) {
688     if (b->number == 0) {
689       // For nonstandard control flows, arcs into the exit block may be
690       // duplicately counted (fork) or not be counted (abnormal exit), and thus
691       // the (exit,entry) counter may be inaccurate. Count the entry block with
692       // the outgoing arcs.
693       for (const GCOVArc *arc : b->succ)
694         count += arc->count;
695     } else {
696       // Add counts from predecessors that are not on the same line.
697       for (const GCOVArc *arc : b->pred)
698         if (!llvm::is_contained(line.blocks, &arc->src))
699           count += arc->count;
700     }
701     for (GCOVArc *arc : b->succ)
702       arc->cycleCount = arc->count;
703   }
704 
705   count += GCOVBlock::getCyclesCount(line.blocks);
706   line.count = count;
707   if (line.exists) {
708     ++summary->lines;
709     if (line.count != 0)
710       ++summary->linesExec;
711   }
712 
713   if (options.BranchInfo)
714     for (const GCOVBlock *b : line.blocks) {
715       if (b->getLastLine() != lineNum)
716         continue;
717       int branches = 0, execBranches = 0, takenBranches = 0;
718       for (const GCOVArc *arc : b->succ) {
719         ++branches;
720         if (count != 0)
721           ++execBranches;
722         if (arc->count != 0)
723           ++takenBranches;
724       }
725       if (branches > 1) {
726         summary->branches += branches;
727         summary->branchesExec += execBranches;
728         summary->branchesTaken += takenBranches;
729       }
730     }
731 }
732 
733 void Context::collectSource(SourceInfo &si, Summary &summary) const {
734   size_t lineNum = 0;
735   for (LineInfo &line : si.lines) {
736     collectSourceLine(si, &summary, line, lineNum);
737     ++lineNum;
738   }
739 }
740 
741 void Context::annotateSource(SourceInfo &si, const GCOVFile &file,
742                              StringRef gcno, StringRef gcda,
743                              raw_ostream &os) const {
744   auto source =
745       options.Intermediate ? LineConsumer() : LineConsumer(si.filename);
746 
747   os << "        -:    0:Source:" << si.displayName << '\n';
748   os << "        -:    0:Graph:" << gcno << '\n';
749   os << "        -:    0:Data:" << gcda << '\n';
750   os << "        -:    0:Runs:" << file.runCount << '\n';
751   if (file.version < GCOV::V900)
752     os << "        -:    0:Programs:" << file.programCount << '\n';
753 
754   for (size_t lineNum = 1; !source.empty(); ++lineNum) {
755     if (lineNum >= si.lines.size()) {
756       os << "        -:";
757       source.printNext(os, lineNum);
758       continue;
759     }
760 
761     const LineInfo &line = si.lines[lineNum];
762     if (options.BranchInfo && lineNum < si.startLineToFunctions.size())
763       for (const auto *f : si.startLineToFunctions[lineNum])
764         printFunctionDetails(*f, os);
765     if (!line.exists)
766       os << "        -:";
767     else if (line.count == 0)
768       os << "    #####:";
769     else
770       os << format("%9" PRIu64 ":", line.count);
771     source.printNext(os, lineNum);
772 
773     uint32_t blockIdx = 0, edgeIdx = 0;
774     for (const GCOVBlock *b : line.blocks) {
775       if (b->getLastLine() != lineNum)
776         continue;
777       if (options.AllBlocks) {
778         if (b->getCount() == 0)
779           os << "    $$$$$:";
780         else
781           os << format("%9" PRIu64 ":", b->count);
782         os << format("%5u-block %2u\n", lineNum, blockIdx++);
783       }
784       if (options.BranchInfo) {
785         size_t NumEdges = b->succ.size();
786         if (NumEdges > 1)
787           printBranchInfo(*b, edgeIdx, os);
788         else if (options.UncondBranch && NumEdges == 1) {
789           uint64_t count = b->succ[0]->count;
790           os << format("unconditional %2u ", edgeIdx++)
791              << formatBranchInfo(options, count, count) << '\n';
792         }
793       }
794     }
795   }
796 }
797 
798 void Context::printSourceToIntermediate(const SourceInfo &si,
799                                         raw_ostream &os) const {
800   os << "file:" << si.filename << '\n';
801   for (const auto &fs : si.startLineToFunctions)
802     for (const GCOVFunction *f : fs)
803       os << "function:" << f->startLine << ',' << f->getEntryCount() << ','
804          << f->getName(options.Demangle) << '\n';
805   for (size_t lineNum = 1, size = si.lines.size(); lineNum < size; ++lineNum) {
806     const LineInfo &line = si.lines[lineNum];
807     if (line.blocks.empty())
808       continue;
809     // GCC 8 (r254259) added third third field for Ada:
810     // lcount:<line>,<count>,<has_unexecuted_blocks>
811     // We don't need the third field.
812     os << "lcount:" << lineNum << ',' << line.count << '\n';
813 
814     if (!options.BranchInfo)
815       continue;
816     for (const GCOVBlock *b : line.blocks) {
817       if (b->succ.size() < 2 || b->getLastLine() != lineNum)
818         continue;
819       for (const GCOVArc *arc : b->succ) {
820         const char *type =
821             b->getCount() ? arc->count ? "taken" : "nottaken" : "notexec";
822         os << "branch:" << lineNum << ',' << type << '\n';
823       }
824     }
825   }
826 }
827 
828 void Context::print(StringRef filename, StringRef gcno, StringRef gcda,
829                     GCOVFile &file) {
830   for (StringRef filename : file.filenames) {
831     sources.emplace_back(filename);
832     SourceInfo &si = sources.back();
833     si.displayName = si.filename;
834     if (!options.SourcePrefix.empty() &&
835         sys::path::replace_path_prefix(si.displayName, options.SourcePrefix,
836                                        "") &&
837         !si.displayName.empty()) {
838       // TODO replace_path_prefix may strip the prefix even if the remaining
839       // part does not start with a separator.
840       if (sys::path::is_separator(si.displayName[0]))
841         si.displayName.erase(si.displayName.begin());
842       else
843         si.displayName = si.filename;
844     }
845     if (options.RelativeOnly && sys::path::is_absolute(si.displayName))
846       si.ignored = true;
847   }
848 
849   raw_ostream &os = llvm::outs();
850   for (GCOVFunction &f : make_pointee_range(file.functions)) {
851     Summary summary(f.getName(options.Demangle));
852     collectFunction(f, summary);
853     if (options.FuncCoverage && !options.UseStdout) {
854       os << "Function '" << summary.Name << "'\n";
855       printSummary(summary, os);
856       os << '\n';
857     }
858   }
859 
860   for (SourceInfo &si : sources) {
861     if (si.ignored)
862       continue;
863     Summary summary(si.displayName);
864     collectSource(si, summary);
865 
866     // Print file summary unless -t is specified.
867     std::string gcovName = getCoveragePath(si.filename, filename);
868     if (!options.UseStdout) {
869       os << "File '" << summary.Name << "'\n";
870       printSummary(summary, os);
871       if (!options.NoOutput && !options.Intermediate)
872         os << "Creating '" << gcovName << "'\n";
873       os << '\n';
874     }
875 
876     if (options.NoOutput || options.Intermediate)
877       continue;
878     Optional<raw_fd_ostream> os;
879     if (!options.UseStdout) {
880       std::error_code ec;
881       os.emplace(gcovName, ec, sys::fs::OF_TextWithCRLF);
882       if (ec) {
883         errs() << ec.message() << '\n';
884         continue;
885       }
886     }
887     annotateSource(si, file, gcno, gcda,
888                    options.UseStdout ? llvm::outs() : *os);
889   }
890 
891   if (options.Intermediate && !options.NoOutput) {
892     // gcov 7.* unexpectedly create multiple .gcov files, which was fixed in 8.0
893     // (PR GCC/82702). We create just one file.
894     std::string outputPath(sys::path::filename(filename));
895     std::error_code ec;
896     raw_fd_ostream os(outputPath + ".gcov", ec, sys::fs::OF_TextWithCRLF);
897     if (ec) {
898       errs() << ec.message() << '\n';
899       return;
900     }
901 
902     for (const SourceInfo &si : sources)
903       printSourceToIntermediate(si, os);
904   }
905 }
906 
907 void Context::printFunctionDetails(const GCOVFunction &f,
908                                    raw_ostream &os) const {
909   const uint64_t entryCount = f.getEntryCount();
910   uint32_t blocksExec = 0;
911   const GCOVBlock &exitBlock = f.getExitBlock();
912   uint64_t exitCount = 0;
913   for (const GCOVArc *arc : exitBlock.pred)
914     exitCount += arc->count;
915   for (const GCOVBlock &b : f.blocksRange())
916     if (b.number != 0 && &b != &exitBlock && b.getCount())
917       ++blocksExec;
918 
919   os << "function " << f.getName(options.Demangle) << " called " << entryCount
920      << " returned " << formatPercentage(exitCount, entryCount)
921      << "% blocks executed "
922      << formatPercentage(blocksExec, f.blocks.size() - 2) << "%\n";
923 }
924 
925 /// printBranchInfo - Print conditional branch probabilities.
926 void Context::printBranchInfo(const GCOVBlock &Block, uint32_t &edgeIdx,
927                               raw_ostream &os) const {
928   uint64_t total = 0;
929   for (const GCOVArc *arc : Block.dsts())
930     total += arc->count;
931   for (const GCOVArc *arc : Block.dsts())
932     os << format("branch %2u ", edgeIdx++)
933        << formatBranchInfo(options, arc->count, total) << '\n';
934 }
935 
936 void Context::printSummary(const Summary &summary, raw_ostream &os) const {
937   os << format("Lines executed:%.2f%% of %" PRIu64 "\n",
938                double(summary.linesExec) * 100 / summary.lines, summary.lines);
939   if (options.BranchInfo) {
940     if (summary.branches == 0) {
941       os << "No branches\n";
942     } else {
943       os << format("Branches executed:%.2f%% of %" PRIu64 "\n",
944                    double(summary.branchesExec) * 100 / summary.branches,
945                    summary.branches);
946       os << format("Taken at least once:%.2f%% of %" PRIu64 "\n",
947                    double(summary.branchesTaken) * 100 / summary.branches,
948                    summary.branches);
949     }
950     os << "No calls\n";
951   }
952 }
953 
954 void llvm::gcovOneInput(const GCOV::Options &options, StringRef filename,
955                         StringRef gcno, StringRef gcda, GCOVFile &file) {
956   Context fi(options);
957   fi.print(filename, gcno, gcda, file);
958 }
959