llvm-cov: Allow creating CoverageMappings from filenames
[oota-llvm.git] / lib / ProfileData / CoverageMapping.cpp
1 //=-- 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"
16
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"
23
24 using namespace llvm;
25 using namespace coverage;
26
27 CounterExpressionBuilder::CounterExpressionBuilder(unsigned NumCounterValues) {
28   Terms.resize(NumCounterValues);
29 }
30
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);
35   }
36   Expressions.push_back(E);
37   return Counter::getExpression(Expressions.size() - 1);
38 }
39
40 void CounterExpressionBuilder::extractTerms(Counter C, int Sign) {
41   switch (C.getKind()) {
42   case Counter::Zero:
43     break;
44   case Counter::CounterValueReference:
45     Terms[C.getCounterID()] += Sign;
46     break;
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);
51     break;
52   }
53 }
54
55 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) {
56   // Gather constant terms.
57   for (auto &I : Terms)
58     I = 0;
59   extractTerms(ExpressionTree);
60
61   Counter C;
62   // Create additions.
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) {
66     if (Terms[I] <= 0)
67       continue;
68     for (int J = 0; J < Terms[I]; ++J) {
69       if (C.isZero())
70         C = Counter::getCounter(I);
71       else
72         C = get(CounterExpression(CounterExpression::Add, C,
73                                   Counter::getCounter(I)));
74     }
75   }
76
77   // Create subtractions.
78   for (unsigned I = 0, S = Terms.size(); I < S; ++I) {
79     if (Terms[I] >= 0)
80       continue;
81     for (int J = 0; J < (-Terms[I]); ++J)
82       C = get(CounterExpression(CounterExpression::Subtract, C,
83                                 Counter::getCounter(I)));
84   }
85   return C;
86 }
87
88 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) {
89   return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS)));
90 }
91
92 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) {
93   return simplify(
94       get(CounterExpression(CounterExpression::Subtract, LHS, RHS)));
95 }
96
97 void CounterMappingContext::dump(const Counter &C,
98                                  llvm::raw_ostream &OS) const {
99   switch (C.getKind()) {
100   case Counter::Zero:
101     OS << '0';
102     return;
103   case Counter::CounterValueReference:
104     OS << '#' << C.getCounterID();
105     break;
106   case Counter::Expression: {
107     if (C.getExpressionID() >= Expressions.size())
108       return;
109     const auto &E = Expressions[C.getExpressionID()];
110     OS << '(';
111     dump(E.LHS, OS);
112     OS << (E.Kind == CounterExpression::Subtract ? " - " : " + ");
113     dump(E.RHS, OS);
114     OS << ')';
115     break;
116   }
117   }
118   if (CounterValues.empty())
119     return;
120   ErrorOr<int64_t> Value = evaluate(C);
121   if (!Value)
122     return;
123   OS << '[' << *Value << ']';
124 }
125
126 ErrorOr<int64_t> CounterMappingContext::evaluate(const Counter &C) const {
127   switch (C.getKind()) {
128   case Counter::Zero:
129     return 0;
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);
139     if (!LHS)
140       return LHS;
141     ErrorOr<int64_t> RHS = evaluate(E.RHS);
142     if (!RHS)
143       return RHS;
144     return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS;
145   }
146   }
147   llvm_unreachable("Unhandled CounterKind");
148 }
149
150 ErrorOr<std::unique_ptr<CoverageMapping>>
151 CoverageMapping::load(ObjectFileCoverageMappingReader &CoverageReader,
152                       IndexedInstrProfReader &ProfileReader) {
153   auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping());
154
155   std::vector<uint64_t> Counts;
156   for (const auto &Record : CoverageReader) {
157     Counts.clear();
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)
162         return EC;
163       Coverage->MismatchedFunctionCount++;
164       continue;
165     }
166
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);
171       if (!ExecutionCount)
172         break;
173       Function.CountedRegions.push_back(CountedRegion(Region, *ExecutionCount));
174     }
175     if (Function.CountedRegions.size() != Record.MappingRegions.size()) {
176       Coverage->MismatchedFunctionCount++;
177       continue;
178     }
179
180     Coverage->Functions.push_back(Function);
181   }
182
183   return std::move(Coverage);
184 }
185
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())
190     return EC;
191   ObjectFileCoverageMappingReader CoverageReader(CounterMappingBuff.get());
192   if (auto EC = CoverageReader.readHeader())
193     return EC;
194   std::unique_ptr<IndexedInstrProfReader> ProfileReader;
195   if (auto EC = IndexedInstrProfReader::create(ProfileFilename, ProfileReader))
196     return EC;
197   return load(CoverageReader, *ProfileReader);
198 }
199
200 namespace {
201 /// \brief Distributes functions into instantiation sets.
202 ///
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;
209
210 public:
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)
214       ++I;
215     assert(I != E && "function does not cover the given file");
216     auto &Functions = InstantiatedFunctions[I->startLoc()];
217     Functions.push_back(&Function);
218   }
219
220   MapT::iterator begin() { return InstantiatedFunctions.begin(); }
221
222   MapT::iterator end() { return InstantiatedFunctions.end(); }
223 };
224
225 class SegmentBuilder {
226   std::vector<CoverageSegment> Segments;
227   SmallVector<const CountedRegion *, 8> ActiveRegions;
228
229   /// Start a segment with no count specified.
230   void startSegment(unsigned Line, unsigned Col) {
231     Segments.emplace_back(Line, Col, /*IsRegionEntry=*/false);
232   }
233
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);
243       S = Segments.back();
244     }
245     // Set this region's count.
246     if (Region.Kind != coverage::CounterMappingRegion::SkippedRegion)
247       Segments.back().setCount(Region.ExecutionCount);
248   }
249
250   /// Start a segment for the given region.
251   void startSegment(const CountedRegion &Region) {
252     startSegment(Region.LineStart, Region.ColumnStart, true, Region);
253   }
254
255   /// Pop the top region off of the active stack, starting a new segment with
256   /// the containing Region's count.
257   void popRegion() {
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);
263     else
264       startSegment(Line, Col, false, *ActiveRegions.back());
265   }
266
267 public:
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())
274         popRegion();
275       // Add this region to the stack.
276       ActiveRegions.push_back(&Region);
277       startSegment(Region);
278     }
279     // Pop any regions that are left in the stack.
280     while (!ActiveRegions.empty())
281       popRegion();
282     return Segments;
283   }
284 };
285 }
286
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());
295   return Filenames;
296 }
297
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(),
302                                                  false);
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])
312       return I;
313   return None;
314 }
315
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])
323       return I;
324   return None;
325 }
326
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])
332       IDs.insert(I);
333   return IDs;
334 }
335
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();
344   });
345 }
346
347 static bool isExpansion(const CountedRegion &R, unsigned FileID) {
348   return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID;
349 }
350
351 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) {
352   CoverageData FileCoverage(Filename);
353   std::vector<coverage::CountedRegion> Regions;
354
355   for (const auto &Function : Functions) {
356     auto MainFileID = findMainViewFileID(Filename, Function);
357     if (!MainFileID)
358       continue;
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);
365       }
366   }
367
368   sortNestedRegions(Regions.begin(), Regions.end());
369   FileCoverage.Segments = SegmentBuilder().buildSegments(Regions);
370
371   return FileCoverage;
372 }
373
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);
379     if (!MainFileID)
380       continue;
381     InstantiationSetCollector.insert(Function, *MainFileID);
382   }
383
384   std::vector<const FunctionRecord *> Result;
385   for (const auto &InstantiationSet : InstantiationSetCollector) {
386     if (InstantiationSet.second.size() < 2)
387       continue;
388     for (auto Function : InstantiationSet.second)
389       Result.push_back(Function);
390   }
391   return Result;
392 }
393
394 CoverageData
395 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) {
396   auto MainFileID = findMainViewFileID(Function);
397   if (!MainFileID)
398     return CoverageData();
399
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);
407     }
408
409   sortNestedRegions(Regions.begin(), Regions.end());
410   FunctionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
411
412   return FunctionCoverage;
413 }
414
415 CoverageData
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);
425     }
426
427   sortNestedRegions(Regions.begin(), Regions.end());
428   ExpansionCoverage.Segments = SegmentBuilder().buildSegments(Regions);
429
430   return ExpansionCoverage;
431 }