xref: /llvm-project/llvm/unittests/ProfileData/CoverageMappingTest.cpp (revision 438fe1db09b0c20708ea1020519d8073c37feae8)
1 //===- unittest/ProfileData/CoverageMappingTest.cpp -------------------------=//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/ProfileData/Coverage/CoverageMapping.h"
10 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
11 #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
12 #include "llvm/ProfileData/InstrProfReader.h"
13 #include "llvm/ProfileData/InstrProfWriter.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/Testing/Support/Error.h"
16 #include "llvm/Testing/Support/SupportHelpers.h"
17 #include "gtest/gtest.h"
18 
19 #include <ostream>
20 #include <utility>
21 
22 using namespace llvm;
23 using namespace coverage;
24 
25 [[nodiscard]] static ::testing::AssertionResult
26 ErrorEquals(Error E, coveragemap_error Expected_Err,
27             const std::string &Expected_Msg = std::string()) {
28   coveragemap_error Found;
29   std::string Msg;
30   std::string FoundMsg;
31   handleAllErrors(std::move(E), [&](const CoverageMapError &CME) {
32     Found = CME.get();
33     Msg = CME.getMessage();
34     FoundMsg = CME.message();
35   });
36   if (Expected_Err == Found && Msg == Expected_Msg)
37     return ::testing::AssertionSuccess();
38   return ::testing::AssertionFailure() << "error: " << FoundMsg << "\n";
39 }
40 
41 namespace llvm {
42 namespace coverage {
43 void PrintTo(const Counter &C, ::std::ostream *os) {
44   if (C.isZero())
45     *os << "Zero";
46   else if (C.isExpression())
47     *os << "Expression " << C.getExpressionID();
48   else
49     *os << "Counter " << C.getCounterID();
50 }
51 
52 void PrintTo(const CoverageSegment &S, ::std::ostream *os) {
53   *os << "CoverageSegment(" << S.Line << ", " << S.Col << ", ";
54   if (S.HasCount)
55     *os << S.Count << ", ";
56   *os << (S.IsRegionEntry ? "true" : "false") << ")";
57 }
58 }
59 }
60 
61 namespace {
62 
63 struct OutputFunctionCoverageData {
64   StringRef Name;
65   uint64_t Hash;
66   std::vector<StringRef> Filenames;
67   std::vector<CounterMappingRegion> Regions;
68   std::vector<CounterExpression> Expressions;
69 
70   OutputFunctionCoverageData() : Hash(0) {}
71 
72   OutputFunctionCoverageData(OutputFunctionCoverageData &&OFCD)
73       : Name(OFCD.Name), Hash(OFCD.Hash), Filenames(std::move(OFCD.Filenames)),
74         Regions(std::move(OFCD.Regions)) {}
75 
76   OutputFunctionCoverageData(const OutputFunctionCoverageData &) = delete;
77   OutputFunctionCoverageData &
78   operator=(const OutputFunctionCoverageData &) = delete;
79   OutputFunctionCoverageData &operator=(OutputFunctionCoverageData &&) = delete;
80 
81   void fillCoverageMappingRecord(CoverageMappingRecord &Record) const {
82     Record.FunctionName = Name;
83     Record.FunctionHash = Hash;
84     Record.Filenames = Filenames;
85     Record.Expressions = Expressions;
86     Record.MappingRegions = Regions;
87   }
88 };
89 
90 struct CoverageMappingReaderMock : CoverageMappingReader {
91   ArrayRef<OutputFunctionCoverageData> Functions;
92 
93   CoverageMappingReaderMock(ArrayRef<OutputFunctionCoverageData> Functions)
94       : Functions(Functions) {}
95 
96   Error readNextRecord(CoverageMappingRecord &Record) override {
97     if (Functions.empty())
98       return make_error<CoverageMapError>(coveragemap_error::eof);
99 
100     Functions.front().fillCoverageMappingRecord(Record);
101     Functions = Functions.slice(1);
102 
103     return Error::success();
104   }
105 };
106 
107 struct InputFunctionCoverageData {
108   // Maps the global file index from CoverageMappingTest.Files
109   // to the index of that file within this function. We can't just use
110   // global file indexes here because local indexes have to be dense.
111   // This map is used during serialization to create the virtual file mapping
112   // (from local fileId to global Index) in the head of the per-function
113   // coverage mapping data.
114   SmallDenseMap<unsigned, unsigned> ReverseVirtualFileMapping;
115   std::string Name;
116   uint64_t Hash;
117   std::vector<CounterMappingRegion> Regions;
118   std::vector<CounterExpression> Expressions;
119 
120   InputFunctionCoverageData(std::string Name, uint64_t Hash)
121       : Name(std::move(Name)), Hash(Hash) {}
122 
123   InputFunctionCoverageData(InputFunctionCoverageData &&IFCD)
124       : ReverseVirtualFileMapping(std::move(IFCD.ReverseVirtualFileMapping)),
125         Name(std::move(IFCD.Name)), Hash(IFCD.Hash),
126         Regions(std::move(IFCD.Regions)) {}
127 
128   InputFunctionCoverageData(const InputFunctionCoverageData &) = delete;
129   InputFunctionCoverageData &
130   operator=(const InputFunctionCoverageData &) = delete;
131   InputFunctionCoverageData &operator=(InputFunctionCoverageData &&) = delete;
132 };
133 
134 struct CoverageMappingTest : ::testing::TestWithParam<std::tuple<bool, bool>> {
135   bool UseMultipleReaders;
136   StringMap<unsigned> Files;
137   std::vector<std::string> Filenames;
138   std::vector<InputFunctionCoverageData> InputFunctions;
139   std::vector<OutputFunctionCoverageData> OutputFunctions;
140 
141   InstrProfWriter ProfileWriter;
142   std::unique_ptr<IndexedInstrProfReader> ProfileReader;
143 
144   std::unique_ptr<CoverageMapping> LoadedCoverage;
145 
146   void SetUp() override {
147     ProfileWriter.setOutputSparse(std::get<0>(GetParam()));
148     UseMultipleReaders = std::get<1>(GetParam());
149   }
150 
151   unsigned getGlobalFileIndex(StringRef Name) {
152     auto R = Files.find(Name);
153     if (R != Files.end())
154       return R->second;
155     unsigned Index = Files.size() + 1;
156     Files.try_emplace(Name, Index);
157     return Index;
158   }
159 
160   // Return the file index of file 'Name' for the current function.
161   // Add the file into the global map if necessary.
162   // See also InputFunctionCoverageData::ReverseVirtualFileMapping
163   // for additional comments.
164   unsigned getFileIndexForFunction(StringRef Name) {
165     unsigned GlobalIndex = getGlobalFileIndex(Name);
166     auto &CurrentFunctionFileMapping =
167         InputFunctions.back().ReverseVirtualFileMapping;
168     auto R = CurrentFunctionFileMapping.find(GlobalIndex);
169     if (R != CurrentFunctionFileMapping.end())
170       return R->second;
171     unsigned IndexInFunction = CurrentFunctionFileMapping.size();
172     CurrentFunctionFileMapping.insert(
173         std::make_pair(GlobalIndex, IndexInFunction));
174     return IndexInFunction;
175   }
176 
177   void startFunction(StringRef FuncName, uint64_t Hash) {
178     InputFunctions.emplace_back(FuncName.str(), Hash);
179   }
180 
181   void addCMR(Counter C, StringRef File, unsigned LS, unsigned CS, unsigned LE,
182               unsigned CE, bool Skipped = false) {
183     auto &Regions = InputFunctions.back().Regions;
184     unsigned FileID = getFileIndexForFunction(File);
185     Regions.push_back(
186         Skipped ? CounterMappingRegion::makeSkipped(FileID, LS, CS, LE, CE)
187                 : CounterMappingRegion::makeRegion(C, FileID, LS, CS, LE, CE));
188   }
189 
190   void addSkipped(StringRef File, unsigned LS, unsigned CS, unsigned LE,
191                   unsigned CE) {
192     addCMR(Counter::getZero(), File, LS, CS, LE, CE, true);
193   }
194 
195   void addMCDCDecisionCMR(unsigned Mask, unsigned NC, StringRef File,
196                           unsigned LS, unsigned CS, unsigned LE, unsigned CE) {
197     auto &Regions = InputFunctions.back().Regions;
198     unsigned FileID = getFileIndexForFunction(File);
199     Regions.push_back(CounterMappingRegion::makeDecisionRegion(
200         CounterMappingRegion::MCDCParameters{Mask, NC}, FileID, LS, CS, LE,
201         CE));
202   }
203 
204   void addMCDCBranchCMR(Counter C1, Counter C2, unsigned ID, unsigned TrueID,
205                         unsigned FalseID, StringRef File, unsigned LS,
206                         unsigned CS, unsigned LE, unsigned CE) {
207     auto &Regions = InputFunctions.back().Regions;
208     unsigned FileID = getFileIndexForFunction(File);
209     Regions.push_back(CounterMappingRegion::makeBranchRegion(
210         C1, C2, CounterMappingRegion::MCDCParameters{0, 0, ID, TrueID, FalseID},
211         FileID, LS, CS, LE, CE));
212   }
213 
214   void addExpansionCMR(StringRef File, StringRef ExpandedFile, unsigned LS,
215                        unsigned CS, unsigned LE, unsigned CE) {
216     InputFunctions.back().Regions.push_back(CounterMappingRegion::makeExpansion(
217         getFileIndexForFunction(File), getFileIndexForFunction(ExpandedFile),
218         LS, CS, LE, CE));
219   }
220 
221   void addExpression(CounterExpression CE) {
222     InputFunctions.back().Expressions.push_back(CE);
223   }
224 
225   std::string writeCoverageRegions(InputFunctionCoverageData &Data) {
226     SmallVector<unsigned, 8> FileIDs(Data.ReverseVirtualFileMapping.size());
227     for (const auto &E : Data.ReverseVirtualFileMapping)
228       FileIDs[E.second] = E.first;
229     std::string Coverage;
230     llvm::raw_string_ostream OS(Coverage);
231     CoverageMappingWriter(FileIDs, Data.Expressions, Data.Regions).write(OS);
232     return OS.str();
233   }
234 
235   void readCoverageRegions(const std::string &Coverage,
236                            OutputFunctionCoverageData &Data) {
237     // We will re-use the StringRef in duplicate tests, clear it to avoid
238     // clobber previous ones.
239     Filenames.clear();
240     Filenames.resize(Files.size() + 1);
241     for (const auto &E : Files)
242       Filenames[E.getValue()] = E.getKey().str();
243     ArrayRef<std::string> FilenameRefs = llvm::ArrayRef(Filenames);
244     RawCoverageMappingReader Reader(Coverage, FilenameRefs, Data.Filenames,
245                                     Data.Expressions, Data.Regions);
246     EXPECT_THAT_ERROR(Reader.read(), Succeeded());
247   }
248 
249   void writeAndReadCoverageRegions(bool EmitFilenames = true) {
250     OutputFunctions.resize(InputFunctions.size());
251     for (unsigned I = 0; I < InputFunctions.size(); ++I) {
252       std::string Regions = writeCoverageRegions(InputFunctions[I]);
253       readCoverageRegions(Regions, OutputFunctions[I]);
254       OutputFunctions[I].Name = InputFunctions[I].Name;
255       OutputFunctions[I].Hash = InputFunctions[I].Hash;
256       if (!EmitFilenames)
257         OutputFunctions[I].Filenames.clear();
258     }
259   }
260 
261   void readProfCounts() {
262     auto Profile = ProfileWriter.writeBuffer();
263     auto ReaderOrErr = IndexedInstrProfReader::create(std::move(Profile));
264     EXPECT_THAT_ERROR(ReaderOrErr.takeError(), Succeeded());
265     ProfileReader = std::move(ReaderOrErr.get());
266   }
267 
268   Expected<std::unique_ptr<CoverageMapping>> readOutputFunctions() {
269     std::vector<std::unique_ptr<CoverageMappingReader>> CoverageReaders;
270     if (UseMultipleReaders) {
271       for (const auto &OF : OutputFunctions) {
272         ArrayRef<OutputFunctionCoverageData> Funcs(OF);
273         CoverageReaders.push_back(
274             std::make_unique<CoverageMappingReaderMock>(Funcs));
275       }
276     } else {
277       ArrayRef<OutputFunctionCoverageData> Funcs(OutputFunctions);
278       CoverageReaders.push_back(
279           std::make_unique<CoverageMappingReaderMock>(Funcs));
280     }
281     return CoverageMapping::load(CoverageReaders, *ProfileReader);
282   }
283 
284   Error loadCoverageMapping(bool EmitFilenames = true) {
285     readProfCounts();
286     writeAndReadCoverageRegions(EmitFilenames);
287     auto CoverageOrErr = readOutputFunctions();
288     if (!CoverageOrErr)
289       return CoverageOrErr.takeError();
290     LoadedCoverage = std::move(CoverageOrErr.get());
291     return Error::success();
292   }
293 };
294 
295 TEST_P(CoverageMappingTest, basic_write_read) {
296   startFunction("func", 0x1234);
297   addCMR(Counter::getCounter(0), "foo", 1, 1, 1, 1);
298   addCMR(Counter::getCounter(1), "foo", 2, 1, 2, 2);
299   addCMR(Counter::getZero(),     "foo", 3, 1, 3, 4);
300   addCMR(Counter::getCounter(2), "foo", 4, 1, 4, 8);
301   addCMR(Counter::getCounter(3), "bar", 1, 2, 3, 4);
302 
303   writeAndReadCoverageRegions();
304   ASSERT_EQ(1u, InputFunctions.size());
305   ASSERT_EQ(1u, OutputFunctions.size());
306   InputFunctionCoverageData &Input = InputFunctions.back();
307   OutputFunctionCoverageData &Output = OutputFunctions.back();
308 
309   size_t N = ArrayRef(Input.Regions).size();
310   ASSERT_EQ(N, Output.Regions.size());
311   for (size_t I = 0; I < N; ++I) {
312     ASSERT_EQ(Input.Regions[I].Count, Output.Regions[I].Count);
313     ASSERT_EQ(Input.Regions[I].FileID, Output.Regions[I].FileID);
314     ASSERT_EQ(Input.Regions[I].startLoc(), Output.Regions[I].startLoc());
315     ASSERT_EQ(Input.Regions[I].endLoc(), Output.Regions[I].endLoc());
316     ASSERT_EQ(Input.Regions[I].Kind, Output.Regions[I].Kind);
317   }
318 }
319 
320 TEST_P(CoverageMappingTest, correct_deserialize_for_more_than_two_files) {
321   const char *FileNames[] = {"bar", "baz", "foo"};
322   static const unsigned N = std::size(FileNames);
323 
324   startFunction("func", 0x1234);
325   for (unsigned I = 0; I < N; ++I)
326     // Use LineStart to hold the index of the file name
327     // in order to preserve that information during possible sorting of CMRs.
328     addCMR(Counter::getCounter(0), FileNames[I], I, 1, I, 1);
329 
330   writeAndReadCoverageRegions();
331   ASSERT_EQ(1u, OutputFunctions.size());
332   OutputFunctionCoverageData &Output = OutputFunctions.back();
333 
334   ASSERT_EQ(N, Output.Regions.size());
335   ASSERT_EQ(N, Output.Filenames.size());
336 
337   for (unsigned I = 0; I < N; ++I) {
338     ASSERT_GT(N, Output.Regions[I].FileID);
339     ASSERT_GT(N, Output.Regions[I].LineStart);
340     EXPECT_EQ(FileNames[Output.Regions[I].LineStart],
341               Output.Filenames[Output.Regions[I].FileID]);
342   }
343 }
344 
345 static const auto Err = [](Error E) { FAIL(); };
346 
347 TEST_P(CoverageMappingTest, load_coverage_for_more_than_two_files) {
348   ProfileWriter.addRecord({"func", 0x1234, {0}}, Err);
349 
350   const char *FileNames[] = {"bar", "baz", "foo"};
351   static const unsigned N = std::size(FileNames);
352 
353   startFunction("func", 0x1234);
354   for (unsigned I = 0; I < N; ++I)
355     // Use LineStart to hold the index of the file name
356     // in order to preserve that information during possible sorting of CMRs.
357     addCMR(Counter::getCounter(0), FileNames[I], I, 1, I, 1);
358 
359   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
360 
361   for (unsigned I = 0; I < N; ++I) {
362     CoverageData Data = LoadedCoverage->getCoverageForFile(FileNames[I]);
363     ASSERT_TRUE(!Data.empty());
364     EXPECT_EQ(I, Data.begin()->Line);
365   }
366 }
367 
368 TEST_P(CoverageMappingTest, load_coverage_with_bogus_function_name) {
369   ProfileWriter.addRecord({"", 0x1234, {10}}, Err);
370   startFunction("", 0x1234);
371   addCMR(Counter::getCounter(0), "foo", 1, 1, 5, 5);
372   EXPECT_TRUE(ErrorEquals(loadCoverageMapping(), coveragemap_error::malformed,
373                           "record function name is empty"));
374 }
375 
376 TEST_P(CoverageMappingTest, load_coverage_for_several_functions) {
377   ProfileWriter.addRecord({"func1", 0x1234, {10}}, Err);
378   ProfileWriter.addRecord({"func2", 0x2345, {20}}, Err);
379 
380   startFunction("func1", 0x1234);
381   addCMR(Counter::getCounter(0), "foo", 1, 1, 5, 5);
382 
383   startFunction("func2", 0x2345);
384   addCMR(Counter::getCounter(0), "bar", 2, 2, 6, 6);
385 
386   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
387 
388   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
389   EXPECT_EQ(2, std::distance(FunctionRecords.begin(), FunctionRecords.end()));
390   for (const auto &FunctionRecord : FunctionRecords) {
391     CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
392     std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
393     ASSERT_EQ(2U, Segments.size());
394     if (FunctionRecord.Name == "func1") {
395       EXPECT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
396       EXPECT_EQ(CoverageSegment(5, 5, false), Segments[1]);
397     } else {
398       ASSERT_EQ("func2", FunctionRecord.Name);
399       EXPECT_EQ(CoverageSegment(2, 2, 20, true), Segments[0]);
400       EXPECT_EQ(CoverageSegment(6, 6, false), Segments[1]);
401     }
402   }
403 }
404 
405 TEST_P(CoverageMappingTest, create_combined_regions) {
406   ProfileWriter.addRecord({"func1", 0x1234, {1, 2, 3}}, Err);
407   startFunction("func1", 0x1234);
408 
409   // Given regions which start at the same location, emit a segment for the
410   // last region.
411   addCMR(Counter::getCounter(0), "file1", 1, 1, 2, 2);
412   addCMR(Counter::getCounter(1), "file1", 1, 1, 2, 2);
413   addCMR(Counter::getCounter(2), "file1", 1, 1, 2, 2);
414 
415   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
416   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
417   const auto &FunctionRecord = *FunctionRecords.begin();
418   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
419   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
420 
421   ASSERT_EQ(2U, Segments.size());
422   EXPECT_EQ(CoverageSegment(1, 1, 6, true), Segments[0]);
423   EXPECT_EQ(CoverageSegment(2, 2, false), Segments[1]);
424 }
425 
426 TEST_P(CoverageMappingTest, skipped_segments_have_no_count) {
427   ProfileWriter.addRecord({"func1", 0x1234, {1}}, Err);
428   startFunction("func1", 0x1234);
429 
430   addCMR(Counter::getCounter(0), "file1", 1, 1, 5, 5);
431   addCMR(Counter::getCounter(0), "file1", 5, 1, 5, 5, /*Skipped=*/true);
432 
433   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
434   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
435   const auto &FunctionRecord = *FunctionRecords.begin();
436   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
437   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
438 
439   ASSERT_EQ(3U, Segments.size());
440   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
441   EXPECT_EQ(CoverageSegment(5, 1, true), Segments[1]);
442   EXPECT_EQ(CoverageSegment(5, 5, false), Segments[2]);
443 }
444 
445 TEST_P(CoverageMappingTest, multiple_regions_end_after_parent_ends) {
446   ProfileWriter.addRecord({"func1", 0x1234, {1, 0}}, Err);
447   startFunction("func1", 0x1234);
448 
449   // 1| F{ a{
450   // 2|
451   // 3|    a} b{ c{
452   // 4|
453   // 5|    b}
454   // 6|
455   // 7| c} d{   e{
456   // 8|
457   // 9| d}      e} F}
458   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9); // < F
459   addCMR(Counter::getCounter(0), "file1", 1, 1, 3, 5); // < a
460   addCMR(Counter::getCounter(0), "file1", 3, 5, 5, 4); // < b
461   addCMR(Counter::getCounter(1), "file1", 3, 5, 7, 3); // < c
462   addCMR(Counter::getCounter(1), "file1", 7, 3, 9, 2); // < d
463   addCMR(Counter::getCounter(1), "file1", 7, 7, 9, 7); // < e
464 
465   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
466   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
467   const auto &FunctionRecord = *FunctionRecords.begin();
468   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
469   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
470 
471   // Old output (not sorted or unique):
472   //   Segment at 1:1 with count 1
473   //   Segment at 1:1 with count 1
474   //   Segment at 3:5 with count 1
475   //   Segment at 3:5 with count 0
476   //   Segment at 3:5 with count 1
477   //   Segment at 5:4 with count 0
478   //   Segment at 7:3 with count 1
479   //   Segment at 7:3 with count 0
480   //   Segment at 7:7 with count 0
481   //   Segment at 9:7 with count 0
482   //   Segment at 9:2 with count 1
483   //   Top level segment at 9:9
484 
485   // New output (sorted and unique):
486   //   Segment at 1:1 (count = 1), RegionEntry
487   //   Segment at 3:5 (count = 1), RegionEntry
488   //   Segment at 5:4 (count = 0)
489   //   Segment at 7:3 (count = 0), RegionEntry
490   //   Segment at 7:7 (count = 0), RegionEntry
491   //   Segment at 9:2 (count = 0)
492   //   Segment at 9:7 (count = 1)
493   //   Segment at 9:9 (count = 0), Skipped
494 
495   ASSERT_EQ(8U, Segments.size());
496   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
497   EXPECT_EQ(CoverageSegment(3, 5, 1, true), Segments[1]);
498   EXPECT_EQ(CoverageSegment(5, 4, 0, false), Segments[2]);
499   EXPECT_EQ(CoverageSegment(7, 3, 0, true), Segments[3]);
500   EXPECT_EQ(CoverageSegment(7, 7, 0, true), Segments[4]);
501   EXPECT_EQ(CoverageSegment(9, 2, 0, false), Segments[5]);
502   EXPECT_EQ(CoverageSegment(9, 7, 1, false), Segments[6]);
503   EXPECT_EQ(CoverageSegment(9, 9, false), Segments[7]);
504 }
505 
506 TEST_P(CoverageMappingTest, multiple_completed_segments_at_same_loc) {
507   ProfileWriter.addRecord({"func1", 0x1234, {0, 1, 2}}, Err);
508   startFunction("func1", 0x1234);
509 
510   // PR35495
511   addCMR(Counter::getCounter(1), "file1", 2, 1, 18, 2);
512   addCMR(Counter::getCounter(0), "file1", 8, 10, 14, 6);
513   addCMR(Counter::getCounter(0), "file1", 8, 12, 14, 6);
514   addCMR(Counter::getCounter(1), "file1", 9, 1, 14, 6);
515   addCMR(Counter::getCounter(2), "file1", 11, 13, 11, 14);
516 
517   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
518   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
519   const auto &FunctionRecord = *FunctionRecords.begin();
520   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
521   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
522 
523   ASSERT_EQ(7U, Segments.size());
524   EXPECT_EQ(CoverageSegment(2, 1, 1, true), Segments[0]);
525   EXPECT_EQ(CoverageSegment(8, 10, 0, true), Segments[1]);
526   EXPECT_EQ(CoverageSegment(8, 12, 0, true), Segments[2]);
527   EXPECT_EQ(CoverageSegment(9, 1, 1, true), Segments[3]);
528   EXPECT_EQ(CoverageSegment(11, 13, 2, true), Segments[4]);
529   // Use count=1 (from 9:1 -> 14:6), not count=0 (from 8:12 -> 14:6).
530   EXPECT_EQ(CoverageSegment(11, 14, 1, false), Segments[5]);
531   EXPECT_EQ(CoverageSegment(18, 2, false), Segments[6]);
532 }
533 
534 TEST_P(CoverageMappingTest, dont_emit_redundant_segments) {
535   ProfileWriter.addRecord({"func1", 0x1234, {1, 1}}, Err);
536   startFunction("func1", 0x1234);
537 
538   addCMR(Counter::getCounter(0), "file1", 1, 1, 4, 4);
539   addCMR(Counter::getCounter(1), "file1", 2, 2, 5, 5);
540   addCMR(Counter::getCounter(0), "file1", 3, 3, 6, 6);
541 
542   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
543   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
544   const auto &FunctionRecord = *FunctionRecords.begin();
545   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
546   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
547 
548   ASSERT_EQ(5U, Segments.size());
549   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
550   EXPECT_EQ(CoverageSegment(2, 2, 1, true), Segments[1]);
551   EXPECT_EQ(CoverageSegment(3, 3, 1, true), Segments[2]);
552   EXPECT_EQ(CoverageSegment(4, 4, 1, false), Segments[3]);
553   // A closing segment starting at 5:5 would be redundant: it would have the
554   // same count as the segment starting at 4:4, and has all the same metadata.
555   EXPECT_EQ(CoverageSegment(6, 6, false), Segments[4]);
556 }
557 
558 TEST_P(CoverageMappingTest, dont_emit_closing_segment_at_new_region_start) {
559   ProfileWriter.addRecord({"func1", 0x1234, {1}}, Err);
560   startFunction("func1", 0x1234);
561 
562   addCMR(Counter::getCounter(0), "file1", 1, 1, 6, 5);
563   addCMR(Counter::getCounter(0), "file1", 2, 2, 6, 5);
564   addCMR(Counter::getCounter(0), "file1", 3, 3, 6, 5);
565   addCMR(Counter::getCounter(0), "file1", 6, 5, 7, 7);
566 
567   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
568   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
569   const auto &FunctionRecord = *FunctionRecords.begin();
570   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
571   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
572 
573   ASSERT_EQ(5U, Segments.size());
574   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
575   EXPECT_EQ(CoverageSegment(2, 2, 1, true), Segments[1]);
576   EXPECT_EQ(CoverageSegment(3, 3, 1, true), Segments[2]);
577   EXPECT_EQ(CoverageSegment(6, 5, 1, true), Segments[3]);
578   // The old segment builder would get this wrong by emitting multiple segments
579   // which start at 6:5 (a few of which were skipped segments). We should just
580   // get a segment for the region entry.
581   EXPECT_EQ(CoverageSegment(7, 7, false), Segments[4]);
582 }
583 
584 TEST_P(CoverageMappingTest, handle_consecutive_regions_with_zero_length) {
585   ProfileWriter.addRecord({"func1", 0x1234, {1, 2}}, Err);
586   startFunction("func1", 0x1234);
587 
588   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
589   addCMR(Counter::getCounter(1), "file1", 1, 1, 1, 1);
590   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
591   addCMR(Counter::getCounter(1), "file1", 1, 1, 1, 1);
592   addCMR(Counter::getCounter(0), "file1", 1, 1, 1, 1);
593 
594   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
595   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
596   const auto &FunctionRecord = *FunctionRecords.begin();
597   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
598   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
599 
600   ASSERT_EQ(1U, Segments.size());
601   EXPECT_EQ(CoverageSegment(1, 1, true), Segments[0]);
602   // We need to get a skipped segment starting at 1:1. In this case there is
603   // also a region entry at 1:1.
604 }
605 
606 TEST_P(CoverageMappingTest, handle_sandwiched_zero_length_region) {
607   ProfileWriter.addRecord({"func1", 0x1234, {2, 1}}, Err);
608   startFunction("func1", 0x1234);
609 
610   addCMR(Counter::getCounter(0), "file1", 1, 5, 4, 4);
611   addCMR(Counter::getCounter(1), "file1", 1, 9, 1, 50);
612   addCMR(Counter::getCounter(1), "file1", 2, 7, 2, 34);
613   addCMR(Counter::getCounter(1), "file1", 3, 5, 3, 21);
614   addCMR(Counter::getCounter(1), "file1", 3, 21, 3, 21);
615   addCMR(Counter::getCounter(1), "file1", 4, 12, 4, 17);
616 
617   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
618   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
619   const auto &FunctionRecord = *FunctionRecords.begin();
620   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
621   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
622 
623   ASSERT_EQ(10U, Segments.size());
624   EXPECT_EQ(CoverageSegment(1, 5, 2, true), Segments[0]);
625   EXPECT_EQ(CoverageSegment(1, 9, 1, true), Segments[1]);
626   EXPECT_EQ(CoverageSegment(1, 50, 2, false), Segments[2]);
627   EXPECT_EQ(CoverageSegment(2, 7, 1, true), Segments[3]);
628   EXPECT_EQ(CoverageSegment(2, 34, 2, false), Segments[4]);
629   EXPECT_EQ(CoverageSegment(3, 5, 1, true), Segments[5]);
630   EXPECT_EQ(CoverageSegment(3, 21, 2, true), Segments[6]);
631   // Handle the zero-length region by creating a segment with its predecessor's
632   // count (i.e the count from 1:5 -> 4:4).
633   EXPECT_EQ(CoverageSegment(4, 4, false), Segments[7]);
634   // The area between 4:4 and 4:12 is skipped.
635   EXPECT_EQ(CoverageSegment(4, 12, 1, true), Segments[8]);
636   EXPECT_EQ(CoverageSegment(4, 17, false), Segments[9]);
637 }
638 
639 TEST_P(CoverageMappingTest, handle_last_completed_region) {
640   ProfileWriter.addRecord({"func1", 0x1234, {1, 2, 3, 4}}, Err);
641   startFunction("func1", 0x1234);
642 
643   addCMR(Counter::getCounter(0), "file1", 1, 1, 8, 8);
644   addCMR(Counter::getCounter(1), "file1", 2, 2, 5, 5);
645   addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4);
646   addCMR(Counter::getCounter(3), "file1", 6, 6, 7, 7);
647 
648   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
649   const auto FunctionRecords = LoadedCoverage->getCoveredFunctions();
650   const auto &FunctionRecord = *FunctionRecords.begin();
651   CoverageData Data = LoadedCoverage->getCoverageForFunction(FunctionRecord);
652   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
653 
654   ASSERT_EQ(8U, Segments.size());
655   EXPECT_EQ(CoverageSegment(1, 1, 1, true), Segments[0]);
656   EXPECT_EQ(CoverageSegment(2, 2, 2, true), Segments[1]);
657   EXPECT_EQ(CoverageSegment(3, 3, 3, true), Segments[2]);
658   EXPECT_EQ(CoverageSegment(4, 4, 2, false), Segments[3]);
659   EXPECT_EQ(CoverageSegment(5, 5, 1, false), Segments[4]);
660   EXPECT_EQ(CoverageSegment(6, 6, 4, true), Segments[5]);
661   EXPECT_EQ(CoverageSegment(7, 7, 1, false), Segments[6]);
662   EXPECT_EQ(CoverageSegment(8, 8, false), Segments[7]);
663 }
664 
665 TEST_P(CoverageMappingTest, expansion_gets_first_counter) {
666   startFunction("func", 0x1234);
667   addCMR(Counter::getCounter(1), "foo", 10, 1, 10, 2);
668   // This starts earlier in "foo", so the expansion should get its counter.
669   addCMR(Counter::getCounter(2), "foo", 1, 1, 20, 1);
670   addExpansionCMR("bar", "foo", 3, 3, 3, 3);
671 
672   writeAndReadCoverageRegions();
673   ASSERT_EQ(1u, OutputFunctions.size());
674   OutputFunctionCoverageData &Output = OutputFunctions.back();
675 
676   ASSERT_EQ(CounterMappingRegion::ExpansionRegion, Output.Regions[2].Kind);
677   ASSERT_EQ(Counter::getCounter(2), Output.Regions[2].Count);
678   ASSERT_EQ(3U, Output.Regions[2].LineStart);
679 }
680 
681 TEST_P(CoverageMappingTest, basic_coverage_iteration) {
682   ProfileWriter.addRecord({"func", 0x1234, {30, 20, 10, 0}}, Err);
683 
684   startFunction("func", 0x1234);
685   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
686   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
687   addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1);
688   addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11);
689   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
690 
691   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
692   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
693   ASSERT_EQ(7U, Segments.size());
694   ASSERT_EQ(CoverageSegment(1, 1, 20, true),  Segments[0]);
695   ASSERT_EQ(CoverageSegment(4, 7, 30, false), Segments[1]);
696   ASSERT_EQ(CoverageSegment(5, 8, 10, true),  Segments[2]);
697   ASSERT_EQ(CoverageSegment(9, 1, 30, false), Segments[3]);
698   ASSERT_EQ(CoverageSegment(9, 9, false),     Segments[4]);
699   ASSERT_EQ(CoverageSegment(10, 10, 0, true), Segments[5]);
700   ASSERT_EQ(CoverageSegment(11, 11, false),   Segments[6]);
701 }
702 
703 TEST_P(CoverageMappingTest, test_line_coverage_iterator) {
704   ProfileWriter.addRecord({"func", 0x1234, {30, 20, 10, 0}}, Err);
705 
706   startFunction("func", 0x1234);
707   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
708   addSkipped("file1", 1, 3, 1, 8); // skipped region inside previous block
709   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
710   addSkipped("file1", 4, 1, 4, 20); // skipped line
711   addCMR(Counter::getCounter(2), "file1", 5, 8, 9, 1);
712   addSkipped("file1", 10, 1, 12,
713              20); // skipped region which contains next region
714   addCMR(Counter::getCounter(3), "file1", 10, 10, 11, 11);
715   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
716   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
717 
718   unsigned Line = 0;
719   const unsigned LineCounts[] = {20, 20, 20, 0, 30, 10, 10, 10, 10, 0, 0, 0, 0};
720   const bool MappedLines[] = {1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0};
721   ASSERT_EQ(std::size(LineCounts), std::size(MappedLines));
722 
723   for (const auto &LCS : getLineCoverageStats(Data)) {
724     ASSERT_LT(Line, std::size(LineCounts));
725     ASSERT_LT(Line, std::size(MappedLines));
726 
727     ASSERT_EQ(Line + 1, LCS.getLine());
728     errs() << "Line: " << Line + 1 << ", count = " << LCS.getExecutionCount()
729            << ", mapped = " << LCS.isMapped() << "\n";
730     ASSERT_EQ(LineCounts[Line], LCS.getExecutionCount());
731     ASSERT_EQ(MappedLines[Line], LCS.isMapped());
732     ++Line;
733   }
734   ASSERT_EQ(12U, Line);
735 
736   // Check that operator->() works / compiles.
737   ASSERT_EQ(1U, LineCoverageIterator(Data)->getLine());
738 }
739 
740 TEST_P(CoverageMappingTest, uncovered_function) {
741   startFunction("func", 0x1234);
742   addCMR(Counter::getZero(), "file1", 1, 2, 3, 4);
743   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
744 
745   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
746   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
747   ASSERT_EQ(2U, Segments.size());
748   ASSERT_EQ(CoverageSegment(1, 2, 0, true), Segments[0]);
749   ASSERT_EQ(CoverageSegment(3, 4, false),   Segments[1]);
750 }
751 
752 TEST_P(CoverageMappingTest, uncovered_function_with_mapping) {
753   startFunction("func", 0x1234);
754   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
755   addCMR(Counter::getCounter(1), "file1", 1, 1, 4, 7);
756   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
757 
758   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
759   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
760   ASSERT_EQ(3U, Segments.size());
761   ASSERT_EQ(CoverageSegment(1, 1, 0, true),  Segments[0]);
762   ASSERT_EQ(CoverageSegment(4, 7, 0, false), Segments[1]);
763   ASSERT_EQ(CoverageSegment(9, 9, false),    Segments[2]);
764 }
765 
766 TEST_P(CoverageMappingTest, combine_regions) {
767   ProfileWriter.addRecord({"func", 0x1234, {10, 20, 30}}, Err);
768 
769   startFunction("func", 0x1234);
770   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
771   addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4);
772   addCMR(Counter::getCounter(2), "file1", 3, 3, 4, 4);
773   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
774 
775   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
776   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
777   ASSERT_EQ(4U, Segments.size());
778   ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
779   ASSERT_EQ(CoverageSegment(3, 3, 50, true), Segments[1]);
780   ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]);
781   ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]);
782 }
783 
784 TEST_P(CoverageMappingTest, restore_combined_counter_after_nested_region) {
785   ProfileWriter.addRecord({"func", 0x1234, {10, 20, 40}}, Err);
786 
787   startFunction("func", 0x1234);
788   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
789   addCMR(Counter::getCounter(1), "file1", 1, 1, 9, 9);
790   addCMR(Counter::getCounter(2), "file1", 3, 3, 5, 5);
791   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
792 
793   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
794   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
795   ASSERT_EQ(4U, Segments.size());
796   EXPECT_EQ(CoverageSegment(1, 1, 30, true), Segments[0]);
797   EXPECT_EQ(CoverageSegment(3, 3, 40, true), Segments[1]);
798   EXPECT_EQ(CoverageSegment(5, 5, 30, false), Segments[2]);
799   EXPECT_EQ(CoverageSegment(9, 9, false), Segments[3]);
800 }
801 
802 // If CodeRegions and ExpansionRegions cover the same area,
803 // only counts of CodeRegions should be used.
804 TEST_P(CoverageMappingTest, dont_combine_expansions) {
805   ProfileWriter.addRecord({"func", 0x1234, {10, 20}}, Err);
806   ProfileWriter.addRecord({"func", 0x1234, {0, 0}}, Err);
807 
808   startFunction("func", 0x1234);
809   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
810   addCMR(Counter::getCounter(1), "file1", 3, 3, 4, 4);
811   addCMR(Counter::getCounter(1), "include1", 6, 6, 7, 7);
812   addExpansionCMR("file1", "include1", 3, 3, 4, 4);
813   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
814 
815   CoverageData Data = LoadedCoverage->getCoverageForFile("file1");
816   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
817   ASSERT_EQ(4U, Segments.size());
818   ASSERT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
819   ASSERT_EQ(CoverageSegment(3, 3, 20, true), Segments[1]);
820   ASSERT_EQ(CoverageSegment(4, 4, 10, false), Segments[2]);
821   ASSERT_EQ(CoverageSegment(9, 9, false), Segments[3]);
822 }
823 
824 // If an area is covered only by ExpansionRegions, they should be combinated.
825 TEST_P(CoverageMappingTest, combine_expansions) {
826   ProfileWriter.addRecord({"func", 0x1234, {2, 3, 7}}, Err);
827 
828   startFunction("func", 0x1234);
829   addCMR(Counter::getCounter(1), "include1", 1, 1, 1, 10);
830   addCMR(Counter::getCounter(2), "include2", 1, 1, 1, 10);
831   addCMR(Counter::getCounter(0), "file", 1, 1, 5, 5);
832   addExpansionCMR("file", "include1", 3, 1, 3, 5);
833   addExpansionCMR("file", "include2", 3, 1, 3, 5);
834 
835   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
836 
837   CoverageData Data = LoadedCoverage->getCoverageForFile("file");
838   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
839   ASSERT_EQ(4U, Segments.size());
840   EXPECT_EQ(CoverageSegment(1, 1, 2, true), Segments[0]);
841   EXPECT_EQ(CoverageSegment(3, 1, 10, true), Segments[1]);
842   EXPECT_EQ(CoverageSegment(3, 5, 2, false), Segments[2]);
843   EXPECT_EQ(CoverageSegment(5, 5, false), Segments[3]);
844 }
845 
846 // Test that counters not associated with any code regions are allowed.
847 TEST_P(CoverageMappingTest, non_code_region_counters) {
848   // No records in profdata
849 
850   startFunction("func", 0x1234);
851   addCMR(Counter::getCounter(0), "file", 1, 1, 5, 5);
852   addCMR(Counter::getExpression(0), "file", 6, 1, 6, 5);
853   addExpression(CounterExpression(
854       CounterExpression::Add, Counter::getCounter(1), Counter::getCounter(2)));
855 
856   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
857 
858   std::vector<std::string> Names;
859   for (const auto &Func : LoadedCoverage->getCoveredFunctions()) {
860     Names.push_back(Func.Name);
861     ASSERT_EQ(2U, Func.CountedRegions.size());
862   }
863   ASSERT_EQ(1U, Names.size());
864 }
865 
866 // Test that MCDC bitmasks not associated with any code regions are allowed.
867 TEST_P(CoverageMappingTest, non_code_region_bitmask) {
868   // No records in profdata
869 
870   startFunction("func", 0x1234);
871   addCMR(Counter::getCounter(0), "file", 1, 1, 5, 5);
872   addCMR(Counter::getCounter(1), "file", 1, 1, 5, 5);
873   addCMR(Counter::getCounter(2), "file", 1, 1, 5, 5);
874   addCMR(Counter::getCounter(3), "file", 1, 1, 5, 5);
875 
876   addMCDCDecisionCMR(0, 2, "file", 7, 1, 7, 6);
877   addMCDCBranchCMR(Counter::getCounter(0), Counter::getCounter(1), 1, 2, 0,
878                    "file", 7, 2, 7, 3);
879   addMCDCBranchCMR(Counter::getCounter(2), Counter::getCounter(3), 2, 0, 0,
880                    "file", 7, 4, 7, 5);
881 
882   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
883 
884   std::vector<std::string> Names;
885   for (const auto &Func : LoadedCoverage->getCoveredFunctions()) {
886     Names.push_back(Func.Name);
887     ASSERT_EQ(2U, Func.CountedBranchRegions.size());
888     ASSERT_EQ(1U, Func.MCDCRecords.size());
889   }
890   ASSERT_EQ(1U, Names.size());
891 }
892 
893 // Test the order of MCDCDecision before Expansion
894 TEST_P(CoverageMappingTest, decision_before_expansion) {
895   startFunction("foo", 0x1234);
896   addCMR(Counter::getCounter(0), "foo", 3, 23, 5, 2);
897 
898   // This(4:11) was put after Expansion(4:11) before the fix
899   addMCDCDecisionCMR(0, 2, "foo", 4, 11, 4, 20);
900 
901   addExpansionCMR("foo", "A", 4, 11, 4, 12);
902   addExpansionCMR("foo", "B", 4, 19, 4, 20);
903   addCMR(Counter::getCounter(0), "A", 1, 14, 1, 17);
904   addCMR(Counter::getCounter(0), "A", 1, 14, 1, 17);
905   addMCDCBranchCMR(Counter::getCounter(0), Counter::getCounter(1), 1, 2, 0, "A",
906                    1, 14, 1, 17);
907   addCMR(Counter::getCounter(1), "B", 1, 14, 1, 17);
908   addMCDCBranchCMR(Counter::getCounter(1), Counter::getCounter(2), 2, 0, 0, "B",
909                    1, 14, 1, 17);
910 
911   // InputFunctionCoverageData::Regions is rewritten after the write.
912   auto InputRegions = InputFunctions.back().Regions;
913 
914   writeAndReadCoverageRegions();
915 
916   const auto &OutputRegions = OutputFunctions.back().Regions;
917 
918   size_t N = ArrayRef(InputRegions).size();
919   ASSERT_EQ(N, OutputRegions.size());
920   for (size_t I = 0; I < N; ++I) {
921     ASSERT_EQ(InputRegions[I].Kind, OutputRegions[I].Kind);
922     ASSERT_EQ(InputRegions[I].FileID, OutputRegions[I].FileID);
923     ASSERT_EQ(InputRegions[I].ExpandedFileID, OutputRegions[I].ExpandedFileID);
924     ASSERT_EQ(InputRegions[I].startLoc(), OutputRegions[I].startLoc());
925     ASSERT_EQ(InputRegions[I].endLoc(), OutputRegions[I].endLoc());
926   }
927 }
928 
929 TEST_P(CoverageMappingTest, strip_filename_prefix) {
930   ProfileWriter.addRecord({"file1:func", 0x1234, {0}}, Err);
931 
932   startFunction("file1:func", 0x1234);
933   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
934   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
935 
936   std::vector<std::string> Names;
937   for (const auto &Func : LoadedCoverage->getCoveredFunctions())
938     Names.push_back(Func.Name);
939   ASSERT_EQ(1U, Names.size());
940   ASSERT_EQ("func", Names[0]);
941 }
942 
943 TEST_P(CoverageMappingTest, strip_unknown_filename_prefix) {
944   ProfileWriter.addRecord({"<unknown>:func", 0x1234, {0}}, Err);
945 
946   startFunction("<unknown>:func", 0x1234);
947   addCMR(Counter::getCounter(0), "", 1, 1, 9, 9);
948   EXPECT_THAT_ERROR(loadCoverageMapping(/*EmitFilenames=*/false), Succeeded());
949 
950   std::vector<std::string> Names;
951   for (const auto &Func : LoadedCoverage->getCoveredFunctions())
952     Names.push_back(Func.Name);
953   ASSERT_EQ(1U, Names.size());
954   ASSERT_EQ("func", Names[0]);
955 }
956 
957 TEST_P(CoverageMappingTest, dont_detect_false_instantiations) {
958   ProfileWriter.addRecord({"foo", 0x1234, {10}}, Err);
959   ProfileWriter.addRecord({"bar", 0x2345, {20}}, Err);
960 
961   startFunction("foo", 0x1234);
962   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
963   addExpansionCMR("main", "expanded", 4, 1, 4, 5);
964 
965   startFunction("bar", 0x2345);
966   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
967   addExpansionCMR("main", "expanded", 9, 1, 9, 5);
968 
969   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
970 
971   std::vector<InstantiationGroup> InstantiationGroups =
972       LoadedCoverage->getInstantiationGroups("expanded");
973   ASSERT_TRUE(InstantiationGroups.empty());
974 }
975 
976 TEST_P(CoverageMappingTest, load_coverage_for_expanded_file) {
977   ProfileWriter.addRecord({"func", 0x1234, {10}}, Err);
978 
979   startFunction("func", 0x1234);
980   addCMR(Counter::getCounter(0), "expanded", 1, 1, 1, 10);
981   addExpansionCMR("main", "expanded", 4, 1, 4, 5);
982 
983   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
984 
985   CoverageData Data = LoadedCoverage->getCoverageForFile("expanded");
986   std::vector<CoverageSegment> Segments(Data.begin(), Data.end());
987   ASSERT_EQ(2U, Segments.size());
988   EXPECT_EQ(CoverageSegment(1, 1, 10, true), Segments[0]);
989   EXPECT_EQ(CoverageSegment(1, 10, false), Segments[1]);
990 }
991 
992 TEST_P(CoverageMappingTest, skip_duplicate_function_record) {
993   ProfileWriter.addRecord({"func", 0x1234, {1}}, Err);
994 
995   // This record should be loaded.
996   startFunction("func", 0x1234);
997   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
998 
999   // This record should be loaded.
1000   startFunction("func", 0x1234);
1001   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
1002   addCMR(Counter::getCounter(0), "file2", 1, 1, 9, 9);
1003 
1004   // This record should be skipped.
1005   startFunction("func", 0x1234);
1006   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
1007 
1008   // This record should be loaded.
1009   startFunction("func", 0x1234);
1010   addCMR(Counter::getCounter(0), "file2", 1, 1, 9, 9);
1011   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
1012 
1013   // This record should be skipped.
1014   startFunction("func", 0x1234);
1015   addCMR(Counter::getCounter(0), "file1", 1, 1, 9, 9);
1016   addCMR(Counter::getCounter(0), "file2", 1, 1, 9, 9);
1017 
1018   EXPECT_THAT_ERROR(loadCoverageMapping(), Succeeded());
1019 
1020   auto Funcs = LoadedCoverage->getCoveredFunctions();
1021   unsigned NumFuncs = std::distance(Funcs.begin(), Funcs.end());
1022   ASSERT_EQ(3U, NumFuncs);
1023 }
1024 
1025 INSTANTIATE_TEST_SUITE_P(ParameterizedCovMapTest, CoverageMappingTest,
1026                          ::testing::Combine(::testing::Bool(),
1027                                             ::testing::Bool()));
1028 
1029 TEST(CoverageMappingTest, filename_roundtrip) {
1030   std::vector<std::string> Paths({"dir", "a", "b", "c", "d", "e"});
1031 
1032   for (bool Compress : {false, true}) {
1033     std::string EncodedFilenames;
1034     {
1035       raw_string_ostream OS(EncodedFilenames);
1036       CoverageFilenamesSectionWriter Writer(Paths);
1037       Writer.write(OS, Compress);
1038     }
1039 
1040     std::vector<std::string> ReadFilenames;
1041     RawCoverageFilenamesReader Reader(EncodedFilenames, ReadFilenames);
1042     EXPECT_THAT_ERROR(Reader.read(CovMapVersion::CurrentVersion), Succeeded());
1043 
1044     ASSERT_EQ(ReadFilenames.size(), Paths.size());
1045     for (unsigned I = 1; I < Paths.size(); ++I) {
1046       SmallString<256> P(Paths[0]);
1047       llvm::sys::path::append(P, Paths[I]);
1048       ASSERT_EQ(ReadFilenames[I], P);
1049     }
1050   }
1051 }
1052 
1053 TEST(CoverageMappingTest, filename_compilation_dir) {
1054   std::vector<std::string> Paths({"dir", "a", "b", "c", "d", "e"});
1055 
1056   for (bool Compress : {false, true}) {
1057     std::string EncodedFilenames;
1058     {
1059       raw_string_ostream OS(EncodedFilenames);
1060       CoverageFilenamesSectionWriter Writer(Paths);
1061       Writer.write(OS, Compress);
1062     }
1063 
1064     StringRef CompilationDir = "out";
1065     std::vector<std::string> ReadFilenames;
1066     RawCoverageFilenamesReader Reader(EncodedFilenames, ReadFilenames,
1067                                       CompilationDir);
1068     EXPECT_THAT_ERROR(Reader.read(CovMapVersion::CurrentVersion), Succeeded());
1069 
1070     ASSERT_EQ(ReadFilenames.size(), Paths.size());
1071     for (unsigned I = 1; I < Paths.size(); ++I) {
1072       SmallString<256> P(CompilationDir);
1073       llvm::sys::path::append(P, Paths[I]);
1074       ASSERT_EQ(ReadFilenames[I], P);
1075     }
1076   }
1077 }
1078 
1079 } // end anonymous namespace
1080