1dc707122SEaswaran Raman //=-- CoverageMappingReader.cpp - Code coverage mapping reader ----*- C++ -*-=//
2dc707122SEaswaran Raman //
3dc707122SEaswaran Raman //                     The LLVM Compiler Infrastructure
4dc707122SEaswaran Raman //
5dc707122SEaswaran Raman // This file is distributed under the University of Illinois Open Source
6dc707122SEaswaran Raman // License. See LICENSE.TXT for details.
7dc707122SEaswaran Raman //
8dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
9dc707122SEaswaran Raman //
10dc707122SEaswaran Raman // This file contains support for reading coverage mapping data for
11dc707122SEaswaran Raman // instrumentation based coverage.
12dc707122SEaswaran Raman //
13dc707122SEaswaran Raman //===----------------------------------------------------------------------===//
14dc707122SEaswaran Raman 
15dc707122SEaswaran Raman #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
16ac40e819SIgor Kudrin #include "llvm/ADT/DenseMap.h"
17dc707122SEaswaran Raman #include "llvm/Object/MachOUniversal.h"
18dc707122SEaswaran Raman #include "llvm/Object/ObjectFile.h"
19dc707122SEaswaran Raman #include "llvm/Support/Debug.h"
20dc707122SEaswaran Raman #include "llvm/Support/Endian.h"
21dc707122SEaswaran Raman #include "llvm/Support/LEB128.h"
22dc707122SEaswaran Raman #include "llvm/Support/MathExtras.h"
23dc707122SEaswaran Raman #include "llvm/Support/raw_ostream.h"
24dc707122SEaswaran Raman 
25dc707122SEaswaran Raman using namespace llvm;
26dc707122SEaswaran Raman using namespace coverage;
27dc707122SEaswaran Raman using namespace object;
28dc707122SEaswaran Raman 
29dc707122SEaswaran Raman #define DEBUG_TYPE "coverage-mapping"
30dc707122SEaswaran Raman 
31dc707122SEaswaran Raman void CoverageMappingIterator::increment() {
32dc707122SEaswaran Raman   // Check if all the records were read or if an error occurred while reading
33dc707122SEaswaran Raman   // the next record.
349152fd17SVedant Kumar   if (auto E = Reader->readNextRecord(Record)) {
359152fd17SVedant Kumar     handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
369152fd17SVedant Kumar       if (CME.get() == coveragemap_error::eof)
37dc707122SEaswaran Raman         *this = CoverageMappingIterator();
389152fd17SVedant Kumar       else
399152fd17SVedant Kumar         llvm_unreachable("Unexpected error in coverage mapping iterator");
409152fd17SVedant Kumar     });
419152fd17SVedant Kumar   }
42dc707122SEaswaran Raman }
43dc707122SEaswaran Raman 
449152fd17SVedant Kumar Error RawCoverageReader::readULEB128(uint64_t &Result) {
45dc707122SEaswaran Raman   if (Data.size() < 1)
469152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
47dc707122SEaswaran Raman   unsigned N = 0;
48dc707122SEaswaran Raman   Result = decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
49dc707122SEaswaran Raman   if (N > Data.size())
509152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
51dc707122SEaswaran Raman   Data = Data.substr(N);
529152fd17SVedant Kumar   return Error::success();
53dc707122SEaswaran Raman }
54dc707122SEaswaran Raman 
559152fd17SVedant Kumar Error RawCoverageReader::readIntMax(uint64_t &Result, uint64_t MaxPlus1) {
56dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
57dc707122SEaswaran Raman     return Err;
58dc707122SEaswaran Raman   if (Result >= MaxPlus1)
599152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
609152fd17SVedant Kumar   return Error::success();
61dc707122SEaswaran Raman }
62dc707122SEaswaran Raman 
639152fd17SVedant Kumar Error RawCoverageReader::readSize(uint64_t &Result) {
64dc707122SEaswaran Raman   if (auto Err = readULEB128(Result))
65dc707122SEaswaran Raman     return Err;
66dc707122SEaswaran Raman   // Sanity check the number.
67dc707122SEaswaran Raman   if (Result > Data.size())
689152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
699152fd17SVedant Kumar   return Error::success();
70dc707122SEaswaran Raman }
71dc707122SEaswaran Raman 
729152fd17SVedant Kumar Error RawCoverageReader::readString(StringRef &Result) {
73dc707122SEaswaran Raman   uint64_t Length;
74dc707122SEaswaran Raman   if (auto Err = readSize(Length))
75dc707122SEaswaran Raman     return Err;
76dc707122SEaswaran Raman   Result = Data.substr(0, Length);
77dc707122SEaswaran Raman   Data = Data.substr(Length);
789152fd17SVedant Kumar   return Error::success();
79dc707122SEaswaran Raman }
80dc707122SEaswaran Raman 
819152fd17SVedant Kumar Error RawCoverageFilenamesReader::read() {
82dc707122SEaswaran Raman   uint64_t NumFilenames;
83dc707122SEaswaran Raman   if (auto Err = readSize(NumFilenames))
84dc707122SEaswaran Raman     return Err;
85dc707122SEaswaran Raman   for (size_t I = 0; I < NumFilenames; ++I) {
86dc707122SEaswaran Raman     StringRef Filename;
87dc707122SEaswaran Raman     if (auto Err = readString(Filename))
88dc707122SEaswaran Raman       return Err;
89dc707122SEaswaran Raman     Filenames.push_back(Filename);
90dc707122SEaswaran Raman   }
919152fd17SVedant Kumar   return Error::success();
92dc707122SEaswaran Raman }
93dc707122SEaswaran Raman 
949152fd17SVedant Kumar Error RawCoverageMappingReader::decodeCounter(unsigned Value, Counter &C) {
95dc707122SEaswaran Raman   auto Tag = Value & Counter::EncodingTagMask;
96dc707122SEaswaran Raman   switch (Tag) {
97dc707122SEaswaran Raman   case Counter::Zero:
98dc707122SEaswaran Raman     C = Counter::getZero();
999152fd17SVedant Kumar     return Error::success();
100dc707122SEaswaran Raman   case Counter::CounterValueReference:
101dc707122SEaswaran Raman     C = Counter::getCounter(Value >> Counter::EncodingTagBits);
1029152fd17SVedant Kumar     return Error::success();
103dc707122SEaswaran Raman   default:
104dc707122SEaswaran Raman     break;
105dc707122SEaswaran Raman   }
106dc707122SEaswaran Raman   Tag -= Counter::Expression;
107dc707122SEaswaran Raman   switch (Tag) {
108dc707122SEaswaran Raman   case CounterExpression::Subtract:
109dc707122SEaswaran Raman   case CounterExpression::Add: {
110dc707122SEaswaran Raman     auto ID = Value >> Counter::EncodingTagBits;
111dc707122SEaswaran Raman     if (ID >= Expressions.size())
1129152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
113dc707122SEaswaran Raman     Expressions[ID].Kind = CounterExpression::ExprKind(Tag);
114dc707122SEaswaran Raman     C = Counter::getExpression(ID);
115dc707122SEaswaran Raman     break;
116dc707122SEaswaran Raman   }
117dc707122SEaswaran Raman   default:
1189152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
119dc707122SEaswaran Raman   }
1209152fd17SVedant Kumar   return Error::success();
121dc707122SEaswaran Raman }
122dc707122SEaswaran Raman 
1239152fd17SVedant Kumar Error RawCoverageMappingReader::readCounter(Counter &C) {
124dc707122SEaswaran Raman   uint64_t EncodedCounter;
125dc707122SEaswaran Raman   if (auto Err =
126dc707122SEaswaran Raman           readIntMax(EncodedCounter, std::numeric_limits<unsigned>::max()))
127dc707122SEaswaran Raman     return Err;
128dc707122SEaswaran Raman   if (auto Err = decodeCounter(EncodedCounter, C))
129dc707122SEaswaran Raman     return Err;
1309152fd17SVedant Kumar   return Error::success();
131dc707122SEaswaran Raman }
132dc707122SEaswaran Raman 
133dc707122SEaswaran Raman static const unsigned EncodingExpansionRegionBit = 1
134dc707122SEaswaran Raman                                                    << Counter::EncodingTagBits;
135dc707122SEaswaran Raman 
136dc707122SEaswaran Raman /// \brief Read the sub-array of regions for the given inferred file id.
137dc707122SEaswaran Raman /// \param NumFileIDs the number of file ids that are defined for this
138dc707122SEaswaran Raman /// function.
1399152fd17SVedant Kumar Error RawCoverageMappingReader::readMappingRegionsSubArray(
140dc707122SEaswaran Raman     std::vector<CounterMappingRegion> &MappingRegions, unsigned InferredFileID,
141dc707122SEaswaran Raman     size_t NumFileIDs) {
142dc707122SEaswaran Raman   uint64_t NumRegions;
143dc707122SEaswaran Raman   if (auto Err = readSize(NumRegions))
144dc707122SEaswaran Raman     return Err;
145dc707122SEaswaran Raman   unsigned LineStart = 0;
146dc707122SEaswaran Raman   for (size_t I = 0; I < NumRegions; ++I) {
147dc707122SEaswaran Raman     Counter C;
148dc707122SEaswaran Raman     CounterMappingRegion::RegionKind Kind = CounterMappingRegion::CodeRegion;
149dc707122SEaswaran Raman 
150dc707122SEaswaran Raman     // Read the combined counter + region kind.
151dc707122SEaswaran Raman     uint64_t EncodedCounterAndRegion;
152dc707122SEaswaran Raman     if (auto Err = readIntMax(EncodedCounterAndRegion,
153dc707122SEaswaran Raman                               std::numeric_limits<unsigned>::max()))
154dc707122SEaswaran Raman       return Err;
155dc707122SEaswaran Raman     unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
156dc707122SEaswaran Raman     uint64_t ExpandedFileID = 0;
157dc707122SEaswaran Raman     if (Tag != Counter::Zero) {
158dc707122SEaswaran Raman       if (auto Err = decodeCounter(EncodedCounterAndRegion, C))
159dc707122SEaswaran Raman         return Err;
160dc707122SEaswaran Raman     } else {
161dc707122SEaswaran Raman       // Is it an expansion region?
162dc707122SEaswaran Raman       if (EncodedCounterAndRegion & EncodingExpansionRegionBit) {
163dc707122SEaswaran Raman         Kind = CounterMappingRegion::ExpansionRegion;
164dc707122SEaswaran Raman         ExpandedFileID = EncodedCounterAndRegion >>
165dc707122SEaswaran Raman                          Counter::EncodingCounterTagAndExpansionRegionTagBits;
166dc707122SEaswaran Raman         if (ExpandedFileID >= NumFileIDs)
1679152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
168dc707122SEaswaran Raman       } else {
169dc707122SEaswaran Raman         switch (EncodedCounterAndRegion >>
170dc707122SEaswaran Raman                 Counter::EncodingCounterTagAndExpansionRegionTagBits) {
171dc707122SEaswaran Raman         case CounterMappingRegion::CodeRegion:
172dc707122SEaswaran Raman           // Don't do anything when we have a code region with a zero counter.
173dc707122SEaswaran Raman           break;
174dc707122SEaswaran Raman         case CounterMappingRegion::SkippedRegion:
175dc707122SEaswaran Raman           Kind = CounterMappingRegion::SkippedRegion;
176dc707122SEaswaran Raman           break;
177dc707122SEaswaran Raman         default:
1789152fd17SVedant Kumar           return make_error<CoverageMapError>(coveragemap_error::malformed);
179dc707122SEaswaran Raman         }
180dc707122SEaswaran Raman       }
181dc707122SEaswaran Raman     }
182dc707122SEaswaran Raman 
183dc707122SEaswaran Raman     // Read the source range.
184dc707122SEaswaran Raman     uint64_t LineStartDelta, ColumnStart, NumLines, ColumnEnd;
185dc707122SEaswaran Raman     if (auto Err =
186dc707122SEaswaran Raman             readIntMax(LineStartDelta, std::numeric_limits<unsigned>::max()))
187dc707122SEaswaran Raman       return Err;
188dc707122SEaswaran Raman     if (auto Err = readULEB128(ColumnStart))
189dc707122SEaswaran Raman       return Err;
190dc707122SEaswaran Raman     if (ColumnStart > std::numeric_limits<unsigned>::max())
1919152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
192dc707122SEaswaran Raman     if (auto Err = readIntMax(NumLines, std::numeric_limits<unsigned>::max()))
193dc707122SEaswaran Raman       return Err;
194dc707122SEaswaran Raman     if (auto Err = readIntMax(ColumnEnd, std::numeric_limits<unsigned>::max()))
195dc707122SEaswaran Raman       return Err;
196dc707122SEaswaran Raman     LineStart += LineStartDelta;
197dc707122SEaswaran Raman     // Adjust the column locations for the empty regions that are supposed to
198dc707122SEaswaran Raman     // cover whole lines. Those regions should be encoded with the
199dc707122SEaswaran Raman     // column range (1 -> std::numeric_limits<unsigned>::max()), but because
200dc707122SEaswaran Raman     // the encoded std::numeric_limits<unsigned>::max() is several bytes long,
201dc707122SEaswaran Raman     // we set the column range to (0 -> 0) to ensure that the column start and
202dc707122SEaswaran Raman     // column end take up one byte each.
203dc707122SEaswaran Raman     // The std::numeric_limits<unsigned>::max() is used to represent a column
204dc707122SEaswaran Raman     // position at the end of the line without knowing the length of that line.
205dc707122SEaswaran Raman     if (ColumnStart == 0 && ColumnEnd == 0) {
206dc707122SEaswaran Raman       ColumnStart = 1;
207dc707122SEaswaran Raman       ColumnEnd = std::numeric_limits<unsigned>::max();
208dc707122SEaswaran Raman     }
209dc707122SEaswaran Raman 
210dc707122SEaswaran Raman     DEBUG({
211dc707122SEaswaran Raman       dbgs() << "Counter in file " << InferredFileID << " " << LineStart << ":"
212dc707122SEaswaran Raman              << ColumnStart << " -> " << (LineStart + NumLines) << ":"
213dc707122SEaswaran Raman              << ColumnEnd << ", ";
214dc707122SEaswaran Raman       if (Kind == CounterMappingRegion::ExpansionRegion)
215dc707122SEaswaran Raman         dbgs() << "Expands to file " << ExpandedFileID;
216dc707122SEaswaran Raman       else
217dc707122SEaswaran Raman         CounterMappingContext(Expressions).dump(C, dbgs());
218dc707122SEaswaran Raman       dbgs() << "\n";
219dc707122SEaswaran Raman     });
220dc707122SEaswaran Raman 
221dc707122SEaswaran Raman     MappingRegions.push_back(CounterMappingRegion(
222dc707122SEaswaran Raman         C, InferredFileID, ExpandedFileID, LineStart, ColumnStart,
223dc707122SEaswaran Raman         LineStart + NumLines, ColumnEnd, Kind));
224dc707122SEaswaran Raman   }
2259152fd17SVedant Kumar   return Error::success();
226dc707122SEaswaran Raman }
227dc707122SEaswaran Raman 
2289152fd17SVedant Kumar Error RawCoverageMappingReader::read() {
229dc707122SEaswaran Raman 
230dc707122SEaswaran Raman   // Read the virtual file mapping.
231dc707122SEaswaran Raman   llvm::SmallVector<unsigned, 8> VirtualFileMapping;
232dc707122SEaswaran Raman   uint64_t NumFileMappings;
233dc707122SEaswaran Raman   if (auto Err = readSize(NumFileMappings))
234dc707122SEaswaran Raman     return Err;
235dc707122SEaswaran Raman   for (size_t I = 0; I < NumFileMappings; ++I) {
236dc707122SEaswaran Raman     uint64_t FilenameIndex;
237dc707122SEaswaran Raman     if (auto Err = readIntMax(FilenameIndex, TranslationUnitFilenames.size()))
238dc707122SEaswaran Raman       return Err;
239dc707122SEaswaran Raman     VirtualFileMapping.push_back(FilenameIndex);
240dc707122SEaswaran Raman   }
241dc707122SEaswaran Raman 
242dc707122SEaswaran Raman   // Construct the files using unique filenames and virtual file mapping.
243dc707122SEaswaran Raman   for (auto I : VirtualFileMapping) {
244dc707122SEaswaran Raman     Filenames.push_back(TranslationUnitFilenames[I]);
245dc707122SEaswaran Raman   }
246dc707122SEaswaran Raman 
247dc707122SEaswaran Raman   // Read the expressions.
248dc707122SEaswaran Raman   uint64_t NumExpressions;
249dc707122SEaswaran Raman   if (auto Err = readSize(NumExpressions))
250dc707122SEaswaran Raman     return Err;
251dc707122SEaswaran Raman   // Create an array of dummy expressions that get the proper counters
252dc707122SEaswaran Raman   // when the expressions are read, and the proper kinds when the counters
253dc707122SEaswaran Raman   // are decoded.
254dc707122SEaswaran Raman   Expressions.resize(
255dc707122SEaswaran Raman       NumExpressions,
256dc707122SEaswaran Raman       CounterExpression(CounterExpression::Subtract, Counter(), Counter()));
257dc707122SEaswaran Raman   for (size_t I = 0; I < NumExpressions; ++I) {
258dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].LHS))
259dc707122SEaswaran Raman       return Err;
260dc707122SEaswaran Raman     if (auto Err = readCounter(Expressions[I].RHS))
261dc707122SEaswaran Raman       return Err;
262dc707122SEaswaran Raman   }
263dc707122SEaswaran Raman 
264dc707122SEaswaran Raman   // Read the mapping regions sub-arrays.
265dc707122SEaswaran Raman   for (unsigned InferredFileID = 0, S = VirtualFileMapping.size();
266dc707122SEaswaran Raman        InferredFileID < S; ++InferredFileID) {
267dc707122SEaswaran Raman     if (auto Err = readMappingRegionsSubArray(MappingRegions, InferredFileID,
268dc707122SEaswaran Raman                                               VirtualFileMapping.size()))
269dc707122SEaswaran Raman       return Err;
270dc707122SEaswaran Raman   }
271dc707122SEaswaran Raman 
272dc707122SEaswaran Raman   // Set the counters for the expansion regions.
273dc707122SEaswaran Raman   // i.e. Counter of expansion region = counter of the first region
274dc707122SEaswaran Raman   // from the expanded file.
275dc707122SEaswaran Raman   // Perform multiple passes to correctly propagate the counters through
276dc707122SEaswaran Raman   // all the nested expansion regions.
277dc707122SEaswaran Raman   SmallVector<CounterMappingRegion *, 8> FileIDExpansionRegionMapping;
278dc707122SEaswaran Raman   FileIDExpansionRegionMapping.resize(VirtualFileMapping.size(), nullptr);
279dc707122SEaswaran Raman   for (unsigned Pass = 1, S = VirtualFileMapping.size(); Pass < S; ++Pass) {
280dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
281dc707122SEaswaran Raman       if (R.Kind != CounterMappingRegion::ExpansionRegion)
282dc707122SEaswaran Raman         continue;
283dc707122SEaswaran Raman       assert(!FileIDExpansionRegionMapping[R.ExpandedFileID]);
284dc707122SEaswaran Raman       FileIDExpansionRegionMapping[R.ExpandedFileID] = &R;
285dc707122SEaswaran Raman     }
286dc707122SEaswaran Raman     for (auto &R : MappingRegions) {
287dc707122SEaswaran Raman       if (FileIDExpansionRegionMapping[R.FileID]) {
288dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID]->Count = R.Count;
289dc707122SEaswaran Raman         FileIDExpansionRegionMapping[R.FileID] = nullptr;
290dc707122SEaswaran Raman       }
291dc707122SEaswaran Raman     }
292dc707122SEaswaran Raman   }
293dc707122SEaswaran Raman 
2949152fd17SVedant Kumar   return Error::success();
295dc707122SEaswaran Raman }
296dc707122SEaswaran Raman 
297ac40e819SIgor Kudrin Expected<bool> RawCoverageMappingDummyChecker::isDummy() {
298ac40e819SIgor Kudrin   // A dummy coverage mapping data consists of just one region with zero count.
299ac40e819SIgor Kudrin   uint64_t NumFileMappings;
300ac40e819SIgor Kudrin   if (Error Err = readSize(NumFileMappings))
301ac40e819SIgor Kudrin     return std::move(Err);
302ac40e819SIgor Kudrin   if (NumFileMappings != 1)
303ac40e819SIgor Kudrin     return false;
304ac40e819SIgor Kudrin   // We don't expect any specific value for the filename index, just skip it.
305ac40e819SIgor Kudrin   uint64_t FilenameIndex;
306ac40e819SIgor Kudrin   if (Error Err =
307ac40e819SIgor Kudrin           readIntMax(FilenameIndex, std::numeric_limits<unsigned>::max()))
308ac40e819SIgor Kudrin     return std::move(Err);
309ac40e819SIgor Kudrin   uint64_t NumExpressions;
310ac40e819SIgor Kudrin   if (Error Err = readSize(NumExpressions))
311ac40e819SIgor Kudrin     return std::move(Err);
312ac40e819SIgor Kudrin   if (NumExpressions != 0)
313ac40e819SIgor Kudrin     return false;
314ac40e819SIgor Kudrin   uint64_t NumRegions;
315ac40e819SIgor Kudrin   if (Error Err = readSize(NumRegions))
316ac40e819SIgor Kudrin     return std::move(Err);
317ac40e819SIgor Kudrin   if (NumRegions != 1)
318ac40e819SIgor Kudrin     return false;
319ac40e819SIgor Kudrin   uint64_t EncodedCounterAndRegion;
320ac40e819SIgor Kudrin   if (Error Err = readIntMax(EncodedCounterAndRegion,
321ac40e819SIgor Kudrin                              std::numeric_limits<unsigned>::max()))
322ac40e819SIgor Kudrin     return std::move(Err);
323ac40e819SIgor Kudrin   unsigned Tag = EncodedCounterAndRegion & Counter::EncodingTagMask;
324ac40e819SIgor Kudrin   return Tag == Counter::Zero;
325ac40e819SIgor Kudrin }
326ac40e819SIgor Kudrin 
3279152fd17SVedant Kumar Error InstrProfSymtab::create(SectionRef &Section) {
3289152fd17SVedant Kumar   if (auto EC = Section.getContents(Data))
3299152fd17SVedant Kumar     return errorCodeToError(EC);
330dc707122SEaswaran Raman   Address = Section.getAddress();
3319152fd17SVedant Kumar   return Error::success();
332dc707122SEaswaran Raman }
333dc707122SEaswaran Raman 
334dc707122SEaswaran Raman StringRef InstrProfSymtab::getFuncName(uint64_t Pointer, size_t Size) {
335dc707122SEaswaran Raman   if (Pointer < Address)
336dc707122SEaswaran Raman     return StringRef();
337dc707122SEaswaran Raman   auto Offset = Pointer - Address;
338dc707122SEaswaran Raman   if (Offset + Size > Data.size())
339dc707122SEaswaran Raman     return StringRef();
340dc707122SEaswaran Raman   return Data.substr(Pointer - Address, Size);
341dc707122SEaswaran Raman }
342dc707122SEaswaran Raman 
343ac40e819SIgor Kudrin // Check if the mapping data is a dummy, i.e. is emitted for an unused function.
344ac40e819SIgor Kudrin static Expected<bool> isCoverageMappingDummy(uint64_t Hash, StringRef Mapping) {
345ac40e819SIgor Kudrin   // The hash value of dummy mapping records is always zero.
346ac40e819SIgor Kudrin   if (Hash)
347ac40e819SIgor Kudrin     return false;
348ac40e819SIgor Kudrin   return RawCoverageMappingDummyChecker(Mapping).isDummy();
349ac40e819SIgor Kudrin }
350ac40e819SIgor Kudrin 
351dc707122SEaswaran Raman namespace {
352dc707122SEaswaran Raman struct CovMapFuncRecordReader {
353*3739b95dSVedant Kumar   // The interface to read coverage mapping function records for a module.
354*3739b95dSVedant Kumar   //
355*3739b95dSVedant Kumar   // \p Buf points to the buffer containing the \c CovHeader of the coverage
356*3739b95dSVedant Kumar   // mapping data associated with the module.
357*3739b95dSVedant Kumar   //
358*3739b95dSVedant Kumar   // Returns a pointer to the next \c CovHeader if it exists, or a pointer
359*3739b95dSVedant Kumar   // greater than \p End if not.
360*3739b95dSVedant Kumar   virtual Expected<const char *> readFunctionRecords(const char *Buf,
361*3739b95dSVedant Kumar                                                      const char *End) = 0;
362dc707122SEaswaran Raman   virtual ~CovMapFuncRecordReader() {}
363dc707122SEaswaran Raman   template <class IntPtrT, support::endianness Endian>
3649152fd17SVedant Kumar   static Expected<std::unique_ptr<CovMapFuncRecordReader>>
365dc707122SEaswaran Raman   get(coverage::CovMapVersion Version, InstrProfSymtab &P,
366dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
367dc707122SEaswaran Raman       std::vector<StringRef> &F);
368dc707122SEaswaran Raman };
369dc707122SEaswaran Raman 
370dc707122SEaswaran Raman // A class for reading coverage mapping function records for a module.
371dc707122SEaswaran Raman template <coverage::CovMapVersion Version, class IntPtrT,
372dc707122SEaswaran Raman           support::endianness Endian>
373dc707122SEaswaran Raman class VersionedCovMapFuncRecordReader : public CovMapFuncRecordReader {
374dc707122SEaswaran Raman   typedef typename coverage::CovMapTraits<
375dc707122SEaswaran Raman       Version, IntPtrT>::CovMapFuncRecordType FuncRecordType;
376dc707122SEaswaran Raman   typedef typename coverage::CovMapTraits<Version, IntPtrT>::NameRefType
377dc707122SEaswaran Raman       NameRefType;
378dc707122SEaswaran Raman 
379ac40e819SIgor Kudrin   // Maps function's name references to the indexes of their records
380ac40e819SIgor Kudrin   // in \c Records.
381ac40e819SIgor Kudrin   llvm::DenseMap<NameRefType, size_t> FunctionRecords;
382dc707122SEaswaran Raman   InstrProfSymtab &ProfileNames;
383dc707122SEaswaran Raman   std::vector<StringRef> &Filenames;
384dc707122SEaswaran Raman   std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records;
385dc707122SEaswaran Raman 
386ac40e819SIgor Kudrin   // Add the record to the collection if we don't already have a record that
387ac40e819SIgor Kudrin   // points to the same function name. This is useful to ignore the redundant
388ac40e819SIgor Kudrin   // records for the functions with ODR linkage.
389ac40e819SIgor Kudrin   // In addition, prefer records with real coverage mapping data to dummy
390ac40e819SIgor Kudrin   // records, which were emitted for inline functions which were seen but
391ac40e819SIgor Kudrin   // not used in the corresponding translation unit.
392ac40e819SIgor Kudrin   Error insertFunctionRecordIfNeeded(const FuncRecordType *CFR,
393ac40e819SIgor Kudrin                                      StringRef Mapping, size_t FilenamesBegin) {
394ac40e819SIgor Kudrin     uint64_t FuncHash = CFR->template getFuncHash<Endian>();
395ac40e819SIgor Kudrin     NameRefType NameRef = CFR->template getFuncNameRef<Endian>();
396ac40e819SIgor Kudrin     auto InsertResult =
397ac40e819SIgor Kudrin         FunctionRecords.insert(std::make_pair(NameRef, Records.size()));
398ac40e819SIgor Kudrin     if (InsertResult.second) {
399ac40e819SIgor Kudrin       StringRef FuncName;
400ac40e819SIgor Kudrin       if (Error Err = CFR->template getFuncName<Endian>(ProfileNames, FuncName))
401ac40e819SIgor Kudrin         return Err;
402ac40e819SIgor Kudrin       Records.emplace_back(Version, FuncName, FuncHash, Mapping, FilenamesBegin,
403ac40e819SIgor Kudrin                            Filenames.size() - FilenamesBegin);
404ac40e819SIgor Kudrin       return Error::success();
405ac40e819SIgor Kudrin     }
406ac40e819SIgor Kudrin     // Update the existing record if it's a dummy and the new record is real.
407ac40e819SIgor Kudrin     size_t OldRecordIndex = InsertResult.first->second;
408ac40e819SIgor Kudrin     BinaryCoverageReader::ProfileMappingRecord &OldRecord =
409ac40e819SIgor Kudrin         Records[OldRecordIndex];
410ac40e819SIgor Kudrin     Expected<bool> OldIsDummyExpected = isCoverageMappingDummy(
411ac40e819SIgor Kudrin         OldRecord.FunctionHash, OldRecord.CoverageMapping);
412ac40e819SIgor Kudrin     if (Error Err = OldIsDummyExpected.takeError())
413ac40e819SIgor Kudrin       return Err;
414ac40e819SIgor Kudrin     if (!*OldIsDummyExpected)
415ac40e819SIgor Kudrin       return Error::success();
416ac40e819SIgor Kudrin     Expected<bool> NewIsDummyExpected =
417ac40e819SIgor Kudrin         isCoverageMappingDummy(FuncHash, Mapping);
418ac40e819SIgor Kudrin     if (Error Err = NewIsDummyExpected.takeError())
419ac40e819SIgor Kudrin       return Err;
420ac40e819SIgor Kudrin     if (*NewIsDummyExpected)
421ac40e819SIgor Kudrin       return Error::success();
422ac40e819SIgor Kudrin     OldRecord.FunctionHash = FuncHash;
423ac40e819SIgor Kudrin     OldRecord.CoverageMapping = Mapping;
424ac40e819SIgor Kudrin     OldRecord.FilenamesBegin = FilenamesBegin;
425ac40e819SIgor Kudrin     OldRecord.FilenamesSize = Filenames.size() - FilenamesBegin;
426ac40e819SIgor Kudrin     return Error::success();
427ac40e819SIgor Kudrin   }
428ac40e819SIgor Kudrin 
429dc707122SEaswaran Raman public:
430dc707122SEaswaran Raman   VersionedCovMapFuncRecordReader(
431dc707122SEaswaran Raman       InstrProfSymtab &P,
432dc707122SEaswaran Raman       std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
433dc707122SEaswaran Raman       std::vector<StringRef> &F)
434dc707122SEaswaran Raman       : ProfileNames(P), Filenames(F), Records(R) {}
435dc707122SEaswaran Raman   ~VersionedCovMapFuncRecordReader() override {}
436dc707122SEaswaran Raman 
437*3739b95dSVedant Kumar   Expected<const char *> readFunctionRecords(const char *Buf,
438*3739b95dSVedant Kumar                                              const char *End) override {
439dc707122SEaswaran Raman     using namespace support;
440dc707122SEaswaran Raman     if (Buf + sizeof(CovMapHeader) > End)
4419152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
442dc707122SEaswaran Raman     auto CovHeader = reinterpret_cast<const coverage::CovMapHeader *>(Buf);
443dc707122SEaswaran Raman     uint32_t NRecords = CovHeader->getNRecords<Endian>();
444dc707122SEaswaran Raman     uint32_t FilenamesSize = CovHeader->getFilenamesSize<Endian>();
445dc707122SEaswaran Raman     uint32_t CoverageSize = CovHeader->getCoverageSize<Endian>();
446dc707122SEaswaran Raman     assert((CovMapVersion)CovHeader->getVersion<Endian>() == Version);
447dc707122SEaswaran Raman     Buf = reinterpret_cast<const char *>(CovHeader + 1);
448dc707122SEaswaran Raman 
449dc707122SEaswaran Raman     // Skip past the function records, saving the start and end for later.
450dc707122SEaswaran Raman     const char *FunBuf = Buf;
451dc707122SEaswaran Raman     Buf += NRecords * sizeof(FuncRecordType);
452dc707122SEaswaran Raman     const char *FunEnd = Buf;
453dc707122SEaswaran Raman 
454dc707122SEaswaran Raman     // Get the filenames.
455dc707122SEaswaran Raman     if (Buf + FilenamesSize > End)
4569152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
457dc707122SEaswaran Raman     size_t FilenamesBegin = Filenames.size();
458dc707122SEaswaran Raman     RawCoverageFilenamesReader Reader(StringRef(Buf, FilenamesSize), Filenames);
459dc707122SEaswaran Raman     if (auto Err = Reader.read())
460*3739b95dSVedant Kumar       return std::move(Err);
461dc707122SEaswaran Raman     Buf += FilenamesSize;
462dc707122SEaswaran Raman 
463dc707122SEaswaran Raman     // We'll read the coverage mapping records in the loop below.
464dc707122SEaswaran Raman     const char *CovBuf = Buf;
465dc707122SEaswaran Raman     Buf += CoverageSize;
466dc707122SEaswaran Raman     const char *CovEnd = Buf;
467dc707122SEaswaran Raman 
468dc707122SEaswaran Raman     if (Buf > End)
4699152fd17SVedant Kumar       return make_error<CoverageMapError>(coveragemap_error::malformed);
470dc707122SEaswaran Raman     // Each coverage map has an alignment of 8, so we need to adjust alignment
471dc707122SEaswaran Raman     // before reading the next map.
472dc707122SEaswaran Raman     Buf += alignmentAdjustment(Buf, 8);
473dc707122SEaswaran Raman 
474dc707122SEaswaran Raman     auto CFR = reinterpret_cast<const FuncRecordType *>(FunBuf);
475dc707122SEaswaran Raman     while ((const char *)CFR < FunEnd) {
476dc707122SEaswaran Raman       // Read the function information
477dc707122SEaswaran Raman       uint32_t DataSize = CFR->template getDataSize<Endian>();
478dc707122SEaswaran Raman 
479dc707122SEaswaran Raman       // Now use that to read the coverage data.
480dc707122SEaswaran Raman       if (CovBuf + DataSize > CovEnd)
4819152fd17SVedant Kumar         return make_error<CoverageMapError>(coveragemap_error::malformed);
482dc707122SEaswaran Raman       auto Mapping = StringRef(CovBuf, DataSize);
483dc707122SEaswaran Raman       CovBuf += DataSize;
484dc707122SEaswaran Raman 
485ac40e819SIgor Kudrin       if (Error Err =
486ac40e819SIgor Kudrin               insertFunctionRecordIfNeeded(CFR, Mapping, FilenamesBegin))
487*3739b95dSVedant Kumar         return std::move(Err);
488dc707122SEaswaran Raman       CFR++;
489dc707122SEaswaran Raman     }
490*3739b95dSVedant Kumar     return Buf;
491dc707122SEaswaran Raman   }
492dc707122SEaswaran Raman };
493dc707122SEaswaran Raman } // end anonymous namespace
494dc707122SEaswaran Raman 
495dc707122SEaswaran Raman template <class IntPtrT, support::endianness Endian>
4969152fd17SVedant Kumar Expected<std::unique_ptr<CovMapFuncRecordReader>> CovMapFuncRecordReader::get(
497dc707122SEaswaran Raman     coverage::CovMapVersion Version, InstrProfSymtab &P,
498dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &R,
499dc707122SEaswaran Raman     std::vector<StringRef> &F) {
500dc707122SEaswaran Raman   using namespace coverage;
501dc707122SEaswaran Raman   switch (Version) {
502dc707122SEaswaran Raman   case CovMapVersion::Version1:
503dc707122SEaswaran Raman     return llvm::make_unique<VersionedCovMapFuncRecordReader<
504dc707122SEaswaran Raman         CovMapVersion::Version1, IntPtrT, Endian>>(P, R, F);
505dc707122SEaswaran Raman   case CovMapVersion::Version2:
506dc707122SEaswaran Raman     // Decompress the name data.
5079152fd17SVedant Kumar     if (Error E = P.create(P.getNameData()))
5089152fd17SVedant Kumar       return std::move(E);
509dc707122SEaswaran Raman     return llvm::make_unique<VersionedCovMapFuncRecordReader<
510dc707122SEaswaran Raman         CovMapVersion::Version2, IntPtrT, Endian>>(P, R, F);
511dc707122SEaswaran Raman   }
512dc707122SEaswaran Raman   llvm_unreachable("Unsupported version");
513dc707122SEaswaran Raman }
514dc707122SEaswaran Raman 
515dc707122SEaswaran Raman template <typename T, support::endianness Endian>
5169152fd17SVedant Kumar static Error readCoverageMappingData(
517dc707122SEaswaran Raman     InstrProfSymtab &ProfileNames, StringRef Data,
518dc707122SEaswaran Raman     std::vector<BinaryCoverageReader::ProfileMappingRecord> &Records,
519dc707122SEaswaran Raman     std::vector<StringRef> &Filenames) {
520dc707122SEaswaran Raman   using namespace coverage;
521dc707122SEaswaran Raman   // Read the records in the coverage data section.
522dc707122SEaswaran Raman   auto CovHeader =
523dc707122SEaswaran Raman       reinterpret_cast<const coverage::CovMapHeader *>(Data.data());
524dc707122SEaswaran Raman   CovMapVersion Version = (CovMapVersion)CovHeader->getVersion<Endian>();
525dc707122SEaswaran Raman   if (Version > coverage::CovMapVersion::CurrentVersion)
5269152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::unsupported_version);
5279152fd17SVedant Kumar   Expected<std::unique_ptr<CovMapFuncRecordReader>> ReaderExpected =
528dc707122SEaswaran Raman       CovMapFuncRecordReader::get<T, Endian>(Version, ProfileNames, Records,
529dc707122SEaswaran Raman                                              Filenames);
5309152fd17SVedant Kumar   if (Error E = ReaderExpected.takeError())
5319152fd17SVedant Kumar     return E;
5329152fd17SVedant Kumar   auto Reader = std::move(ReaderExpected.get());
533dc707122SEaswaran Raman   for (const char *Buf = Data.data(), *End = Buf + Data.size(); Buf < End;) {
534*3739b95dSVedant Kumar     auto NextHeaderOrErr = Reader->readFunctionRecords(Buf, End);
535*3739b95dSVedant Kumar     if (auto E = NextHeaderOrErr.takeError())
5369152fd17SVedant Kumar       return E;
537*3739b95dSVedant Kumar     Buf = NextHeaderOrErr.get();
538dc707122SEaswaran Raman   }
5399152fd17SVedant Kumar   return Error::success();
540dc707122SEaswaran Raman }
541dc707122SEaswaran Raman static const char *TestingFormatMagic = "llvmcovmtestdata";
542dc707122SEaswaran Raman 
5439152fd17SVedant Kumar static Error loadTestingFormat(StringRef Data, InstrProfSymtab &ProfileNames,
544dc707122SEaswaran Raman                                StringRef &CoverageMapping,
545dc707122SEaswaran Raman                                uint8_t &BytesInAddress,
546dc707122SEaswaran Raman                                support::endianness &Endian) {
547dc707122SEaswaran Raman   BytesInAddress = 8;
548dc707122SEaswaran Raman   Endian = support::endianness::little;
549dc707122SEaswaran Raman 
550dc707122SEaswaran Raman   Data = Data.substr(StringRef(TestingFormatMagic).size());
551dc707122SEaswaran Raman   if (Data.size() < 1)
5529152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
553dc707122SEaswaran Raman   unsigned N = 0;
554dc707122SEaswaran Raman   auto ProfileNamesSize =
555dc707122SEaswaran Raman       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
556dc707122SEaswaran Raman   if (N > Data.size())
5579152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
558dc707122SEaswaran Raman   Data = Data.substr(N);
559dc707122SEaswaran Raman   if (Data.size() < 1)
5609152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
561dc707122SEaswaran Raman   N = 0;
562dc707122SEaswaran Raman   uint64_t Address =
563dc707122SEaswaran Raman       decodeULEB128(reinterpret_cast<const uint8_t *>(Data.data()), &N);
564dc707122SEaswaran Raman   if (N > Data.size())
5659152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
566dc707122SEaswaran Raman   Data = Data.substr(N);
567dc707122SEaswaran Raman   if (Data.size() < ProfileNamesSize)
5689152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
5699152fd17SVedant Kumar   if (Error E = ProfileNames.create(Data.substr(0, ProfileNamesSize), Address))
5709152fd17SVedant Kumar     return E;
571dc707122SEaswaran Raman   CoverageMapping = Data.substr(ProfileNamesSize);
572eb103073SIgor Kudrin   // Skip the padding bytes because coverage map data has an alignment of 8.
573eb103073SIgor Kudrin   if (CoverageMapping.size() < 1)
5749152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::truncated);
575eb103073SIgor Kudrin   size_t Pad = alignmentAdjustment(CoverageMapping.data(), 8);
576eb103073SIgor Kudrin   if (CoverageMapping.size() < Pad)
5779152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
578eb103073SIgor Kudrin   CoverageMapping = CoverageMapping.substr(Pad);
5799152fd17SVedant Kumar   return Error::success();
580dc707122SEaswaran Raman }
581dc707122SEaswaran Raman 
5829152fd17SVedant Kumar static Expected<SectionRef> lookupSection(ObjectFile &OF, StringRef Name) {
583dc707122SEaswaran Raman   StringRef FoundName;
584dc707122SEaswaran Raman   for (const auto &Section : OF.sections()) {
585dc707122SEaswaran Raman     if (auto EC = Section.getName(FoundName))
5869152fd17SVedant Kumar       return errorCodeToError(EC);
587dc707122SEaswaran Raman     if (FoundName == Name)
588dc707122SEaswaran Raman       return Section;
589dc707122SEaswaran Raman   }
5909152fd17SVedant Kumar   return make_error<CoverageMapError>(coveragemap_error::no_data_found);
591dc707122SEaswaran Raman }
592dc707122SEaswaran Raman 
5939152fd17SVedant Kumar static Error loadBinaryFormat(MemoryBufferRef ObjectBuffer,
5949152fd17SVedant Kumar                               InstrProfSymtab &ProfileNames,
5959152fd17SVedant Kumar                               StringRef &CoverageMapping,
5969152fd17SVedant Kumar                               uint8_t &BytesInAddress,
597dc707122SEaswaran Raman                               support::endianness &Endian, StringRef Arch) {
598dc707122SEaswaran Raman   auto BinOrErr = object::createBinary(ObjectBuffer);
599dc707122SEaswaran Raman   if (!BinOrErr)
6009152fd17SVedant Kumar     return BinOrErr.takeError();
601dc707122SEaswaran Raman   auto Bin = std::move(BinOrErr.get());
602dc707122SEaswaran Raman   std::unique_ptr<ObjectFile> OF;
603dc707122SEaswaran Raman   if (auto *Universal = dyn_cast<object::MachOUniversalBinary>(Bin.get())) {
604dc707122SEaswaran Raman     // If we have a universal binary, try to look up the object for the
605dc707122SEaswaran Raman     // appropriate architecture.
606dc707122SEaswaran Raman     auto ObjectFileOrErr = Universal->getObjectForArch(Arch);
6079acb1099SKevin Enderby     if (!ObjectFileOrErr)
6089acb1099SKevin Enderby       return ObjectFileOrErr.takeError();
609dc707122SEaswaran Raman     OF = std::move(ObjectFileOrErr.get());
610dc707122SEaswaran Raman   } else if (isa<object::ObjectFile>(Bin.get())) {
611dc707122SEaswaran Raman     // For any other object file, upcast and take ownership.
612dc707122SEaswaran Raman     OF.reset(cast<object::ObjectFile>(Bin.release()));
613dc707122SEaswaran Raman     // If we've asked for a particular arch, make sure they match.
614dc707122SEaswaran Raman     if (!Arch.empty() && OF->getArch() != Triple(Arch).getArch())
6159152fd17SVedant Kumar       return errorCodeToError(object_error::arch_not_found);
616dc707122SEaswaran Raman   } else
617dc707122SEaswaran Raman     // We can only handle object files.
6189152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
619dc707122SEaswaran Raman 
620dc707122SEaswaran Raman   // The coverage uses native pointer sizes for the object it's written in.
621dc707122SEaswaran Raman   BytesInAddress = OF->getBytesInAddress();
622dc707122SEaswaran Raman   Endian = OF->isLittleEndian() ? support::endianness::little
623dc707122SEaswaran Raman                                 : support::endianness::big;
624dc707122SEaswaran Raman 
625dc707122SEaswaran Raman   // Look for the sections that we are interested in.
626dc707122SEaswaran Raman   auto NamesSection = lookupSection(*OF, getInstrProfNameSectionName(false));
6279152fd17SVedant Kumar   if (auto E = NamesSection.takeError())
6289152fd17SVedant Kumar     return E;
629dc707122SEaswaran Raman   auto CoverageSection =
630dc707122SEaswaran Raman       lookupSection(*OF, getInstrProfCoverageSectionName(false));
6319152fd17SVedant Kumar   if (auto E = CoverageSection.takeError())
6329152fd17SVedant Kumar     return E;
633dc707122SEaswaran Raman 
634dc707122SEaswaran Raman   // Get the contents of the given sections.
6359152fd17SVedant Kumar   if (auto EC = CoverageSection->getContents(CoverageMapping))
6369152fd17SVedant Kumar     return errorCodeToError(EC);
6379152fd17SVedant Kumar   if (Error E = ProfileNames.create(*NamesSection))
6389152fd17SVedant Kumar     return E;
639dc707122SEaswaran Raman 
6409152fd17SVedant Kumar   return Error::success();
641dc707122SEaswaran Raman }
642dc707122SEaswaran Raman 
6439152fd17SVedant Kumar Expected<std::unique_ptr<BinaryCoverageReader>>
644dc707122SEaswaran Raman BinaryCoverageReader::create(std::unique_ptr<MemoryBuffer> &ObjectBuffer,
645dc707122SEaswaran Raman                              StringRef Arch) {
646dc707122SEaswaran Raman   std::unique_ptr<BinaryCoverageReader> Reader(new BinaryCoverageReader());
647dc707122SEaswaran Raman 
648dc707122SEaswaran Raman   StringRef Coverage;
649dc707122SEaswaran Raman   uint8_t BytesInAddress;
650dc707122SEaswaran Raman   support::endianness Endian;
6519152fd17SVedant Kumar   Error E;
6529152fd17SVedant Kumar   consumeError(std::move(E));
653dc707122SEaswaran Raman   if (ObjectBuffer->getBuffer().startswith(TestingFormatMagic))
654dc707122SEaswaran Raman     // This is a special format used for testing.
6559152fd17SVedant Kumar     E = loadTestingFormat(ObjectBuffer->getBuffer(), Reader->ProfileNames,
656dc707122SEaswaran Raman                           Coverage, BytesInAddress, Endian);
657dc707122SEaswaran Raman   else
6589152fd17SVedant Kumar     E = loadBinaryFormat(ObjectBuffer->getMemBufferRef(), Reader->ProfileNames,
659dc707122SEaswaran Raman                          Coverage, BytesInAddress, Endian, Arch);
6609152fd17SVedant Kumar   if (E)
6619152fd17SVedant Kumar     return std::move(E);
662dc707122SEaswaran Raman 
663dc707122SEaswaran Raman   if (BytesInAddress == 4 && Endian == support::endianness::little)
6649152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::little>(
665dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
666dc707122SEaswaran Raman         Reader->Filenames);
667dc707122SEaswaran Raman   else if (BytesInAddress == 4 && Endian == support::endianness::big)
6689152fd17SVedant Kumar     E = readCoverageMappingData<uint32_t, support::endianness::big>(
669dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
670dc707122SEaswaran Raman         Reader->Filenames);
671dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::little)
6729152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::little>(
673dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
674dc707122SEaswaran Raman         Reader->Filenames);
675dc707122SEaswaran Raman   else if (BytesInAddress == 8 && Endian == support::endianness::big)
6769152fd17SVedant Kumar     E = readCoverageMappingData<uint64_t, support::endianness::big>(
677dc707122SEaswaran Raman         Reader->ProfileNames, Coverage, Reader->MappingRecords,
678dc707122SEaswaran Raman         Reader->Filenames);
679dc707122SEaswaran Raman   else
6809152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::malformed);
6819152fd17SVedant Kumar   if (E)
6829152fd17SVedant Kumar     return std::move(E);
683dc707122SEaswaran Raman   return std::move(Reader);
684dc707122SEaswaran Raman }
685dc707122SEaswaran Raman 
6869152fd17SVedant Kumar Error BinaryCoverageReader::readNextRecord(CoverageMappingRecord &Record) {
687dc707122SEaswaran Raman   if (CurrentRecord >= MappingRecords.size())
6889152fd17SVedant Kumar     return make_error<CoverageMapError>(coveragemap_error::eof);
689dc707122SEaswaran Raman 
690dc707122SEaswaran Raman   FunctionsFilenames.clear();
691dc707122SEaswaran Raman   Expressions.clear();
692dc707122SEaswaran Raman   MappingRegions.clear();
693dc707122SEaswaran Raman   auto &R = MappingRecords[CurrentRecord];
694dc707122SEaswaran Raman   RawCoverageMappingReader Reader(
695dc707122SEaswaran Raman       R.CoverageMapping,
696dc707122SEaswaran Raman       makeArrayRef(Filenames).slice(R.FilenamesBegin, R.FilenamesSize),
697dc707122SEaswaran Raman       FunctionsFilenames, Expressions, MappingRegions);
698dc707122SEaswaran Raman   if (auto Err = Reader.read())
699dc707122SEaswaran Raman     return Err;
700dc707122SEaswaran Raman 
701dc707122SEaswaran Raman   Record.FunctionName = R.FunctionName;
702dc707122SEaswaran Raman   Record.FunctionHash = R.FunctionHash;
703dc707122SEaswaran Raman   Record.Filenames = FunctionsFilenames;
704dc707122SEaswaran Raman   Record.Expressions = Expressions;
705dc707122SEaswaran Raman   Record.MappingRegions = MappingRegions;
706dc707122SEaswaran Raman 
707dc707122SEaswaran Raman   ++CurrentRecord;
7089152fd17SVedant Kumar   return Error::success();
709dc707122SEaswaran Raman }
710