CoverageMappingGen.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116
  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. #include "CoverageMappingGen.h"
  14. #include "CodeGenFunction.h"
  15. #include "clang/AST/StmtVisitor.h"
  16. #include "clang/Lex/Lexer.h"
  17. #include "llvm/ADT/SmallSet.h"
  18. #include "llvm/ADT/StringExtras.h"
  19. #include "llvm/ADT/Optional.h"
  20. #include "llvm/ProfileData/Coverage/CoverageMapping.h"
  21. #include "llvm/ProfileData/Coverage/CoverageMappingReader.h"
  22. #include "llvm/ProfileData/Coverage/CoverageMappingWriter.h"
  23. #include "llvm/ProfileData/InstrProfReader.h"
  24. #include "llvm/Support/FileSystem.h"
  25. using namespace clang;
  26. using namespace CodeGen;
  27. using namespace llvm::coverage;
  28. void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
  29. SkippedRanges.push_back(Range);
  30. }
  31. namespace {
  32. /// \brief A region of source code that can be mapped to a counter.
  33. class SourceMappingRegion {
  34. Counter Count;
  35. /// \brief The region's starting location.
  36. Optional<SourceLocation> LocStart;
  37. /// \brief The region's ending location.
  38. Optional<SourceLocation> LocEnd;
  39. public:
  40. SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
  41. Optional<SourceLocation> LocEnd)
  42. : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
  43. const Counter &getCounter() const { return Count; }
  44. void setCounter(Counter C) { Count = C; }
  45. bool hasStartLoc() const { return LocStart.hasValue(); }
  46. void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
  47. SourceLocation getStartLoc() const {
  48. assert(LocStart && "Region has no start location");
  49. return *LocStart;
  50. }
  51. bool hasEndLoc() const { return LocEnd.hasValue(); }
  52. void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
  53. SourceLocation getEndLoc() const {
  54. assert(LocEnd && "Region has no end location");
  55. return *LocEnd;
  56. }
  57. };
  58. /// \brief Provides the common functionality for the different
  59. /// coverage mapping region builders.
  60. class CoverageMappingBuilder {
  61. public:
  62. CoverageMappingModuleGen &CVM;
  63. SourceManager &SM;
  64. const LangOptions &LangOpts;
  65. private:
  66. /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
  67. llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
  68. FileIDMapping;
  69. public:
  70. /// \brief The coverage mapping regions for this function
  71. llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
  72. /// \brief The source mapping regions for this function.
  73. std::vector<SourceMappingRegion> SourceRegions;
  74. CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  75. const LangOptions &LangOpts)
  76. : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
  77. /// \brief Return the precise end location for the given token.
  78. SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
  79. // We avoid getLocForEndOfToken here, because it doesn't do what we want for
  80. // macro locations, which we just treat as expanded files.
  81. unsigned TokLen =
  82. Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
  83. return Loc.getLocWithOffset(TokLen);
  84. }
  85. /// \brief Return the start location of an included file or expanded macro.
  86. SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
  87. if (Loc.isMacroID())
  88. return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
  89. return SM.getLocForStartOfFile(SM.getFileID(Loc));
  90. }
  91. /// \brief Return the end location of an included file or expanded macro.
  92. SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
  93. if (Loc.isMacroID())
  94. return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
  95. SM.getFileOffset(Loc));
  96. return SM.getLocForEndOfFile(SM.getFileID(Loc));
  97. }
  98. /// \brief Find out where the current file is included or macro is expanded.
  99. SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
  100. return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
  101. : SM.getIncludeLoc(SM.getFileID(Loc));
  102. }
  103. /// \brief Return true if \c Loc is a location in a built-in macro.
  104. bool isInBuiltin(SourceLocation Loc) {
  105. return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0;
  106. }
  107. /// \brief Check whether \c Loc is included or expanded from \c Parent.
  108. bool isNestedIn(SourceLocation Loc, FileID Parent) {
  109. do {
  110. Loc = getIncludeOrExpansionLoc(Loc);
  111. if (Loc.isInvalid())
  112. return false;
  113. } while (!SM.isInFileID(Loc, Parent));
  114. return true;
  115. }
  116. /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
  117. SourceLocation getStart(const Stmt *S) {
  118. SourceLocation Loc = S->getLocStart();
  119. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  120. Loc = SM.getImmediateExpansionRange(Loc).first;
  121. return Loc;
  122. }
  123. /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
  124. SourceLocation getEnd(const Stmt *S) {
  125. SourceLocation Loc = S->getLocEnd();
  126. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  127. Loc = SM.getImmediateExpansionRange(Loc).first;
  128. return getPreciseTokenLocEnd(Loc);
  129. }
  130. /// \brief Find the set of files we have regions for and assign IDs
  131. ///
  132. /// Fills \c Mapping with the virtual file mapping needed to write out
  133. /// coverage and collects the necessary file information to emit source and
  134. /// expansion regions.
  135. void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
  136. FileIDMapping.clear();
  137. llvm::SmallSet<FileID, 8> Visited;
  138. SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
  139. for (const auto &Region : SourceRegions) {
  140. SourceLocation Loc = Region.getStartLoc();
  141. FileID File = SM.getFileID(Loc);
  142. if (!Visited.insert(File).second)
  143. continue;
  144. unsigned Depth = 0;
  145. for (SourceLocation Parent = getIncludeOrExpansionLoc(Loc);
  146. Parent.isValid(); Parent = getIncludeOrExpansionLoc(Parent))
  147. ++Depth;
  148. FileLocs.push_back(std::make_pair(Loc, Depth));
  149. }
  150. std::stable_sort(FileLocs.begin(), FileLocs.end(), llvm::less_second());
  151. for (const auto &FL : FileLocs) {
  152. SourceLocation Loc = FL.first;
  153. FileID SpellingFile = SM.getDecomposedSpellingLoc(Loc).first;
  154. auto Entry = SM.getFileEntryForID(SpellingFile);
  155. if (!Entry)
  156. continue;
  157. FileIDMapping[SM.getFileID(Loc)] = std::make_pair(Mapping.size(), Loc);
  158. Mapping.push_back(CVM.getFileID(Entry));
  159. }
  160. }
  161. /// \brief Get the coverage mapping file ID for \c Loc.
  162. ///
  163. /// If such file id doesn't exist, return None.
  164. Optional<unsigned> getCoverageFileID(SourceLocation Loc) {
  165. auto Mapping = FileIDMapping.find(SM.getFileID(Loc));
  166. if (Mapping != FileIDMapping.end())
  167. return Mapping->second.first;
  168. return None;
  169. }
  170. /// \brief Return true if the given clang's file id has a corresponding
  171. /// coverage file id.
  172. bool hasExistingCoverageFileID(FileID File) const {
  173. return FileIDMapping.count(File);
  174. }
  175. /// \brief Gather all the regions that were skipped by the preprocessor
  176. /// using the constructs like #if.
  177. void gatherSkippedRegions() {
  178. /// An array of the minimum lineStarts and the maximum lineEnds
  179. /// for mapping regions from the appropriate source files.
  180. llvm::SmallVector<std::pair<unsigned, unsigned>, 8> FileLineRanges;
  181. FileLineRanges.resize(
  182. FileIDMapping.size(),
  183. std::make_pair(std::numeric_limits<unsigned>::max(), 0));
  184. for (const auto &R : MappingRegions) {
  185. FileLineRanges[R.FileID].first =
  186. std::min(FileLineRanges[R.FileID].first, R.LineStart);
  187. FileLineRanges[R.FileID].second =
  188. std::max(FileLineRanges[R.FileID].second, R.LineEnd);
  189. }
  190. auto SkippedRanges = CVM.getSourceInfo().getSkippedRanges();
  191. for (const auto &I : SkippedRanges) {
  192. auto LocStart = I.getBegin();
  193. auto LocEnd = I.getEnd();
  194. assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
  195. "region spans multiple files");
  196. auto CovFileID = getCoverageFileID(LocStart);
  197. if (!CovFileID)
  198. continue;
  199. unsigned LineStart = SM.getSpellingLineNumber(LocStart);
  200. unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
  201. unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
  202. unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
  203. auto Region = CounterMappingRegion::makeSkipped(
  204. *CovFileID, LineStart, ColumnStart, LineEnd, ColumnEnd);
  205. // Make sure that we only collect the regions that are inside
  206. // the souce code of this function.
  207. if (Region.LineStart >= FileLineRanges[*CovFileID].first &&
  208. Region.LineEnd <= FileLineRanges[*CovFileID].second)
  209. MappingRegions.push_back(Region);
  210. }
  211. }
  212. /// \brief Generate the coverage counter mapping regions from collected
  213. /// source regions.
  214. void emitSourceRegions() {
  215. for (const auto &Region : SourceRegions) {
  216. assert(Region.hasEndLoc() && "incomplete region");
  217. SourceLocation LocStart = Region.getStartLoc();
  218. assert(SM.getFileID(LocStart).isValid() && "region in invalid file");
  219. auto CovFileID = getCoverageFileID(LocStart);
  220. // Ignore regions that don't have a file, such as builtin macros.
  221. if (!CovFileID)
  222. continue;
  223. SourceLocation LocEnd = Region.getEndLoc();
  224. assert(SM.isWrittenInSameFile(LocStart, LocEnd) &&
  225. "region spans multiple files");
  226. // Find the spilling locations for the mapping region.
  227. unsigned LineStart = SM.getSpellingLineNumber(LocStart);
  228. unsigned ColumnStart = SM.getSpellingColumnNumber(LocStart);
  229. unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
  230. unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
  231. assert(LineStart <= LineEnd && "region start and end out of order");
  232. MappingRegions.push_back(CounterMappingRegion::makeRegion(
  233. Region.getCounter(), *CovFileID, LineStart, ColumnStart, LineEnd,
  234. ColumnEnd));
  235. }
  236. }
  237. /// \brief Generate expansion regions for each virtual file we've seen.
  238. void emitExpansionRegions() {
  239. for (const auto &FM : FileIDMapping) {
  240. SourceLocation ExpandedLoc = FM.second.second;
  241. SourceLocation ParentLoc = getIncludeOrExpansionLoc(ExpandedLoc);
  242. if (ParentLoc.isInvalid())
  243. continue;
  244. auto ParentFileID = getCoverageFileID(ParentLoc);
  245. if (!ParentFileID)
  246. continue;
  247. auto ExpandedFileID = getCoverageFileID(ExpandedLoc);
  248. assert(ExpandedFileID && "expansion in uncovered file");
  249. SourceLocation LocEnd = getPreciseTokenLocEnd(ParentLoc);
  250. assert(SM.isWrittenInSameFile(ParentLoc, LocEnd) &&
  251. "region spans multiple files");
  252. unsigned LineStart = SM.getSpellingLineNumber(ParentLoc);
  253. unsigned ColumnStart = SM.getSpellingColumnNumber(ParentLoc);
  254. unsigned LineEnd = SM.getSpellingLineNumber(LocEnd);
  255. unsigned ColumnEnd = SM.getSpellingColumnNumber(LocEnd);
  256. MappingRegions.push_back(CounterMappingRegion::makeExpansion(
  257. *ParentFileID, *ExpandedFileID, LineStart, ColumnStart, LineEnd,
  258. ColumnEnd));
  259. }
  260. }
  261. };
  262. /// \brief Creates unreachable coverage regions for the functions that
  263. /// are not emitted.
  264. struct EmptyCoverageMappingBuilder : public CoverageMappingBuilder {
  265. EmptyCoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  266. const LangOptions &LangOpts)
  267. : CoverageMappingBuilder(CVM, SM, LangOpts) {}
  268. void VisitDecl(const Decl *D) {
  269. if (!D->hasBody())
  270. return;
  271. auto Body = D->getBody();
  272. SourceLocation Start = getStart(Body);
  273. SourceLocation End = getEnd(Body);
  274. if (!SM.isWrittenInSameFile(Start, End)) {
  275. // Walk up to find the common ancestor.
  276. // Correct the locations accordingly.
  277. FileID StartFileID = SM.getFileID(Start);
  278. FileID EndFileID = SM.getFileID(End);
  279. while (StartFileID != EndFileID && !isNestedIn(End, StartFileID)) {
  280. Start = getIncludeOrExpansionLoc(Start);
  281. assert(Start.isValid() &&
  282. "Declaration start location not nested within a known region");
  283. StartFileID = SM.getFileID(Start);
  284. }
  285. while (StartFileID != EndFileID) {
  286. End = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(End));
  287. assert(End.isValid() &&
  288. "Declaration end location not nested within a known region");
  289. EndFileID = SM.getFileID(End);
  290. }
  291. }
  292. SourceRegions.emplace_back(Counter(), Start, End);
  293. }
  294. /// \brief Write the mapping data to the output stream
  295. void write(llvm::raw_ostream &OS) {
  296. SmallVector<unsigned, 16> FileIDMapping;
  297. gatherFileIDs(FileIDMapping);
  298. emitSourceRegions();
  299. CoverageMappingWriter Writer(FileIDMapping, None, MappingRegions);
  300. Writer.write(OS);
  301. }
  302. };
  303. /// \brief A StmtVisitor that creates coverage mapping regions which map
  304. /// from the source code locations to the PGO counters.
  305. struct CounterCoverageMappingBuilder
  306. : public CoverageMappingBuilder,
  307. public ConstStmtVisitor<CounterCoverageMappingBuilder> {
  308. /// \brief The map of statements to count values.
  309. llvm::DenseMap<const Stmt *, unsigned> &CounterMap;
  310. /// \brief A stack of currently live regions.
  311. std::vector<SourceMappingRegion> RegionStack;
  312. CounterExpressionBuilder Builder;
  313. /// \brief A location in the most recently visited file or macro.
  314. ///
  315. /// This is used to adjust the active source regions appropriately when
  316. /// expressions cross file or macro boundaries.
  317. SourceLocation MostRecentLocation;
  318. /// \brief Return a counter for the subtraction of \c RHS from \c LHS
  319. Counter subtractCounters(Counter LHS, Counter RHS) {
  320. return Builder.subtract(LHS, RHS);
  321. }
  322. /// \brief Return a counter for the sum of \c LHS and \c RHS.
  323. Counter addCounters(Counter LHS, Counter RHS) {
  324. return Builder.add(LHS, RHS);
  325. }
  326. Counter addCounters(Counter C1, Counter C2, Counter C3) {
  327. return addCounters(addCounters(C1, C2), C3);
  328. }
  329. Counter addCounters(Counter C1, Counter C2, Counter C3, Counter C4) {
  330. return addCounters(addCounters(C1, C2, C3), C4);
  331. }
  332. /// \brief Return the region counter for the given statement.
  333. ///
  334. /// This should only be called on statements that have a dedicated counter.
  335. Counter getRegionCounter(const Stmt *S) {
  336. return Counter::getCounter(CounterMap[S]);
  337. }
  338. /// \brief Push a region onto the stack.
  339. ///
  340. /// Returns the index on the stack where the region was pushed. This can be
  341. /// used with popRegions to exit a "scope", ending the region that was pushed.
  342. size_t pushRegion(Counter Count, Optional<SourceLocation> StartLoc = None,
  343. Optional<SourceLocation> EndLoc = None) {
  344. if (StartLoc)
  345. MostRecentLocation = *StartLoc;
  346. RegionStack.emplace_back(Count, StartLoc, EndLoc);
  347. return RegionStack.size() - 1;
  348. }
  349. /// \brief Pop regions from the stack into the function's list of regions.
  350. ///
  351. /// Adds all regions from \c ParentIndex to the top of the stack to the
  352. /// function's \c SourceRegions.
  353. void popRegions(size_t ParentIndex) {
  354. assert(RegionStack.size() >= ParentIndex && "parent not in stack");
  355. while (RegionStack.size() > ParentIndex) {
  356. SourceMappingRegion &Region = RegionStack.back();
  357. if (Region.hasStartLoc()) {
  358. SourceLocation StartLoc = Region.getStartLoc();
  359. SourceLocation EndLoc = Region.hasEndLoc()
  360. ? Region.getEndLoc()
  361. : RegionStack[ParentIndex].getEndLoc();
  362. while (!SM.isWrittenInSameFile(StartLoc, EndLoc)) {
  363. // The region ends in a nested file or macro expansion. Create a
  364. // separate region for each expansion.
  365. SourceLocation NestedLoc = getStartOfFileOrMacro(EndLoc);
  366. assert(SM.isWrittenInSameFile(NestedLoc, EndLoc));
  367. SourceRegions.emplace_back(Region.getCounter(), NestedLoc, EndLoc);
  368. EndLoc = getPreciseTokenLocEnd(getIncludeOrExpansionLoc(EndLoc));
  369. if (EndLoc.isInvalid())
  370. llvm::report_fatal_error("File exit not handled before popRegions");
  371. }
  372. Region.setEndLoc(EndLoc);
  373. MostRecentLocation = EndLoc;
  374. // If this region happens to span an entire expansion, we need to make
  375. // sure we don't overlap the parent region with it.
  376. if (StartLoc == getStartOfFileOrMacro(StartLoc) &&
  377. EndLoc == getEndOfFileOrMacro(EndLoc))
  378. MostRecentLocation = getIncludeOrExpansionLoc(EndLoc);
  379. assert(SM.isWrittenInSameFile(Region.getStartLoc(), EndLoc));
  380. SourceRegions.push_back(Region);
  381. }
  382. RegionStack.pop_back();
  383. }
  384. }
  385. /// \brief Return the currently active region.
  386. SourceMappingRegion &getRegion() {
  387. assert(!RegionStack.empty() && "statement has no region");
  388. return RegionStack.back();
  389. }
  390. /// \brief Propagate counts through the children of \c S.
  391. Counter propagateCounts(Counter TopCount, const Stmt *S) {
  392. size_t Index = pushRegion(TopCount, getStart(S), getEnd(S));
  393. Visit(S);
  394. Counter ExitCount = getRegion().getCounter();
  395. popRegions(Index);
  396. // The statement may be spanned by an expansion. Make sure we handle a file
  397. // exit out of this expansion before moving to the next statement.
  398. if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart()))
  399. MostRecentLocation = getEnd(S);
  400. return ExitCount;
  401. }
  402. /// \brief Check whether a region with bounds \c StartLoc and \c EndLoc
  403. /// is already added to \c SourceRegions.
  404. bool isRegionAlreadyAdded(SourceLocation StartLoc, SourceLocation EndLoc) {
  405. return SourceRegions.rend() !=
  406. std::find_if(SourceRegions.rbegin(), SourceRegions.rend(),
  407. [&](const SourceMappingRegion &Region) {
  408. return Region.getStartLoc() == StartLoc &&
  409. Region.getEndLoc() == EndLoc;
  410. });
  411. }
  412. /// \brief Adjust the most recently visited location to \c EndLoc.
  413. ///
  414. /// This should be used after visiting any statements in non-source order.
  415. void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
  416. MostRecentLocation = EndLoc;
  417. // The code region for a whole macro is created in handleFileExit() when
  418. // it detects exiting of the virtual file of that macro. If we visited
  419. // statements in non-source order, we might already have such a region
  420. // added, for example, if a body of a loop is divided among multiple
  421. // macros. Avoid adding duplicate regions in such case.
  422. if (getRegion().hasEndLoc() &&
  423. MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation) &&
  424. isRegionAlreadyAdded(getStartOfFileOrMacro(MostRecentLocation),
  425. MostRecentLocation))
  426. MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
  427. }
  428. /// \brief Adjust regions and state when \c NewLoc exits a file.
  429. ///
  430. /// If moving from our most recently tracked location to \c NewLoc exits any
  431. /// files, this adjusts our current region stack and creates the file regions
  432. /// for the exited file.
  433. void handleFileExit(SourceLocation NewLoc) {
  434. if (NewLoc.isInvalid() ||
  435. SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
  436. return;
  437. // If NewLoc is not in a file that contains MostRecentLocation, walk up to
  438. // find the common ancestor.
  439. SourceLocation LCA = NewLoc;
  440. FileID ParentFile = SM.getFileID(LCA);
  441. while (!isNestedIn(MostRecentLocation, ParentFile)) {
  442. LCA = getIncludeOrExpansionLoc(LCA);
  443. if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
  444. // Since there isn't a common ancestor, no file was exited. We just need
  445. // to adjust our location to the new file.
  446. MostRecentLocation = NewLoc;
  447. return;
  448. }
  449. ParentFile = SM.getFileID(LCA);
  450. }
  451. llvm::SmallSet<SourceLocation, 8> StartLocs;
  452. Optional<Counter> ParentCounter;
  453. for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
  454. if (!I.hasStartLoc())
  455. continue;
  456. SourceLocation Loc = I.getStartLoc();
  457. if (!isNestedIn(Loc, ParentFile)) {
  458. ParentCounter = I.getCounter();
  459. break;
  460. }
  461. while (!SM.isInFileID(Loc, ParentFile)) {
  462. // The most nested region for each start location is the one with the
  463. // correct count. We avoid creating redundant regions by stopping once
  464. // we've seen this region.
  465. if (StartLocs.insert(Loc).second)
  466. SourceRegions.emplace_back(I.getCounter(), Loc,
  467. getEndOfFileOrMacro(Loc));
  468. Loc = getIncludeOrExpansionLoc(Loc);
  469. }
  470. I.setStartLoc(getPreciseTokenLocEnd(Loc));
  471. }
  472. if (ParentCounter) {
  473. // If the file is contained completely by another region and doesn't
  474. // immediately start its own region, the whole file gets a region
  475. // corresponding to the parent.
  476. SourceLocation Loc = MostRecentLocation;
  477. while (isNestedIn(Loc, ParentFile)) {
  478. SourceLocation FileStart = getStartOfFileOrMacro(Loc);
  479. if (StartLocs.insert(FileStart).second)
  480. SourceRegions.emplace_back(*ParentCounter, FileStart,
  481. getEndOfFileOrMacro(Loc));
  482. Loc = getIncludeOrExpansionLoc(Loc);
  483. }
  484. }
  485. MostRecentLocation = NewLoc;
  486. }
  487. /// \brief Ensure that \c S is included in the current region.
  488. void extendRegion(const Stmt *S) {
  489. SourceMappingRegion &Region = getRegion();
  490. SourceLocation StartLoc = getStart(S);
  491. handleFileExit(StartLoc);
  492. if (!Region.hasStartLoc())
  493. Region.setStartLoc(StartLoc);
  494. }
  495. /// \brief Mark \c S as a terminator, starting a zero region.
  496. void terminateRegion(const Stmt *S) {
  497. extendRegion(S);
  498. SourceMappingRegion &Region = getRegion();
  499. if (!Region.hasEndLoc())
  500. Region.setEndLoc(getEnd(S));
  501. pushRegion(Counter::getZero());
  502. }
  503. /// \brief Keep counts of breaks and continues inside loops.
  504. struct BreakContinue {
  505. Counter BreakCount;
  506. Counter ContinueCount;
  507. };
  508. SmallVector<BreakContinue, 8> BreakContinueStack;
  509. CounterCoverageMappingBuilder(
  510. CoverageMappingModuleGen &CVM,
  511. llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
  512. const LangOptions &LangOpts)
  513. : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
  514. /// \brief Write the mapping data to the output stream
  515. void write(llvm::raw_ostream &OS) {
  516. llvm::SmallVector<unsigned, 8> VirtualFileMapping;
  517. gatherFileIDs(VirtualFileMapping);
  518. emitSourceRegions();
  519. emitExpansionRegions();
  520. gatherSkippedRegions();
  521. CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
  522. MappingRegions);
  523. Writer.write(OS);
  524. }
  525. void VisitStmt(const Stmt *S) {
  526. if (S->getLocStart().isValid())
  527. extendRegion(S);
  528. for (const Stmt *Child : S->children())
  529. if (Child)
  530. this->Visit(Child);
  531. handleFileExit(getEnd(S));
  532. }
  533. void VisitDecl(const Decl *D) {
  534. Stmt *Body = D->getBody();
  535. propagateCounts(getRegionCounter(Body), Body);
  536. }
  537. void VisitReturnStmt(const ReturnStmt *S) {
  538. extendRegion(S);
  539. if (S->getRetValue())
  540. Visit(S->getRetValue());
  541. terminateRegion(S);
  542. }
  543. void VisitCXXThrowExpr(const CXXThrowExpr *E) {
  544. extendRegion(E);
  545. if (E->getSubExpr())
  546. Visit(E->getSubExpr());
  547. terminateRegion(E);
  548. }
  549. void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
  550. void VisitLabelStmt(const LabelStmt *S) {
  551. SourceLocation Start = getStart(S);
  552. // We can't extendRegion here or we risk overlapping with our new region.
  553. handleFileExit(Start);
  554. pushRegion(getRegionCounter(S), Start);
  555. Visit(S->getSubStmt());
  556. }
  557. void VisitBreakStmt(const BreakStmt *S) {
  558. assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
  559. BreakContinueStack.back().BreakCount = addCounters(
  560. BreakContinueStack.back().BreakCount, getRegion().getCounter());
  561. terminateRegion(S);
  562. }
  563. void VisitContinueStmt(const ContinueStmt *S) {
  564. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  565. BreakContinueStack.back().ContinueCount = addCounters(
  566. BreakContinueStack.back().ContinueCount, getRegion().getCounter());
  567. terminateRegion(S);
  568. }
  569. void VisitWhileStmt(const WhileStmt *S) {
  570. extendRegion(S);
  571. Counter ParentCount = getRegion().getCounter();
  572. Counter BodyCount = getRegionCounter(S);
  573. // Handle the body first so that we can get the backedge count.
  574. BreakContinueStack.push_back(BreakContinue());
  575. extendRegion(S->getBody());
  576. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  577. BreakContinue BC = BreakContinueStack.pop_back_val();
  578. // Go back to handle the condition.
  579. Counter CondCount =
  580. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  581. propagateCounts(CondCount, S->getCond());
  582. adjustForOutOfOrderTraversal(getEnd(S));
  583. Counter OutCount =
  584. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  585. if (OutCount != ParentCount)
  586. pushRegion(OutCount);
  587. }
  588. void VisitDoStmt(const DoStmt *S) {
  589. extendRegion(S);
  590. Counter ParentCount = getRegion().getCounter();
  591. Counter BodyCount = getRegionCounter(S);
  592. BreakContinueStack.push_back(BreakContinue());
  593. extendRegion(S->getBody());
  594. Counter BackedgeCount =
  595. propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
  596. BreakContinue BC = BreakContinueStack.pop_back_val();
  597. Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
  598. propagateCounts(CondCount, S->getCond());
  599. Counter OutCount =
  600. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  601. if (OutCount != ParentCount)
  602. pushRegion(OutCount);
  603. }
  604. void VisitForStmt(const ForStmt *S) {
  605. extendRegion(S);
  606. if (S->getInit())
  607. Visit(S->getInit());
  608. Counter ParentCount = getRegion().getCounter();
  609. Counter BodyCount = getRegionCounter(S);
  610. // Handle the body first so that we can get the backedge count.
  611. BreakContinueStack.push_back(BreakContinue());
  612. extendRegion(S->getBody());
  613. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  614. BreakContinue BC = BreakContinueStack.pop_back_val();
  615. // The increment is essentially part of the body but it needs to include
  616. // the count for all the continue statements.
  617. if (const Stmt *Inc = S->getInc())
  618. propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
  619. // Go back to handle the condition.
  620. Counter CondCount =
  621. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  622. if (const Expr *Cond = S->getCond()) {
  623. propagateCounts(CondCount, Cond);
  624. adjustForOutOfOrderTraversal(getEnd(S));
  625. }
  626. Counter OutCount =
  627. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  628. if (OutCount != ParentCount)
  629. pushRegion(OutCount);
  630. }
  631. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  632. extendRegion(S);
  633. Visit(S->getLoopVarStmt());
  634. Visit(S->getRangeStmt());
  635. Counter ParentCount = getRegion().getCounter();
  636. Counter BodyCount = getRegionCounter(S);
  637. BreakContinueStack.push_back(BreakContinue());
  638. extendRegion(S->getBody());
  639. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  640. BreakContinue BC = BreakContinueStack.pop_back_val();
  641. Counter LoopCount =
  642. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  643. Counter OutCount =
  644. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  645. if (OutCount != ParentCount)
  646. pushRegion(OutCount);
  647. }
  648. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  649. extendRegion(S);
  650. Visit(S->getElement());
  651. Counter ParentCount = getRegion().getCounter();
  652. Counter BodyCount = getRegionCounter(S);
  653. BreakContinueStack.push_back(BreakContinue());
  654. extendRegion(S->getBody());
  655. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  656. BreakContinue BC = BreakContinueStack.pop_back_val();
  657. Counter LoopCount =
  658. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  659. Counter OutCount =
  660. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  661. if (OutCount != ParentCount)
  662. pushRegion(OutCount);
  663. }
  664. void VisitSwitchStmt(const SwitchStmt *S) {
  665. extendRegion(S);
  666. Visit(S->getCond());
  667. BreakContinueStack.push_back(BreakContinue());
  668. const Stmt *Body = S->getBody();
  669. extendRegion(Body);
  670. if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
  671. if (!CS->body_empty()) {
  672. // The body of the switch needs a zero region so that fallthrough counts
  673. // behave correctly, but it would be misleading to include the braces of
  674. // the compound statement in the zeroed area, so we need to handle this
  675. // specially.
  676. size_t Index =
  677. pushRegion(Counter::getZero(), getStart(CS->body_front()),
  678. getEnd(CS->body_back()));
  679. for (const auto *Child : CS->children())
  680. Visit(Child);
  681. popRegions(Index);
  682. }
  683. } else
  684. propagateCounts(Counter::getZero(), Body);
  685. BreakContinue BC = BreakContinueStack.pop_back_val();
  686. if (!BreakContinueStack.empty())
  687. BreakContinueStack.back().ContinueCount = addCounters(
  688. BreakContinueStack.back().ContinueCount, BC.ContinueCount);
  689. Counter ExitCount = getRegionCounter(S);
  690. SourceLocation ExitLoc = getEnd(S);
  691. pushRegion(ExitCount, getStart(S), ExitLoc);
  692. handleFileExit(ExitLoc);
  693. }
  694. void VisitSwitchCase(const SwitchCase *S) {
  695. extendRegion(S);
  696. SourceMappingRegion &Parent = getRegion();
  697. Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
  698. // Reuse the existing region if it starts at our label. This is typical of
  699. // the first case in a switch.
  700. if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
  701. Parent.setCounter(Count);
  702. else
  703. pushRegion(Count, getStart(S));
  704. if (const auto *CS = dyn_cast<CaseStmt>(S)) {
  705. Visit(CS->getLHS());
  706. if (const Expr *RHS = CS->getRHS())
  707. Visit(RHS);
  708. }
  709. Visit(S->getSubStmt());
  710. }
  711. void VisitIfStmt(const IfStmt *S) {
  712. extendRegion(S);
  713. // Extend into the condition before we propagate through it below - this is
  714. // needed to handle macros that generate the "if" but not the condition.
  715. extendRegion(S->getCond());
  716. Counter ParentCount = getRegion().getCounter();
  717. Counter ThenCount = getRegionCounter(S);
  718. // Emitting a counter for the condition makes it easier to interpret the
  719. // counter for the body when looking at the coverage.
  720. propagateCounts(ParentCount, S->getCond());
  721. extendRegion(S->getThen());
  722. Counter OutCount = propagateCounts(ThenCount, S->getThen());
  723. Counter ElseCount = subtractCounters(ParentCount, ThenCount);
  724. if (const Stmt *Else = S->getElse()) {
  725. extendRegion(S->getElse());
  726. OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
  727. } else
  728. OutCount = addCounters(OutCount, ElseCount);
  729. if (OutCount != ParentCount)
  730. pushRegion(OutCount);
  731. }
  732. void VisitCXXTryStmt(const CXXTryStmt *S) {
  733. extendRegion(S);
  734. // Handle macros that generate the "try" but not the rest.
  735. extendRegion(S->getTryBlock());
  736. Counter ParentCount = getRegion().getCounter();
  737. propagateCounts(ParentCount, S->getTryBlock());
  738. for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
  739. Visit(S->getHandler(I));
  740. Counter ExitCount = getRegionCounter(S);
  741. pushRegion(ExitCount);
  742. }
  743. void VisitCXXCatchStmt(const CXXCatchStmt *S) {
  744. propagateCounts(getRegionCounter(S), S->getHandlerBlock());
  745. }
  746. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  747. extendRegion(E);
  748. Counter ParentCount = getRegion().getCounter();
  749. Counter TrueCount = getRegionCounter(E);
  750. Visit(E->getCond());
  751. if (!isa<BinaryConditionalOperator>(E)) {
  752. extendRegion(E->getTrueExpr());
  753. propagateCounts(TrueCount, E->getTrueExpr());
  754. }
  755. extendRegion(E->getFalseExpr());
  756. propagateCounts(subtractCounters(ParentCount, TrueCount),
  757. E->getFalseExpr());
  758. }
  759. void VisitBinLAnd(const BinaryOperator *E) {
  760. extendRegion(E);
  761. Visit(E->getLHS());
  762. extendRegion(E->getRHS());
  763. propagateCounts(getRegionCounter(E), E->getRHS());
  764. }
  765. void VisitBinLOr(const BinaryOperator *E) {
  766. extendRegion(E);
  767. Visit(E->getLHS());
  768. extendRegion(E->getRHS());
  769. propagateCounts(getRegionCounter(E), E->getRHS());
  770. }
  771. void VisitLambdaExpr(const LambdaExpr *LE) {
  772. // Lambdas are treated as their own functions for now, so we shouldn't
  773. // propagate counts into them.
  774. }
  775. };
  776. }
  777. static bool isMachO(const CodeGenModule &CGM) {
  778. return CGM.getTarget().getTriple().isOSBinFormatMachO();
  779. }
  780. static StringRef getCoverageSection(const CodeGenModule &CGM) {
  781. return llvm::getInstrProfCoverageSectionName(isMachO(CGM));
  782. }
  783. static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
  784. ArrayRef<CounterExpression> Expressions,
  785. ArrayRef<CounterMappingRegion> Regions) {
  786. OS << FunctionName << ":\n";
  787. CounterMappingContext Ctx(Expressions);
  788. for (const auto &R : Regions) {
  789. OS.indent(2);
  790. switch (R.Kind) {
  791. case CounterMappingRegion::CodeRegion:
  792. break;
  793. case CounterMappingRegion::ExpansionRegion:
  794. OS << "Expansion,";
  795. break;
  796. case CounterMappingRegion::SkippedRegion:
  797. OS << "Skipped,";
  798. break;
  799. }
  800. OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
  801. << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
  802. Ctx.dump(R.Count, OS);
  803. if (R.Kind == CounterMappingRegion::ExpansionRegion)
  804. OS << " (Expanded file = " << R.ExpandedFileID << ")";
  805. OS << "\n";
  806. }
  807. }
  808. void CoverageMappingModuleGen::addFunctionMappingRecord(
  809. llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
  810. const std::string &CoverageMapping, bool IsUsed) {
  811. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  812. if (!FunctionRecordTy) {
  813. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
  814. llvm::Type *FunctionRecordTypes[] = {
  815. #include "llvm/ProfileData/InstrProfData.inc"
  816. };
  817. FunctionRecordTy =
  818. llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
  819. /*isPacked=*/true);
  820. }
  821. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
  822. llvm::Constant *FunctionRecordVals[] = {
  823. #include "llvm/ProfileData/InstrProfData.inc"
  824. };
  825. FunctionRecords.push_back(llvm::ConstantStruct::get(
  826. FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
  827. if (!IsUsed)
  828. FunctionNames.push_back(
  829. llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
  830. CoverageMappings.push_back(CoverageMapping);
  831. if (CGM.getCodeGenOpts().DumpCoverageMapping) {
  832. // Dump the coverage mapping data for this function by decoding the
  833. // encoded data. This allows us to dump the mapping regions which were
  834. // also processed by the CoverageMappingWriter which performs
  835. // additional minimization operations such as reducing the number of
  836. // expressions.
  837. std::vector<StringRef> Filenames;
  838. std::vector<CounterExpression> Expressions;
  839. std::vector<CounterMappingRegion> Regions;
  840. llvm::SmallVector<StringRef, 16> FilenameRefs;
  841. FilenameRefs.resize(FileEntries.size());
  842. for (const auto &Entry : FileEntries)
  843. FilenameRefs[Entry.second] = Entry.first->getName();
  844. RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
  845. Expressions, Regions);
  846. if (Reader.read())
  847. return;
  848. dump(llvm::outs(), NameValue, Expressions, Regions);
  849. }
  850. }
  851. void CoverageMappingModuleGen::emit() {
  852. if (FunctionRecords.empty())
  853. return;
  854. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  855. auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
  856. // Create the filenames and merge them with coverage mappings
  857. llvm::SmallVector<std::string, 16> FilenameStrs;
  858. llvm::SmallVector<StringRef, 16> FilenameRefs;
  859. FilenameStrs.resize(FileEntries.size());
  860. FilenameRefs.resize(FileEntries.size());
  861. for (const auto &Entry : FileEntries) {
  862. llvm::SmallString<256> Path(Entry.first->getName());
  863. llvm::sys::fs::make_absolute(Path);
  864. auto I = Entry.second;
  865. FilenameStrs[I] = std::string(Path.begin(), Path.end());
  866. FilenameRefs[I] = FilenameStrs[I];
  867. }
  868. std::string FilenamesAndCoverageMappings;
  869. llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
  870. CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
  871. std::string RawCoverageMappings =
  872. llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
  873. OS << RawCoverageMappings;
  874. size_t CoverageMappingSize = RawCoverageMappings.size();
  875. size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
  876. // Append extra zeroes if necessary to ensure that the size of the filenames
  877. // and coverage mappings is a multiple of 8.
  878. if (size_t Rem = OS.str().size() % 8) {
  879. CoverageMappingSize += 8 - Rem;
  880. for (size_t I = 0, S = 8 - Rem; I < S; ++I)
  881. OS << '\0';
  882. }
  883. auto *FilenamesAndMappingsVal =
  884. llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
  885. // Create the deferred function records array
  886. auto RecordsTy =
  887. llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
  888. auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
  889. llvm::Type *CovDataHeaderTypes[] = {
  890. #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
  891. #include "llvm/ProfileData/InstrProfData.inc"
  892. };
  893. auto CovDataHeaderTy =
  894. llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
  895. llvm::Constant *CovDataHeaderVals[] = {
  896. #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
  897. #include "llvm/ProfileData/InstrProfData.inc"
  898. };
  899. auto CovDataHeaderVal = llvm::ConstantStruct::get(
  900. CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
  901. // Create the coverage data record
  902. llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
  903. FilenamesAndMappingsVal->getType()};
  904. auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
  905. llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
  906. FilenamesAndMappingsVal};
  907. auto CovDataVal =
  908. llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
  909. auto CovData = new llvm::GlobalVariable(
  910. CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
  911. CovDataVal, llvm::getCoverageMappingVarName());
  912. CovData->setSection(getCoverageSection(CGM));
  913. CovData->setAlignment(8);
  914. // Make sure the data doesn't get deleted.
  915. CGM.addUsedGlobal(CovData);
  916. // Create the deferred function records array
  917. if (!FunctionNames.empty()) {
  918. auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
  919. FunctionNames.size());
  920. auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
  921. // This variable will *NOT* be emitted to the object file. It is used
  922. // to pass the list of names referenced to codegen.
  923. new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
  924. llvm::GlobalValue::InternalLinkage, NamesArrVal,
  925. llvm::getCoverageUnusedNamesVarName());
  926. }
  927. }
  928. unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
  929. auto It = FileEntries.find(File);
  930. if (It != FileEntries.end())
  931. return It->second;
  932. unsigned FileID = FileEntries.size();
  933. FileEntries.insert(std::make_pair(File, FileID));
  934. return FileID;
  935. }
  936. void CoverageMappingGen::emitCounterMapping(const Decl *D,
  937. llvm::raw_ostream &OS) {
  938. assert(CounterMap);
  939. CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
  940. Walker.VisitDecl(D);
  941. Walker.write(OS);
  942. }
  943. void CoverageMappingGen::emitEmptyMapping(const Decl *D,
  944. llvm::raw_ostream &OS) {
  945. EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
  946. Walker.VisitDecl(D);
  947. Walker.write(OS);
  948. }