CoverageMappingGen.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073
  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/CoverageMapping.h"
  21. #include "llvm/ProfileData/CoverageMappingReader.h"
  22. #include "llvm/ProfileData/CoverageMappingWriter.h"
  23. #include "llvm/ProfileData/InstrProfReader.h"
  24. #include "llvm/Support/FileSystem.h"
  25. using namespace clang;
  26. using namespace CodeGen;
  27. using namespace llvm::coverage;
  28. void CoverageSourceInfo::SourceRangeSkipped(SourceRange Range) {
  29. SkippedRanges.push_back(Range);
  30. }
  31. namespace {
  32. /// \brief A region of source code that can be mapped to a counter.
  33. class SourceMappingRegion {
  34. Counter Count;
  35. /// \brief The region's starting location.
  36. Optional<SourceLocation> LocStart;
  37. /// \brief The region's ending location.
  38. Optional<SourceLocation> LocEnd;
  39. public:
  40. SourceMappingRegion(Counter Count, Optional<SourceLocation> LocStart,
  41. Optional<SourceLocation> LocEnd)
  42. : Count(Count), LocStart(LocStart), LocEnd(LocEnd) {}
  43. const Counter &getCounter() const { return Count; }
  44. void setCounter(Counter C) { Count = C; }
  45. bool hasStartLoc() const { return LocStart.hasValue(); }
  46. void setStartLoc(SourceLocation Loc) { LocStart = Loc; }
  47. SourceLocation getStartLoc() const {
  48. assert(LocStart && "Region has no start location");
  49. return *LocStart;
  50. }
  51. bool hasEndLoc() const { return LocEnd.hasValue(); }
  52. void setEndLoc(SourceLocation Loc) { LocEnd = Loc; }
  53. SourceLocation getEndLoc() const {
  54. assert(LocEnd && "Region has no end location");
  55. return *LocEnd;
  56. }
  57. };
  58. /// \brief Provides the common functionality for the different
  59. /// coverage mapping region builders.
  60. class CoverageMappingBuilder {
  61. public:
  62. CoverageMappingModuleGen &CVM;
  63. SourceManager &SM;
  64. const LangOptions &LangOpts;
  65. private:
  66. /// \brief Map of clang's FileIDs to IDs used for coverage mapping.
  67. llvm::SmallDenseMap<FileID, std::pair<unsigned, SourceLocation>, 8>
  68. FileIDMapping;
  69. public:
  70. /// \brief The coverage mapping regions for this function
  71. llvm::SmallVector<CounterMappingRegion, 32> MappingRegions;
  72. /// \brief The source mapping regions for this function.
  73. std::vector<SourceMappingRegion> SourceRegions;
  74. CoverageMappingBuilder(CoverageMappingModuleGen &CVM, SourceManager &SM,
  75. const LangOptions &LangOpts)
  76. : CVM(CVM), SM(SM), LangOpts(LangOpts) {}
  77. /// \brief Return the precise end location for the given token.
  78. SourceLocation getPreciseTokenLocEnd(SourceLocation Loc) {
  79. // We avoid getLocForEndOfToken here, because it doesn't do what we want for
  80. // macro locations, which we just treat as expanded files.
  81. unsigned TokLen =
  82. Lexer::MeasureTokenLength(SM.getSpellingLoc(Loc), SM, LangOpts);
  83. return Loc.getLocWithOffset(TokLen);
  84. }
  85. /// \brief Return the start location of an included file or expanded macro.
  86. SourceLocation getStartOfFileOrMacro(SourceLocation Loc) {
  87. if (Loc.isMacroID())
  88. return Loc.getLocWithOffset(-SM.getFileOffset(Loc));
  89. return SM.getLocForStartOfFile(SM.getFileID(Loc));
  90. }
  91. /// \brief Return the end location of an included file or expanded macro.
  92. SourceLocation getEndOfFileOrMacro(SourceLocation Loc) {
  93. if (Loc.isMacroID())
  94. return Loc.getLocWithOffset(SM.getFileIDSize(SM.getFileID(Loc)) -
  95. SM.getFileOffset(Loc));
  96. return SM.getLocForEndOfFile(SM.getFileID(Loc));
  97. }
  98. /// \brief Find out where the current file is included or macro is expanded.
  99. SourceLocation getIncludeOrExpansionLoc(SourceLocation Loc) {
  100. return Loc.isMacroID() ? SM.getImmediateExpansionRange(Loc).first
  101. : SM.getIncludeLoc(SM.getFileID(Loc));
  102. }
  103. /// \brief Return true if \c Loc is a location in a built-in macro.
  104. bool isInBuiltin(SourceLocation Loc) {
  105. return strcmp(SM.getBufferName(SM.getSpellingLoc(Loc)), "<built-in>") == 0;
  106. }
  107. /// \brief Get the start of \c S ignoring macro arguments and builtin macros.
  108. SourceLocation getStart(const Stmt *S) {
  109. SourceLocation Loc = S->getLocStart();
  110. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  111. Loc = SM.getImmediateExpansionRange(Loc).first;
  112. return Loc;
  113. }
  114. /// \brief Get the end of \c S ignoring macro arguments and builtin macros.
  115. SourceLocation getEnd(const Stmt *S) {
  116. SourceLocation Loc = S->getLocEnd();
  117. while (SM.isMacroArgExpansion(Loc) || isInBuiltin(Loc))
  118. Loc = SM.getImmediateExpansionRange(Loc).first;
  119. return getPreciseTokenLocEnd(Loc);
  120. }
  121. /// \brief Find the set of files we have regions for and assign IDs
  122. ///
  123. /// Fills \c Mapping with the virtual file mapping needed to write out
  124. /// coverage and collects the necessary file information to emit source and
  125. /// expansion regions.
  126. void gatherFileIDs(SmallVectorImpl<unsigned> &Mapping) {
  127. FileIDMapping.clear();
  128. llvm::SmallSet<FileID, 8> Visited;
  129. SmallVector<std::pair<SourceLocation, unsigned>, 8> FileLocs;
  130. for (const auto &Region : SourceRegions) {
  131. SourceLocation Loc = Region.getStartLoc();
  132. FileID File = SM.getFileID(Loc);
  133. if (!Visited.insert(File).second)
  134. continue;
  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. // The statement may be spanned by an expansion. Make sure we handle a file
  368. // exit out of this expansion before moving to the next statement.
  369. if (SM.isBeforeInTranslationUnit(getStart(S), S->getLocStart()))
  370. MostRecentLocation = getEnd(S);
  371. return ExitCount;
  372. }
  373. /// \brief Adjust the most recently visited location to \c EndLoc.
  374. ///
  375. /// This should be used after visiting any statements in non-source order.
  376. void adjustForOutOfOrderTraversal(SourceLocation EndLoc) {
  377. MostRecentLocation = EndLoc;
  378. // Avoid adding duplicate regions if we have a completed region on the top
  379. // of the stack and are adjusting to the end of a virtual file.
  380. if (getRegion().hasEndLoc() &&
  381. MostRecentLocation == getEndOfFileOrMacro(MostRecentLocation))
  382. MostRecentLocation = getIncludeOrExpansionLoc(MostRecentLocation);
  383. }
  384. /// \brief Check whether \c Loc is included or expanded from \c Parent.
  385. bool isNestedIn(SourceLocation Loc, FileID Parent) {
  386. do {
  387. Loc = getIncludeOrExpansionLoc(Loc);
  388. if (Loc.isInvalid())
  389. return false;
  390. } while (!SM.isInFileID(Loc, Parent));
  391. return true;
  392. }
  393. /// \brief Adjust regions and state when \c NewLoc exits a file.
  394. ///
  395. /// If moving from our most recently tracked location to \c NewLoc exits any
  396. /// files, this adjusts our current region stack and creates the file regions
  397. /// for the exited file.
  398. void handleFileExit(SourceLocation NewLoc) {
  399. if (NewLoc.isInvalid() ||
  400. SM.isWrittenInSameFile(MostRecentLocation, NewLoc))
  401. return;
  402. // If NewLoc is not in a file that contains MostRecentLocation, walk up to
  403. // find the common ancestor.
  404. SourceLocation LCA = NewLoc;
  405. FileID ParentFile = SM.getFileID(LCA);
  406. while (!isNestedIn(MostRecentLocation, ParentFile)) {
  407. LCA = getIncludeOrExpansionLoc(LCA);
  408. if (LCA.isInvalid() || SM.isWrittenInSameFile(LCA, MostRecentLocation)) {
  409. // Since there isn't a common ancestor, no file was exited. We just need
  410. // to adjust our location to the new file.
  411. MostRecentLocation = NewLoc;
  412. return;
  413. }
  414. ParentFile = SM.getFileID(LCA);
  415. }
  416. llvm::SmallSet<SourceLocation, 8> StartLocs;
  417. Optional<Counter> ParentCounter;
  418. for (SourceMappingRegion &I : llvm::reverse(RegionStack)) {
  419. if (!I.hasStartLoc())
  420. continue;
  421. SourceLocation Loc = I.getStartLoc();
  422. if (!isNestedIn(Loc, ParentFile)) {
  423. ParentCounter = I.getCounter();
  424. break;
  425. }
  426. while (!SM.isInFileID(Loc, ParentFile)) {
  427. // The most nested region for each start location is the one with the
  428. // correct count. We avoid creating redundant regions by stopping once
  429. // we've seen this region.
  430. if (StartLocs.insert(Loc).second)
  431. SourceRegions.emplace_back(I.getCounter(), Loc,
  432. getEndOfFileOrMacro(Loc));
  433. Loc = getIncludeOrExpansionLoc(Loc);
  434. }
  435. I.setStartLoc(getPreciseTokenLocEnd(Loc));
  436. }
  437. if (ParentCounter) {
  438. // If the file is contained completely by another region and doesn't
  439. // immediately start its own region, the whole file gets a region
  440. // corresponding to the parent.
  441. SourceLocation Loc = MostRecentLocation;
  442. while (isNestedIn(Loc, ParentFile)) {
  443. SourceLocation FileStart = getStartOfFileOrMacro(Loc);
  444. if (StartLocs.insert(FileStart).second)
  445. SourceRegions.emplace_back(*ParentCounter, FileStart,
  446. getEndOfFileOrMacro(Loc));
  447. Loc = getIncludeOrExpansionLoc(Loc);
  448. }
  449. }
  450. MostRecentLocation = NewLoc;
  451. }
  452. /// \brief Ensure that \c S is included in the current region.
  453. void extendRegion(const Stmt *S) {
  454. SourceMappingRegion &Region = getRegion();
  455. SourceLocation StartLoc = getStart(S);
  456. handleFileExit(StartLoc);
  457. if (!Region.hasStartLoc())
  458. Region.setStartLoc(StartLoc);
  459. }
  460. /// \brief Mark \c S as a terminator, starting a zero region.
  461. void terminateRegion(const Stmt *S) {
  462. extendRegion(S);
  463. SourceMappingRegion &Region = getRegion();
  464. if (!Region.hasEndLoc())
  465. Region.setEndLoc(getEnd(S));
  466. pushRegion(Counter::getZero());
  467. }
  468. /// \brief Keep counts of breaks and continues inside loops.
  469. struct BreakContinue {
  470. Counter BreakCount;
  471. Counter ContinueCount;
  472. };
  473. SmallVector<BreakContinue, 8> BreakContinueStack;
  474. CounterCoverageMappingBuilder(
  475. CoverageMappingModuleGen &CVM,
  476. llvm::DenseMap<const Stmt *, unsigned> &CounterMap, SourceManager &SM,
  477. const LangOptions &LangOpts)
  478. : CoverageMappingBuilder(CVM, SM, LangOpts), CounterMap(CounterMap) {}
  479. /// \brief Write the mapping data to the output stream
  480. void write(llvm::raw_ostream &OS) {
  481. llvm::SmallVector<unsigned, 8> VirtualFileMapping;
  482. gatherFileIDs(VirtualFileMapping);
  483. emitSourceRegions();
  484. emitExpansionRegions();
  485. gatherSkippedRegions();
  486. CoverageMappingWriter Writer(VirtualFileMapping, Builder.getExpressions(),
  487. MappingRegions);
  488. Writer.write(OS);
  489. }
  490. void VisitStmt(const Stmt *S) {
  491. if (S->getLocStart().isValid())
  492. extendRegion(S);
  493. for (const Stmt *Child : S->children())
  494. if (Child)
  495. this->Visit(Child);
  496. handleFileExit(getEnd(S));
  497. }
  498. void VisitDecl(const Decl *D) {
  499. Stmt *Body = D->getBody();
  500. propagateCounts(getRegionCounter(Body), Body);
  501. }
  502. void VisitReturnStmt(const ReturnStmt *S) {
  503. extendRegion(S);
  504. if (S->getRetValue())
  505. Visit(S->getRetValue());
  506. terminateRegion(S);
  507. }
  508. void VisitCXXThrowExpr(const CXXThrowExpr *E) {
  509. extendRegion(E);
  510. if (E->getSubExpr())
  511. Visit(E->getSubExpr());
  512. terminateRegion(E);
  513. }
  514. void VisitGotoStmt(const GotoStmt *S) { terminateRegion(S); }
  515. void VisitLabelStmt(const LabelStmt *S) {
  516. SourceLocation Start = getStart(S);
  517. // We can't extendRegion here or we risk overlapping with our new region.
  518. handleFileExit(Start);
  519. pushRegion(getRegionCounter(S), Start);
  520. Visit(S->getSubStmt());
  521. }
  522. void VisitBreakStmt(const BreakStmt *S) {
  523. assert(!BreakContinueStack.empty() && "break not in a loop or switch!");
  524. BreakContinueStack.back().BreakCount = addCounters(
  525. BreakContinueStack.back().BreakCount, getRegion().getCounter());
  526. terminateRegion(S);
  527. }
  528. void VisitContinueStmt(const ContinueStmt *S) {
  529. assert(!BreakContinueStack.empty() && "continue stmt not in a loop!");
  530. BreakContinueStack.back().ContinueCount = addCounters(
  531. BreakContinueStack.back().ContinueCount, getRegion().getCounter());
  532. terminateRegion(S);
  533. }
  534. void VisitWhileStmt(const WhileStmt *S) {
  535. extendRegion(S);
  536. Counter ParentCount = getRegion().getCounter();
  537. Counter BodyCount = getRegionCounter(S);
  538. // Handle the body first so that we can get the backedge count.
  539. BreakContinueStack.push_back(BreakContinue());
  540. extendRegion(S->getBody());
  541. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  542. BreakContinue BC = BreakContinueStack.pop_back_val();
  543. // Go back to handle the condition.
  544. Counter CondCount =
  545. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  546. propagateCounts(CondCount, S->getCond());
  547. adjustForOutOfOrderTraversal(getEnd(S));
  548. Counter OutCount =
  549. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  550. if (OutCount != ParentCount)
  551. pushRegion(OutCount);
  552. }
  553. void VisitDoStmt(const DoStmt *S) {
  554. extendRegion(S);
  555. Counter ParentCount = getRegion().getCounter();
  556. Counter BodyCount = getRegionCounter(S);
  557. BreakContinueStack.push_back(BreakContinue());
  558. extendRegion(S->getBody());
  559. Counter BackedgeCount =
  560. propagateCounts(addCounters(ParentCount, BodyCount), S->getBody());
  561. BreakContinue BC = BreakContinueStack.pop_back_val();
  562. Counter CondCount = addCounters(BackedgeCount, BC.ContinueCount);
  563. propagateCounts(CondCount, S->getCond());
  564. Counter OutCount =
  565. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  566. if (OutCount != ParentCount)
  567. pushRegion(OutCount);
  568. }
  569. void VisitForStmt(const ForStmt *S) {
  570. extendRegion(S);
  571. if (S->getInit())
  572. Visit(S->getInit());
  573. Counter ParentCount = getRegion().getCounter();
  574. Counter BodyCount = getRegionCounter(S);
  575. // Handle the body first so that we can get the backedge count.
  576. BreakContinueStack.push_back(BreakContinue());
  577. extendRegion(S->getBody());
  578. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  579. BreakContinue BC = BreakContinueStack.pop_back_val();
  580. // The increment is essentially part of the body but it needs to include
  581. // the count for all the continue statements.
  582. if (const Stmt *Inc = S->getInc())
  583. propagateCounts(addCounters(BackedgeCount, BC.ContinueCount), Inc);
  584. // Go back to handle the condition.
  585. Counter CondCount =
  586. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  587. if (const Expr *Cond = S->getCond()) {
  588. propagateCounts(CondCount, Cond);
  589. adjustForOutOfOrderTraversal(getEnd(S));
  590. }
  591. Counter OutCount =
  592. addCounters(BC.BreakCount, subtractCounters(CondCount, BodyCount));
  593. if (OutCount != ParentCount)
  594. pushRegion(OutCount);
  595. }
  596. void VisitCXXForRangeStmt(const CXXForRangeStmt *S) {
  597. extendRegion(S);
  598. Visit(S->getLoopVarStmt());
  599. Visit(S->getRangeStmt());
  600. Counter ParentCount = getRegion().getCounter();
  601. Counter BodyCount = getRegionCounter(S);
  602. BreakContinueStack.push_back(BreakContinue());
  603. extendRegion(S->getBody());
  604. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  605. BreakContinue BC = BreakContinueStack.pop_back_val();
  606. Counter LoopCount =
  607. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  608. Counter OutCount =
  609. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  610. if (OutCount != ParentCount)
  611. pushRegion(OutCount);
  612. }
  613. void VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
  614. extendRegion(S);
  615. Visit(S->getElement());
  616. Counter ParentCount = getRegion().getCounter();
  617. Counter BodyCount = getRegionCounter(S);
  618. BreakContinueStack.push_back(BreakContinue());
  619. extendRegion(S->getBody());
  620. Counter BackedgeCount = propagateCounts(BodyCount, S->getBody());
  621. BreakContinue BC = BreakContinueStack.pop_back_val();
  622. Counter LoopCount =
  623. addCounters(ParentCount, BackedgeCount, BC.ContinueCount);
  624. Counter OutCount =
  625. addCounters(BC.BreakCount, subtractCounters(LoopCount, BodyCount));
  626. if (OutCount != ParentCount)
  627. pushRegion(OutCount);
  628. }
  629. void VisitSwitchStmt(const SwitchStmt *S) {
  630. extendRegion(S);
  631. Visit(S->getCond());
  632. BreakContinueStack.push_back(BreakContinue());
  633. const Stmt *Body = S->getBody();
  634. extendRegion(Body);
  635. if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
  636. if (!CS->body_empty()) {
  637. // The body of the switch needs a zero region so that fallthrough counts
  638. // behave correctly, but it would be misleading to include the braces of
  639. // the compound statement in the zeroed area, so we need to handle this
  640. // specially.
  641. size_t Index =
  642. pushRegion(Counter::getZero(), getStart(CS->body_front()),
  643. getEnd(CS->body_back()));
  644. for (const auto *Child : CS->children())
  645. Visit(Child);
  646. popRegions(Index);
  647. }
  648. } else
  649. propagateCounts(Counter::getZero(), Body);
  650. BreakContinue BC = BreakContinueStack.pop_back_val();
  651. if (!BreakContinueStack.empty())
  652. BreakContinueStack.back().ContinueCount = addCounters(
  653. BreakContinueStack.back().ContinueCount, BC.ContinueCount);
  654. Counter ExitCount = getRegionCounter(S);
  655. pushRegion(ExitCount, getStart(S), getEnd(S));
  656. }
  657. void VisitSwitchCase(const SwitchCase *S) {
  658. extendRegion(S);
  659. SourceMappingRegion &Parent = getRegion();
  660. Counter Count = addCounters(Parent.getCounter(), getRegionCounter(S));
  661. // Reuse the existing region if it starts at our label. This is typical of
  662. // the first case in a switch.
  663. if (Parent.hasStartLoc() && Parent.getStartLoc() == getStart(S))
  664. Parent.setCounter(Count);
  665. else
  666. pushRegion(Count, getStart(S));
  667. if (const auto *CS = dyn_cast<CaseStmt>(S)) {
  668. Visit(CS->getLHS());
  669. if (const Expr *RHS = CS->getRHS())
  670. Visit(RHS);
  671. }
  672. Visit(S->getSubStmt());
  673. }
  674. void VisitIfStmt(const IfStmt *S) {
  675. extendRegion(S);
  676. // Extend into the condition before we propagate through it below - this is
  677. // needed to handle macros that generate the "if" but not the condition.
  678. extendRegion(S->getCond());
  679. Counter ParentCount = getRegion().getCounter();
  680. Counter ThenCount = getRegionCounter(S);
  681. // Emitting a counter for the condition makes it easier to interpret the
  682. // counter for the body when looking at the coverage.
  683. propagateCounts(ParentCount, S->getCond());
  684. extendRegion(S->getThen());
  685. Counter OutCount = propagateCounts(ThenCount, S->getThen());
  686. Counter ElseCount = subtractCounters(ParentCount, ThenCount);
  687. if (const Stmt *Else = S->getElse()) {
  688. extendRegion(S->getElse());
  689. OutCount = addCounters(OutCount, propagateCounts(ElseCount, Else));
  690. } else
  691. OutCount = addCounters(OutCount, ElseCount);
  692. if (OutCount != ParentCount)
  693. pushRegion(OutCount);
  694. }
  695. void VisitCXXTryStmt(const CXXTryStmt *S) {
  696. extendRegion(S);
  697. Visit(S->getTryBlock());
  698. for (unsigned I = 0, E = S->getNumHandlers(); I < E; ++I)
  699. Visit(S->getHandler(I));
  700. Counter ExitCount = getRegionCounter(S);
  701. pushRegion(ExitCount);
  702. }
  703. void VisitCXXCatchStmt(const CXXCatchStmt *S) {
  704. propagateCounts(getRegionCounter(S), S->getHandlerBlock());
  705. }
  706. void VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
  707. extendRegion(E);
  708. Counter ParentCount = getRegion().getCounter();
  709. Counter TrueCount = getRegionCounter(E);
  710. Visit(E->getCond());
  711. if (!isa<BinaryConditionalOperator>(E)) {
  712. extendRegion(E->getTrueExpr());
  713. propagateCounts(TrueCount, E->getTrueExpr());
  714. }
  715. extendRegion(E->getFalseExpr());
  716. propagateCounts(subtractCounters(ParentCount, TrueCount),
  717. E->getFalseExpr());
  718. }
  719. void VisitBinLAnd(const BinaryOperator *E) {
  720. extendRegion(E);
  721. Visit(E->getLHS());
  722. extendRegion(E->getRHS());
  723. propagateCounts(getRegionCounter(E), E->getRHS());
  724. }
  725. void VisitBinLOr(const BinaryOperator *E) {
  726. extendRegion(E);
  727. Visit(E->getLHS());
  728. extendRegion(E->getRHS());
  729. propagateCounts(getRegionCounter(E), E->getRHS());
  730. }
  731. void VisitLambdaExpr(const LambdaExpr *LE) {
  732. // Lambdas are treated as their own functions for now, so we shouldn't
  733. // propagate counts into them.
  734. }
  735. };
  736. }
  737. static bool isMachO(const CodeGenModule &CGM) {
  738. return CGM.getTarget().getTriple().isOSBinFormatMachO();
  739. }
  740. static StringRef getCoverageSection(const CodeGenModule &CGM) {
  741. return llvm::getInstrProfCoverageSectionName(isMachO(CGM));
  742. }
  743. static void dump(llvm::raw_ostream &OS, StringRef FunctionName,
  744. ArrayRef<CounterExpression> Expressions,
  745. ArrayRef<CounterMappingRegion> Regions) {
  746. OS << FunctionName << ":\n";
  747. CounterMappingContext Ctx(Expressions);
  748. for (const auto &R : Regions) {
  749. OS.indent(2);
  750. switch (R.Kind) {
  751. case CounterMappingRegion::CodeRegion:
  752. break;
  753. case CounterMappingRegion::ExpansionRegion:
  754. OS << "Expansion,";
  755. break;
  756. case CounterMappingRegion::SkippedRegion:
  757. OS << "Skipped,";
  758. break;
  759. }
  760. OS << "File " << R.FileID << ", " << R.LineStart << ":" << R.ColumnStart
  761. << " -> " << R.LineEnd << ":" << R.ColumnEnd << " = ";
  762. Ctx.dump(R.Count, OS);
  763. if (R.Kind == CounterMappingRegion::ExpansionRegion)
  764. OS << " (Expanded file = " << R.ExpandedFileID << ")";
  765. OS << "\n";
  766. }
  767. }
  768. void CoverageMappingModuleGen::addFunctionMappingRecord(
  769. llvm::GlobalVariable *NamePtr, StringRef NameValue, uint64_t FuncHash,
  770. const std::string &CoverageMapping, bool IsUsed) {
  771. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  772. if (!FunctionRecordTy) {
  773. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) LLVMType,
  774. llvm::Type *FunctionRecordTypes[] = {
  775. #include "llvm/ProfileData/InstrProfData.inc"
  776. };
  777. FunctionRecordTy =
  778. llvm::StructType::get(Ctx, makeArrayRef(FunctionRecordTypes),
  779. /*isPacked=*/true);
  780. }
  781. #define COVMAP_FUNC_RECORD(Type, LLVMType, Name, Init) Init,
  782. llvm::Constant *FunctionRecordVals[] = {
  783. #include "llvm/ProfileData/InstrProfData.inc"
  784. };
  785. FunctionRecords.push_back(llvm::ConstantStruct::get(
  786. FunctionRecordTy, makeArrayRef(FunctionRecordVals)));
  787. if (!IsUsed)
  788. FunctionNames.push_back(
  789. llvm::ConstantExpr::getBitCast(NamePtr, llvm::Type::getInt8PtrTy(Ctx)));
  790. CoverageMappings.push_back(CoverageMapping);
  791. if (CGM.getCodeGenOpts().DumpCoverageMapping) {
  792. // Dump the coverage mapping data for this function by decoding the
  793. // encoded data. This allows us to dump the mapping regions which were
  794. // also processed by the CoverageMappingWriter which performs
  795. // additional minimization operations such as reducing the number of
  796. // expressions.
  797. std::vector<StringRef> Filenames;
  798. std::vector<CounterExpression> Expressions;
  799. std::vector<CounterMappingRegion> Regions;
  800. llvm::SmallVector<StringRef, 16> FilenameRefs;
  801. FilenameRefs.resize(FileEntries.size());
  802. for (const auto &Entry : FileEntries)
  803. FilenameRefs[Entry.second] = Entry.first->getName();
  804. RawCoverageMappingReader Reader(CoverageMapping, FilenameRefs, Filenames,
  805. Expressions, Regions);
  806. if (Reader.read())
  807. return;
  808. dump(llvm::outs(), NameValue, Expressions, Regions);
  809. }
  810. }
  811. void CoverageMappingModuleGen::emit() {
  812. if (FunctionRecords.empty())
  813. return;
  814. llvm::LLVMContext &Ctx = CGM.getLLVMContext();
  815. auto *Int32Ty = llvm::Type::getInt32Ty(Ctx);
  816. // Create the filenames and merge them with coverage mappings
  817. llvm::SmallVector<std::string, 16> FilenameStrs;
  818. llvm::SmallVector<StringRef, 16> FilenameRefs;
  819. FilenameStrs.resize(FileEntries.size());
  820. FilenameRefs.resize(FileEntries.size());
  821. for (const auto &Entry : FileEntries) {
  822. llvm::SmallString<256> Path(Entry.first->getName());
  823. llvm::sys::fs::make_absolute(Path);
  824. auto I = Entry.second;
  825. FilenameStrs[I] = std::string(Path.begin(), Path.end());
  826. FilenameRefs[I] = FilenameStrs[I];
  827. }
  828. std::string FilenamesAndCoverageMappings;
  829. llvm::raw_string_ostream OS(FilenamesAndCoverageMappings);
  830. CoverageFilenamesSectionWriter(FilenameRefs).write(OS);
  831. std::string RawCoverageMappings =
  832. llvm::join(CoverageMappings.begin(), CoverageMappings.end(), "");
  833. OS << RawCoverageMappings;
  834. size_t CoverageMappingSize = RawCoverageMappings.size();
  835. size_t FilenamesSize = OS.str().size() - CoverageMappingSize;
  836. // Append extra zeroes if necessary to ensure that the size of the filenames
  837. // and coverage mappings is a multiple of 8.
  838. if (size_t Rem = OS.str().size() % 8) {
  839. CoverageMappingSize += 8 - Rem;
  840. for (size_t I = 0, S = 8 - Rem; I < S; ++I)
  841. OS << '\0';
  842. }
  843. auto *FilenamesAndMappingsVal =
  844. llvm::ConstantDataArray::getString(Ctx, OS.str(), false);
  845. // Create the deferred function records array
  846. auto RecordsTy =
  847. llvm::ArrayType::get(FunctionRecordTy, FunctionRecords.size());
  848. auto RecordsVal = llvm::ConstantArray::get(RecordsTy, FunctionRecords);
  849. llvm::Type *CovDataHeaderTypes[] = {
  850. #define COVMAP_HEADER(Type, LLVMType, Name, Init) LLVMType,
  851. #include "llvm/ProfileData/InstrProfData.inc"
  852. };
  853. auto CovDataHeaderTy =
  854. llvm::StructType::get(Ctx, makeArrayRef(CovDataHeaderTypes));
  855. llvm::Constant *CovDataHeaderVals[] = {
  856. #define COVMAP_HEADER(Type, LLVMType, Name, Init) Init,
  857. #include "llvm/ProfileData/InstrProfData.inc"
  858. };
  859. auto CovDataHeaderVal = llvm::ConstantStruct::get(
  860. CovDataHeaderTy, makeArrayRef(CovDataHeaderVals));
  861. // Create the coverage data record
  862. llvm::Type *CovDataTypes[] = {CovDataHeaderTy, RecordsTy,
  863. FilenamesAndMappingsVal->getType()};
  864. auto CovDataTy = llvm::StructType::get(Ctx, makeArrayRef(CovDataTypes));
  865. llvm::Constant *TUDataVals[] = {CovDataHeaderVal, RecordsVal,
  866. FilenamesAndMappingsVal};
  867. auto CovDataVal =
  868. llvm::ConstantStruct::get(CovDataTy, makeArrayRef(TUDataVals));
  869. auto CovData = new llvm::GlobalVariable(
  870. CGM.getModule(), CovDataTy, true, llvm::GlobalValue::InternalLinkage,
  871. CovDataVal, llvm::getCoverageMappingVarName());
  872. CovData->setSection(getCoverageSection(CGM));
  873. CovData->setAlignment(8);
  874. // Make sure the data doesn't get deleted.
  875. CGM.addUsedGlobal(CovData);
  876. // Create the deferred function records array
  877. if (!FunctionNames.empty()) {
  878. auto NamesArrTy = llvm::ArrayType::get(llvm::Type::getInt8PtrTy(Ctx),
  879. FunctionNames.size());
  880. auto NamesArrVal = llvm::ConstantArray::get(NamesArrTy, FunctionNames);
  881. // This variable will *NOT* be emitted to the object file. It is used
  882. // to pass the list of names referenced to codegen.
  883. new llvm::GlobalVariable(CGM.getModule(), NamesArrTy, true,
  884. llvm::GlobalValue::InternalLinkage, NamesArrVal,
  885. llvm::getCoverageUnusedNamesVarName());
  886. }
  887. }
  888. unsigned CoverageMappingModuleGen::getFileID(const FileEntry *File) {
  889. auto It = FileEntries.find(File);
  890. if (It != FileEntries.end())
  891. return It->second;
  892. unsigned FileID = FileEntries.size();
  893. FileEntries.insert(std::make_pair(File, FileID));
  894. return FileID;
  895. }
  896. void CoverageMappingGen::emitCounterMapping(const Decl *D,
  897. llvm::raw_ostream &OS) {
  898. assert(CounterMap);
  899. CounterCoverageMappingBuilder Walker(CVM, *CounterMap, SM, LangOpts);
  900. Walker.VisitDecl(D);
  901. Walker.write(OS);
  902. }
  903. void CoverageMappingGen::emitEmptyMapping(const Decl *D,
  904. llvm::raw_ostream &OS) {
  905. EmptyCoverageMappingBuilder Walker(CVM, SM, LangOpts);
  906. Walker.VisitDecl(D);
  907. Walker.write(OS);
  908. }