CoverageMappingWriter.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. //===- CoverageMappingWriter.cpp - Code coverage mapping writer -----------===//
  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. // This file contains support for writing coverage mapping data for
  10. // instrumentation based coverage.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/ProfileData/InstrProf.h"
  14. #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/Support/Compression.h"
  18. #include "llvm/Support/LEB128.h"
  19. #include "llvm/Support/raw_ostream.h"
  20. #include <algorithm>
  21. #include <cassert>
  22. #include <limits>
  23. #include <vector>
  24. using namespace llvm;
  25. using namespace coverage;
  26. CoverageFilenamesSectionWriter::CoverageFilenamesSectionWriter(
  27. ArrayRef<std::string> Filenames)
  28. : Filenames(Filenames) {
  29. #ifndef NDEBUG
  30. StringSet<> NameSet;
  31. for (StringRef Name : Filenames)
  32. assert(NameSet.insert(Name).second && "Duplicate filename");
  33. #endif
  34. }
  35. void CoverageFilenamesSectionWriter::write(raw_ostream &OS, bool Compress) {
  36. std::string FilenamesStr;
  37. {
  38. raw_string_ostream FilenamesOS{FilenamesStr};
  39. for (const auto &Filename : Filenames) {
  40. encodeULEB128(Filename.size(), FilenamesOS);
  41. FilenamesOS << Filename;
  42. }
  43. }
  44. SmallVector<uint8_t, 128> CompressedStr;
  45. bool doCompression = Compress && compression::zlib::isAvailable() &&
  46. DoInstrProfNameCompression;
  47. if (doCompression)
  48. compression::zlib::compress(arrayRefFromStringRef(FilenamesStr),
  49. CompressedStr,
  50. compression::zlib::BestSizeCompression);
  51. // ::= <num-filenames>
  52. // <uncompressed-len>
  53. // <compressed-len-or-zero>
  54. // (<compressed-filenames> | <uncompressed-filenames>)
  55. encodeULEB128(Filenames.size(), OS);
  56. encodeULEB128(FilenamesStr.size(), OS);
  57. encodeULEB128(doCompression ? CompressedStr.size() : 0U, OS);
  58. OS << (doCompression ? toStringRef(CompressedStr) : StringRef(FilenamesStr));
  59. }
  60. namespace {
  61. /// Gather only the expressions that are used by the mapping
  62. /// regions in this function.
  63. class CounterExpressionsMinimizer {
  64. ArrayRef<CounterExpression> Expressions;
  65. SmallVector<CounterExpression, 16> UsedExpressions;
  66. std::vector<unsigned> AdjustedExpressionIDs;
  67. public:
  68. CounterExpressionsMinimizer(ArrayRef<CounterExpression> Expressions,
  69. ArrayRef<CounterMappingRegion> MappingRegions)
  70. : Expressions(Expressions) {
  71. AdjustedExpressionIDs.resize(Expressions.size(), 0);
  72. for (const auto &I : MappingRegions) {
  73. mark(I.Count);
  74. mark(I.FalseCount);
  75. }
  76. for (const auto &I : MappingRegions) {
  77. gatherUsed(I.Count);
  78. gatherUsed(I.FalseCount);
  79. }
  80. }
  81. void mark(Counter C) {
  82. if (!C.isExpression())
  83. return;
  84. unsigned ID = C.getExpressionID();
  85. AdjustedExpressionIDs[ID] = 1;
  86. mark(Expressions[ID].LHS);
  87. mark(Expressions[ID].RHS);
  88. }
  89. void gatherUsed(Counter C) {
  90. if (!C.isExpression() || !AdjustedExpressionIDs[C.getExpressionID()])
  91. return;
  92. AdjustedExpressionIDs[C.getExpressionID()] = UsedExpressions.size();
  93. const auto &E = Expressions[C.getExpressionID()];
  94. UsedExpressions.push_back(E);
  95. gatherUsed(E.LHS);
  96. gatherUsed(E.RHS);
  97. }
  98. ArrayRef<CounterExpression> getExpressions() const { return UsedExpressions; }
  99. /// Adjust the given counter to correctly transition from the old
  100. /// expression ids to the new expression ids.
  101. Counter adjust(Counter C) const {
  102. if (C.isExpression())
  103. C = Counter::getExpression(AdjustedExpressionIDs[C.getExpressionID()]);
  104. return C;
  105. }
  106. };
  107. } // end anonymous namespace
  108. /// Encode the counter.
  109. ///
  110. /// The encoding uses the following format:
  111. /// Low 2 bits - Tag:
  112. /// Counter::Zero(0) - A Counter with kind Counter::Zero
  113. /// Counter::CounterValueReference(1) - A counter with kind
  114. /// Counter::CounterValueReference
  115. /// Counter::Expression(2) + CounterExpression::Subtract(0) -
  116. /// A counter with kind Counter::Expression and an expression
  117. /// with kind CounterExpression::Subtract
  118. /// Counter::Expression(2) + CounterExpression::Add(1) -
  119. /// A counter with kind Counter::Expression and an expression
  120. /// with kind CounterExpression::Add
  121. /// Remaining bits - Counter/Expression ID.
  122. static unsigned encodeCounter(ArrayRef<CounterExpression> Expressions,
  123. Counter C) {
  124. unsigned Tag = unsigned(C.getKind());
  125. if (C.isExpression())
  126. Tag += Expressions[C.getExpressionID()].Kind;
  127. unsigned ID = C.getCounterID();
  128. assert(ID <=
  129. (std::numeric_limits<unsigned>::max() >> Counter::EncodingTagBits));
  130. return Tag | (ID << Counter::EncodingTagBits);
  131. }
  132. static void writeCounter(ArrayRef<CounterExpression> Expressions, Counter C,
  133. raw_ostream &OS) {
  134. encodeULEB128(encodeCounter(Expressions, C), OS);
  135. }
  136. void CoverageMappingWriter::write(raw_ostream &OS) {
  137. // Check that we don't have any bogus regions.
  138. assert(all_of(MappingRegions,
  139. [](const CounterMappingRegion &CMR) {
  140. return CMR.startLoc() <= CMR.endLoc();
  141. }) &&
  142. "Source region does not begin before it ends");
  143. // Sort the regions in an ascending order by the file id and the starting
  144. // location. Sort by region kinds to ensure stable order for tests.
  145. llvm::stable_sort(MappingRegions, [](const CounterMappingRegion &LHS,
  146. const CounterMappingRegion &RHS) {
  147. if (LHS.FileID != RHS.FileID)
  148. return LHS.FileID < RHS.FileID;
  149. if (LHS.startLoc() != RHS.startLoc())
  150. return LHS.startLoc() < RHS.startLoc();
  151. return LHS.Kind < RHS.Kind;
  152. });
  153. // Write out the fileid -> filename mapping.
  154. encodeULEB128(VirtualFileMapping.size(), OS);
  155. for (const auto &FileID : VirtualFileMapping)
  156. encodeULEB128(FileID, OS);
  157. // Write out the expressions.
  158. CounterExpressionsMinimizer Minimizer(Expressions, MappingRegions);
  159. auto MinExpressions = Minimizer.getExpressions();
  160. encodeULEB128(MinExpressions.size(), OS);
  161. for (const auto &E : MinExpressions) {
  162. writeCounter(MinExpressions, Minimizer.adjust(E.LHS), OS);
  163. writeCounter(MinExpressions, Minimizer.adjust(E.RHS), OS);
  164. }
  165. // Write out the mapping regions.
  166. // Split the regions into subarrays where each region in a
  167. // subarray has a fileID which is the index of that subarray.
  168. unsigned PrevLineStart = 0;
  169. unsigned CurrentFileID = ~0U;
  170. for (auto I = MappingRegions.begin(), E = MappingRegions.end(); I != E; ++I) {
  171. if (I->FileID != CurrentFileID) {
  172. // Ensure that all file ids have at least one mapping region.
  173. assert(I->FileID == (CurrentFileID + 1));
  174. // Find the number of regions with this file id.
  175. unsigned RegionCount = 1;
  176. for (auto J = I + 1; J != E && I->FileID == J->FileID; ++J)
  177. ++RegionCount;
  178. // Start a new region sub-array.
  179. encodeULEB128(RegionCount, OS);
  180. CurrentFileID = I->FileID;
  181. PrevLineStart = 0;
  182. }
  183. Counter Count = Minimizer.adjust(I->Count);
  184. Counter FalseCount = Minimizer.adjust(I->FalseCount);
  185. switch (I->Kind) {
  186. case CounterMappingRegion::CodeRegion:
  187. case CounterMappingRegion::GapRegion:
  188. writeCounter(MinExpressions, Count, OS);
  189. break;
  190. case CounterMappingRegion::ExpansionRegion: {
  191. assert(Count.isZero());
  192. assert(I->ExpandedFileID <=
  193. (std::numeric_limits<unsigned>::max() >>
  194. Counter::EncodingCounterTagAndExpansionRegionTagBits));
  195. // Mark an expansion region with a set bit that follows the counter tag,
  196. // and pack the expanded file id into the remaining bits.
  197. unsigned EncodedTagExpandedFileID =
  198. (1 << Counter::EncodingTagBits) |
  199. (I->ExpandedFileID
  200. << Counter::EncodingCounterTagAndExpansionRegionTagBits);
  201. encodeULEB128(EncodedTagExpandedFileID, OS);
  202. break;
  203. }
  204. case CounterMappingRegion::SkippedRegion:
  205. assert(Count.isZero());
  206. encodeULEB128(unsigned(I->Kind)
  207. << Counter::EncodingCounterTagAndExpansionRegionTagBits,
  208. OS);
  209. break;
  210. case CounterMappingRegion::BranchRegion:
  211. encodeULEB128(unsigned(I->Kind)
  212. << Counter::EncodingCounterTagAndExpansionRegionTagBits,
  213. OS);
  214. writeCounter(MinExpressions, Count, OS);
  215. writeCounter(MinExpressions, FalseCount, OS);
  216. break;
  217. }
  218. assert(I->LineStart >= PrevLineStart);
  219. encodeULEB128(I->LineStart - PrevLineStart, OS);
  220. encodeULEB128(I->ColumnStart, OS);
  221. assert(I->LineEnd >= I->LineStart);
  222. encodeULEB128(I->LineEnd - I->LineStart, OS);
  223. encodeULEB128(I->ColumnEnd, OS);
  224. PrevLineStart = I->LineStart;
  225. }
  226. // Ensure that all file ids have at least one mapping region.
  227. assert(CurrentFileID == (VirtualFileMapping.size() - 1));
  228. }