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