blob: 2d833204c919c8edd95cf3d68c705f0f1e176ea4 [file] [log] [blame]
Alex Lorenza20a5d52014-07-24 23:57:54 +00001//=-- CoverageMapping.cpp - Code coverage mapping support ---------*- C++ -*-=//
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
Easwaran Ramandc707122016-04-29 18:53:05 +000015#include "llvm/ProfileData/Coverage/CoverageMapping.h"
Justin Bogner953e2402014-09-20 15:31:56 +000016#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/Optional.h"
Benjamin Kramer71e1eb52015-02-12 16:18:07 +000018#include "llvm/ADT/SmallBitVector.h"
Easwaran Ramandc707122016-04-29 18:53:05 +000019#include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
Justin Bogner953e2402014-09-20 15:31:56 +000020#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb35a72a2014-09-25 00:34:18 +000021#include "llvm/Support/Debug.h"
Rafael Espindola74f29322015-06-13 17:23:04 +000022#include "llvm/Support/Errc.h"
Justin Bogner85b0a032014-09-08 21:04:00 +000023#include "llvm/Support/ErrorHandling.h"
Justin Bogner367a9f22015-05-06 23:19:35 +000024#include "llvm/Support/ManagedStatic.h"
Justin Bogner0b4c4842015-05-05 23:44:48 +000025#include "llvm/Support/Path.h"
Benjamin Kramer799003b2015-03-23 19:32:43 +000026#include "llvm/Support/raw_ostream.h"
Alex Lorenza20a5d52014-07-24 23:57:54 +000027
28using namespace llvm;
29using namespace coverage;
30
Justin Bognerb35a72a2014-09-25 00:34:18 +000031#define DEBUG_TYPE "coverage-mapping"
32
Alex Lorenza20a5d52014-07-24 23:57:54 +000033Counter CounterExpressionBuilder::get(const CounterExpression &E) {
Justin Bognerad69e642014-10-02 17:14:18 +000034 auto It = ExpressionIndices.find(E);
35 if (It != ExpressionIndices.end())
36 return Counter::getExpression(It->second);
37 unsigned I = Expressions.size();
Alex Lorenza20a5d52014-07-24 23:57:54 +000038 Expressions.push_back(E);
Justin Bognerad69e642014-10-02 17:14:18 +000039 ExpressionIndices[E] = I;
40 return Counter::getExpression(I);
Alex Lorenza20a5d52014-07-24 23:57:54 +000041}
42
Justin Bognerf9535c42014-10-02 16:43:31 +000043void CounterExpressionBuilder::extractTerms(
44 Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
Alex Lorenza20a5d52014-07-24 23:57:54 +000045 switch (C.getKind()) {
46 case Counter::Zero:
47 break;
48 case Counter::CounterValueReference:
Justin Bognerf9535c42014-10-02 16:43:31 +000049 Terms.push_back(std::make_pair(C.getCounterID(), Sign));
Alex Lorenza20a5d52014-07-24 23:57:54 +000050 break;
51 case Counter::Expression:
52 const auto &E = Expressions[C.getExpressionID()];
Justin Bognerf9535c42014-10-02 16:43:31 +000053 extractTerms(E.LHS, Sign, Terms);
54 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
55 Terms);
Alex Lorenza20a5d52014-07-24 23:57:54 +000056 break;
57 }
58}
59
60Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
61 // Gather constant terms.
Justin Bognerf9535c42014-10-02 16:43:31 +000062 llvm::SmallVector<std::pair<unsigned, int>, 32> Terms;
63 extractTerms(ExpressionTree, +1, Terms);
64
65 // If there are no terms, this is just a zero. The algorithm below assumes at
66 // least one term.
67 if (Terms.size() == 0)
68 return Counter::getZero();
69
70 // Group the terms by counter ID.
71 std::sort(Terms.begin(), Terms.end(),
72 [](const std::pair<unsigned, int> &LHS,
73 const std::pair<unsigned, int> &RHS) {
74 return LHS.first < RHS.first;
75 });
76
77 // Combine terms by counter ID to eliminate counters that sum to zero.
78 auto Prev = Terms.begin();
79 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
80 if (I->first == Prev->first) {
81 Prev->second += I->second;
82 continue;
83 }
84 ++Prev;
85 *Prev = *I;
86 }
87 Terms.erase(++Prev, Terms.end());
Alex Lorenza20a5d52014-07-24 23:57:54 +000088
89 Counter C;
Justin Bognerf9535c42014-10-02 16:43:31 +000090 // Create additions. We do this before subtractions to avoid constructs like
91 // ((0 - X) + Y), as opposed to (Y - X).
92 for (auto Term : Terms) {
93 if (Term.second <= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +000094 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +000095 for (int I = 0; I < Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +000096 if (C.isZero())
Justin Bognerf9535c42014-10-02 16:43:31 +000097 C = Counter::getCounter(Term.first);
Alex Lorenza20a5d52014-07-24 23:57:54 +000098 else
99 C = get(CounterExpression(CounterExpression::Add, C,
Justin Bognerf9535c42014-10-02 16:43:31 +0000100 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000101 }
102
103 // Create subtractions.
Justin Bognerf9535c42014-10-02 16:43:31 +0000104 for (auto Term : Terms) {
105 if (Term.second >= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000106 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +0000107 for (int I = 0; I < -Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000108 C = get(CounterExpression(CounterExpression::Subtract, C,
Justin Bognerf9535c42014-10-02 16:43:31 +0000109 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000110 }
111 return C;
112}
113
114Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
115 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
116}
117
118Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
119 return simplify(
120 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
121}
122
123void CounterMappingContext::dump(const Counter &C,
124 llvm::raw_ostream &OS) const {
125 switch (C.getKind()) {
126 case Counter::Zero:
127 OS << '0';
128 return;
129 case Counter::CounterValueReference:
130 OS << '#' << C.getCounterID();
131 break;
132 case Counter::Expression: {
133 if (C.getExpressionID() >= Expressions.size())
134 return;
135 const auto &E = Expressions[C.getExpressionID()];
136 OS << '(';
Alex Lorenza422911c2014-07-29 19:58:16 +0000137 dump(E.LHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000138 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
Alex Lorenza422911c2014-07-29 19:58:16 +0000139 dump(E.RHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000140 OS << ')';
141 break;
142 }
143 }
144 if (CounterValues.empty())
145 return;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000146 Expected<int64_t> Value = evaluate(C);
147 if (auto E = Value.takeError()) {
148 llvm::consumeError(std::move(E));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000149 return;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000150 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000151 OS << '[' << *Value << ']';
Alex Lorenza20a5d52014-07-24 23:57:54 +0000152}
153
Vedant Kumar9152fd12016-05-19 03:54:45 +0000154Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000155 switch (C.getKind()) {
156 case Counter::Zero:
157 return 0;
158 case Counter::CounterValueReference:
Justin Bogner85b0a032014-09-08 21:04:00 +0000159 if (C.getCounterID() >= CounterValues.size())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000160 return errorCodeToError(errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000161 return CounterValues[C.getCounterID()];
162 case Counter::Expression: {
Justin Bogner85b0a032014-09-08 21:04:00 +0000163 if (C.getExpressionID() >= Expressions.size())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000164 return errorCodeToError(errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000165 const auto &E = Expressions[C.getExpressionID()];
Vedant Kumar9152fd12016-05-19 03:54:45 +0000166 Expected<int64_t> LHS = evaluate(E.LHS);
Justin Bogner85b0a032014-09-08 21:04:00 +0000167 if (!LHS)
168 return LHS;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000169 Expected<int64_t> RHS = evaluate(E.RHS);
Justin Bogner85b0a032014-09-08 21:04:00 +0000170 if (!RHS)
171 return RHS;
172 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000173 }
174 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000175 llvm_unreachable("Unhandled CounterKind");
Alex Lorenza20a5d52014-07-24 23:57:54 +0000176}
Justin Bogner953e2402014-09-20 15:31:56 +0000177
Justin Bognerd5fca922014-11-14 01:50:32 +0000178void FunctionRecordIterator::skipOtherFiles() {
179 while (Current != Records.end() && !Filename.empty() &&
180 Filename != Current->Filenames[0])
181 ++Current;
182 if (Current == Records.end())
183 *this = FunctionRecordIterator();
184}
185
Vedant Kumar9152fd12016-05-19 03:54:45 +0000186Expected<std::unique_ptr<CoverageMapping>>
Justin Bogner1d29c082015-02-18 18:01:14 +0000187CoverageMapping::load(CoverageMappingReader &CoverageReader,
Justin Bogner953e2402014-09-20 15:31:56 +0000188 IndexedInstrProfReader &ProfileReader) {
189 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
190
191 std::vector<uint64_t> Counts;
192 for (const auto &Record : CoverageReader) {
Justin Bogner428c6052015-02-18 18:40:46 +0000193 CounterMappingContext Ctx(Record.Expressions);
194
Justin Bogner953e2402014-09-20 15:31:56 +0000195 Counts.clear();
Vedant Kumar9152fd12016-05-19 03:54:45 +0000196 if (Error E = ProfileReader.getFunctionCounts(
Justin Bogner953e2402014-09-20 15:31:56 +0000197 Record.FunctionName, Record.FunctionHash, Counts)) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000198 instrprof_error IPE = InstrProfError::take(std::move(E));
199 if (IPE == instrprof_error::hash_mismatch) {
Justin Bogner428c6052015-02-18 18:40:46 +0000200 Coverage->MismatchedFunctionCount++;
201 continue;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000202 } else if (IPE != instrprof_error::unknown_function)
203 return make_error<InstrProfError>(IPE);
Justin Bogner82a64512015-05-13 22:03:04 +0000204 Counts.assign(Record.MappingRegions.size(), 0);
205 }
206 Ctx.setCounts(Counts);
Justin Bogner953e2402014-09-20 15:31:56 +0000207
Justin Bogner428c6052015-02-18 18:40:46 +0000208 assert(!Record.MappingRegions.empty() && "Function has no regions");
Justin Bogner0b4c4842015-05-05 23:44:48 +0000209
Xinliang David Li4ec40142015-12-15 19:44:45 +0000210 StringRef OrigFuncName = Record.FunctionName;
Vedant Kumar43a85652016-03-28 15:49:08 +0000211 if (Record.Filenames.empty())
212 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName);
213 else
Xinliang David Li4ec40142015-12-15 19:44:45 +0000214 OrigFuncName =
215 getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]);
216 FunctionRecord Function(OrigFuncName, Record.Filenames);
Justin Bogner953e2402014-09-20 15:31:56 +0000217 for (const auto &Region : Record.MappingRegions) {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000218 Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
219 if (auto E = ExecutionCount.takeError()) {
220 llvm::consumeError(std::move(E));
Justin Bogner953e2402014-09-20 15:31:56 +0000221 break;
Vedant Kumar9152fd12016-05-19 03:54:45 +0000222 }
Justin Bogner428c6052015-02-18 18:40:46 +0000223 Function.pushRegion(Region, *ExecutionCount);
Justin Bogner953e2402014-09-20 15:31:56 +0000224 }
225 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
226 Coverage->MismatchedFunctionCount++;
227 continue;
228 }
229
Benjamin Kramere12a6ba2014-10-03 18:33:16 +0000230 Coverage->Functions.push_back(std::move(Function));
Justin Bogner953e2402014-09-20 15:31:56 +0000231 }
232
233 return std::move(Coverage);
234}
235
Vedant Kumar9152fd12016-05-19 03:54:45 +0000236Expected<std::unique_ptr<CoverageMapping>>
Justin Bogner43795352015-03-11 02:30:51 +0000237CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename,
Frederic Rissebc162a2015-06-22 21:33:24 +0000238 StringRef Arch) {
Justin Bogner19a93ba2014-09-20 17:19:52 +0000239 auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
Justin Bogner43e51632015-02-26 20:06:28 +0000240 if (std::error_code EC = CounterMappingBuff.getError())
Vedant Kumar9152fd12016-05-19 03:54:45 +0000241 return errorCodeToError(EC);
Justin Bogner43e51632015-02-26 20:06:28 +0000242 auto CoverageReaderOrErr =
Justin Bogner43795352015-03-11 02:30:51 +0000243 BinaryCoverageReader::create(CounterMappingBuff.get(), Arch);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000244 if (Error E = CoverageReaderOrErr.takeError())
245 return std::move(E);
Justin Bogner43e51632015-02-26 20:06:28 +0000246 auto CoverageReader = std::move(CoverageReaderOrErr.get());
Justin Bognerab89ed72015-02-16 21:28:58 +0000247 auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename);
Vedant Kumar9152fd12016-05-19 03:54:45 +0000248 if (Error E = ProfileReaderOrErr.takeError())
249 return std::move(E);
Justin Bognerab89ed72015-02-16 21:28:58 +0000250 auto ProfileReader = std::move(ProfileReaderOrErr.get());
Justin Bogner43e51632015-02-26 20:06:28 +0000251 return load(*CoverageReader, *ProfileReader);
Justin Bogner19a93ba2014-09-20 17:19:52 +0000252}
253
Justin Bogner953e2402014-09-20 15:31:56 +0000254namespace {
255/// \brief Distributes functions into instantiation sets.
256///
257/// An instantiation set is a collection of functions that have the same source
258/// code, ie, template functions specializations.
259class FunctionInstantiationSetCollector {
260 typedef DenseMap<std::pair<unsigned, unsigned>,
261 std::vector<const FunctionRecord *>> MapT;
262 MapT InstantiatedFunctions;
263
264public:
265 void insert(const FunctionRecord &Function, unsigned FileID) {
266 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
267 while (I != E && I->FileID != FileID)
268 ++I;
269 assert(I != E && "function does not cover the given file");
270 auto &Functions = InstantiatedFunctions[I->startLoc()];
271 Functions.push_back(&Function);
272 }
273
274 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
275
276 MapT::iterator end() { return InstantiatedFunctions.end(); }
277};
278
279class SegmentBuilder {
Igor Kudrinc0774e62016-04-14 09:10:00 +0000280 std::vector<CoverageSegment> &Segments;
Justin Bogner953e2402014-09-20 15:31:56 +0000281 SmallVector<const CountedRegion *, 8> ActiveRegions;
282
Igor Kudrinc0774e62016-04-14 09:10:00 +0000283 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {}
284
Justin Bogner953e2402014-09-20 15:31:56 +0000285 /// Start a segment with no count specified.
286 void startSegment(unsigned Line, unsigned Col) {
Justin Bognerb35a72a2014-09-25 00:34:18 +0000287 DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000288 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
289 }
290
291 /// Start a segment with the given Region's count.
292 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
293 const CountedRegion &Region) {
Justin Bogner953e2402014-09-20 15:31:56 +0000294 // Avoid creating empty regions.
Igor Kudrined99a962016-04-25 09:43:37 +0000295 if (!Segments.empty() && Segments.back().Line == Line &&
296 Segments.back().Col == Col)
297 Segments.pop_back();
Justin Bognerb35a72a2014-09-25 00:34:18 +0000298 DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
Justin Bogner953e2402014-09-20 15:31:56 +0000299 // Set this region's count.
Justin Bognerb35a72a2014-09-25 00:34:18 +0000300 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
301 DEBUG(dbgs() << " with count " << Region.ExecutionCount);
Igor Kudrined99a962016-04-25 09:43:37 +0000302 Segments.emplace_back(Line, Col, Region.ExecutionCount, IsRegionEntry);
303 } else
304 Segments.emplace_back(Line, Col, IsRegionEntry);
Justin Bognerb35a72a2014-09-25 00:34:18 +0000305 DEBUG(dbgs() << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000306 }
307
308 /// Start a segment for the given region.
309 void startSegment(const CountedRegion &Region) {
310 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
311 }
312
313 /// Pop the top region off of the active stack, starting a new segment with
314 /// the containing Region's count.
315 void popRegion() {
316 const CountedRegion *Active = ActiveRegions.back();
317 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
318 ActiveRegions.pop_back();
319 if (ActiveRegions.empty())
320 startSegment(Line, Col);
321 else
322 startSegment(Line, Col, false, *ActiveRegions.back());
323 }
324
Igor Kudrinc0774e62016-04-14 09:10:00 +0000325 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) {
Justin Bogner953e2402014-09-20 15:31:56 +0000326 for (const auto &Region : Regions) {
327 // Pop any regions that end before this one starts.
328 while (!ActiveRegions.empty() &&
329 ActiveRegions.back()->endLoc() <= Region.startLoc())
330 popRegion();
Igor Kudrined99a962016-04-25 09:43:37 +0000331 // Add this region to the stack.
332 ActiveRegions.push_back(&Region);
333 startSegment(Region);
Justin Bogner953e2402014-09-20 15:31:56 +0000334 }
335 // Pop any regions that are left in the stack.
336 while (!ActiveRegions.empty())
337 popRegion();
Igor Kudrinc0774e62016-04-14 09:10:00 +0000338 }
339
Igor Kudrined99a962016-04-25 09:43:37 +0000340 /// Sort a nested sequence of regions from a single file.
341 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) {
Igor Kudrin27d8dd32016-05-05 09:39:45 +0000342 std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS,
343 const CountedRegion &RHS) {
344 if (LHS.startLoc() != RHS.startLoc())
345 return LHS.startLoc() < RHS.startLoc();
346 if (LHS.endLoc() != RHS.endLoc())
347 // When LHS completely contains RHS, we sort LHS first.
348 return RHS.endLoc() < LHS.endLoc();
349 // If LHS and RHS cover the same area, we need to sort them according
350 // to their kinds so that the most suitable region will become "active"
351 // in combineRegions(). Because we accumulate counter values only from
352 // regions of the same kind as the first region of the area, prefer
353 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion.
354 static_assert(coverage::CounterMappingRegion::CodeRegion <
355 coverage::CounterMappingRegion::ExpansionRegion &&
356 coverage::CounterMappingRegion::ExpansionRegion <
357 coverage::CounterMappingRegion::SkippedRegion,
358 "Unexpected order of region kind values");
359 return LHS.Kind < RHS.Kind;
360 });
Igor Kudrined99a962016-04-25 09:43:37 +0000361 }
362
363 /// Combine counts of regions which cover the same area.
364 static ArrayRef<CountedRegion>
365 combineRegions(MutableArrayRef<CountedRegion> Regions) {
366 if (Regions.empty())
367 return Regions;
368 auto Active = Regions.begin();
369 auto End = Regions.end();
370 for (auto I = Regions.begin() + 1; I != End; ++I) {
371 if (Active->startLoc() != I->startLoc() ||
372 Active->endLoc() != I->endLoc()) {
373 // Shift to the next region.
374 ++Active;
375 if (Active != I)
376 *Active = *I;
377 continue;
378 }
379 // Merge duplicate region.
Igor Kudrin27d8dd32016-05-05 09:39:45 +0000380 // If CodeRegions and ExpansionRegions cover the same area, it's probably
381 // a macro which is fully expanded to another macro. In that case, we need
382 // to accumulate counts only from CodeRegions, or else the area will be
383 // counted twice.
384 // On the other hand, a macro may have a nested macro in its body. If the
385 // outer macro is used several times, the ExpansionRegion for the nested
386 // macro will also be added several times. These ExpansionRegions cover
387 // the same source locations and have to be combined to reach the correct
388 // value for that area.
389 // We add counts of the regions of the same kind as the active region
390 // to handle the both situations.
391 if (I->Kind == Active->Kind)
Igor Kudrined99a962016-04-25 09:43:37 +0000392 Active->ExecutionCount += I->ExecutionCount;
393 }
394 return Regions.drop_back(std::distance(++Active, End));
395 }
396
Igor Kudrinc0774e62016-04-14 09:10:00 +0000397public:
Igor Kudrined99a962016-04-25 09:43:37 +0000398 /// Build a list of CoverageSegments from a list of Regions.
Igor Kudrinc0774e62016-04-14 09:10:00 +0000399 static std::vector<CoverageSegment>
Igor Kudrined99a962016-04-25 09:43:37 +0000400 buildSegments(MutableArrayRef<CountedRegion> Regions) {
Igor Kudrinc0774e62016-04-14 09:10:00 +0000401 std::vector<CoverageSegment> Segments;
402 SegmentBuilder Builder(Segments);
Igor Kudrined99a962016-04-25 09:43:37 +0000403
404 sortNestedRegions(Regions);
405 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions);
406
407 Builder.buildSegmentsImpl(CombinedRegions);
Justin Bogner953e2402014-09-20 15:31:56 +0000408 return Segments;
409 }
410};
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000411}
Justin Bogner953e2402014-09-20 15:31:56 +0000412
Justin Bognerd5fca922014-11-14 01:50:32 +0000413std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const {
Justin Bogner953e2402014-09-20 15:31:56 +0000414 std::vector<StringRef> Filenames;
415 for (const auto &Function : getCoveredFunctions())
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000416 Filenames.insert(Filenames.end(), Function.Filenames.begin(),
417 Function.Filenames.end());
Justin Bogner953e2402014-09-20 15:31:56 +0000418 std::sort(Filenames.begin(), Filenames.end());
419 auto Last = std::unique(Filenames.begin(), Filenames.end());
420 Filenames.erase(Last, Filenames.end());
421 return Filenames;
422}
423
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000424static SmallBitVector gatherFileIDs(StringRef SourceFile,
425 const FunctionRecord &Function) {
426 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false);
Justin Bogner953e2402014-09-20 15:31:56 +0000427 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
428 if (SourceFile == Function.Filenames[I])
429 FilenameEquivalence[I] = true;
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000430 return FilenameEquivalence;
431}
432
Igor Kudrin1c14dc42016-04-18 15:36:30 +0000433/// Return the ID of the file where the definition of the function is located.
Justin Bogner953e2402014-09-20 15:31:56 +0000434static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
Benjamin Kramer40957cc2015-02-12 16:30:00 +0000435 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true);
Justin Bogner953e2402014-09-20 15:31:56 +0000436 for (const auto &CR : Function.CountedRegions)
437 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
Benjamin Kramer40957cc2015-02-12 16:30:00 +0000438 IsNotExpandedFile[CR.ExpandedFileID] = false;
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000439 int I = IsNotExpandedFile.find_first();
Justin Bognerc4f5a5e2015-02-20 07:28:28 +0000440 if (I == -1)
441 return None;
442 return I;
Justin Bogner953e2402014-09-20 15:31:56 +0000443}
444
Igor Kudrin1c14dc42016-04-18 15:36:30 +0000445/// Check if SourceFile is the file that contains the definition of
446/// the Function. Return the ID of the file in that case or None otherwise.
447static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
448 const FunctionRecord &Function) {
449 Optional<unsigned> I = findMainViewFileID(Function);
450 if (I && SourceFile == Function.Filenames[*I])
451 return I;
452 return None;
453}
454
Justin Bogner953e2402014-09-20 15:31:56 +0000455static bool isExpansion(const CountedRegion &R, unsigned FileID) {
456 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
457}
458
459CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
460 CoverageData FileCoverage(Filename);
461 std::vector<coverage::CountedRegion> Regions;
462
463 for (const auto &Function : Functions) {
464 auto MainFileID = findMainViewFileID(Filename, Function);
Justin Bogner953e2402014-09-20 15:31:56 +0000465 auto FileIDs = gatherFileIDs(Filename, Function);
466 for (const auto &CR : Function.CountedRegions)
Benjamin Kramer71e1eb52015-02-12 16:18:07 +0000467 if (FileIDs.test(CR.FileID)) {
Justin Bogner953e2402014-09-20 15:31:56 +0000468 Regions.push_back(CR);
Igor Kudrin1c14dc42016-04-18 15:36:30 +0000469 if (MainFileID && isExpansion(CR, *MainFileID))
Justin Bogner953e2402014-09-20 15:31:56 +0000470 FileCoverage.Expansions.emplace_back(CR, Function);
471 }
472 }
473
Justin Bogner3c0f1242015-01-24 20:58:52 +0000474 DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000475 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000476
477 return FileCoverage;
478}
479
480std::vector<const FunctionRecord *>
481CoverageMapping::getInstantiations(StringRef Filename) {
482 FunctionInstantiationSetCollector InstantiationSetCollector;
483 for (const auto &Function : Functions) {
484 auto MainFileID = findMainViewFileID(Filename, Function);
485 if (!MainFileID)
486 continue;
487 InstantiationSetCollector.insert(Function, *MainFileID);
488 }
489
490 std::vector<const FunctionRecord *> Result;
491 for (const auto &InstantiationSet : InstantiationSetCollector) {
492 if (InstantiationSet.second.size() < 2)
493 continue;
Benjamin Kramer6cd780f2015-02-17 15:29:18 +0000494 Result.insert(Result.end(), InstantiationSet.second.begin(),
495 InstantiationSet.second.end());
Justin Bogner953e2402014-09-20 15:31:56 +0000496 }
497 return Result;
498}
499
500CoverageData
501CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
502 auto MainFileID = findMainViewFileID(Function);
503 if (!MainFileID)
504 return CoverageData();
505
506 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
507 std::vector<coverage::CountedRegion> Regions;
508 for (const auto &CR : Function.CountedRegions)
509 if (CR.FileID == *MainFileID) {
510 Regions.push_back(CR);
511 if (isExpansion(CR, *MainFileID))
512 FunctionCoverage.Expansions.emplace_back(CR, Function);
513 }
514
Justin Bogner3c0f1242015-01-24 20:58:52 +0000515 DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000516 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000517
518 return FunctionCoverage;
519}
520
521CoverageData
522CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
523 CoverageData ExpansionCoverage(
524 Expansion.Function.Filenames[Expansion.FileID]);
525 std::vector<coverage::CountedRegion> Regions;
526 for (const auto &CR : Expansion.Function.CountedRegions)
527 if (CR.FileID == Expansion.FileID) {
528 Regions.push_back(CR);
529 if (isExpansion(CR, Expansion.FileID))
530 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
531 }
532
Justin Bogner3c0f1242015-01-24 20:58:52 +0000533 DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID
534 << "\n");
Igor Kudrinc0774e62016-04-14 09:10:00 +0000535 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions);
Justin Bogner953e2402014-09-20 15:31:56 +0000536
537 return ExpansionCoverage;
538}
Justin Bogner367a9f22015-05-06 23:19:35 +0000539
540namespace {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000541std::string getCoverageMapErrString(coveragemap_error Err) {
542 switch (Err) {
543 case coveragemap_error::success:
544 return "Success";
545 case coveragemap_error::eof:
546 return "End of File";
547 case coveragemap_error::no_data_found:
548 return "No coverage data found";
549 case coveragemap_error::unsupported_version:
550 return "Unsupported coverage format version";
551 case coveragemap_error::truncated:
552 return "Truncated coverage data";
553 case coveragemap_error::malformed:
554 return "Malformed coverage data";
555 }
556 llvm_unreachable("A value of coveragemap_error has no message.");
557}
558
Peter Collingbourne4718f8b2016-05-24 20:13:46 +0000559// FIXME: This class is only here to support the transition to llvm::Error. It
560// will be removed once this transition is complete. Clients should prefer to
561// deal with the Error value directly, rather than converting to error_code.
Justin Bogner367a9f22015-05-06 23:19:35 +0000562class CoverageMappingErrorCategoryType : public std::error_category {
563 const char *name() const LLVM_NOEXCEPT override { return "llvm.coveragemap"; }
564 std::string message(int IE) const override {
Vedant Kumar9152fd12016-05-19 03:54:45 +0000565 return getCoverageMapErrString(static_cast<coveragemap_error>(IE));
Justin Bogner367a9f22015-05-06 23:19:35 +0000566 }
567};
Vedant Kumar9152fd12016-05-19 03:54:45 +0000568} // end anonymous namespace
569
570std::string CoverageMapError::message() const {
571 return getCoverageMapErrString(Err);
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000572}
Justin Bogner367a9f22015-05-06 23:19:35 +0000573
574static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory;
575
Xinliang David Li8a5bdb52016-01-10 21:56:33 +0000576const std::error_category &llvm::coverage::coveragemap_category() {
Justin Bogner367a9f22015-05-06 23:19:35 +0000577 return *ErrorCategory;
578}
Vedant Kumar9152fd12016-05-19 03:54:45 +0000579
580char CoverageMapError::ID = 0;