1 //===- CoverageMapping.cpp - Code coverage mapping support ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file contains support for clang's and llvm's instrumentation based 11 // code coverage. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/ProfileData/Coverage/CoverageMapping.h" 16 #include "llvm/ADT/ArrayRef.h" 17 #include "llvm/ADT/DenseMap.h" 18 #include "llvm/ADT/None.h" 19 #include "llvm/ADT/Optional.h" 20 #include "llvm/ADT/SmallBitVector.h" 21 #include "llvm/ADT/SmallVector.h" 22 #include "llvm/ADT/StringRef.h" 23 #include "llvm/ProfileData/Coverage/CoverageMappingReader.h" 24 #include "llvm/ProfileData/InstrProfReader.h" 25 #include "llvm/Support/Debug.h" 26 #include "llvm/Support/Errc.h" 27 #include "llvm/Support/Error.h" 28 #include "llvm/Support/ErrorHandling.h" 29 #include "llvm/Support/ManagedStatic.h" 30 #include "llvm/Support/MemoryBuffer.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <cstdint> 35 #include <iterator> 36 #include <memory> 37 #include <string> 38 #include <system_error> 39 #include <utility> 40 #include <vector> 41 42 using namespace llvm; 43 using namespace coverage; 44 45 #define DEBUG_TYPE "coverage-mapping" 46 47 Counter CounterExpressionBuilder::get(const CounterExpression &E) { 48 auto It = ExpressionIndices.find(E); 49 if (It != ExpressionIndices.end()) 50 return Counter::getExpression(It->second); 51 unsigned I = Expressions.size(); 52 Expressions.push_back(E); 53 ExpressionIndices[E] = I; 54 return Counter::getExpression(I); 55 } 56 57 void CounterExpressionBuilder::extractTerms(Counter C, int Factor, 58 SmallVectorImpl<Term> &Terms) { 59 switch (C.getKind()) { 60 case Counter::Zero: 61 break; 62 case Counter::CounterValueReference: 63 Terms.emplace_back(C.getCounterID(), Factor); 64 break; 65 case Counter::Expression: 66 const auto &E = Expressions[C.getExpressionID()]; 67 extractTerms(E.LHS, Factor, Terms); 68 extractTerms( 69 E.RHS, E.Kind == CounterExpression::Subtract ? -Factor : Factor, Terms); 70 break; 71 } 72 } 73 74 Counter CounterExpressionBuilder::simplify(Counter ExpressionTree) { 75 // Gather constant terms. 76 SmallVector<Term, 32> Terms; 77 extractTerms(ExpressionTree, +1, Terms); 78 79 // If there are no terms, this is just a zero. The algorithm below assumes at 80 // least one term. 81 if (Terms.size() == 0) 82 return Counter::getZero(); 83 84 // Group the terms by counter ID. 85 std::sort(Terms.begin(), Terms.end(), [](const Term &LHS, const Term &RHS) { 86 return LHS.CounterID < RHS.CounterID; 87 }); 88 89 // Combine terms by counter ID to eliminate counters that sum to zero. 90 auto Prev = Terms.begin(); 91 for (auto I = Prev + 1, E = Terms.end(); I != E; ++I) { 92 if (I->CounterID == Prev->CounterID) { 93 Prev->Factor += I->Factor; 94 continue; 95 } 96 ++Prev; 97 *Prev = *I; 98 } 99 Terms.erase(++Prev, Terms.end()); 100 101 Counter C; 102 // Create additions. We do this before subtractions to avoid constructs like 103 // ((0 - X) + Y), as opposed to (Y - X). 104 for (auto T : Terms) { 105 if (T.Factor <= 0) 106 continue; 107 for (int I = 0; I < T.Factor; ++I) 108 if (C.isZero()) 109 C = Counter::getCounter(T.CounterID); 110 else 111 C = get(CounterExpression(CounterExpression::Add, C, 112 Counter::getCounter(T.CounterID))); 113 } 114 115 // Create subtractions. 116 for (auto T : Terms) { 117 if (T.Factor >= 0) 118 continue; 119 for (int I = 0; I < -T.Factor; ++I) 120 C = get(CounterExpression(CounterExpression::Subtract, C, 121 Counter::getCounter(T.CounterID))); 122 } 123 return C; 124 } 125 126 Counter CounterExpressionBuilder::add(Counter LHS, Counter RHS) { 127 return simplify(get(CounterExpression(CounterExpression::Add, LHS, RHS))); 128 } 129 130 Counter CounterExpressionBuilder::subtract(Counter LHS, Counter RHS) { 131 return simplify( 132 get(CounterExpression(CounterExpression::Subtract, LHS, RHS))); 133 } 134 135 void CounterMappingContext::dump(const Counter &C, raw_ostream &OS) const { 136 switch (C.getKind()) { 137 case Counter::Zero: 138 OS << '0'; 139 return; 140 case Counter::CounterValueReference: 141 OS << '#' << C.getCounterID(); 142 break; 143 case Counter::Expression: { 144 if (C.getExpressionID() >= Expressions.size()) 145 return; 146 const auto &E = Expressions[C.getExpressionID()]; 147 OS << '('; 148 dump(E.LHS, OS); 149 OS << (E.Kind == CounterExpression::Subtract ? " - " : " + "); 150 dump(E.RHS, OS); 151 OS << ')'; 152 break; 153 } 154 } 155 if (CounterValues.empty()) 156 return; 157 Expected<int64_t> Value = evaluate(C); 158 if (auto E = Value.takeError()) { 159 consumeError(std::move(E)); 160 return; 161 } 162 OS << '[' << *Value << ']'; 163 } 164 165 Expected<int64_t> CounterMappingContext::evaluate(const Counter &C) const { 166 switch (C.getKind()) { 167 case Counter::Zero: 168 return 0; 169 case Counter::CounterValueReference: 170 if (C.getCounterID() >= CounterValues.size()) 171 return errorCodeToError(errc::argument_out_of_domain); 172 return CounterValues[C.getCounterID()]; 173 case Counter::Expression: { 174 if (C.getExpressionID() >= Expressions.size()) 175 return errorCodeToError(errc::argument_out_of_domain); 176 const auto &E = Expressions[C.getExpressionID()]; 177 Expected<int64_t> LHS = evaluate(E.LHS); 178 if (!LHS) 179 return LHS; 180 Expected<int64_t> RHS = evaluate(E.RHS); 181 if (!RHS) 182 return RHS; 183 return E.Kind == CounterExpression::Subtract ? *LHS - *RHS : *LHS + *RHS; 184 } 185 } 186 llvm_unreachable("Unhandled CounterKind"); 187 } 188 189 void FunctionRecordIterator::skipOtherFiles() { 190 while (Current != Records.end() && !Filename.empty() && 191 Filename != Current->Filenames[0]) 192 ++Current; 193 if (Current == Records.end()) 194 *this = FunctionRecordIterator(); 195 } 196 197 Error CoverageMapping::loadFunctionRecord( 198 const CoverageMappingRecord &Record, 199 IndexedInstrProfReader &ProfileReader) { 200 StringRef OrigFuncName = Record.FunctionName; 201 if (OrigFuncName.empty()) 202 return make_error<CoverageMapError>(coveragemap_error::malformed); 203 204 if (Record.Filenames.empty()) 205 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName); 206 else 207 OrigFuncName = getFuncNameWithoutPrefix(OrigFuncName, Record.Filenames[0]); 208 209 // Don't load records for functions we've already seen. 210 if (!FunctionNames.insert(OrigFuncName).second) 211 return Error::success(); 212 213 CounterMappingContext Ctx(Record.Expressions); 214 215 std::vector<uint64_t> Counts; 216 if (Error E = ProfileReader.getFunctionCounts(Record.FunctionName, 217 Record.FunctionHash, Counts)) { 218 instrprof_error IPE = InstrProfError::take(std::move(E)); 219 if (IPE == instrprof_error::hash_mismatch) { 220 MismatchedFunctionCount++; 221 return Error::success(); 222 } else if (IPE != instrprof_error::unknown_function) 223 return make_error<InstrProfError>(IPE); 224 Counts.assign(Record.MappingRegions.size(), 0); 225 } 226 Ctx.setCounts(Counts); 227 228 assert(!Record.MappingRegions.empty() && "Function has no regions"); 229 230 FunctionRecord Function(OrigFuncName, Record.Filenames); 231 for (const auto &Region : Record.MappingRegions) { 232 Expected<int64_t> ExecutionCount = Ctx.evaluate(Region.Count); 233 if (auto E = ExecutionCount.takeError()) { 234 consumeError(std::move(E)); 235 return Error::success(); 236 } 237 Function.pushRegion(Region, *ExecutionCount); 238 } 239 if (Function.CountedRegions.size() != Record.MappingRegions.size()) { 240 MismatchedFunctionCount++; 241 return Error::success(); 242 } 243 244 Functions.push_back(std::move(Function)); 245 return Error::success(); 246 } 247 248 Expected<std::unique_ptr<CoverageMapping>> CoverageMapping::load( 249 ArrayRef<std::unique_ptr<CoverageMappingReader>> CoverageReaders, 250 IndexedInstrProfReader &ProfileReader) { 251 auto Coverage = std::unique_ptr<CoverageMapping>(new CoverageMapping()); 252 253 for (const auto &CoverageReader : CoverageReaders) { 254 for (auto RecordOrErr : *CoverageReader) { 255 if (Error E = RecordOrErr.takeError()) 256 return std::move(E); 257 const auto &Record = *RecordOrErr; 258 if (Error E = Coverage->loadFunctionRecord(Record, ProfileReader)) 259 return std::move(E); 260 } 261 } 262 263 return std::move(Coverage); 264 } 265 266 Expected<std::unique_ptr<CoverageMapping>> 267 CoverageMapping::load(ArrayRef<StringRef> ObjectFilenames, 268 StringRef ProfileFilename, ArrayRef<StringRef> Arches) { 269 auto ProfileReaderOrErr = IndexedInstrProfReader::create(ProfileFilename); 270 if (Error E = ProfileReaderOrErr.takeError()) 271 return std::move(E); 272 auto ProfileReader = std::move(ProfileReaderOrErr.get()); 273 274 SmallVector<std::unique_ptr<CoverageMappingReader>, 4> Readers; 275 SmallVector<std::unique_ptr<MemoryBuffer>, 4> Buffers; 276 for (const auto &File : llvm::enumerate(ObjectFilenames)) { 277 auto CovMappingBufOrErr = MemoryBuffer::getFileOrSTDIN(File.value()); 278 if (std::error_code EC = CovMappingBufOrErr.getError()) 279 return errorCodeToError(EC); 280 StringRef Arch = Arches.empty() ? StringRef() : Arches[File.index()]; 281 auto CoverageReaderOrErr = 282 BinaryCoverageReader::create(CovMappingBufOrErr.get(), Arch); 283 if (Error E = CoverageReaderOrErr.takeError()) 284 return std::move(E); 285 Readers.push_back(std::move(CoverageReaderOrErr.get())); 286 Buffers.push_back(std::move(CovMappingBufOrErr.get())); 287 } 288 return load(Readers, *ProfileReader); 289 } 290 291 namespace { 292 293 /// \brief Distributes functions into instantiation sets. 294 /// 295 /// An instantiation set is a collection of functions that have the same source 296 /// code, ie, template functions specializations. 297 class FunctionInstantiationSetCollector { 298 using MapT = DenseMap<LineColPair, std::vector<const FunctionRecord *>>; 299 MapT InstantiatedFunctions; 300 301 public: 302 void insert(const FunctionRecord &Function, unsigned FileID) { 303 auto I = Function.CountedRegions.begin(), E = Function.CountedRegions.end(); 304 while (I != E && I->FileID != FileID) 305 ++I; 306 assert(I != E && "function does not cover the given file"); 307 auto &Functions = InstantiatedFunctions[I->startLoc()]; 308 Functions.push_back(&Function); 309 } 310 311 MapT::iterator begin() { return InstantiatedFunctions.begin(); } 312 MapT::iterator end() { return InstantiatedFunctions.end(); } 313 }; 314 315 class SegmentBuilder { 316 std::vector<CoverageSegment> &Segments; 317 SmallVector<const CountedRegion *, 8> ActiveRegions; 318 319 SegmentBuilder(std::vector<CoverageSegment> &Segments) : Segments(Segments) {} 320 321 /// Emit a segment with the count from \p Region starting at \p StartLoc. 322 // 323 /// \p IsRegionEntry: The segment is at the start of a new non-gap region. 324 /// \p EmitSkippedRegion: The segment must be emitted as a skipped region. 325 void startSegment(const CountedRegion &Region, LineColPair StartLoc, 326 bool IsRegionEntry, bool EmitSkippedRegion = false) { 327 bool HasCount = !EmitSkippedRegion && 328 (Region.Kind != CounterMappingRegion::SkippedRegion); 329 330 // If the new segment wouldn't affect coverage rendering, skip it. 331 if (!Segments.empty() && !IsRegionEntry && !EmitSkippedRegion) { 332 const auto &Last = Segments.back(); 333 if (Last.HasCount == HasCount && Last.Count == Region.ExecutionCount && 334 !Last.IsRegionEntry) 335 return; 336 } 337 338 if (HasCount) 339 Segments.emplace_back(StartLoc.first, StartLoc.second, 340 Region.ExecutionCount, IsRegionEntry, 341 Region.Kind == CounterMappingRegion::GapRegion); 342 else 343 Segments.emplace_back(StartLoc.first, StartLoc.second, IsRegionEntry); 344 345 DEBUG({ 346 const auto &Last = Segments.back(); 347 dbgs() << "Segment at " << Last.Line << ":" << Last.Col 348 << " (count = " << Last.Count << ")" 349 << (Last.IsRegionEntry ? ", RegionEntry" : "") 350 << (!Last.HasCount ? ", Skipped" : "") 351 << (Last.IsGapRegion ? ", Gap" : "") << "\n"; 352 }); 353 } 354 355 /// Emit segments for active regions which end before \p Loc. 356 /// 357 /// \p Loc: The start location of the next region. If None, all active 358 /// regions are completed. 359 /// \p FirstCompletedRegion: Index of the first completed region. 360 void completeRegionsUntil(Optional<LineColPair> Loc, 361 unsigned FirstCompletedRegion) { 362 // Sort the completed regions by end location. This makes it simple to 363 // emit closing segments in sorted order. 364 auto CompletedRegionsIt = ActiveRegions.begin() + FirstCompletedRegion; 365 std::stable_sort(CompletedRegionsIt, ActiveRegions.end(), 366 [](const CountedRegion *L, const CountedRegion *R) { 367 return L->endLoc() < R->endLoc(); 368 }); 369 370 // Emit segments for all completed regions. 371 for (unsigned I = FirstCompletedRegion + 1, E = ActiveRegions.size(); I < E; 372 ++I) { 373 const auto *CompletedRegion = ActiveRegions[I]; 374 assert((!Loc || CompletedRegion->endLoc() <= *Loc) && 375 "Completed region ends after start of new region"); 376 377 const auto *PrevCompletedRegion = ActiveRegions[I - 1]; 378 auto CompletedSegmentLoc = PrevCompletedRegion->endLoc(); 379 380 // Don't emit any more segments if they start where the new region begins. 381 if (Loc && CompletedSegmentLoc == *Loc) 382 break; 383 384 // Don't emit a segment if the next completed region ends at the same 385 // location as this one. 386 if (CompletedSegmentLoc == CompletedRegion->endLoc()) 387 continue; 388 389 startSegment(*CompletedRegion, CompletedSegmentLoc, false); 390 } 391 392 auto Last = ActiveRegions.back(); 393 if (FirstCompletedRegion && Last->endLoc() != *Loc) { 394 // If there's a gap after the end of the last completed region and the 395 // start of the new region, use the last active region to fill the gap. 396 startSegment(*ActiveRegions[FirstCompletedRegion - 1], Last->endLoc(), 397 false); 398 } else if (!FirstCompletedRegion && (!Loc || *Loc != Last->endLoc())) { 399 // Emit a skipped segment if there are no more active regions. This 400 // ensures that gaps between functions are marked correctly. 401 startSegment(*Last, Last->endLoc(), false, true); 402 } 403 404 // Pop the completed regions. 405 ActiveRegions.erase(CompletedRegionsIt, ActiveRegions.end()); 406 } 407 408 void buildSegmentsImpl(ArrayRef<CountedRegion> Regions) { 409 for (const auto &CR : enumerate(Regions)) { 410 auto CurStartLoc = CR.value().startLoc(); 411 412 // Active regions which end before the current region need to be popped. 413 auto CompletedRegions = 414 std::stable_partition(ActiveRegions.begin(), ActiveRegions.end(), 415 [&](const CountedRegion *Region) { 416 return !(Region->endLoc() <= CurStartLoc); 417 }); 418 if (CompletedRegions != ActiveRegions.end()) { 419 unsigned FirstCompletedRegion = 420 std::distance(ActiveRegions.begin(), CompletedRegions); 421 completeRegionsUntil(CurStartLoc, FirstCompletedRegion); 422 } 423 424 bool GapRegion = CR.value().Kind == CounterMappingRegion::GapRegion; 425 426 // Try to emit a segment for the current region. 427 if (CurStartLoc == CR.value().endLoc()) { 428 // Avoid making zero-length regions active. If it's the last region, 429 // emit a skipped segment. Otherwise use its predecessor's count. 430 const bool Skipped = (CR.index() + 1) == Regions.size(); 431 startSegment(ActiveRegions.empty() ? CR.value() : *ActiveRegions.back(), 432 CurStartLoc, !GapRegion, Skipped); 433 continue; 434 } 435 if (CR.index() + 1 == Regions.size() || 436 CurStartLoc != Regions[CR.index() + 1].startLoc()) { 437 // Emit a segment if the next region doesn't start at the same location 438 // as this one. 439 startSegment(CR.value(), CurStartLoc, !GapRegion); 440 } 441 442 // This region is active (i.e not completed). 443 ActiveRegions.push_back(&CR.value()); 444 } 445 446 // Complete any remaining active regions. 447 if (!ActiveRegions.empty()) 448 completeRegionsUntil(None, 0); 449 } 450 451 /// Sort a nested sequence of regions from a single file. 452 static void sortNestedRegions(MutableArrayRef<CountedRegion> Regions) { 453 std::sort(Regions.begin(), Regions.end(), [](const CountedRegion &LHS, 454 const CountedRegion &RHS) { 455 if (LHS.startLoc() != RHS.startLoc()) 456 return LHS.startLoc() < RHS.startLoc(); 457 if (LHS.endLoc() != RHS.endLoc()) 458 // When LHS completely contains RHS, we sort LHS first. 459 return RHS.endLoc() < LHS.endLoc(); 460 // If LHS and RHS cover the same area, we need to sort them according 461 // to their kinds so that the most suitable region will become "active" 462 // in combineRegions(). Because we accumulate counter values only from 463 // regions of the same kind as the first region of the area, prefer 464 // CodeRegion to ExpansionRegion and ExpansionRegion to SkippedRegion. 465 static_assert(CounterMappingRegion::CodeRegion < 466 CounterMappingRegion::ExpansionRegion && 467 CounterMappingRegion::ExpansionRegion < 468 CounterMappingRegion::SkippedRegion, 469 "Unexpected order of region kind values"); 470 return LHS.Kind < RHS.Kind; 471 }); 472 } 473 474 /// Combine counts of regions which cover the same area. 475 static ArrayRef<CountedRegion> 476 combineRegions(MutableArrayRef<CountedRegion> Regions) { 477 if (Regions.empty()) 478 return Regions; 479 auto Active = Regions.begin(); 480 auto End = Regions.end(); 481 for (auto I = Regions.begin() + 1; I != End; ++I) { 482 if (Active->startLoc() != I->startLoc() || 483 Active->endLoc() != I->endLoc()) { 484 // Shift to the next region. 485 ++Active; 486 if (Active != I) 487 *Active = *I; 488 continue; 489 } 490 // Merge duplicate region. 491 // If CodeRegions and ExpansionRegions cover the same area, it's probably 492 // a macro which is fully expanded to another macro. In that case, we need 493 // to accumulate counts only from CodeRegions, or else the area will be 494 // counted twice. 495 // On the other hand, a macro may have a nested macro in its body. If the 496 // outer macro is used several times, the ExpansionRegion for the nested 497 // macro will also be added several times. These ExpansionRegions cover 498 // the same source locations and have to be combined to reach the correct 499 // value for that area. 500 // We add counts of the regions of the same kind as the active region 501 // to handle the both situations. 502 if (I->Kind == Active->Kind) 503 Active->ExecutionCount += I->ExecutionCount; 504 } 505 return Regions.drop_back(std::distance(++Active, End)); 506 } 507 508 public: 509 /// Build a sorted list of CoverageSegments from a list of Regions. 510 static std::vector<CoverageSegment> 511 buildSegments(MutableArrayRef<CountedRegion> Regions) { 512 std::vector<CoverageSegment> Segments; 513 SegmentBuilder Builder(Segments); 514 515 sortNestedRegions(Regions); 516 ArrayRef<CountedRegion> CombinedRegions = combineRegions(Regions); 517 518 DEBUG({ 519 dbgs() << "Combined regions:\n"; 520 for (const auto &CR : CombinedRegions) 521 dbgs() << " " << CR.LineStart << ":" << CR.ColumnStart << " -> " 522 << CR.LineEnd << ":" << CR.ColumnEnd 523 << " (count=" << CR.ExecutionCount << ")\n"; 524 }); 525 526 Builder.buildSegmentsImpl(CombinedRegions); 527 528 #ifndef NDEBUG 529 for (unsigned I = 1, E = Segments.size(); I < E; ++I) { 530 const auto &L = Segments[I - 1]; 531 const auto &R = Segments[I]; 532 if (!(L.Line < R.Line) && !(L.Line == R.Line && L.Col < R.Col)) { 533 DEBUG(dbgs() << " ! Segment " << L.Line << ":" << L.Col 534 << " followed by " << R.Line << ":" << R.Col << "\n"); 535 assert(false && "Coverage segments not unique or sorted"); 536 } 537 } 538 #endif 539 540 return Segments; 541 } 542 }; 543 544 } // end anonymous namespace 545 546 std::vector<StringRef> CoverageMapping::getUniqueSourceFiles() const { 547 std::vector<StringRef> Filenames; 548 for (const auto &Function : getCoveredFunctions()) 549 Filenames.insert(Filenames.end(), Function.Filenames.begin(), 550 Function.Filenames.end()); 551 std::sort(Filenames.begin(), Filenames.end()); 552 auto Last = std::unique(Filenames.begin(), Filenames.end()); 553 Filenames.erase(Last, Filenames.end()); 554 return Filenames; 555 } 556 557 static SmallBitVector gatherFileIDs(StringRef SourceFile, 558 const FunctionRecord &Function) { 559 SmallBitVector FilenameEquivalence(Function.Filenames.size(), false); 560 for (unsigned I = 0, E = Function.Filenames.size(); I < E; ++I) 561 if (SourceFile == Function.Filenames[I]) 562 FilenameEquivalence[I] = true; 563 return FilenameEquivalence; 564 } 565 566 /// Return the ID of the file where the definition of the function is located. 567 static Optional<unsigned> findMainViewFileID(const FunctionRecord &Function) { 568 SmallBitVector IsNotExpandedFile(Function.Filenames.size(), true); 569 for (const auto &CR : Function.CountedRegions) 570 if (CR.Kind == CounterMappingRegion::ExpansionRegion) 571 IsNotExpandedFile[CR.ExpandedFileID] = false; 572 int I = IsNotExpandedFile.find_first(); 573 if (I == -1) 574 return None; 575 return I; 576 } 577 578 /// Check if SourceFile is the file that contains the definition of 579 /// the Function. Return the ID of the file in that case or None otherwise. 580 static Optional<unsigned> findMainViewFileID(StringRef SourceFile, 581 const FunctionRecord &Function) { 582 Optional<unsigned> I = findMainViewFileID(Function); 583 if (I && SourceFile == Function.Filenames[*I]) 584 return I; 585 return None; 586 } 587 588 static bool isExpansion(const CountedRegion &R, unsigned FileID) { 589 return R.Kind == CounterMappingRegion::ExpansionRegion && R.FileID == FileID; 590 } 591 592 CoverageData CoverageMapping::getCoverageForFile(StringRef Filename) const { 593 CoverageData FileCoverage(Filename); 594 std::vector<CountedRegion> Regions; 595 596 for (const auto &Function : Functions) { 597 auto MainFileID = findMainViewFileID(Filename, Function); 598 auto FileIDs = gatherFileIDs(Filename, Function); 599 for (const auto &CR : Function.CountedRegions) 600 if (FileIDs.test(CR.FileID)) { 601 Regions.push_back(CR); 602 if (MainFileID && isExpansion(CR, *MainFileID)) 603 FileCoverage.Expansions.emplace_back(CR, Function); 604 } 605 } 606 607 DEBUG(dbgs() << "Emitting segments for file: " << Filename << "\n"); 608 FileCoverage.Segments = SegmentBuilder::buildSegments(Regions); 609 610 return FileCoverage; 611 } 612 613 std::vector<InstantiationGroup> 614 CoverageMapping::getInstantiationGroups(StringRef Filename) const { 615 FunctionInstantiationSetCollector InstantiationSetCollector; 616 for (const auto &Function : Functions) { 617 auto MainFileID = findMainViewFileID(Filename, Function); 618 if (!MainFileID) 619 continue; 620 InstantiationSetCollector.insert(Function, *MainFileID); 621 } 622 623 std::vector<InstantiationGroup> Result; 624 for (const auto &InstantiationSet : InstantiationSetCollector) { 625 InstantiationGroup IG{InstantiationSet.first.first, 626 InstantiationSet.first.second, 627 std::move(InstantiationSet.second)}; 628 Result.emplace_back(std::move(IG)); 629 } 630 return Result; 631 } 632 633 CoverageData 634 CoverageMapping::getCoverageForFunction(const FunctionRecord &Function) const { 635 auto MainFileID = findMainViewFileID(Function); 636 if (!MainFileID) 637 return CoverageData(); 638 639 CoverageData FunctionCoverage(Function.Filenames[*MainFileID]); 640 std::vector<CountedRegion> Regions; 641 for (const auto &CR : Function.CountedRegions) 642 if (CR.FileID == *MainFileID) { 643 Regions.push_back(CR); 644 if (isExpansion(CR, *MainFileID)) 645 FunctionCoverage.Expansions.emplace_back(CR, Function); 646 } 647 648 DEBUG(dbgs() << "Emitting segments for function: " << Function.Name << "\n"); 649 FunctionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 650 651 return FunctionCoverage; 652 } 653 654 CoverageData CoverageMapping::getCoverageForExpansion( 655 const ExpansionRecord &Expansion) const { 656 CoverageData ExpansionCoverage( 657 Expansion.Function.Filenames[Expansion.FileID]); 658 std::vector<CountedRegion> Regions; 659 for (const auto &CR : Expansion.Function.CountedRegions) 660 if (CR.FileID == Expansion.FileID) { 661 Regions.push_back(CR); 662 if (isExpansion(CR, Expansion.FileID)) 663 ExpansionCoverage.Expansions.emplace_back(CR, Expansion.Function); 664 } 665 666 DEBUG(dbgs() << "Emitting segments for expansion of file " << Expansion.FileID 667 << "\n"); 668 ExpansionCoverage.Segments = SegmentBuilder::buildSegments(Regions); 669 670 return ExpansionCoverage; 671 } 672 673 static std::string getCoverageMapErrString(coveragemap_error Err) { 674 switch (Err) { 675 case coveragemap_error::success: 676 return "Success"; 677 case coveragemap_error::eof: 678 return "End of File"; 679 case coveragemap_error::no_data_found: 680 return "No coverage data found"; 681 case coveragemap_error::unsupported_version: 682 return "Unsupported coverage format version"; 683 case coveragemap_error::truncated: 684 return "Truncated coverage data"; 685 case coveragemap_error::malformed: 686 return "Malformed coverage data"; 687 } 688 llvm_unreachable("A value of coveragemap_error has no message."); 689 } 690 691 namespace { 692 693 // FIXME: This class is only here to support the transition to llvm::Error. It 694 // will be removed once this transition is complete. Clients should prefer to 695 // deal with the Error value directly, rather than converting to error_code. 696 class CoverageMappingErrorCategoryType : public std::error_category { 697 const char *name() const noexcept override { return "llvm.coveragemap"; } 698 std::string message(int IE) const override { 699 return getCoverageMapErrString(static_cast<coveragemap_error>(IE)); 700 } 701 }; 702 703 } // end anonymous namespace 704 705 std::string CoverageMapError::message() const { 706 return getCoverageMapErrString(Err); 707 } 708 709 static ManagedStatic<CoverageMappingErrorCategoryType> ErrorCategory; 710 711 const std::error_category &llvm::coverage::coveragemap_category() { 712 return *ErrorCategory; 713 } 714 715 char CoverageMapError::ID = 0; 716