CoverageMappingGen.cpp 37 KB

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