CoverageMappingGen.cpp 40 KB

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