GCOV.cpp 30 KB

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