CoverageMapping.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  1. //===- CoverageMapping.cpp - Code coverage mapping support ----------------===//
  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. // This file contains support for clang's and llvm's instrumentation based
  11. // code coverage.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ProfileData/Coverage/CoverageMapping.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/None.h"
  18. #include "llvm/ADT/Optional.h"
  19. #include "llvm/ADT/SmallBitVector.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringRef.h"
  22. #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
  23. #include "llvm/ProfileData/InstrProfReader.h"
  24. #include "llvm/Support/Debug.h"
  25. #include "llvm/Support/Errc.h"
  26. #include "llvm/Support/Error.h"
  27. #include "llvm/Support/ErrorHandling.h"
  28. #include "llvm/Support/ManagedStatic.h"
  29. #include "llvm/Support/MemoryBuffer.h"
  30. #include "llvm/Support/raw_ostream.h"
  31. #include <algorithm>
  32. #include <cassert>
  33. #include <cstdint>
  34. #include <iterator>
  35. #include <map>
  36. #include <memory>
  37. #include <string>
  38. #include <system_error>
  39. #include <utility>
  40. #include <vector>
  41. using namespace llvm;
  42. using namespace coverage;
  43. #define DEBUG_TYPE "coverage-mapping"
  44. Counter CounterExpressionBuilder::get(const CounterExpression &E) {
  45. auto It = ExpressionIndices.find(E);
  46. if (It != ExpressionIndices.end())
  47. return Counter::getExpression(It->second);
  48. unsigned I = Expressions.size();
  49. Expressions.push_back(E);
  50. ExpressionIndices[E] = I;
  51. return Counter::getExpression(I);
  52. }
  53. void CounterExpressionBuilder::extractTerms(Counter C, int Factor,
  54. SmallVectorImpl<Term> &Terms) {
  55. switch (C.getKind()) {
  56. case Counter::Zero:
  57. break;
  58. case Counter::CounterValueReference:
  59. Terms.emplace_back(C.getCounterID(), Factor);
  60. break;
  61. case Counter::Expression:
  62. const auto &E = Expressions[C.getExpressionID()];
  63. extractTerms(E.LHS, Factor, Terms);
  64. extractTerms(
  65. E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms);
  66. break;
  67. }
  68. }
  69. Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
  70. // Gather constant terms.
  71. SmallVector<Term, 32> Terms;
  72. extractTerms(ExpressionTree, +1, Terms);
  73. // If there are no terms, this is just a zero. The algorithm below assumes at
  74. // least one term.
  75. if (Terms.size() == 0)
  76. return Counter::getZero();
  77. // Group the terms by counter ID.
  78. llvm::sort(Terms.begin(), Terms.end(), [](const Term &LHS, const Term &RHS) {
  79. return LHS.CounterID < RHS.CounterID;
  80. });
  81. // Combine terms by counter ID to eliminate counters that sum to zero.
  82. auto Prev = Terms.begin();
  83. for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
  84. if (I->CounterID == Prev->CounterID) {
  85. Prev->Factor += I->Factor;
  86. continue;
  87. }
  88. ++Prev;
  89. *Prev = *I;
  90. }
  91. Terms.erase(++Prev, Terms.end());
  92. Counter C;
  93. // Create additions. We do this before subtractions to avoid constructs like
  94. // ((0 - X) + Y), as opposed to (Y - X).
  95. for (auto T : Terms) {
  96. if (T.Factor <= 0)
  97. continue;
  98. for (int I = 0; I < T.Factor; ++I)
  99. if (C.isZero())
  100. C = Counter::getCounter(T.CounterID);
  101. else
  102. C = get(CounterExpression(CounterExpression::Add, C,
  103. Counter::getCounter(T.CounterID)));
  104. }
  105. // Create subtractions.
  106. for (auto T : Terms) {
  107. if (T.Factor >= 0)
  108. continue;
  109. for (int I = 0; I < -T.Factor; ++I)
  110. C = get(CounterExpression(CounterExpression::Subtract, C,
  111. Counter::getCounter(T.CounterID)));
  112. }
  113. return C;
  114. }
  115. Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
  116. return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
  117. }
  118. Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
  119. return simplify(
  120. get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
  121. }
  122. void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const {
  123. switch (C.getKind()) {
  124. case Counter::Zero:
  125. OS << '0';
  126. return;
  127. case Counter::CounterValueReference:
  128. OS << '#' << C.getCounterID();
  129. break;
  130. case Counter::Expression: {
  131. if (C.getExpressionID() >= Expressions.size())
  132. return;
  133. const auto &E = Expressions[C.getExpressionID()];
  134. OS << '(';
  135. dump(E.LHS, OS);
  136. OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
  137. dump(E.RHS, OS);
  138. OS << ')';
  139. break;
  140. }
  141. }
  142. if (CounterValues.empty())
  143. return;
  144. Expected<int64_t> Value = evaluate(C);
  145. if (auto E = Value.takeError()) {
  146. consumeError(std::move(E));
  147. return;
  148. }
  149. OS << '[' << *Value << ']';
  150. }
  151. Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
  152. switch (C.getKind()) {
  153. case Counter::Zero:
  154. return 0;
  155. case Counter::CounterValueReference:
  156. if (C.getCounterID() >= CounterValues.size())
  157. return errorCodeToError(errc::argument_out_of_domain);
  158. return CounterValues[C.getCounterID()];
  159. case Counter::Expression: {
  160. if (C.getExpressionID() >= Expressions.size())
  161. return errorCodeToError(errc::argument_out_of_domain);
  162. const auto &E = Expressions[C.getExpressionID()];
  163. Expected<int64_t> LHS = evaluate(E.LHS);
  164. if (!LHS)
  165. return LHS;
  166. Expected<int64_t> RHS = evaluate(E.RHS);
  167. if (!RHS)
  168. return RHS;
  169. return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
  170. }
  171. }
  172. llvm_unreachable("Unhandled CounterKind");
  173. }
  174. void FunctionRecordIterator::skipOtherFiles() {
  175. while (Current != Records.end() && !Filename.empty() &&
  176. Filename != Current->Filenames[0])
  177. ++Current;
  178. if (Current == Records.end())
  179. *this = FunctionRecordIterator();
  180. }
  181. Error CoverageMapping::loadFunctionRecord(
  182. const CoverageMappingRecord &Record,
  183. IndexedInstrProfReader &ProfileReader) {
  184. StringRef OrigFuncName = Record.FunctionName;
  185. if (OrigFuncName.empty())
  186. return make_error<CoverageMapError>(coveragemap_error::malformed);
  187. if (Record.Filenames.empty())
  188. OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
  189. else
  190. OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
  191. // Don't load records for (filenames, function) pairs we've already seen.
  192. auto FilenamesHash = hash_combine_range(Record.Filenames.begin(),
  193. Record.Filenames.end());
  194. if (!RecordProvenance[FilenamesHash].insert(hash_value(OrigFuncName)).second)
  195. return Error::success();
  196. CounterMappingContext Ctx(Record.Expressions);
  197. std::vector<uint64_t> Counts;
  198. if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName,
  199. Record.FunctionHash, Counts)) {
  200. instrprof_error IPE = InstrProfError::take(std::move(E));
  201. if (IPE == instrprof_error::hash_mismatch) {
  202. FuncHashMismatches.emplace_back(Record.FunctionName, Record.FunctionHash);
  203. return Error::success();
  204. } else if (IPE != instrprof_error::unknown_function)
  205. return make_error<InstrProfError>(IPE);
  206. Counts.assign(Record.MappingRegions.size(), 0);
  207. }
  208. Ctx.setCounts(Counts);
  209. assert(!Record.MappingRegions.empty() && "Function has no regions");
  210. FunctionRecord Function(OrigFuncName, Record.Filenames);
  211. for (const auto &Region : Record.MappingRegions) {
  212. Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
  213. if (auto E = ExecutionCount.takeError()) {
  214. consumeError(std::move(E));
  215. return Error::success();
  216. }
  217. Function.pushRegion(Region, *ExecutionCount);
  218. }
  219. if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
  220. FuncCounterMismatches.emplace_back(Record.FunctionName,
  221. Function.CountedRegions.size());
  222. return Error::success();
  223. }
  224. Functions.push_back(std::move(Function));
  225. return Error::success();
  226. }
  227. Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load(
  228. ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders,
  229. IndexedInstrProfReader &ProfileReader) {
  230. auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
  231. for (const auto &CoverageReader : CoverageReaders) {
  232. for (auto RecordOrErr : *CoverageReader) {
  233. if (Error E = RecordOrErr.takeError())
  234. return std::move(E);
  235. const auto &Record = *RecordOrErr;
  236. if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader))
  237. return std::move(E);
  238. }
  239. }
  240. return std::move(Coverage);
  241. }
  242. Expected<std::unique_ptr<CoverageMapping>>
  243. CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames,
  244. StringRef ProfileFilename, ArrayRef<StringRef> Arches) {
  245. auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
  246. if (Error E = ProfileReaderOrErr.takeError())
  247. return std::move(E);
  248. auto ProfileReader = std::move(ProfileReaderOrErr.get());
  249. SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers;
  250. SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers;
  251. for (const auto &File : llvm::enumerate(ObjectFilenames)) {
  252. auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value());
  253. if (std::error_code EC = CovMappingBufOrErr.getError())
  254. return errorCodeToError(EC);
  255. StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()];
  256. auto CoverageReaderOrErr =
  257. BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch);
  258. if (Error E = CoverageReaderOrErr.takeError())
  259. return std::move(E);
  260. Readers.push_back(std::move(CoverageReaderOrErr.get()));
  261. Buffers.push_back(std::move(CovMappingBufOrErr.get()));
  262. }
  263. return load(Readers, *ProfileReader);
  264. }
  265. namespace {
  266. /// Distributes functions into instantiation sets.
  267. ///
  268. /// An instantiation set is a collection of functions that have the same source
  269. /// code, ie, template functions specializations.
  270. class FunctionInstantiationSetCollector {
  271. using MapT = std::map<LineColPair, std::vector<const FunctionRecord *>>;
  272. MapT InstantiatedFunctions;
  273. public:
  274. void insert(const FunctionRecord &Function, unsigned FileID) {
  275. auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
  276. while (I != E && I->FileID != FileID)
  277. ++I;
  278. assert(I != E && "function does not cover the given file");
  279. auto &Functions = InstantiatedFunctions[I->startLoc()];
  280. Functions.push_back(&Function);
  281. }
  282. MapT::iterator begin() { return InstantiatedFunctions.begin(); }
  283. MapT::iterator end() { return InstantiatedFunctions.end(); }
  284. };
  285. class SegmentBuilder {
  286. std::vector<CoverageSegment> &Segments;
  287. SmallVector<const CountedRegion *, 8> ActiveRegions;
  288. SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
  289. /// Emit a segment with the count from \p Region starting at \p StartLoc.
  290. //
  291. /// \p IsRegionEntry: The segment is at the start of a new non-gap region.
  292. /// \p EmitSkippedRegion: The segment must be emitted as a skipped region.
  293. void startSegment(const CountedRegion &Region, LineColPair StartLoc,
  294. bool IsRegionEntry, bool EmitSkippedRegion = false) {
  295. bool HasCount = !EmitSkippedRegion &&
  296. (Region.Kind != CounterMappingRegion::SkippedRegion);
  297. // If the new segment wouldn't affect coverage rendering, skip it.
  298. if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) {
  299. const auto &Last = Segments.back();
  300. if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount &&
  301. !Last.IsRegionEntry)
  302. return;
  303. }
  304. if (HasCount)
  305. Segments.emplace_back(StartLoc.first, StartLoc.second,
  306. Region.ExecutionCount, IsRegionEntry,
  307. Region.Kind == CounterMappingRegion::GapRegion);
  308. else
  309. Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry);
  310. DEBUG({
  311. const auto &Last = Segments.back();
  312. dbgs() << "Segment at " << Last.Line << ":" << Last.Col
  313. << " (count = " << Last.Count << ")"
  314. << (Last.IsRegionEntry ? ", RegionEntry" : "")
  315. << (!Last.HasCount ? ", Skipped" : "")
  316. << (Last.IsGapRegion ? ", Gap" : "") << "\n";
  317. });
  318. }
  319. /// Emit segments for active regions which end before \p Loc.
  320. ///
  321. /// \p Loc: The start location of the next region. If None, all active
  322. /// regions are completed.
  323. /// \p FirstCompletedRegion: Index of the first completed region.
  324. void completeRegionsUntil(Optional<LineColPair> Loc,
  325. unsigned FirstCompletedRegion) {
  326. // Sort the completed regions by end location. This makes it simple to
  327. // emit closing segments in sorted order.
  328. auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion;
  329. std::stable_sort(CompletedRegionsIt, ActiveRegions.end(),
  330. [](const CountedRegion *L, const CountedRegion *R) {
  331. return L->endLoc() < R->endLoc();
  332. });
  333. // Emit segments for all completed regions.
  334. for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E;
  335. ++I) {
  336. const auto *CompletedRegion = ActiveRegions[I];
  337. assert((!Loc || CompletedRegion->endLoc() <= *Loc) &&
  338. "Completed region ends after start of new region");
  339. const auto *PrevCompletedRegion = ActiveRegions[I - 1];
  340. auto CompletedSegmentLoc = PrevCompletedRegion->endLoc();
  341. // Don't emit any more segments if they start where the new region begins.
  342. if (Loc && CompletedSegmentLoc == *Loc)
  343. break;
  344. // Don't emit a segment if the next completed region ends at the same
  345. // location as this one.
  346. if (CompletedSegmentLoc == CompletedRegion->endLoc())
  347. continue;
  348. // Use the count from the last completed region which ends at this loc.
  349. for (unsigned J = I + 1; J < E; ++J)
  350. if (CompletedRegion->endLoc() == ActiveRegions[J]->endLoc())
  351. CompletedRegion = ActiveRegions[J];
  352. startSegment(*CompletedRegion, CompletedSegmentLoc, false);
  353. }
  354. auto Last = ActiveRegions.back();
  355. if (FirstCompletedRegion && Last->endLoc() != *Loc) {
  356. // If there's a gap after the end of the last completed region and the
  357. // start of the new region, use the last active region to fill the gap.
  358. startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(),
  359. false);
  360. } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) {
  361. // Emit a skipped segment if there are no more active regions. This
  362. // ensures that gaps between functions are marked correctly.
  363. startSegment(*Last, Last->endLoc(), false, true);
  364. }
  365. // Pop the completed regions.
  366. ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end());
  367. }
  368. void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
  369. for (const auto &CR : enumerate(Regions)) {
  370. auto CurStartLoc = CR.value().startLoc();
  371. // Active regions which end before the current region need to be popped.
  372. auto CompletedRegions =
  373. std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(),
  374. [&](const CountedRegion *Region) {
  375. return !(Region->endLoc() <= CurStartLoc);
  376. });
  377. if (CompletedRegions != ActiveRegions.end()) {
  378. unsigned FirstCompletedRegion =
  379. std::distance(ActiveRegions.begin(), CompletedRegions);
  380. completeRegionsUntil(CurStartLoc, FirstCompletedRegion);
  381. }
  382. bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion;
  383. // Try to emit a segment for the current region.
  384. if (CurStartLoc == CR.value().endLoc()) {
  385. // Avoid making zero-length regions active. If it's the last region,
  386. // emit a skipped segment. Otherwise use its predecessor's count.
  387. const bool Skipped = (CR.index() + 1) == Regions.size();
  388. startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(),
  389. CurStartLoc, !GapRegion, Skipped);
  390. continue;
  391. }
  392. if (CR.index() + 1 == Regions.size() ||
  393. CurStartLoc != Regions[CR.index() + 1].startLoc()) {
  394. // Emit a segment if the next region doesn't start at the same location
  395. // as this one.
  396. startSegment(CR.value(), CurStartLoc, !GapRegion);
  397. }
  398. // This region is active (i.e not completed).
  399. ActiveRegions.push_back(&CR.value());
  400. }
  401. // Complete any remaining active regions.
  402. if (!ActiveRegions.empty())
  403. completeRegionsUntil(None, 0);
  404. }
  405. /// Sort a nested sequence of regions from a single file.
  406. static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
  407. llvm::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
  408. const CountedRegion &RHS) {
  409. if (LHS.startLoc() != RHS.startLoc())
  410. return LHS.startLoc() < RHS.startLoc();
  411. if (LHS.endLoc() != RHS.endLoc())
  412. // When LHS completely contains RHS, we sort LHS first.
  413. return RHS.endLoc() < LHS.endLoc();
  414. // If LHS and RHS cover the same area, we need to sort them according
  415. // to their kinds so that the most suitable region will become "active"
  416. // in combineRegions(). Because we accumulate counter values only from
  417. // regions of the same kind as the first region of the area, prefer
  418. // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
  419. static_assert(CounterMappingRegion::CodeRegion <
  420. CounterMappingRegion::ExpansionRegion &&
  421. CounterMappingRegion::ExpansionRegion <
  422. CounterMappingRegion::SkippedRegion,
  423. "Unexpected order of region kind values");
  424. return LHS.Kind < RHS.Kind;
  425. });
  426. }
  427. /// Combine counts of regions which cover the same area.
  428. static ArrayRef<CountedRegion>
  429. combineRegions(MutableArrayRef<CountedRegion> Regions) {
  430. if (Regions.empty())
  431. return Regions;
  432. auto Active = Regions.begin();
  433. auto End = Regions.end();
  434. for (auto I = Regions.begin() + 1; I != End; ++I) {
  435. if (Active->startLoc() != I->startLoc() ||
  436. Active->endLoc() != I->endLoc()) {
  437. // Shift to the next region.
  438. ++Active;
  439. if (Active != I)
  440. *Active = *I;
  441. continue;
  442. }
  443. // Merge duplicate region.
  444. // If CodeRegions and ExpansionRegions cover the same area, it's probably
  445. // a macro which is fully expanded to another macro. In that case, we need
  446. // to accumulate counts only from CodeRegions, or else the area will be
  447. // counted twice.
  448. // On the other hand, a macro may have a nested macro in its body. If the
  449. // outer macro is used several times, the ExpansionRegion for the nested
  450. // macro will also be added several times. These ExpansionRegions cover
  451. // the same source locations and have to be combined to reach the correct
  452. // value for that area.
  453. // We add counts of the regions of the same kind as the active region
  454. // to handle the both situations.
  455. if (I->Kind == Active->Kind)
  456. Active->ExecutionCount += I->ExecutionCount;
  457. }
  458. return Regions.drop_back(std::distance(++Active, End));
  459. }
  460. public:
  461. /// Build a sorted list of CoverageSegments from a list of Regions.
  462. static std::vector<CoverageSegment>
  463. buildSegments(MutableArrayRef<CountedRegion> Regions) {
  464. std::vector<CoverageSegment> Segments;
  465. SegmentBuilder Builder(Segments);
  466. sortNestedRegions(Regions);
  467. ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
  468. DEBUG({
  469. dbgs() << "Combined regions:\n";
  470. for (const auto &CR : CombinedRegions)
  471. dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> "
  472. << CR.LineEnd << ":" << CR.ColumnEnd
  473. << " (count=" << CR.ExecutionCount << ")\n";
  474. });
  475. Builder.buildSegmentsImpl(CombinedRegions);
  476. #ifndef NDEBUG
  477. for (unsigned I = 1, E = Segments.size(); I < E; ++I) {
  478. const auto &L = Segments[I - 1];
  479. const auto &R = Segments[I];
  480. if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) {
  481. DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col
  482. << " followed by " << R.Line << ":" << R.Col << "\n");
  483. assert(false && "Coverage segments not unique or sorted");
  484. }
  485. }
  486. #endif
  487. return Segments;
  488. }
  489. };
  490. } // end anonymous namespace
  491. std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
  492. std::vector<StringRef> Filenames;
  493. for (const auto &Function : getCoveredFunctions())
  494. Filenames.insert(Filenames.end(), Function.Filenames.begin(),
  495. Function.Filenames.end());
  496. llvm::sort(Filenames.begin(), Filenames.end());
  497. auto Last = std::unique(Filenames.begin(), Filenames.end());
  498. Filenames.erase(Last, Filenames.end());
  499. return Filenames;
  500. }
  501. static SmallBitVector gatherFileIDs(StringRef SourceFile,
  502. const FunctionRecord &Function) {
  503. SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
  504. for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
  505. if (SourceFile == Function.Filenames[I])
  506. FilenameEquivalence[I] = true;
  507. return FilenameEquivalence;
  508. }
  509. /// Return the ID of the file where the definition of the function is located.
  510. static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
  511. SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
  512. for (const auto &CR : Function.CountedRegions)
  513. if (CR.Kind == CounterMappingRegion::ExpansionRegion)
  514. IsNotExpandedFile[CR.ExpandedFileID] = false;
  515. int I = IsNotExpandedFile.find_first();
  516. if (I == -1)
  517. return None;
  518. return I;
  519. }
  520. /// Check if SourceFile is the file that contains the definition of
  521. /// the Function. Return the ID of the file in that case or None otherwise.
  522. static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
  523. const FunctionRecord &Function) {
  524. Optional<unsigned> I = findMainViewFileID(Function);
  525. if (I && SourceFile == Function.Filenames[*I])
  526. return I;
  527. return None;
  528. }
  529. static bool isExpansion(const CountedRegion &R, unsigned FileID) {
  530. return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
  531. }
  532. CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const {
  533. CoverageData FileCoverage(Filename);
  534. std::vector<CountedRegion> Regions;
  535. for (const auto &Function : Functions) {
  536. auto MainFileID = findMainViewFileID(Filename, Function);
  537. auto FileIDs = gatherFileIDs(Filename, Function);
  538. for (const auto &CR : Function.CountedRegions)
  539. if (FileIDs.test(CR.FileID)) {
  540. Regions.push_back(CR);
  541. if (MainFileID && isExpansion(CR, *MainFileID))
  542. FileCoverage.Expansions.emplace_back(CR, Function);
  543. }
  544. }
  545. DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
  546. FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
  547. return FileCoverage;
  548. }
  549. std::vector<InstantiationGroup>
  550. CoverageMapping::getInstantiationGroups(StringRef Filename) const {
  551. FunctionInstantiationSetCollector InstantiationSetCollector;
  552. for (const auto &Function : Functions) {
  553. auto MainFileID = findMainViewFileID(Filename, Function);
  554. if (!MainFileID)
  555. continue;
  556. InstantiationSetCollector.insert(Function, *MainFileID);
  557. }
  558. std::vector<InstantiationGroup> Result;
  559. for (auto &InstantiationSet : InstantiationSetCollector) {
  560. InstantiationGroup IG{InstantiationSet.first.first,
  561. InstantiationSet.first.second,
  562. std::move(InstantiationSet.second)};
  563. Result.emplace_back(std::move(IG));
  564. }
  565. return Result;
  566. }
  567. CoverageData
  568. CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const {
  569. auto MainFileID = findMainViewFileID(Function);
  570. if (!MainFileID)
  571. return CoverageData();
  572. CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
  573. std::vector<CountedRegion> Regions;
  574. for (const auto &CR : Function.CountedRegions)
  575. if (CR.FileID == *MainFileID) {
  576. Regions.push_back(CR);
  577. if (isExpansion(CR, *MainFileID))
  578. FunctionCoverage.Expansions.emplace_back(CR, Function);
  579. }
  580. DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
  581. FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
  582. return FunctionCoverage;
  583. }
  584. CoverageData CoverageMapping::getCoverageForExpansion(
  585. const ExpansionRecord &Expansion) const {
  586. CoverageData ExpansionCoverage(
  587. Expansion.Function.Filenames[Expansion.FileID]);
  588. std::vector<CountedRegion> Regions;
  589. for (const auto &CR : Expansion.Function.CountedRegions)
  590. if (CR.FileID == Expansion.FileID) {
  591. Regions.push_back(CR);
  592. if (isExpansion(CR, Expansion.FileID))
  593. ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
  594. }
  595. DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
  596. << "\n");
  597. ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
  598. return ExpansionCoverage;
  599. }
  600. LineCoverageStats::LineCoverageStats(
  601. ArrayRef<const CoverageSegment *> LineSegments,
  602. const CoverageSegment *WrappedSegment, unsigned Line)
  603. : ExecutionCount(0), HasMultipleRegions(false), Mapped(false), Line(Line),
  604. LineSegments(LineSegments), WrappedSegment(WrappedSegment) {
  605. // Find the minimum number of regions which start in this line.
  606. unsigned MinRegionCount = 0;
  607. auto isStartOfRegion = [](const CoverageSegment *S) {
  608. return !S->IsGapRegion && S->HasCount && S->IsRegionEntry;
  609. };
  610. for (unsigned I = 0; I < LineSegments.size() && MinRegionCount < 2; ++I)
  611. if (isStartOfRegion(LineSegments[I]))
  612. ++MinRegionCount;
  613. bool StartOfSkippedRegion = !LineSegments.empty() &&
  614. !LineSegments.front()->HasCount &&
  615. LineSegments.front()->IsRegionEntry;
  616. HasMultipleRegions = MinRegionCount > 1;
  617. Mapped =
  618. !StartOfSkippedRegion &&
  619. ((WrappedSegment && WrappedSegment->HasCount) || (MinRegionCount > 0));
  620. if (!Mapped)
  621. return;
  622. // Pick the max count from the non-gap, region entry segments and the
  623. // wrapped count.
  624. if (WrappedSegment)
  625. ExecutionCount = WrappedSegment->Count;
  626. if (!MinRegionCount)
  627. return;
  628. for (const auto *LS : LineSegments)
  629. if (isStartOfRegion(LS))
  630. ExecutionCount = std::max(ExecutionCount, LS->Count);
  631. }
  632. LineCoverageIterator &LineCoverageIterator::operator++() {
  633. if (Next == CD.end()) {
  634. Stats = LineCoverageStats();
  635. Ended = true;
  636. return *this;
  637. }
  638. if (Segments.size())
  639. WrappedSegment = Segments.back();
  640. Segments.clear();
  641. while (Next != CD.end() && Next->Line == Line)
  642. Segments.push_back(&*Next++);
  643. Stats = LineCoverageStats(Segments, WrappedSegment, Line);
  644. ++Line;
  645. return *this;
  646. }
  647. static std::string getCoverageMapErrString(coveragemap_error Err) {
  648. switch (Err) {
  649. case coveragemap_error::success:
  650. return "Success";
  651. case coveragemap_error::eof:
  652. return "End of File";
  653. case coveragemap_error::no_data_found:
  654. return "No coverage data found";
  655. case coveragemap_error::unsupported_version:
  656. return "Unsupported coverage format version";
  657. case coveragemap_error::truncated:
  658. return "Truncated coverage data";
  659. case coveragemap_error::malformed:
  660. return "Malformed coverage data";
  661. }
  662. llvm_unreachable("A value of coveragemap_error has no message.");
  663. }
  664. namespace {
  665. // FIXME: This class is only here to support the transition to llvm::Error. It
  666. // will be removed once this transition is complete. Clients should prefer to
  667. // deal with the Error value directly, rather than converting to error_code.
  668. class CoverageMappingErrorCategoryType : public std::error_category {
  669. const char *name() const noexcept override { return "llvm.coveragemap"; }
  670. std::string message(int IE) const override {
  671. return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
  672. }
  673. };
  674. } // end anonymous namespace
  675. std::string CoverageMapError::message() const {
  676. return getCoverageMapErrString(Err);
  677. }
  678. static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
  679. const std::error_category &llvm::coverage::coveragemap_category() {
  680. return *ErrorCategory;
  681. }
  682. char CoverageMapError::ID = 0;