CoverageMappingGen.cpp 51 KB

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