1 //=-- CoverageMapping.cpp - Code coverage mapping support ---------*- C++ -*-=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains support for clang's and llvm's instrumentation based
13 //===----------------------------------------------------------------------===//
15 #include "llvm/ProfileData/CoverageMapping.h"
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"
22 #include "llvm/Support/ErrorHandling.h"
25 using namespace coverage;
27 CounterExpressionBuilder::CounterExpressionBuilder(unsigned NumCounterValues) {
28 Terms.resize(NumCounterValues);
31 Counter CounterExpressionBuilder::get(const CounterExpression &E) {
32 for (unsigned I = 0, S = Expressions.size(); I < S; ++I) {
33 if (Expressions[I] == E)
34 return Counter::getExpression(I);
36 Expressions.push_back(E);
37 return Counter::getExpression(Expressions.size() - 1);
40 void CounterExpressionBuilder::extractTerms(Counter C, int Sign) {
41 switch (C.getKind()) {
44 case Counter::CounterValueReference:
45 Terms[C.getCounterID()] += Sign;
47 case Counter::Expression:
48 const auto &E = Expressions[C.getExpressionID()];
49 extractTerms(E.LHS, Sign);
50 extractTerms(E.RHS, E.Kind == CounterExpression::Subtract ? -Sign : Sign);
55 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
56 // Gather constant terms.
59 extractTerms(ExpressionTree);
63 // Note: the additions are created first
64 // to avoid creation of a tree like ((0 - X) + Y) instead of (Y - X).
65 for (unsigned I = 0, S = Terms.size(); I < S; ++I) {
68 for (int J = 0; J < Terms[I]; ++J) {
70 C = Counter::getCounter(I);
72 C = get(CounterExpression(CounterExpression::Add, C,
73 Counter::getCounter(I)));
77 // Create subtractions.
78 for (unsigned I = 0, S = Terms.size(); I < S; ++I) {
81 for (int J = 0; J < (-Terms[I]); ++J)
82 C = get(CounterExpression(CounterExpression::Subtract, C,
83 Counter::getCounter(I)));
88 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
89 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
92 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
94 get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
97 void CounterMappingContext::dump(const Counter &C,
98 llvm::raw_ostream &OS) const {
99 switch (C.getKind()) {
103 case Counter::CounterValueReference:
104 OS << '#' << C.getCounterID();
106 case Counter::Expression: {
107 if (C.getExpressionID() >= Expressions.size())
109 const auto &E = Expressions[C.getExpressionID()];
112 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
118 if (CounterValues.empty())
120 ErrorOr<int64_t> Value = evaluate(C);
123 OS << '[' << *Value << ']';
126 ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
127 switch (C.getKind()) {
130 case Counter::CounterValueReference:
131 if (C.getCounterID() >= CounterValues.size())
132 return std::make_error_code(std::errc::argument_out_of_domain);
133 return CounterValues[C.getCounterID()];
134 case Counter::Expression: {
135 if (C.getExpressionID() >= Expressions.size())
136 return std::make_error_code(std::errc::argument_out_of_domain);
137 const auto &E = Expressions[C.getExpressionID()];
138 ErrorOr<int64_t> LHS = evaluate(E.LHS);
141 ErrorOr<int64_t> RHS = evaluate(E.RHS);
144 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
147 llvm_unreachable("Unhandled CounterKind");
150 ErrorOr<std::unique_ptr<CoverageMapping>>
151 CoverageMapping::load(ObjectFileCoverageMappingReader &CoverageReader,
152 IndexedInstrProfReader &ProfileReader) {
153 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
155 std::vector<uint64_t> Counts;
156 for (const auto &Record : CoverageReader) {
158 if (std::error_code EC = ProfileReader.getFunctionCounts(
159 Record.FunctionName, Record.FunctionHash, Counts)) {
160 if (EC != instrprof_error::hash_mismatch &&
161 EC != instrprof_error::unknown_function)
163 Coverage->MismatchedFunctionCount++;
167 FunctionRecord Function(Record.FunctionName, Record.Filenames);
168 CounterMappingContext Ctx(Record.Expressions, Counts);
169 for (const auto &Region : Record.MappingRegions) {
170 ErrorOr<int64_t> ExecutionCount = Ctx.evaluate(Region.Count);
173 Function.CountedRegions.push_back(CountedRegion(Region, *ExecutionCount));
175 if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
176 Coverage->MismatchedFunctionCount++;
180 Coverage->Functions.push_back(Function);
183 return std::move(Coverage);
186 ErrorOr<std::unique_ptr<CoverageMapping>>
187 CoverageMapping::load(StringRef ObjectFilename, StringRef ProfileFilename) {
188 auto CounterMappingBuff = MemoryBuffer::getFileOrSTDIN(ObjectFilename);
189 if (auto EC = CounterMappingBuff.getError())
191 ObjectFileCoverageMappingReader CoverageReader(CounterMappingBuff.get());
192 if (auto EC = CoverageReader.readHeader())
194 std::unique_ptr<IndexedInstrProfReader> ProfileReader;
195 if (auto EC = IndexedInstrProfReader::create(ProfileFilename, ProfileReader))
197 return load(CoverageReader, *ProfileReader);
201 /// \brief Distributes functions into instantiation sets.
203 /// An instantiation set is a collection of functions that have the same source
204 /// code, ie, template functions specializations.
205 class FunctionInstantiationSetCollector {
206 typedef DenseMap<std::pair<unsigned, unsigned>,
207 std::vector<const FunctionRecord *>> MapT;
208 MapT InstantiatedFunctions;
211 void insert(const FunctionRecord &Function, unsigned FileID) {
212 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end();
213 while (I != E && I->FileID != FileID)
215 assert(I != E && "function does not cover the given file");
216 auto &Functions = InstantiatedFunctions[I->startLoc()];
217 Functions.push_back(&Function);
220 MapT::iterator begin() { return InstantiatedFunctions.begin(); }
222 MapT::iterator end() { return InstantiatedFunctions.end(); }
225 class SegmentBuilder {
226 std::vector<CoverageSegment> Segments;
227 SmallVector<const CountedRegion *, 8> ActiveRegions;
229 /// Start a segment with no count specified.
230 void startSegment(unsigned Line, unsigned Col) {
231 Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
234 /// Start a segment with the given Region's count.
235 void startSegment(unsigned Line, unsigned Col, bool IsRegionEntry,
236 const CountedRegion &Region) {
237 if (Segments.empty())
238 Segments.emplace_back(Line, Col, IsRegionEntry);
239 CoverageSegment S = Segments.back();
240 // Avoid creating empty regions.
241 if (S.Line != Line || S.Col != Col) {
242 Segments.emplace_back(Line, Col, IsRegionEntry);
245 // Set this region's count.
246 if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion)
247 Segments.back().setCount(Region.ExecutionCount);
250 /// Start a segment for the given region.
251 void startSegment(const CountedRegion &Region) {
252 startSegment(Region.LineStart, Region.ColumnStart, true, Region);
255 /// Pop the top region off of the active stack, starting a new segment with
256 /// the containing Region's count.
258 const CountedRegion *Active = ActiveRegions.back();
259 unsigned Line = Active->LineEnd, Col = Active->ColumnEnd;
260 ActiveRegions.pop_back();
261 if (ActiveRegions.empty())
262 startSegment(Line, Col);
264 startSegment(Line, Col, false, *ActiveRegions.back());
268 /// Build a list of CoverageSegments from a sorted list of Regions.
269 std::vector<CoverageSegment> buildSegments(ArrayRef<CountedRegion> Regions) {
270 for (const auto &Region : Regions) {
271 // Pop any regions that end before this one starts.
272 while (!ActiveRegions.empty() &&
273 ActiveRegions.back()->endLoc() <= Region.startLoc())
275 // Add this region to the stack.
276 ActiveRegions.push_back(&Region);
277 startSegment(Region);
279 // Pop any regions that are left in the stack.
280 while (!ActiveRegions.empty())
287 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() {
288 std::vector<StringRef> Filenames;
289 for (const auto &Function : getCoveredFunctions())
290 for (const auto &Filename : Function.Filenames)
291 Filenames.push_back(Filename);
292 std::sort(Filenames.begin(), Filenames.end());
293 auto Last = std::unique(Filenames.begin(), Filenames.end());
294 Filenames.erase(Last, Filenames.end());
298 static Optional<unsigned> findMainViewFileID(StringRef SourceFile,
299 const FunctionRecord &Function) {
300 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
301 llvm::SmallVector<bool, 8> FilenameEquivalence(Function.Filenames.size(),
303 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
304 if (SourceFile == Function.Filenames[I])
305 FilenameEquivalence[I] = true;
306 for (const auto &CR : Function.CountedRegions)
307 if (CR.Kind == CounterMappingRegion::ExpansionRegion &&
308 FilenameEquivalence[CR.FileID])
309 IsExpandedFile[CR.ExpandedFileID] = true;
310 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
311 if (FilenameEquivalence[I] && !IsExpandedFile[I])
316 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) {
317 llvm::SmallVector<bool, 8> IsExpandedFile(Function.Filenames.size(), false);
318 for (const auto &CR : Function.CountedRegions)
319 if (CR.Kind == CounterMappingRegion::ExpansionRegion)
320 IsExpandedFile[CR.ExpandedFileID] = true;
321 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
322 if (!IsExpandedFile[I])
327 static SmallSet<unsigned, 8> gatherFileIDs(StringRef SourceFile,
328 const FunctionRecord &Function) {
329 SmallSet<unsigned, 8> IDs;
330 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I)
331 if (SourceFile == Function.Filenames[I])
336 /// Sort a nested sequence of regions from a single file.
337 template <class It> static void sortNestedRegions(It First, It Last) {
338 std::sort(First, Last,
339 [](const CountedRegion &LHS, const CountedRegion &RHS) {
340 if (LHS.startLoc() == RHS.startLoc())
341 // When LHS completely contains RHS, we sort LHS first.
342 return RHS.endLoc() < LHS.endLoc();
343 return LHS.startLoc() < RHS.startLoc();
347 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
348 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
351 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
352 CoverageData FileCoverage(Filename);
353 std::vector<coverage::CountedRegion> Regions;
355 for (const auto &Function : Functions) {
356 auto MainFileID = findMainViewFileID(Filename, Function);
359 auto FileIDs = gatherFileIDs(Filename, Function);
360 for (const auto &CR : Function.CountedRegions)
361 if (FileIDs.count(CR.FileID)) {
362 Regions.push_back(CR);
363 if (isExpansion(CR, *MainFileID))
364 FileCoverage.Expansions.emplace_back(CR, Function);
368 sortNestedRegions(Regions.begin(), Regions.end());
369 FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
374 std::vector<const FunctionRecord *>
375 CoverageMapping::getInstantiations(StringRef Filename) {
376 FunctionInstantiationSetCollector InstantiationSetCollector;
377 for (const auto &Function : Functions) {
378 auto MainFileID = findMainViewFileID(Filename, Function);
381 InstantiationSetCollector.insert(Function, *MainFileID);
384 std::vector<const FunctionRecord *> Result;
385 for (const auto &InstantiationSet : InstantiationSetCollector) {
386 if (InstantiationSet.second.size() < 2)
388 for (auto Function : InstantiationSet.second)
389 Result.push_back(Function);
395 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
396 auto MainFileID = findMainViewFileID(Function);
398 return CoverageData();
400 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]);
401 std::vector<coverage::CountedRegion> Regions;
402 for (const auto &CR : Function.CountedRegions)
403 if (CR.FileID == *MainFileID) {
404 Regions.push_back(CR);
405 if (isExpansion(CR, *MainFileID))
406 FunctionCoverage.Expansions.emplace_back(CR, Function);
409 sortNestedRegions(Regions.begin(), Regions.end());
410 FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
412 return FunctionCoverage;
416 CoverageMapping::getCoverageForExpansion(const ExpansionRecord &Expansion) {
417 CoverageData ExpansionCoverage(
418 Expansion.Function.Filenames[Expansion.FileID]);
419 std::vector<coverage::CountedRegion> Regions;
420 for (const auto &CR : Expansion.Function.CountedRegions)
421 if (CR.FileID == Expansion.FileID) {
422 Regions.push_back(CR);
423 if (isExpansion(CR, Expansion.FileID))
424 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function);
427 sortNestedRegions(Regions.begin(), Regions.end());
428 ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
430 return ExpansionCoverage;