blob: afddbc31c2d2a5e6318d73e4b74a7ee967bb1284 [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
15#include "llvm/ProfileData/CoverageMapping.h"
Justin Bogner953e2402014-09-20 15:31:56 +000016
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/Optional.h"
19#include "llvm/ADT/SmallSet.h"
20#include "llvm/ProfileData/CoverageMappingReader.h"
21#include "llvm/ProfileData/InstrProfReader.h"
Justin Bognerb35a72a2014-09-25 00:34:18 +000022#include "llvm/Support/Debug.h"
Justin Bogner85b0a032014-09-08 21:04:00 +000023#include "llvm/Support/ErrorHandling.h"
Alex Lorenza20a5d52014-07-24 23:57:54 +000024
25using namespace llvm;
26using namespace coverage;
27
Justin Bognerb35a72a2014-09-25 00:34:18 +000028#define DEBUG_TYPE "coverage-mapping"
29
Alex Lorenza20a5d52014-07-24 23:57:54 +000030Counter CounterExpressionBuilder::get(const CounterExpression &E) {
31 for (unsigned I = 0, S = Expressions.size(); I < S; ++I) {
32 if (Expressions[I] == E)
33 return Counter::getExpression(I);
34 }
35 Expressions.push_back(E);
36 return Counter::getExpression(Expressions.size() - 1);
37}
38
Justin Bognerf9535c42014-10-02 16:43:31 +000039void CounterExpressionBuilder::extractTerms(
40 Counter C, int Sign, SmallVectorImpl<std::pair<unsigned, int>> &Terms) {
Alex Lorenza20a5d52014-07-24 23:57:54 +000041 switch (C.getKind()) {
42 case Counter::Zero:
43 break;
44 case Counter::CounterValueReference:
Justin Bognerf9535c42014-10-02 16:43:31 +000045 Terms.push_back(std::make_pair(C.getCounterID(), Sign));
Alex Lorenza20a5d52014-07-24 23:57:54 +000046 break;
47 case Counter::Expression:
48 const auto &E = Expressions[C.getExpressionID()];
Justin Bognerf9535c42014-10-02 16:43:31 +000049 extractTerms(E.LHS, Sign, Terms);
50 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign,
51 Terms);
Alex Lorenza20a5d52014-07-24 23:57:54 +000052 break;
53 }
54}
55
56Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
57 // Gather constant terms.
Justin Bognerf9535c42014-10-02 16:43:31 +000058 llvm::SmallVector<std::pair<unsigned, int>, 32> Terms;
59 extractTerms(ExpressionTree, +1, Terms);
60
61 // If there are no terms, this is just a zero. The algorithm below assumes at
62 // least one term.
63 if (Terms.size() == 0)
64 return Counter::getZero();
65
66 // Group the terms by counter ID.
67 std::sort(Terms.begin(), Terms.end(),
68 [](const std::pair<unsigned, int> &LHS,
69 const std::pair<unsigned, int> &RHS) {
70 return LHS.first < RHS.first;
71 });
72
73 // Combine terms by counter ID to eliminate counters that sum to zero.
74 auto Prev = Terms.begin();
75 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) {
76 if (I->first == Prev->first) {
77 Prev->second += I->second;
78 continue;
79 }
80 ++Prev;
81 *Prev = *I;
82 }
83 Terms.erase(++Prev, Terms.end());
Alex Lorenza20a5d52014-07-24 23:57:54 +000084
85 Counter C;
Justin Bognerf9535c42014-10-02 16:43:31 +000086 // Create additions. We do this before subtractions to avoid constructs like
87 // ((0 - X) + Y), as opposed to (Y - X).
88 for (auto Term : Terms) {
89 if (Term.second <= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +000090 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +000091 for (int I = 0; I < Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +000092 if (C.isZero())
Justin Bognerf9535c42014-10-02 16:43:31 +000093 C = Counter::getCounter(Term.first);
Alex Lorenza20a5d52014-07-24 23:57:54 +000094 else
95 C = get(CounterExpression(CounterExpression::Add, C,
Justin Bognerf9535c42014-10-02 16:43:31 +000096 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +000097 }
98
99 // Create subtractions.
Justin Bognerf9535c42014-10-02 16:43:31 +0000100 for (auto Term : Terms) {
101 if (Term.second >= 0)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000102 continue;
Justin Bognerf9535c42014-10-02 16:43:31 +0000103 for (int I = 0; I < -Term.second; ++I)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000104 C = get(CounterExpression(CounterExpression::Subtract, C,
Justin Bognerf9535c42014-10-02 16:43:31 +0000105 Counter::getCounter(Term.first)));
Alex Lorenza20a5d52014-07-24 23:57:54 +0000106 }
107 return C;
108}
109
110Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
111 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
112}
113
114Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
115 return simplify(
116 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
117}
118
119void CounterMappingContext::dump(const Counter &C,
120 llvm::raw_ostream &OS) const {
121 switch (C.getKind()) {
122 case Counter::Zero:
123 OS << '0';
124 return;
125 case Counter::CounterValueReference:
126 OS << '#' << C.getCounterID();
127 break;
128 case Counter::Expression: {
129 if (C.getExpressionID() >= Expressions.size())
130 return;
131 const auto &E = Expressions[C.getExpressionID()];
132 OS << '(';
Alex Lorenza422911c2014-07-29 19:58:16 +0000133 dump(E.LHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000134 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
Alex Lorenza422911c2014-07-29 19:58:16 +0000135 dump(E.RHS, OS);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000136 OS << ')';
137 break;
138 }
139 }
140 if (CounterValues.empty())
141 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000142 ErrorOr<int64_t> Value = evaluate(C);
143 if (!Value)
Alex Lorenza20a5d52014-07-24 23:57:54 +0000144 return;
Justin Bogner85b0a032014-09-08 21:04:00 +0000145 OS << '[' << *Value << ']';
Alex Lorenza20a5d52014-07-24 23:57:54 +0000146}
147
Justin Bogner85b0a032014-09-08 21:04:00 +0000148ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
Alex Lorenza20a5d52014-07-24 23:57:54 +0000149 switch (C.getKind()) {
150 case Counter::Zero:
151 return 0;
152 case Counter::CounterValueReference:
Justin Bogner85b0a032014-09-08 21:04:00 +0000153 if (C.getCounterID() >= CounterValues.size())
Justin Bogner3f188342014-09-08 21:31:43 +0000154 return std::make_error_code(std::errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000155 return CounterValues[C.getCounterID()];
156 case Counter::Expression: {
Justin Bogner85b0a032014-09-08 21:04:00 +0000157 if (C.getExpressionID() >= Expressions.size())
Justin Bogner3f188342014-09-08 21:31:43 +0000158 return std::make_error_code(std::errc::argument_out_of_domain);
Alex Lorenza20a5d52014-07-24 23:57:54 +0000159 const auto &E = Expressions[C.getExpressionID()];
Justin Bogner85b0a032014-09-08 21:04:00 +0000160 ErrorOr<int64_t> LHS = evaluate(E.LHS);
161 if (!LHS)
162 return LHS;
163 ErrorOr<int64_t> RHS = evaluate(E.RHS);
164 if (!RHS)
165 return RHS;
166 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
Alex Lorenza20a5d52014-07-24 23:57:54 +0000167 }
168 }
Justin Bogner85b0a032014-09-08 21:04:00 +0000169 llvm_unreachable("Unhandled CounterKind");
Alex Lorenza20a5d52014-07-24 23:57:54 +0000170}
Justin Bogner953e2402014-09-20 15:31:56 +0000171
172ErrorOr<std::unique_ptr<CoverageMapping>>
173CoverageMapping::load(ObjectFileCoverageMappingReader &CoverageReader,
174 IndexedInstrProfReader &ProfileReader) {
175 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
176
177 std::vector<uint64_t> Counts;
178 for (const auto &Record : CoverageReader) {
179 Counts.clear();
180 if (std::error_code EC = ProfileReader.getFunctionCounts(
181 Record.FunctionName, Record.FunctionHash, Counts)) {
182 if (EC != instrprof_error::hash_mismatch &&
183 EC != instrprof_error::unknown_function)
184 return EC;
185 Coverage->MismatchedFunctionCount++;
186 continue;
187 }
188
Alex Lorenzcb1702d2014-09-30 12:45:13 +0000189 assert(Counts.size() != 0 && "Function's counts are empty");
190 FunctionRecord Function(Record.FunctionName, Record.Filenames,
191 Counts.front());
Justin Bogner953e2402014-09-20 15:31:56 +0000192 CounterMappingContext Ctx(Record.Expressions, Counts);
193 for (const auto &Region : Record.MappingRegions) {
194 ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
195 if (!ExecutionCount)
196 break;
197 Function.CountedRegions.push_back(CountedRegion(Region, *ExecutionCount));
198 }
199 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
200 Coverage->MismatchedFunctionCount++;
201 continue;
202 }
203
204 Coverage->Functions.push_back(Function);
205 }
206
207 return std::move(Coverage);
208}
209
Justin Bogner19a93ba2014-09-20 17:19:52 +0000210ErrorOr<std::unique_ptr<CoverageMapping>>
211CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename) {
212 auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
213 if (auto EC = CounterMappingBuff.getError())
214 return EC;
215 ObjectFileCoverageMappingReader CoverageReader(CounterMappingBuff.get());
216 if (auto EC = CoverageReader.readHeader())
217 return EC;
218 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
219 if (auto EC = IndexedInstrProfReader::create(ProfileFilename, ProfileReader))
220 return EC;
221 return load(CoverageReader, *ProfileReader);
222}
223
Justin Bogner953e2402014-09-20 15:31:56 +0000224namespace {
225/// \brief Distributes functions into instantiation sets.
226///
227/// An instantiation set is a collection of functions that have the same source
228/// code, ie, template functions specializations.
229class FunctionInstantiationSetCollector {
230 typedef DenseMap<std::pair<unsigned, unsigned>,
231 std::vector<const FunctionRecord *>> MapT;
232 MapT InstantiatedFunctions;
233
234public:
235 void insert(const FunctionRecord &Function, unsigned FileID) {
236 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
237 while (I != E && I->FileID != FileID)
238 ++I;
239 assert(I != E && "function does not cover the given file");
240 auto &Functions = InstantiatedFunctions[I->startLoc()];
241 Functions.push_back(&Function);
242 }
243
244 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
245
246 MapT::iterator end() { return InstantiatedFunctions.end(); }
247};
248
249class SegmentBuilder {
250 std::vector<CoverageSegment> Segments;
251 SmallVector<const CountedRegion *, 8> ActiveRegions;
252
253 /// Start a segment with no count specified.
254 void startSegment(unsigned Line, unsigned Col) {
Justin Bognerb35a72a2014-09-25 00:34:18 +0000255 DEBUG(dbgs() << "Top level segment at " << Line << ":" << Col << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000256 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
257 }
258
259 /// Start a segment with the given Region's count.
260 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
261 const CountedRegion &Region) {
262 if (Segments.empty())
263 Segments.emplace_back(Line, Col, IsRegionEntry);
264 CoverageSegment S = Segments.back();
265 // Avoid creating empty regions.
266 if (S.Line != Line || S.Col != Col) {
267 Segments.emplace_back(Line, Col, IsRegionEntry);
268 S = Segments.back();
269 }
Justin Bognerb35a72a2014-09-25 00:34:18 +0000270 DEBUG(dbgs() << "Segment at " << Line << ":" << Col);
Justin Bogner953e2402014-09-20 15:31:56 +0000271 // Set this region's count.
Justin Bognerb35a72a2014-09-25 00:34:18 +0000272 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion) {
273 DEBUG(dbgs() << " with count " << Region.ExecutionCount);
Justin Bogner953e2402014-09-20 15:31:56 +0000274 Segments.back().setCount(Region.ExecutionCount);
Justin Bognerb35a72a2014-09-25 00:34:18 +0000275 }
276 DEBUG(dbgs() << "\n");
Justin Bogner953e2402014-09-20 15:31:56 +0000277 }
278
279 /// Start a segment for the given region.
280 void startSegment(const CountedRegion &Region) {
281 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
282 }
283
284 /// Pop the top region off of the active stack, starting a new segment with
285 /// the containing Region's count.
286 void popRegion() {
287 const CountedRegion *Active = ActiveRegions.back();
288 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
289 ActiveRegions.pop_back();
290 if (ActiveRegions.empty())
291 startSegment(Line, Col);
292 else
293 startSegment(Line, Col, false, *ActiveRegions.back());
294 }
295
296public:
297 /// Build a list of CoverageSegments from a sorted list of Regions.
298 std::vector<CoverageSegment> buildSegments(ArrayRef<CountedRegion> Regions) {
299 for (const auto &Region : Regions) {
300 // Pop any regions that end before this one starts.
301 while (!ActiveRegions.empty() &&
302 ActiveRegions.back()->endLoc() <= Region.startLoc())
303 popRegion();
Justin Bognerb35a72a2014-09-25 00:34:18 +0000304 if (Segments.size() && Segments.back().Line == Region.LineStart &&
305 Segments.back().Col == Region.ColumnStart) {
306 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion)
307 Segments.back().addCount(Region.ExecutionCount);
308 } else {
309 // Add this region to the stack.
310 ActiveRegions.push_back(&Region);
311 startSegment(Region);
312 }
Justin Bogner953e2402014-09-20 15:31:56 +0000313 }
314 // Pop any regions that are left in the stack.
315 while (!ActiveRegions.empty())
316 popRegion();
317 return Segments;
318 }
319};
320}
321
322std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() {
323 std::vector<StringRef> Filenames;
324 for (const auto &Function : getCoveredFunctions())
325 for (const auto &Filename : Function.Filenames)
326 Filenames.push_back(Filename);
327 std::sort(Filenames.begin(), Filenames.end());
328 auto Last = std::unique(Filenames.begin(), Filenames.end());
329 Filenames.erase(Last, Filenames.end());
330 return Filenames;
331}
332
333static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
334 const FunctionRecord &Function) {
335 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
336 llvm::SmallVector<bool, 8> FilenameEquivalence(Function.Filenames.size(),
337 false);
338 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
339 if (SourceFile == Function.Filenames[I])
340 FilenameEquivalence[I] = true;
341 for (const auto &CR : Function.CountedRegions)
342 if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
343 FilenameEquivalence[CR.FileID])
344 IsExpandedFile[CR.ExpandedFileID] = true;
345 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
346 if (FilenameEquivalence[I] && !IsExpandedFile[I])
347 return I;
348 return None;
349}
350
351static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
352 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
353 for (const auto &CR : Function.CountedRegions)
354 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
355 IsExpandedFile[CR.ExpandedFileID] = true;
356 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
357 if (!IsExpandedFile[I])
358 return I;
359 return None;
360}
361
362static SmallSet<unsigned, 8> gatherFileIDs(StringRef SourceFile,
363 const FunctionRecord &Function) {
364 SmallSet<unsigned, 8> IDs;
365 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
366 if (SourceFile == Function.Filenames[I])
367 IDs.insert(I);
368 return IDs;
369}
370
371/// Sort a nested sequence of regions from a single file.
372template <class It> static void sortNestedRegions(It First, It Last) {
373 std::sort(First, Last,
374 [](const CountedRegion &LHS, const CountedRegion &RHS) {
375 if (LHS.startLoc() == RHS.startLoc())
376 // When LHS completely contains RHS, we sort LHS first.
377 return RHS.endLoc() < LHS.endLoc();
378 return LHS.startLoc() < RHS.startLoc();
379 });
380}
381
382static bool isExpansion(const CountedRegion &R, unsigned FileID) {
383 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
384}
385
386CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
387 CoverageData FileCoverage(Filename);
388 std::vector<coverage::CountedRegion> Regions;
389
390 for (const auto &Function : Functions) {
391 auto MainFileID = findMainViewFileID(Filename, Function);
392 if (!MainFileID)
393 continue;
394 auto FileIDs = gatherFileIDs(Filename, Function);
395 for (const auto &CR : Function.CountedRegions)
396 if (FileIDs.count(CR.FileID)) {
397 Regions.push_back(CR);
398 if (isExpansion(CR, *MainFileID))
399 FileCoverage.Expansions.emplace_back(CR, Function);
400 }
401 }
402
403 sortNestedRegions(Regions.begin(), Regions.end());
404 FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
405
406 return FileCoverage;
407}
408
409std::vector<const FunctionRecord *>
410CoverageMapping::getInstantiations(StringRef Filename) {
411 FunctionInstantiationSetCollector InstantiationSetCollector;
412 for (const auto &Function : Functions) {
413 auto MainFileID = findMainViewFileID(Filename, Function);
414 if (!MainFileID)
415 continue;
416 InstantiationSetCollector.insert(Function, *MainFileID);
417 }
418
419 std::vector<const FunctionRecord *> Result;
420 for (const auto &InstantiationSet : InstantiationSetCollector) {
421 if (InstantiationSet.second.size() < 2)
422 continue;
423 for (auto Function : InstantiationSet.second)
424 Result.push_back(Function);
425 }
426 return Result;
427}
428
429CoverageData
430CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
431 auto MainFileID = findMainViewFileID(Function);
432 if (!MainFileID)
433 return CoverageData();
434
435 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
436 std::vector<coverage::CountedRegion> Regions;
437 for (const auto &CR : Function.CountedRegions)
438 if (CR.FileID == *MainFileID) {
439 Regions.push_back(CR);
440 if (isExpansion(CR, *MainFileID))
441 FunctionCoverage.Expansions.emplace_back(CR, Function);
442 }
443
444 sortNestedRegions(Regions.begin(), Regions.end());
445 FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
446
447 return FunctionCoverage;
448}
449
450CoverageData
451CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
452 CoverageData ExpansionCoverage(
453 Expansion.Function.Filenames[Expansion.FileID]);
454 std::vector<coverage::CountedRegion> Regions;
455 for (const auto &CR : Expansion.Function.CountedRegions)
456 if (CR.FileID == Expansion.FileID) {
457 Regions.push_back(CR);
458 if (isExpansion(CR, Expansion.FileID))
459 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
460 }
461
462 sortNestedRegions(Regions.begin(), Regions.end());
463 ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
464
465 return ExpansionCoverage;
466}