CoverageMappingGen.cpp 38 KB

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