1 //===--- CoverageMappingGen.cpp - Coverage mapping generation ---*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // Instrumentation-based code coverage mapping generator 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CoverageMappingGen.h" 15 #include "CodeGenFunction.h" 16 #include "clang/AST/StmtVisitor.h" 17 #include "clang/Lex/Lexer.h" 18 #include "llvm/ProfileData/InstrProfReader.h" 19 #include "llvm/ProfileData/CoverageMapping.h" 20 #include "llvm/ProfileData/CoverageMappingWriter.h" 21 #include "llvm/ProfileData/CoverageMappingReader.h" 22 #include "llvm/Support/FileSystem.h" 23 24 using namespace clang; 25 using namespace CodeGen; 26 using namespace llvm::coverage; 27 28 void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) { 29 SkippedRanges.push_back(Range); 30 } 31 32 namespace { 33 34 /// \brief A region of source code that can be mapped to a counter. 35 struct SourceMappingRegion { 36 enum RegionFlags { 37 /// \brief This region won't be emitted if it wasn't extended. 38 /// This is useful so that we won't emit source ranges for single tokens 39 /// that we don't really care that much about, like: 40 /// the '(' token in #define MACRO ( 41 IgnoreIfNotExtended = 0x0001, 42 }; 43 44 FileID File, MacroArgumentFile; 45 46 Counter Count; 47 48 /// \brief A statement that initiated the count of Zero. 49 /// 50 /// This initiator statement is useful to prevent merging of unreachable 51 /// regions with different statements that caused the counter to become 52 /// unreachable. 53 const Stmt *UnreachableInitiator; 54 55 /// \brief A statement that separates certain mapping regions into groups. 56 /// 57 /// The group statement is sometimes useful when we are emitting the source 58 /// regions not in their correct lexical order, e.g. the regions for the 59 /// incrementation expression in the 'for' construct. By marking the regions 60 /// in the incrementation expression with the group statement, we avoid the 61 /// merging of the regions from the incrementation expression and the loop's 62 /// body. 63 const Stmt *Group; 64 65 /// \brief The region's starting location. 66 SourceLocation LocStart; 67 68 /// \brief The region's ending location. 69 SourceLocation LocEnd, AlternativeLocEnd; 70 unsigned Flags; 71 CounterMappingRegion::RegionKind Kind; 72 73 SourceMappingRegion(FileID File, FileID MacroArgumentFile, Counter Count, 74 const Stmt *UnreachableInitiator, const Stmt *Group, 75 SourceLocation LocStart, SourceLocation LocEnd, 76 unsigned Flags = 0, 77 CounterMappingRegion::RegionKind Kind = 78 CounterMappingRegion::CodeRegion) 79 : File(File), MacroArgumentFile(MacroArgumentFile), Count(Count), 80 UnreachableInitiator(UnreachableInitiator), Group(Group), 81 LocStart(LocStart), LocEnd(LocEnd), AlternativeLocEnd(LocStart), 82 Flags(Flags), Kind(Kind) {} 83 84 bool hasFlag(RegionFlags Flag) const { return (Flags & Flag) != 0; } 85 86 void setFlag(RegionFlags Flag) { Flags |= Flag; } 87 88 void clearFlag(RegionFlags Flag) { Flags &= ~Flag; } 89 90 /// \brief Return true if two regions can be merged together. 91 bool isMergeable(SourceMappingRegion &R) { 92 return File == R.File && MacroArgumentFile == R.MacroArgumentFile && 93 Count == R.Count && UnreachableInitiator == R.UnreachableInitiator && 94 Group == R.Group && Kind == R.Kind; 95 } 96 97 /// \brief Merge two regions by extending the 'this' region to cover the 98 /// given region. 99 void mergeByExtendingTo(SourceMappingRegion &R) { 100 LocEnd = R.LocEnd; 101 AlternativeLocEnd = R.LocStart; 102 if (hasFlag(IgnoreIfNotExtended)) 103 clearFlag(IgnoreIfNotExtended); 104 } 105 }; 106 107 /// \brief The state of the coverage mapping builder. 108 struct SourceMappingState { 109 Counter CurrentRegionCount; 110 const Stmt *CurrentSourceGroup; 111 const Stmt *CurrentUnreachableRegionInitiator; 112 113 SourceMappingState(Counter CurrentRegionCount, const Stmt *CurrentSourceGroup, 114 const Stmt *CurrentUnreachableRegionInitiator) 115 : CurrentRegionCount(CurrentRegionCount), 116 CurrentSourceGroup(CurrentSourceGroup), 117 CurrentUnreachableRegionInitiator(CurrentUnreachableRegionInitiator) {} 118 }; 119 120 /// \brief Provides the common functionality for the different 121 /// coverage mapping region builders. 122 class CoverageMappingBuilder { 123 public: 124 CoverageMappingModuleGen &CVM; 125 SourceManager &SM; 126 const LangOptions &LangOpts; 127 128 private: 129 struct FileInfo { 130 /// \brief The file id that will be used by the coverage mapping system. 131 unsigned CovMappingFileID; 132 const FileEntry *Entry; 133 134 FileInfo(unsigned CovMappingFileID, const FileEntry *Entry) 135 : CovMappingFileID(CovMappingFileID), Entry(Entry) {} 136 }; 137 138 /// \brief This mapping maps clang's FileIDs to file ids used 139 /// by the coverage mapping system and clang's file entries. 140 llvm::SmallDenseMap<FileID, FileInfo, 8> FileIDMapping; 141 142 public: 143 /// \brief The statement that corresponds to the current source group. 144 const Stmt *CurrentSourceGroup; 145 146 /// \brief The statement the initiated the current unreachable region. 147 const Stmt *CurrentUnreachableRegionInitiator; 148 149 /// \brief The coverage mapping regions for this function 150 llvm::SmallVector<CounterMappingRegion, 32> MappingRegions; 151 /// \brief The source mapping regions for this function. 152 llvm::SmallVector<SourceMappingRegion, 32> SourceRegions; 153 154 CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 155 const LangOptions &LangOpts) 156 : CVM(CVM), SM(SM), LangOpts(LangOpts), 157 CurrentSourceGroup(nullptr), 158 CurrentUnreachableRegionInitiator(nullptr) {} 159 160 /// \brief Return the precise end location for the given token. 161 SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) { 162 return Lexer::getLocForEndOfToken(SM.getSpellingLoc(Loc), 0, SM, LangOpts); 163 } 164 165 /// \brief Create the mapping that maps from the function's file ids to 166 /// the indices for the translation unit's filenames. 167 void createFileIDMapping(SmallVectorImpl<unsigned> &Mapping) { 168 Mapping.resize(FileIDMapping.size(), 0); 169 for (const auto &I : FileIDMapping) 170 Mapping[I.second.CovMappingFileID] = CVM.getFileID(I.second.Entry); 171 } 172 173 /// \brief Get the coverage mapping file id that corresponds to the given 174 /// clang file id. If such file id doesn't exist, it gets added to the 175 /// mapping that maps from clang's file ids to coverage mapping file ids. 176 /// Return true if there was an error getting the coverage mapping file id. 177 /// An example of an when this function fails is when the region tries 178 /// to get a coverage file id for a location in a built-in macro. 179 bool getCoverageFileID(SourceLocation LocStart, FileID File, 180 FileID SpellingFile, unsigned &Result) { 181 auto Mapping = FileIDMapping.find(File); 182 if (Mapping != FileIDMapping.end()) { 183 Result = Mapping->second.CovMappingFileID; 184 return false; 185 } 186 187 auto Entry = SM.getFileEntryForID(SpellingFile); 188 if (!Entry) 189 return true; 190 191 Result = FileIDMapping.size(); 192 FileIDMapping.insert(std::make_pair(File, FileInfo(Result, Entry))); 193 createFileExpansionRegion(LocStart, File); 194 return false; 195 } 196 197 /// \brief Get the coverage mapping file id that corresponds to the given 198 /// clang file id. 199 /// Return true if there was an error getting the coverage mapping file id. 200 bool getExistingCoverageFileID(FileID File, unsigned &Result) { 201 // Make sure that the file is valid. 202 if (File.isInvalid()) 203 return true; 204 auto Mapping = FileIDMapping.find(File); 205 if (Mapping != FileIDMapping.end()) { 206 Result = Mapping->second.CovMappingFileID; 207 return false; 208 } 209 return true; 210 } 211 212 /// \brief Return true if the given clang's file id has a corresponding 213 /// coverage file id. 214 bool hasExistingCoverageFileID(FileID File) const { 215 return FileIDMapping.count(File); 216 } 217 218 /// \brief Gather all the regions that were skipped by the preprocessor 219 /// using the constructs like #if. 220 void gatherSkippedRegions() { 221 /// An array of the minimum lineStarts and the maximum lineEnds 222 /// for mapping regions from the appropriate source files. 223 llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges; 224 FileLineRanges.resize( 225 FileIDMapping.size(), 226 std::make_pair(std::numeric_limits<unsigned>::max(), 0)); 227 for (const auto &R : MappingRegions) { 228 FileLineRanges[R.FileID].first = 229 std::min(FileLineRanges[R.FileID].first, R.LineStart); 230 FileLineRanges[R.FileID].second = 231 std::max(FileLineRanges[R.FileID].second, R.LineEnd); 232 } 233 234 auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges(); 235 for (const auto &I : SkippedRanges) { 236 auto LocStart = I.getBegin(); 237 auto LocEnd = I.getEnd(); 238 auto FileStart = SM.getFileID(LocStart); 239 if (!hasExistingCoverageFileID(FileStart)) 240 continue; 241 auto ActualFileStart = SM.getDecomposedSpellingLoc(LocStart).first; 242 if (ActualFileStart != SM.getDecomposedSpellingLoc(LocEnd).first) 243 // Ignore regions that span across multiple files. 244 continue; 245 246 unsigned CovFileID; 247 if (getCoverageFileID(LocStart, FileStart, ActualFileStart, CovFileID)) 248 continue; 249 unsigned LineStart = SM.getSpellingLineNumber(LocStart); 250 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 251 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 252 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 253 CounterMappingRegion Region(Counter(), CovFileID, LineStart, ColumnStart, 254 LineEnd, ColumnEnd, false, 255 CounterMappingRegion::SkippedRegion); 256 // Make sure that we only collect the regions that are inside 257 // the souce code of this function. 258 if (Region.LineStart >= FileLineRanges[CovFileID].first && 259 Region.LineEnd <= FileLineRanges[CovFileID].second) 260 MappingRegions.push_back(Region); 261 } 262 } 263 264 /// \brief Create a mapping region that correponds to an expansion of 265 /// a macro or an embedded include. 266 void createFileExpansionRegion(SourceLocation Loc, FileID ExpandedFile) { 267 SourceLocation LocStart; 268 if (Loc.isMacroID()) 269 LocStart = SM.getImmediateExpansionRange(Loc).first; 270 else { 271 LocStart = SM.getIncludeLoc(ExpandedFile); 272 if (LocStart.isInvalid()) 273 return; // This file has no expansion region. 274 } 275 276 auto File = SM.getFileID(LocStart); 277 auto SpellingFile = SM.getDecomposedSpellingLoc(LocStart).first; 278 unsigned CovFileID, ExpandedFileID; 279 if (getExistingCoverageFileID(ExpandedFile, ExpandedFileID)) 280 return; 281 if (getCoverageFileID(LocStart, File, SpellingFile, CovFileID)) 282 return; 283 unsigned LineStart = SM.getSpellingLineNumber(LocStart); 284 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 285 unsigned LineEnd = LineStart; 286 // Compute the end column manually as Lexer::getLocForEndOfToken doesn't 287 // give the correct result in all cases. 288 unsigned ColumnEnd = 289 ColumnStart + 290 Lexer::MeasureTokenLength(SM.getSpellingLoc(LocStart), SM, LangOpts); 291 292 MappingRegions.push_back(CounterMappingRegion( 293 Counter(), CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd, 294 false, CounterMappingRegion::ExpansionRegion)); 295 MappingRegions.back().ExpandedFileID = ExpandedFileID; 296 } 297 298 /// \brief Enter a source region group that is identified by the given 299 /// statement. 300 /// It's not possible to enter a group when there is already 301 /// another group present. 302 void beginSourceRegionGroup(const Stmt *Group) { 303 assert(!CurrentSourceGroup); 304 CurrentSourceGroup = Group; 305 } 306 307 /// \brief Exit the current source region group. 308 void endSourceRegionGroup() { CurrentSourceGroup = nullptr; } 309 310 /// \brief Brings a region that has the same counter and file to the back 311 /// of the source regions array. 312 void bringSimilarRegionBack(Counter Count, FileID File, 313 FileID MacroArgumentFile, 314 const Stmt *UnreachableInitiator, 315 const Stmt *SourceGroup) { 316 for (size_t I = SourceRegions.size(); I != 0;) { 317 --I; 318 if (SourceRegions[I].Count == Count && SourceRegions[I].File == File && 319 SourceRegions[I].MacroArgumentFile == MacroArgumentFile && 320 SourceRegions[I].UnreachableInitiator == UnreachableInitiator && 321 SourceRegions[I].Group == SourceGroup) { 322 if (I != SourceRegions.size() - 1) 323 std::swap(SourceRegions[I], SourceRegions.back()); 324 return; 325 } 326 } 327 } 328 329 /// \brief Associate a counter with a given source code range. 330 void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd, 331 Counter Count, const Stmt *UnreachableInitiator, 332 const Stmt *SourceGroup, unsigned Flags = 0, 333 FileID MacroArgumentFile = FileID()) { 334 if (SM.isMacroArgExpansion(LocStart)) { 335 // Map the code range with the macro argument's value. 336 mapSourceCodeRange(SM.getImmediateSpellingLoc(LocStart), 337 SM.getImmediateSpellingLoc(LocEnd), Count, 338 UnreachableInitiator, SourceGroup, Flags, 339 SM.getFileID(LocStart)); 340 // Map the code range where the macro argument is referenced. 341 SourceLocation RefLocStart(SM.getImmediateExpansionRange(LocStart).first); 342 SourceLocation RefLocEnd(RefLocStart); 343 if (SM.isMacroArgExpansion(RefLocStart)) 344 mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator, 345 SourceGroup, 0, SM.getFileID(RefLocStart)); 346 else 347 mapSourceCodeRange(RefLocStart, RefLocEnd, Count, UnreachableInitiator, 348 SourceGroup); 349 return; 350 } 351 auto File = SM.getFileID(LocStart); 352 // Make sure that the file id is valid. 353 if (File.isInvalid()) 354 return; 355 bringSimilarRegionBack(Count, File, MacroArgumentFile, UnreachableInitiator, 356 SourceGroup); 357 SourceMappingRegion R(File, MacroArgumentFile, Count, UnreachableInitiator, 358 SourceGroup, LocStart, LocEnd, Flags); 359 if (SourceRegions.empty() || !SourceRegions.back().isMergeable(R)) { 360 SourceRegions.push_back(R); 361 return; 362 } 363 SourceRegions.back().mergeByExtendingTo(R); 364 } 365 366 void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd, 367 Counter Count, unsigned Flags = 0) { 368 mapSourceCodeRange(LocStart, LocEnd, Count, 369 CurrentUnreachableRegionInitiator, CurrentSourceGroup, 370 Flags); 371 } 372 373 void mapSourceCodeRange(const SourceMappingState &State, 374 SourceLocation LocStart, SourceLocation LocEnd, 375 unsigned Flags = 0) { 376 mapSourceCodeRange(LocStart, LocEnd, State.CurrentRegionCount, 377 State.CurrentUnreachableRegionInitiator, 378 State.CurrentSourceGroup, Flags); 379 } 380 381 /// \brief Generate the coverage counter mapping regions from collected 382 /// source regions. 383 void emitSourceRegions() { 384 for (const auto &R : SourceRegions) { 385 SourceLocation LocStart = R.LocStart; 386 SourceLocation LocEnd = R.LocEnd; 387 if (SM.getFileID(LocEnd) != R.File) 388 LocEnd = R.AlternativeLocEnd; 389 390 if (R.hasFlag(SourceMappingRegion::IgnoreIfNotExtended) && 391 LocStart == LocEnd) 392 continue; 393 394 LocEnd = getPreciseTokenLocEnd(LocEnd); 395 unsigned LineStart = SM.getSpellingLineNumber(LocStart); 396 unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart); 397 unsigned LineEnd = SM.getSpellingLineNumber(LocEnd); 398 unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd); 399 400 auto SpellingFile = SM.getDecomposedSpellingLoc(R.LocStart).first; 401 unsigned CovFileID; 402 if (getCoverageFileID(R.LocStart, R.File, SpellingFile, CovFileID)) 403 continue; 404 405 assert(LineStart <= LineEnd); 406 MappingRegions.push_back(CounterMappingRegion( 407 R.Count, CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd, 408 false, CounterMappingRegion::CodeRegion)); 409 } 410 } 411 }; 412 413 /// \brief Creates unreachable coverage regions for the functions that 414 /// are not emitted. 415 struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder { 416 EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM, 417 const LangOptions &LangOpts) 418 : CoverageMappingBuilder(CVM, SM, LangOpts) {} 419 420 void VisitDecl(const Decl *D) { 421 if (!D->hasBody()) 422 return; 423 auto Body = D->getBody(); 424 mapSourceCodeRange(Body->getLocStart(), Body->getLocEnd(), Counter()); 425 } 426 427 /// \brief Write the mapping data to the output stream 428 void write(llvm::raw_ostream &OS) { 429 emitSourceRegions(); 430 SmallVector<unsigned, 16> FileIDMapping; 431 createFileIDMapping(FileIDMapping); 432 433 CoverageMappingWriter Writer( 434 FileIDMapping, ArrayRef<CounterExpression>(), MappingRegions); 435 Writer.write(OS); 436 } 437 }; 438 439 /// \brief A StmtVisitor that creates coverage mapping regions which map 440 /// from the source code locations to the PGO counters. 441 struct CounterCoverageMappingBuilder 442 : public CoverageMappingBuilder, 443 public ConstStmtVisitor<CounterCoverageMappingBuilder> { 444 /// \brief The map of statements to count values. 445 llvm::DenseMap<const Stmt *, unsigned> &CounterMap; 446 447 Counter CurrentRegionCount; 448 449 CounterExpressionBuilder Builder; 450 451 /// \brief Return a counter that represents the 452 /// expression that subracts rhs from lhs. 453 Counter subtractCounters(Counter LHS, Counter RHS) { 454 return Builder.subtract(LHS, RHS); 455 } 456 457 /// \brief Return a counter that represents the 458 /// the exression that adds lhs and rhs. 459 Counter addCounters(Counter LHS, Counter RHS) { 460 return Builder.add(LHS, RHS); 461 } 462 463 /// \brief Return the region counter for the given statement. 464 /// This should only be called on statements that have a dedicated counter. 465 unsigned getRegionCounter(const Stmt *S) { return CounterMap[S]; } 466 467 /// \brief Return the region count for the counter at the given index. 468 Counter getRegionCount(unsigned CounterId) { 469 return Counter::getCounter(CounterId); 470 } 471 472 /// \brief Return the counter value of the current region. 473 Counter getCurrentRegionCount() { return CurrentRegionCount; } 474 475 /// \brief Set the counter value for the current region. 476 /// This is used to keep track of changes to the most recent counter 477 /// from control flow and non-local exits. 478 void setCurrentRegionCount(Counter Count) { 479 CurrentRegionCount = Count; 480 CurrentUnreachableRegionInitiator = nullptr; 481 } 482 483 /// \brief Indicate that the current region is never reached, 484 /// and thus should have a counter value of zero. 485 /// This is important so that subsequent regions can correctly track 486 /// their parent counts. 487 void setCurrentRegionUnreachable(const Stmt *Initiator) { 488 CurrentRegionCount = Counter::getZero(); 489 CurrentUnreachableRegionInitiator = Initiator; 490 } 491 492 /// \brief A counter for a particular region. 493 /// This is the primary interface through 494 /// which the coverage mapping builder manages counters and their values. 495 class RegionMapper { 496 CounterCoverageMappingBuilder &Mapping; 497 Counter Count; 498 Counter ParentCount; 499 Counter RegionCount; 500 Counter Adjust; 501 502 public: 503 RegionMapper(CounterCoverageMappingBuilder *Mapper, const Stmt *S) 504 : Mapping(*Mapper), 505 Count(Mapper->getRegionCount(Mapper->getRegionCounter(S))), 506 ParentCount(Mapper->getCurrentRegionCount()) {} 507 508 /// Get the value of the counter. In most cases this is the number of times 509 /// the region of the counter was entered, but for switch labels it's the 510 /// number of direct jumps to that label. 511 Counter getCount() const { return Count; } 512 513 /// Get the value of the counter with adjustments applied. Adjustments occur 514 /// when control enters or leaves the region abnormally; i.e., if there is a 515 /// jump to a label within the region, or if the function can return from 516 /// within the region. The adjusted count, then, is the value of the counter 517 /// at the end of the region. 518 Counter getAdjustedCount() const { 519 return Mapping.addCounters(Count, Adjust); 520 } 521 522 /// Get the value of the counter in this region's parent, i.e., the region 523 /// that was active when this region began. This is useful for deriving 524 /// counts in implicitly counted regions, like the false case of a condition 525 /// or the normal exits of a loop. 526 Counter getParentCount() const { return ParentCount; } 527 528 /// Activate the counter by emitting an increment and starting to track 529 /// adjustments. If AddIncomingFallThrough is true, the current region count 530 /// will be added to the counter for the purposes of tracking the region. 531 void beginRegion(bool AddIncomingFallThrough = false) { 532 RegionCount = Count; 533 if (AddIncomingFallThrough) 534 RegionCount = 535 Mapping.addCounters(RegionCount, Mapping.getCurrentRegionCount()); 536 Mapping.setCurrentRegionCount(RegionCount); 537 } 538 539 /// For counters on boolean branches, begins tracking adjustments for the 540 /// uncounted path. 541 void beginElseRegion() { 542 RegionCount = Mapping.subtractCounters(ParentCount, Count); 543 Mapping.setCurrentRegionCount(RegionCount); 544 } 545 546 /// Reset the current region count. 547 void setCurrentRegionCount(Counter CurrentCount) { 548 RegionCount = CurrentCount; 549 Mapping.setCurrentRegionCount(RegionCount); 550 } 551 552 /// Adjust for non-local control flow after emitting a subexpression or 553 /// substatement. This must be called to account for constructs such as 554 /// gotos, 555 /// labels, and returns, so that we can ensure that our region's count is 556 /// correct in the code that follows. 557 void adjustForControlFlow() { 558 Adjust = Mapping.addCounters( 559 Adjust, Mapping.subtractCounters(Mapping.getCurrentRegionCount(), 560 RegionCount)); 561 // Reset the region count in case this is called again later. 562 RegionCount = Mapping.getCurrentRegionCount(); 563 } 564 565 /// Commit all adjustments to the current region. If the region is a loop, 566 /// the LoopAdjust value should be the count of all the breaks and continues 567 /// from the loop, to compensate for those counts being deducted from the 568 /// adjustments for the body of the loop. 569 void applyAdjustmentsToRegion() { 570 Mapping.setCurrentRegionCount(Mapping.addCounters(ParentCount, Adjust)); 571 } 572 void applyAdjustmentsToRegion(Counter LoopAdjust) { 573 Mapping.setCurrentRegionCount(Mapping.addCounters( 574 Mapping.addCounters(ParentCount, Adjust), LoopAdjust)); 575 } 576 }; 577 578 /// \brief Keep counts of breaks and continues inside loops. 579 struct BreakContinue { 580 Counter BreakCount; 581 Counter ContinueCount; 582 }; 583 SmallVector<BreakContinue, 8> BreakContinueStack; 584 585 CounterCoverageMappingBuilder( 586 CoverageMappingModuleGen &CVM, 587 llvm::DenseMap<const Stmt *, unsigned> &CounterMap, 588 unsigned NumRegionCounters, SourceManager &SM, 589 const LangOptions &LangOpts) 590 : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap), 591 Builder(NumRegionCounters) {} 592 593 /// \brief Write the mapping data to the output stream 594 void write(llvm::raw_ostream &OS) { 595 emitSourceRegions(); 596 llvm::SmallVector<unsigned, 8> VirtualFileMapping; 597 createFileIDMapping(VirtualFileMapping); 598 gatherSkippedRegions(); 599 600 CoverageMappingWriter Writer( 601 VirtualFileMapping, Builder.getExpressions(), MappingRegions); 602 Writer.write(OS); 603 } 604 605 /// \brief Return the current source mapping state. 606 SourceMappingState getCurrentState() const { 607 return SourceMappingState(CurrentRegionCount, CurrentSourceGroup, 608 CurrentUnreachableRegionInitiator); 609 } 610 611 /// \brief Associate the source code range with the current region count. 612 void mapSourceCodeRange(SourceLocation LocStart, SourceLocation LocEnd, 613 unsigned Flags = 0) { 614 CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocEnd, 615 CurrentRegionCount, Flags); 616 } 617 618 void mapSourceCodeRange(SourceLocation LocStart) { 619 CoverageMappingBuilder::mapSourceCodeRange(LocStart, LocStart, 620 CurrentRegionCount); 621 } 622 623 /// \brief Associate the source range of a token with the current region 624 /// count. 625 /// Ignore the source range for this token if it produces a distinct 626 /// mapping region with no other source ranges. 627 void mapToken(SourceLocation LocStart) { 628 CoverageMappingBuilder::mapSourceCodeRange( 629 LocStart, LocStart, CurrentRegionCount, 630 SourceMappingRegion::IgnoreIfNotExtended); 631 } 632 633 void mapToken(const SourceMappingState &State, SourceLocation LocStart) { 634 CoverageMappingBuilder::mapSourceCodeRange( 635 State, LocStart, LocStart, SourceMappingRegion::IgnoreIfNotExtended); 636 } 637 638 void VisitStmt(const Stmt *S) { 639 mapSourceCodeRange(S->getLocStart()); 640 for (Stmt::const_child_range I = S->children(); I; ++I) { 641 if (*I) 642 this->Visit(*I); 643 } 644 } 645 646 /// \brief If the given statement is a compound statement, 647 /// map '}' with the same count as '{'. 648 void VisitSubStmtRBraceState(const Stmt *S) { 649 if (!isa<CompoundStmt>(S)) 650 return Visit(S); 651 const auto *CS = cast<CompoundStmt>(S); 652 auto State = getCurrentState(); 653 mapSourceCodeRange(CS->getLBracLoc()); 654 for (Stmt::const_child_range I = S->children(); I; ++I) { 655 if (*I) 656 this->Visit(*I); 657 } 658 CoverageMappingBuilder::mapSourceCodeRange(State, CS->getRBracLoc(), 659 CS->getRBracLoc()); 660 } 661 662 void VisitDecl(const Decl *D) { 663 if (!D->hasBody()) 664 return; 665 // Counter tracks entry to the function body. 666 auto Body = D->getBody(); 667 RegionMapper Cnt(this, Body); 668 Cnt.beginRegion(); 669 VisitSubStmtRBraceState(Body); 670 } 671 672 void VisitDeclStmt(const DeclStmt *S) { 673 mapSourceCodeRange(S->getLocStart()); 674 for (Stmt::const_child_range I = static_cast<const Stmt *>(S)->children(); 675 I; ++I) { 676 if (*I) 677 this->Visit(*I); 678 } 679 } 680 681 void VisitCompoundStmt(const CompoundStmt *S) { 682 mapSourceCodeRange(S->getLBracLoc()); 683 for (Stmt::const_child_range I = S->children(); I; ++I) { 684 if (*I) 685 this->Visit(*I); 686 } 687 mapSourceCodeRange(S->getRBracLoc(), S->getRBracLoc()); 688 } 689 690 void VisitReturnStmt(const ReturnStmt *S) { 691 mapSourceCodeRange(S->getLocStart()); 692 if (S->getRetValue()) 693 Visit(S->getRetValue()); 694 setCurrentRegionUnreachable(S); 695 } 696 697 void VisitGotoStmt(const GotoStmt *S) { 698 mapSourceCodeRange(S->getLocStart()); 699 mapToken(S->getLabelLoc()); 700 setCurrentRegionUnreachable(S); 701 } 702 703 void VisitLabelStmt(const LabelStmt *S) { 704 // Counter tracks the block following the label. 705 RegionMapper Cnt(this, S); 706 Cnt.beginRegion(); 707 mapSourceCodeRange(S->getLocStart()); 708 // Can't map the ':' token as its location isn't known. 709 Visit(S->getSubStmt()); 710 } 711 712 void VisitBreakStmt(const BreakStmt *S) { 713 mapSourceCodeRange(S->getLocStart()); 714 assert(!BreakContinueStack.empty() && "break not in a loop or switch!"); 715 BreakContinueStack.back().BreakCount = addCounters( 716 BreakContinueStack.back().BreakCount, getCurrentRegionCount()); 717 setCurrentRegionUnreachable(S); 718 } 719 720 void VisitContinueStmt(const ContinueStmt *S) { 721 mapSourceCodeRange(S->getLocStart()); 722 assert(!BreakContinueStack.empty() && "continue stmt not in a loop!"); 723 BreakContinueStack.back().ContinueCount = addCounters( 724 BreakContinueStack.back().ContinueCount, getCurrentRegionCount()); 725 setCurrentRegionUnreachable(S); 726 } 727 728 void VisitWhileStmt(const WhileStmt *S) { 729 mapSourceCodeRange(S->getLocStart()); 730 // Counter tracks the body of the loop. 731 RegionMapper Cnt(this, S); 732 BreakContinueStack.push_back(BreakContinue()); 733 // Visit the body region first so the break/continue adjustments can be 734 // included when visiting the condition. 735 Cnt.beginRegion(); 736 VisitSubStmtRBraceState(S->getBody()); 737 Cnt.adjustForControlFlow(); 738 739 // ...then go back and propagate counts through the condition. The count 740 // at the start of the condition is the sum of the incoming edges, 741 // the backedge from the end of the loop body, and the edges from 742 // continue statements. 743 BreakContinue BC = BreakContinueStack.pop_back_val(); 744 Cnt.setCurrentRegionCount( 745 addCounters(Cnt.getParentCount(), 746 addCounters(Cnt.getAdjustedCount(), BC.ContinueCount))); 747 beginSourceRegionGroup(S->getCond()); 748 Visit(S->getCond()); 749 endSourceRegionGroup(); 750 Cnt.adjustForControlFlow(); 751 Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount)); 752 } 753 754 void VisitDoStmt(const DoStmt *S) { 755 mapSourceCodeRange(S->getLocStart()); 756 // Counter tracks the body of the loop. 757 RegionMapper Cnt(this, S); 758 BreakContinueStack.push_back(BreakContinue()); 759 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 760 VisitSubStmtRBraceState(S->getBody()); 761 Cnt.adjustForControlFlow(); 762 763 BreakContinue BC = BreakContinueStack.pop_back_val(); 764 // The count at the start of the condition is equal to the count at the 765 // end of the body. The adjusted count does not include either the 766 // fall-through count coming into the loop or the continue count, so add 767 // both of those separately. This is coincidentally the same equation as 768 // with while loops but for different reasons. 769 Cnt.setCurrentRegionCount( 770 addCounters(Cnt.getParentCount(), 771 addCounters(Cnt.getAdjustedCount(), BC.ContinueCount))); 772 Visit(S->getCond()); 773 Cnt.adjustForControlFlow(); 774 Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount)); 775 } 776 777 void VisitForStmt(const ForStmt *S) { 778 mapSourceCodeRange(S->getLocStart()); 779 if (S->getInit()) 780 Visit(S->getInit()); 781 782 // Counter tracks the body of the loop. 783 RegionMapper Cnt(this, S); 784 BreakContinueStack.push_back(BreakContinue()); 785 // Visit the body region first. (This is basically the same as a while 786 // loop; see further comments in VisitWhileStmt.) 787 Cnt.beginRegion(); 788 VisitSubStmtRBraceState(S->getBody()); 789 Cnt.adjustForControlFlow(); 790 791 // The increment is essentially part of the body but it needs to include 792 // the count for all the continue statements. 793 if (S->getInc()) { 794 Cnt.setCurrentRegionCount(addCounters( 795 getCurrentRegionCount(), BreakContinueStack.back().ContinueCount)); 796 beginSourceRegionGroup(S->getInc()); 797 Visit(S->getInc()); 798 endSourceRegionGroup(); 799 Cnt.adjustForControlFlow(); 800 } 801 802 BreakContinue BC = BreakContinueStack.pop_back_val(); 803 804 // ...then go back and propagate counts through the condition. 805 if (S->getCond()) { 806 Cnt.setCurrentRegionCount( 807 addCounters(addCounters(Cnt.getParentCount(), Cnt.getAdjustedCount()), 808 BC.ContinueCount)); 809 beginSourceRegionGroup(S->getCond()); 810 Visit(S->getCond()); 811 endSourceRegionGroup(); 812 Cnt.adjustForControlFlow(); 813 } 814 Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount)); 815 } 816 817 void VisitCXXForRangeStmt(const CXXForRangeStmt *S) { 818 mapSourceCodeRange(S->getLocStart()); 819 Visit(S->getRangeStmt()); 820 Visit(S->getBeginEndStmt()); 821 // Counter tracks the body of the loop. 822 RegionMapper Cnt(this, S); 823 BreakContinueStack.push_back(BreakContinue()); 824 // Visit the body region first. (This is basically the same as a while 825 // loop; see further comments in VisitWhileStmt.) 826 Cnt.beginRegion(); 827 VisitSubStmtRBraceState(S->getBody()); 828 Cnt.adjustForControlFlow(); 829 BreakContinue BC = BreakContinueStack.pop_back_val(); 830 Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount)); 831 } 832 833 void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) { 834 mapSourceCodeRange(S->getLocStart()); 835 Visit(S->getElement()); 836 // Counter tracks the body of the loop. 837 RegionMapper Cnt(this, S); 838 BreakContinueStack.push_back(BreakContinue()); 839 VisitSubStmtRBraceState(S->getBody()); 840 BreakContinue BC = BreakContinueStack.pop_back_val(); 841 Cnt.adjustForControlFlow(); 842 Cnt.applyAdjustmentsToRegion(addCounters(BC.BreakCount, BC.ContinueCount)); 843 } 844 845 void VisitSwitchStmt(const SwitchStmt *S) { 846 mapSourceCodeRange(S->getLocStart()); 847 Visit(S->getCond()); 848 BreakContinueStack.push_back(BreakContinue()); 849 // Map the '}' for the body to have the same count as the regions after 850 // the switch. 851 SourceLocation RBracLoc; 852 if (const auto *CS = dyn_cast<CompoundStmt>(S->getBody())) { 853 mapSourceCodeRange(CS->getLBracLoc()); 854 setCurrentRegionUnreachable(S); 855 for (Stmt::const_child_range I = CS->children(); I; ++I) { 856 if (*I) 857 this->Visit(*I); 858 } 859 RBracLoc = CS->getRBracLoc(); 860 } else { 861 setCurrentRegionUnreachable(S); 862 Visit(S->getBody()); 863 } 864 // If the switch is inside a loop, add the continue counts. 865 BreakContinue BC = BreakContinueStack.pop_back_val(); 866 if (!BreakContinueStack.empty()) 867 BreakContinueStack.back().ContinueCount = addCounters( 868 BreakContinueStack.back().ContinueCount, BC.ContinueCount); 869 // Counter tracks the exit block of the switch. 870 RegionMapper ExitCnt(this, S); 871 ExitCnt.beginRegion(); 872 if (RBracLoc.isValid()) 873 mapSourceCodeRange(RBracLoc); 874 } 875 876 void VisitCaseStmt(const CaseStmt *S) { 877 // Counter for this particular case. This counts only jumps from the 878 // switch header and does not include fallthrough from the case before 879 // this one. 880 RegionMapper Cnt(this, S); 881 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 882 mapSourceCodeRange(S->getLocStart()); 883 mapToken(S->getColonLoc()); 884 Visit(S->getSubStmt()); 885 } 886 887 void VisitDefaultStmt(const DefaultStmt *S) { 888 // Counter for this default case. This does not include fallthrough from 889 // the previous case. 890 RegionMapper Cnt(this, S); 891 Cnt.beginRegion(/*AddIncomingFallThrough=*/true); 892 mapSourceCodeRange(S->getLocStart()); 893 mapToken(S->getColonLoc()); 894 Visit(S->getSubStmt()); 895 } 896 897 void VisitIfStmt(const IfStmt *S) { 898 mapSourceCodeRange(S->getLocStart()); 899 Visit(S->getCond()); 900 mapToken(S->getElseLoc()); 901 902 // Counter tracks the "then" part of an if statement. The count for 903 // the "else" part, if it exists, will be calculated from this counter. 904 RegionMapper Cnt(this, S); 905 Cnt.beginRegion(); 906 VisitSubStmtRBraceState(S->getThen()); 907 Cnt.adjustForControlFlow(); 908 909 if (S->getElse()) { 910 Cnt.beginElseRegion(); 911 VisitSubStmtRBraceState(S->getElse()); 912 Cnt.adjustForControlFlow(); 913 } 914 Cnt.applyAdjustmentsToRegion(); 915 } 916 917 void VisitCXXTryStmt(const CXXTryStmt *S) { 918 mapSourceCodeRange(S->getLocStart()); 919 Visit(S->getTryBlock()); 920 for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I) 921 Visit(S->getHandler(I)); 922 // Counter tracks the continuation block of the try statement. 923 RegionMapper Cnt(this, S); 924 Cnt.beginRegion(); 925 } 926 927 void VisitCXXCatchStmt(const CXXCatchStmt *S) { 928 mapSourceCodeRange(S->getLocStart()); 929 // Counter tracks the catch statement's handler block. 930 RegionMapper Cnt(this, S); 931 Cnt.beginRegion(); 932 VisitSubStmtRBraceState(S->getHandlerBlock()); 933 } 934 935 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) { 936 Visit(E->getCond()); 937 mapToken(E->getQuestionLoc()); 938 auto State = getCurrentState(); 939 940 // Counter tracks the "true" part of a conditional operator. The 941 // count in the "false" part will be calculated from this counter. 942 RegionMapper Cnt(this, E); 943 Cnt.beginRegion(); 944 Visit(E->getTrueExpr()); 945 Cnt.adjustForControlFlow(); 946 947 mapToken(State, E->getColonLoc()); 948 949 Cnt.beginElseRegion(); 950 Visit(E->getFalseExpr()); 951 Cnt.adjustForControlFlow(); 952 953 Cnt.applyAdjustmentsToRegion(); 954 } 955 956 void VisitBinLAnd(const BinaryOperator *E) { 957 Visit(E->getLHS()); 958 mapToken(E->getOperatorLoc()); 959 // Counter tracks the right hand side of a logical and operator. 960 RegionMapper Cnt(this, E); 961 Cnt.beginRegion(); 962 Visit(E->getRHS()); 963 Cnt.adjustForControlFlow(); 964 Cnt.applyAdjustmentsToRegion(); 965 } 966 967 void VisitBinLOr(const BinaryOperator *E) { 968 Visit(E->getLHS()); 969 mapToken(E->getOperatorLoc()); 970 // Counter tracks the right hand side of a logical or operator. 971 RegionMapper Cnt(this, E); 972 Cnt.beginRegion(); 973 Visit(E->getRHS()); 974 Cnt.adjustForControlFlow(); 975 Cnt.applyAdjustmentsToRegion(); 976 } 977 978 void VisitParenExpr(const ParenExpr *E) { 979 mapToken(E->getLParen()); 980 Visit(E->getSubExpr()); 981 mapToken(E->getRParen()); 982 } 983 984 void VisitBinaryOperator(const BinaryOperator *E) { 985 Visit(E->getLHS()); 986 mapToken(E->getOperatorLoc()); 987 Visit(E->getRHS()); 988 } 989 990 void VisitUnaryOperator(const UnaryOperator *E) { 991 bool Postfix = E->isPostfix(); 992 if (!Postfix) 993 mapToken(E->getOperatorLoc()); 994 Visit(E->getSubExpr()); 995 if (Postfix) 996 mapToken(E->getOperatorLoc()); 997 } 998 999 void VisitMemberExpr(const MemberExpr *E) { 1000 Visit(E->getBase()); 1001 mapToken(E->getMemberLoc()); 1002 } 1003 1004 void VisitCallExpr(const CallExpr *E) { 1005 Visit(E->getCallee()); 1006 for (const auto &Arg : E->arguments()) 1007 Visit(Arg); 1008 mapToken(E->getRParenLoc()); 1009 } 1010 1011 void VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1012 Visit(E->getLHS()); 1013 Visit(E->getRHS()); 1014 mapToken(E->getRBracketLoc()); 1015 } 1016 1017 void VisitCStyleCastExpr(const CStyleCastExpr *E) { 1018 mapToken(E->getLParenLoc()); 1019 mapToken(E->getRParenLoc()); 1020 Visit(E->getSubExpr()); 1021 } 1022 1023 // Map literals as tokens so that the macros like #define PI 3.14 1024 // won't generate coverage mapping regions. 1025 1026 void VisitIntegerLiteral(const IntegerLiteral *E) { 1027 mapToken(E->getLocStart()); 1028 } 1029 1030 void VisitFloatingLiteral(const FloatingLiteral *E) { 1031 mapToken(E->getLocStart()); 1032 } 1033 1034 void VisitCharacterLiteral(const CharacterLiteral *E) { 1035 mapToken(E->getLocStart()); 1036 } 1037 1038 void VisitStringLiteral(const StringLiteral *E) { 1039 mapToken(E->getLocStart()); 1040 } 1041 1042 void VisitImaginaryLiteral(const ImaginaryLiteral *E) { 1043 mapToken(E->getLocStart()); 1044 } 1045 }; 1046 } 1047 1048 static bool isMachO(const CodeGenModule &CGM) { 1049 return CGM.getTarget().getTriple().isOSBinFormatMachO(); 1050 } 1051 1052 static StringRef getCoverageSection(const CodeGenModule &CGM) { 1053 return isMachO(CGM) ? "__DATA,__llvm_covmap" : "__llvm_covmap"; 1054 } 1055 1056 static void dump(llvm::raw_ostream &OS, const CoverageMappingRecord &Function) { 1057 OS << Function.FunctionName << ":\n"; 1058 CounterMappingContext Ctx(Function.Expressions); 1059 for (const auto &R : Function.MappingRegions) { 1060 OS.indent(2); 1061 switch (R.Kind) { 1062 case CounterMappingRegion::CodeRegion: 1063 break; 1064 case CounterMappingRegion::ExpansionRegion: 1065 OS << "Expansion,"; 1066 break; 1067 case CounterMappingRegion::SkippedRegion: 1068 OS << "Skipped,"; 1069 break; 1070 } 1071 1072 OS << "File " << R.FileID << ", " << R.LineStart << ":" 1073 << R.ColumnStart << " -> " << R.LineEnd << ":" << R.ColumnEnd 1074 << " = "; 1075 Ctx.dump(R.Count); 1076 OS << " (HasCodeBefore = " << R.HasCodeBefore; 1077 if (R.Kind == CounterMappingRegion::ExpansionRegion) 1078 OS << ", Expanded file = " << R.ExpandedFileID; 1079 1080 OS << ")\n"; 1081 } 1082 } 1083 1084 void CoverageMappingModuleGen::addFunctionMappingRecord( 1085 llvm::GlobalVariable *FunctionName, StringRef FunctionNameValue, 1086 const std::string &CoverageMapping) { 1087 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1088 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 1089 auto *Int8PtrTy = llvm::Type::getInt8PtrTy(Ctx); 1090 if (!FunctionRecordTy) { 1091 llvm::Type *FunctionRecordTypes[] = {Int8PtrTy, Int32Ty, Int32Ty}; 1092 FunctionRecordTy = 1093 llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes)); 1094 } 1095 1096 llvm::Constant *FunctionRecordVals[] = { 1097 llvm::ConstantExpr::getBitCast(FunctionName, Int8PtrTy), 1098 llvm::ConstantInt::get(Int32Ty, FunctionNameValue.size()), 1099 llvm::ConstantInt::get(Int32Ty, CoverageMapping.size())}; 1100 FunctionRecords.push_back(llvm::ConstantStruct::get( 1101 FunctionRecordTy, makeArrayRef(FunctionRecordVals))); 1102 CoverageMappings += CoverageMapping; 1103 1104 if (CGM.getCodeGenOpts().DumpCoverageMapping) { 1105 // Dump the coverage mapping data for this function by decoding the 1106 // encoded data. This allows us to dump the mapping regions which were 1107 // also processed by the CoverageMappingWriter which performs 1108 // additional minimization operations such as reducing the number of 1109 // expressions. 1110 std::vector<StringRef> Filenames; 1111 std::vector<CounterExpression> Expressions; 1112 std::vector<CounterMappingRegion> Regions; 1113 llvm::SmallVector<StringRef, 16> FilenameRefs; 1114 FilenameRefs.resize(FileEntries.size()); 1115 for (const auto &Entry : FileEntries) 1116 FilenameRefs[Entry.second] = Entry.first->getName(); 1117 RawCoverageMappingReader Reader(FunctionNameValue, CoverageMapping, 1118 FilenameRefs, 1119 Filenames, Expressions, Regions); 1120 CoverageMappingRecord FunctionRecord; 1121 if (Reader.read(FunctionRecord)) 1122 return; 1123 dump(llvm::outs(), FunctionRecord); 1124 } 1125 } 1126 1127 void CoverageMappingModuleGen::emit() { 1128 if (FunctionRecords.empty()) 1129 return; 1130 llvm::LLVMContext &Ctx = CGM.getLLVMContext(); 1131 auto *Int32Ty = llvm::Type::getInt32Ty(Ctx); 1132 1133 // Create the filenames and merge them with coverage mappings 1134 llvm::SmallVector<std::string, 16> FilenameStrs; 1135 llvm::SmallVector<StringRef, 16> FilenameRefs; 1136 FilenameStrs.resize(FileEntries.size()); 1137 FilenameRefs.resize(FileEntries.size()); 1138 for (const auto &Entry : FileEntries) { 1139 llvm::SmallString<256> Path(Entry.first->getName()); 1140 llvm::sys::fs::make_absolute(Path); 1141 1142 auto I = Entry.second; 1143 FilenameStrs[I] = std::move(std::string(Path.begin(), Path.end())); 1144 FilenameRefs[I] = FilenameStrs[I]; 1145 } 1146 1147 std::string FilenamesAndCoverageMappings; 1148 llvm::raw_string_ostream OS(FilenamesAndCoverageMappings); 1149 CoverageFilenamesSectionWriter(FilenameRefs).write(OS); 1150 OS << CoverageMappings; 1151 size_t CoverageMappingSize = CoverageMappings.size(); 1152 size_t FilenamesSize = OS.str().size() - CoverageMappingSize; 1153 // Append extra zeroes if necessary to ensure that the size of the filenames 1154 // and coverage mappings is a multiple of 8. 1155 if (size_t Rem = OS.str().size() % 8) { 1156 CoverageMappingSize += 8 - Rem; 1157 for (size_t I = 0, S = 8 - Rem; I < S; ++I) 1158 OS << '\0'; 1159 } 1160 auto *FilenamesAndMappingsVal = 1161 llvm::ConstantDataArray::getString(Ctx, OS.str(), false); 1162 1163 // Create the deferred function records array 1164 auto RecordsTy = 1165 llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size()); 1166 auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords); 1167 1168 // Create the coverage data record 1169 llvm::Type *CovDataTypes[] = {Int32Ty, Int32Ty, 1170 Int32Ty, Int32Ty, 1171 RecordsTy, FilenamesAndMappingsVal->getType()}; 1172 auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes)); 1173 llvm::Constant *TUDataVals[] = { 1174 llvm::ConstantInt::get(Int32Ty, FunctionRecords.size()), 1175 llvm::ConstantInt::get(Int32Ty, FilenamesSize), 1176 llvm::ConstantInt::get(Int32Ty, CoverageMappingSize), 1177 llvm::ConstantInt::get(Int32Ty, 1178 /*Version=*/CoverageMappingVersion1), 1179 RecordsVal, FilenamesAndMappingsVal}; 1180 auto CovDataVal = 1181 llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals)); 1182 auto CovData = new llvm::GlobalVariable(CGM.getModule(), CovDataTy, true, 1183 llvm::GlobalValue::InternalLinkage, 1184 CovDataVal, 1185 "__llvm_coverage_mapping"); 1186 1187 CovData->setSection(getCoverageSection(CGM)); 1188 CovData->setAlignment(8); 1189 1190 // Make sure the data doesn't get deleted. 1191 CGM.addUsedGlobal(CovData); 1192 } 1193 1194 unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) { 1195 auto It = FileEntries.find(File); 1196 if (It != FileEntries.end()) 1197 return It->second; 1198 unsigned FileID = FileEntries.size(); 1199 FileEntries.insert(std::make_pair(File, FileID)); 1200 return FileID; 1201 } 1202 1203 void CoverageMappingGen::emitCounterMapping(const Decl *D, 1204 llvm::raw_ostream &OS) { 1205 assert(CounterMap); 1206 CounterCoverageMappingBuilder Walker(CVM, *CounterMap, NumRegionCounters, SM, 1207 LangOpts); 1208 Walker.VisitDecl(D); 1209 Walker.write(OS); 1210 } 1211 1212 void CoverageMappingGen::emitEmptyMapping(const Decl *D, 1213 llvm::raw_ostream &OS) { 1214 EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts); 1215 Walker.VisitDecl(D); 1216 Walker.write(OS); 1217 } 1218