CoverageMappingGen.cpp 41 KB

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