ScopeInfo.h 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ScopeInfo.h - Information about a semantic context -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines FunctionScopeInfo and its subclasses, which contain
  15. // information about a single function, block, lambda, or method body.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_CLANG_SEMA_SCOPEINFO_H
  19. #define LLVM_CLANG_SEMA_SCOPEINFO_H
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ExprCXX.h"
  22. #include "clang/AST/Type.h"
  23. #include "clang/Basic/CapturedStmt.h"
  24. #include "clang/Basic/LLVM.h"
  25. #include "clang/Basic/PartialDiagnostic.h"
  26. #include "clang/Basic/SourceLocation.h"
  27. #include "clang/Sema/CleanupInfo.h"
  28. #include "clang/Sema/DeclSpec.h"
  29. #include "llvm/ADT/DenseMap.h"
  30. #include "llvm/ADT/DenseMapInfo.h"
  31. #include "llvm/ADT/MapVector.h"
  32. #include "llvm/ADT/PointerIntPair.h"
  33. #include "llvm/ADT/SmallPtrSet.h"
  34. #include "llvm/ADT/SmallSet.h"
  35. #include "llvm/ADT/SmallVector.h"
  36. #include "llvm/ADT/StringRef.h"
  37. #include "llvm/ADT/StringSwitch.h"
  38. #include "llvm/ADT/TinyPtrVector.h"
  39. #include "llvm/Support/Casting.h"
  40. #include "llvm/Support/ErrorHandling.h"
  41. #include <algorithm>
  42. #include <cassert>
  43. #include <utility>
  44. namespace clang {
  45. class BlockDecl;
  46. class CapturedDecl;
  47. class CXXMethodDecl;
  48. class CXXRecordDecl;
  49. class ImplicitParamDecl;
  50. class NamedDecl;
  51. class ObjCIvarRefExpr;
  52. class ObjCMessageExpr;
  53. class ObjCPropertyDecl;
  54. class ObjCPropertyRefExpr;
  55. class ParmVarDecl;
  56. class RecordDecl;
  57. class ReturnStmt;
  58. class Scope;
  59. class Stmt;
  60. class SwitchStmt;
  61. class TemplateParameterList;
  62. class VarDecl;
  63. namespace sema {
  64. /// Contains information about the compound statement currently being
  65. /// parsed.
  66. class CompoundScopeInfo {
  67. public:
  68. /// Whether this compound stamement contains `for' or `while' loops
  69. /// with empty bodies.
  70. bool HasEmptyLoopBodies = false;
  71. /// Whether this compound statement corresponds to a GNU statement
  72. /// expression.
  73. bool IsStmtExpr;
  74. CompoundScopeInfo(bool IsStmtExpr) : IsStmtExpr(IsStmtExpr) {}
  75. void setHasEmptyLoopBodies() {
  76. HasEmptyLoopBodies = true;
  77. }
  78. };
  79. class PossiblyUnreachableDiag {
  80. public:
  81. PartialDiagnostic PD;
  82. SourceLocation Loc;
  83. llvm::TinyPtrVector<const Stmt*> Stmts;
  84. PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
  85. ArrayRef<const Stmt *> Stmts)
  86. : PD(PD), Loc(Loc), Stmts(Stmts) {}
  87. };
  88. /// Retains information about a function, method, or block that is
  89. /// currently being parsed.
  90. class FunctionScopeInfo {
  91. protected:
  92. enum ScopeKind {
  93. SK_Function,
  94. SK_Block,
  95. SK_Lambda,
  96. SK_CapturedRegion
  97. };
  98. public:
  99. /// What kind of scope we are describing.
  100. ScopeKind Kind : 3;
  101. /// Whether this function contains a VLA, \@try, try, C++
  102. /// initializer, or anything else that can't be jumped past.
  103. bool HasBranchProtectedScope : 1;
  104. /// Whether this function contains any switches or direct gotos.
  105. bool HasBranchIntoScope : 1;
  106. /// Whether this function contains any indirect gotos.
  107. bool HasIndirectGoto : 1;
  108. /// Whether this function contains any statement marked with
  109. /// \c [[clang::musttail]].
  110. bool HasMustTail : 1;
  111. /// Whether a statement was dropped because it was invalid.
  112. bool HasDroppedStmt : 1;
  113. /// True if current scope is for OpenMP declare reduction combiner.
  114. bool HasOMPDeclareReductionCombiner : 1;
  115. /// Whether there is a fallthrough statement in this function.
  116. bool HasFallthroughStmt : 1;
  117. /// Whether this function uses constrained floating point intrinsics
  118. bool UsesFPIntrin : 1;
  119. /// Whether we make reference to a declaration that could be
  120. /// unavailable.
  121. bool HasPotentialAvailabilityViolations : 1;
  122. /// A flag that is set when parsing a method that must call super's
  123. /// implementation, such as \c -dealloc, \c -finalize, or any method marked
  124. /// with \c __attribute__((objc_requires_super)).
  125. bool ObjCShouldCallSuper : 1;
  126. /// True when this is a method marked as a designated initializer.
  127. bool ObjCIsDesignatedInit : 1;
  128. /// This starts true for a method marked as designated initializer and will
  129. /// be set to false if there is an invocation to a designated initializer of
  130. /// the super class.
  131. bool ObjCWarnForNoDesignatedInitChain : 1;
  132. /// True when this is an initializer method not marked as a designated
  133. /// initializer within a class that has at least one initializer marked as a
  134. /// designated initializer.
  135. bool ObjCIsSecondaryInit : 1;
  136. /// This starts true for a secondary initializer method and will be set to
  137. /// false if there is an invocation of an initializer on 'self'.
  138. bool ObjCWarnForNoInitDelegation : 1;
  139. /// True only when this function has not already built, or attempted
  140. /// to build, the initial and final coroutine suspend points
  141. bool NeedsCoroutineSuspends : 1;
  142. /// An enumeration represeting the kind of the first coroutine statement
  143. /// in the function. One of co_return, co_await, or co_yield.
  144. unsigned char FirstCoroutineStmtKind : 2;
  145. /// First coroutine statement in the current function.
  146. /// (ex co_return, co_await, co_yield)
  147. SourceLocation FirstCoroutineStmtLoc;
  148. /// First 'return' statement in the current function.
  149. SourceLocation FirstReturnLoc;
  150. /// First C++ 'try' or ObjC @try statement in the current function.
  151. SourceLocation FirstCXXOrObjCTryLoc;
  152. enum { TryLocIsCXX, TryLocIsObjC, Unknown } FirstTryType = Unknown;
  153. /// First SEH '__try' statement in the current function.
  154. SourceLocation FirstSEHTryLoc;
  155. private:
  156. /// Used to determine if errors occurred in this function or block.
  157. DiagnosticErrorTrap ErrorTrap;
  158. public:
  159. /// A SwitchStmt, along with a flag indicating if its list of case statements
  160. /// is incomplete (because we dropped an invalid one while parsing).
  161. using SwitchInfo = llvm::PointerIntPair<SwitchStmt*, 1, bool>;
  162. /// SwitchStack - This is the current set of active switch statements in the
  163. /// block.
  164. SmallVector<SwitchInfo, 8> SwitchStack;
  165. /// The list of return statements that occur within the function or
  166. /// block, if there is any chance of applying the named return value
  167. /// optimization, or if we need to infer a return type.
  168. SmallVector<ReturnStmt*, 4> Returns;
  169. /// The promise object for this coroutine, if any.
  170. VarDecl *CoroutinePromise = nullptr;
  171. /// A mapping between the coroutine function parameters that were moved
  172. /// to the coroutine frame, and their move statements.
  173. llvm::SmallMapVector<ParmVarDecl *, Stmt *, 4> CoroutineParameterMoves;
  174. /// The initial and final coroutine suspend points.
  175. std::pair<Stmt *, Stmt *> CoroutineSuspends;
  176. /// The stack of currently active compound stamement scopes in the
  177. /// function.
  178. SmallVector<CompoundScopeInfo, 4> CompoundScopes;
  179. /// The set of blocks that are introduced in this function.
  180. llvm::SmallPtrSet<const BlockDecl *, 1> Blocks;
  181. /// The set of __block variables that are introduced in this function.
  182. llvm::TinyPtrVector<VarDecl *> ByrefBlockVars;
  183. /// A list of PartialDiagnostics created but delayed within the
  184. /// current function scope. These diagnostics are vetted for reachability
  185. /// prior to being emitted.
  186. SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
  187. /// A list of parameters which have the nonnull attribute and are
  188. /// modified in the function.
  189. llvm::SmallPtrSet<const ParmVarDecl *, 8> ModifiedNonNullParams;
  190. public:
  191. /// Represents a simple identification of a weak object.
  192. ///
  193. /// Part of the implementation of -Wrepeated-use-of-weak.
  194. ///
  195. /// This is used to determine if two weak accesses refer to the same object.
  196. /// Here are some examples of how various accesses are "profiled":
  197. ///
  198. /// Access Expression | "Base" Decl | "Property" Decl
  199. /// :---------------: | :-----------------: | :------------------------------:
  200. /// self.property | self (VarDecl) | property (ObjCPropertyDecl)
  201. /// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl)
  202. /// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
  203. /// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl)
  204. /// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl)
  205. /// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl)
  206. /// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
  207. /// MyClass.foo.prop | +foo (ObjCMethodDecl) | -prop (ObjCPropertyDecl)
  208. /// weakVar | 0 (known) | weakVar (VarDecl)
  209. /// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl)
  210. ///
  211. /// Objects are identified with only two Decls to make it reasonably fast to
  212. /// compare them.
  213. class WeakObjectProfileTy {
  214. /// The base object decl, as described in the class documentation.
  215. ///
  216. /// The extra flag is "true" if the Base and Property are enough to uniquely
  217. /// identify the object in memory.
  218. ///
  219. /// \sa isExactProfile()
  220. using BaseInfoTy = llvm::PointerIntPair<const NamedDecl *, 1, bool>;
  221. BaseInfoTy Base;
  222. /// The "property" decl, as described in the class documentation.
  223. ///
  224. /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
  225. /// case of "implicit" properties (regular methods accessed via dot syntax).
  226. const NamedDecl *Property = nullptr;
  227. /// Used to find the proper base profile for a given base expression.
  228. static BaseInfoTy getBaseInfo(const Expr *BaseE);
  229. inline WeakObjectProfileTy();
  230. static inline WeakObjectProfileTy getSentinel();
  231. public:
  232. WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
  233. WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
  234. WeakObjectProfileTy(const DeclRefExpr *RE);
  235. WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
  236. const NamedDecl *getBase() const { return Base.getPointer(); }
  237. const NamedDecl *getProperty() const { return Property; }
  238. /// Returns true if the object base specifies a known object in memory,
  239. /// rather than, say, an instance variable or property of another object.
  240. ///
  241. /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
  242. /// considered an exact profile if \c foo is a local variable, even if
  243. /// another variable \c foo2 refers to the same object as \c foo.
  244. ///
  245. /// For increased precision, accesses with base variables that are
  246. /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
  247. /// be exact, though this is not true for arbitrary variables
  248. /// (foo.prop1.prop2).
  249. bool isExactProfile() const {
  250. return Base.getInt();
  251. }
  252. bool operator==(const WeakObjectProfileTy &Other) const {
  253. return Base == Other.Base && Property == Other.Property;
  254. }
  255. // For use in DenseMap.
  256. // We can't specialize the usual llvm::DenseMapInfo at the end of the file
  257. // because by that point the DenseMap in FunctionScopeInfo has already been
  258. // instantiated.
  259. class DenseMapInfo {
  260. public:
  261. static inline WeakObjectProfileTy getEmptyKey() {
  262. return WeakObjectProfileTy();
  263. }
  264. static inline WeakObjectProfileTy getTombstoneKey() {
  265. return WeakObjectProfileTy::getSentinel();
  266. }
  267. static unsigned getHashValue(const WeakObjectProfileTy &Val) {
  268. using Pair = std::pair<BaseInfoTy, const NamedDecl *>;
  269. return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
  270. Val.Property));
  271. }
  272. static bool isEqual(const WeakObjectProfileTy &LHS,
  273. const WeakObjectProfileTy &RHS) {
  274. return LHS == RHS;
  275. }
  276. };
  277. };
  278. /// Represents a single use of a weak object.
  279. ///
  280. /// Stores both the expression and whether the access is potentially unsafe
  281. /// (i.e. it could potentially be warned about).
  282. ///
  283. /// Part of the implementation of -Wrepeated-use-of-weak.
  284. class WeakUseTy {
  285. llvm::PointerIntPair<const Expr *, 1, bool> Rep;
  286. public:
  287. WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
  288. const Expr *getUseExpr() const { return Rep.getPointer(); }
  289. bool isUnsafe() const { return Rep.getInt(); }
  290. void markSafe() { Rep.setInt(false); }
  291. bool operator==(const WeakUseTy &Other) const {
  292. return Rep == Other.Rep;
  293. }
  294. };
  295. /// Used to collect uses of a particular weak object in a function body.
  296. ///
  297. /// Part of the implementation of -Wrepeated-use-of-weak.
  298. using WeakUseVector = SmallVector<WeakUseTy, 4>;
  299. /// Used to collect all uses of weak objects in a function body.
  300. ///
  301. /// Part of the implementation of -Wrepeated-use-of-weak.
  302. using WeakObjectUseMap =
  303. llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
  304. WeakObjectProfileTy::DenseMapInfo>;
  305. private:
  306. /// Used to collect all uses of weak objects in this function body.
  307. ///
  308. /// Part of the implementation of -Wrepeated-use-of-weak.
  309. WeakObjectUseMap WeakObjectUses;
  310. protected:
  311. FunctionScopeInfo(const FunctionScopeInfo&) = default;
  312. public:
  313. FunctionScopeInfo(DiagnosticsEngine &Diag)
  314. : Kind(SK_Function), HasBranchProtectedScope(false),
  315. HasBranchIntoScope(false), HasIndirectGoto(false), HasMustTail(false),
  316. HasDroppedStmt(false), HasOMPDeclareReductionCombiner(false),
  317. HasFallthroughStmt(false), UsesFPIntrin(false),
  318. HasPotentialAvailabilityViolations(false), ObjCShouldCallSuper(false),
  319. ObjCIsDesignatedInit(false), ObjCWarnForNoDesignatedInitChain(false),
  320. ObjCIsSecondaryInit(false), ObjCWarnForNoInitDelegation(false),
  321. NeedsCoroutineSuspends(true), ErrorTrap(Diag) {}
  322. virtual ~FunctionScopeInfo();
  323. /// Determine whether an unrecoverable error has occurred within this
  324. /// function. Note that this may return false even if the function body is
  325. /// invalid, because the errors may be suppressed if they're caused by prior
  326. /// invalid declarations.
  327. ///
  328. /// FIXME: Migrate the caller of this to use containsErrors() instead once
  329. /// it's ready.
  330. bool hasUnrecoverableErrorOccurred() const {
  331. return ErrorTrap.hasUnrecoverableErrorOccurred();
  332. }
  333. /// Record that a weak object was accessed.
  334. ///
  335. /// Part of the implementation of -Wrepeated-use-of-weak.
  336. template <typename ExprT>
  337. inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
  338. void recordUseOfWeak(const ObjCMessageExpr *Msg,
  339. const ObjCPropertyDecl *Prop);
  340. /// Record that a given expression is a "safe" access of a weak object (e.g.
  341. /// assigning it to a strong variable.)
  342. ///
  343. /// Part of the implementation of -Wrepeated-use-of-weak.
  344. void markSafeWeakUse(const Expr *E);
  345. const WeakObjectUseMap &getWeakObjectUses() const {
  346. return WeakObjectUses;
  347. }
  348. void setHasBranchIntoScope() {
  349. HasBranchIntoScope = true;
  350. }
  351. void setHasBranchProtectedScope() {
  352. HasBranchProtectedScope = true;
  353. }
  354. void setHasIndirectGoto() {
  355. HasIndirectGoto = true;
  356. }
  357. void setHasMustTail() { HasMustTail = true; }
  358. void setHasDroppedStmt() {
  359. HasDroppedStmt = true;
  360. }
  361. void setHasOMPDeclareReductionCombiner() {
  362. HasOMPDeclareReductionCombiner = true;
  363. }
  364. void setHasFallthroughStmt() {
  365. HasFallthroughStmt = true;
  366. }
  367. void setUsesFPIntrin() {
  368. UsesFPIntrin = true;
  369. }
  370. void setHasCXXTry(SourceLocation TryLoc) {
  371. setHasBranchProtectedScope();
  372. FirstCXXOrObjCTryLoc = TryLoc;
  373. FirstTryType = TryLocIsCXX;
  374. }
  375. void setHasObjCTry(SourceLocation TryLoc) {
  376. setHasBranchProtectedScope();
  377. FirstCXXOrObjCTryLoc = TryLoc;
  378. FirstTryType = TryLocIsObjC;
  379. }
  380. void setHasSEHTry(SourceLocation TryLoc) {
  381. setHasBranchProtectedScope();
  382. FirstSEHTryLoc = TryLoc;
  383. }
  384. bool NeedsScopeChecking() const {
  385. return !HasDroppedStmt && (HasIndirectGoto || HasMustTail ||
  386. (HasBranchProtectedScope && HasBranchIntoScope));
  387. }
  388. // Add a block introduced in this function.
  389. void addBlock(const BlockDecl *BD) {
  390. Blocks.insert(BD);
  391. }
  392. // Add a __block variable introduced in this function.
  393. void addByrefBlockVar(VarDecl *VD) {
  394. ByrefBlockVars.push_back(VD);
  395. }
  396. bool isCoroutine() const { return !FirstCoroutineStmtLoc.isInvalid(); }
  397. void setFirstCoroutineStmt(SourceLocation Loc, StringRef Keyword) {
  398. assert(FirstCoroutineStmtLoc.isInvalid() &&
  399. "first coroutine statement location already set");
  400. FirstCoroutineStmtLoc = Loc;
  401. FirstCoroutineStmtKind = llvm::StringSwitch<unsigned char>(Keyword)
  402. .Case("co_return", 0)
  403. .Case("co_await", 1)
  404. .Case("co_yield", 2);
  405. }
  406. StringRef getFirstCoroutineStmtKeyword() const {
  407. assert(FirstCoroutineStmtLoc.isValid()
  408. && "no coroutine statement available");
  409. switch (FirstCoroutineStmtKind) {
  410. case 0: return "co_return";
  411. case 1: return "co_await";
  412. case 2: return "co_yield";
  413. default:
  414. llvm_unreachable("FirstCoroutineStmtKind has an invalid value");
  415. };
  416. }
  417. void setNeedsCoroutineSuspends(bool value = true) {
  418. assert((!value || CoroutineSuspends.first == nullptr) &&
  419. "we already have valid suspend points");
  420. NeedsCoroutineSuspends = value;
  421. }
  422. bool hasInvalidCoroutineSuspends() const {
  423. return !NeedsCoroutineSuspends && CoroutineSuspends.first == nullptr;
  424. }
  425. void setCoroutineSuspends(Stmt *Initial, Stmt *Final) {
  426. assert(Initial && Final && "suspend points cannot be null");
  427. assert(CoroutineSuspends.first == nullptr && "suspend points already set");
  428. NeedsCoroutineSuspends = false;
  429. CoroutineSuspends.first = Initial;
  430. CoroutineSuspends.second = Final;
  431. }
  432. /// Clear out the information in this function scope, making it
  433. /// suitable for reuse.
  434. void Clear();
  435. bool isPlainFunction() const { return Kind == SK_Function; }
  436. };
  437. class Capture {
  438. // There are three categories of capture: capturing 'this', capturing
  439. // local variables, and C++1y initialized captures (which can have an
  440. // arbitrary initializer, and don't really capture in the traditional
  441. // sense at all).
  442. //
  443. // There are three ways to capture a local variable:
  444. // - capture by copy in the C++11 sense,
  445. // - capture by reference in the C++11 sense, and
  446. // - __block capture.
  447. // Lambdas explicitly specify capture by copy or capture by reference.
  448. // For blocks, __block capture applies to variables with that annotation,
  449. // variables of reference type are captured by reference, and other
  450. // variables are captured by copy.
  451. enum CaptureKind {
  452. Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
  453. };
  454. union {
  455. /// If Kind == Cap_VLA, the captured type.
  456. const VariableArrayType *CapturedVLA;
  457. /// Otherwise, the captured variable (if any).
  458. VarDecl *CapturedVar;
  459. };
  460. /// The source location at which the first capture occurred.
  461. SourceLocation Loc;
  462. /// The location of the ellipsis that expands a parameter pack.
  463. SourceLocation EllipsisLoc;
  464. /// The type as it was captured, which is the type of the non-static data
  465. /// member that would hold the capture.
  466. QualType CaptureType;
  467. /// The CaptureKind of this capture.
  468. unsigned Kind : 2;
  469. /// Whether this is a nested capture (a capture of an enclosing capturing
  470. /// scope's capture).
  471. unsigned Nested : 1;
  472. /// Whether this is a capture of '*this'.
  473. unsigned CapturesThis : 1;
  474. /// Whether an explicit capture has been odr-used in the body of the
  475. /// lambda.
  476. unsigned ODRUsed : 1;
  477. /// Whether an explicit capture has been non-odr-used in the body of
  478. /// the lambda.
  479. unsigned NonODRUsed : 1;
  480. /// Whether the capture is invalid (a capture was required but the entity is
  481. /// non-capturable).
  482. unsigned Invalid : 1;
  483. public:
  484. Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
  485. SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType,
  486. bool Invalid)
  487. : CapturedVar(Var), Loc(Loc), EllipsisLoc(EllipsisLoc),
  488. CaptureType(CaptureType),
  489. Kind(Block ? Cap_Block : ByRef ? Cap_ByRef : Cap_ByCopy),
  490. Nested(IsNested), CapturesThis(false), ODRUsed(false),
  491. NonODRUsed(false), Invalid(Invalid) {}
  492. enum IsThisCapture { ThisCapture };
  493. Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
  494. QualType CaptureType, const bool ByCopy, bool Invalid)
  495. : Loc(Loc), CaptureType(CaptureType),
  496. Kind(ByCopy ? Cap_ByCopy : Cap_ByRef), Nested(IsNested),
  497. CapturesThis(true), ODRUsed(false), NonODRUsed(false),
  498. Invalid(Invalid) {}
  499. enum IsVLACapture { VLACapture };
  500. Capture(IsVLACapture, const VariableArrayType *VLA, bool IsNested,
  501. SourceLocation Loc, QualType CaptureType)
  502. : CapturedVLA(VLA), Loc(Loc), CaptureType(CaptureType), Kind(Cap_VLA),
  503. Nested(IsNested), CapturesThis(false), ODRUsed(false),
  504. NonODRUsed(false), Invalid(false) {}
  505. bool isThisCapture() const { return CapturesThis; }
  506. bool isVariableCapture() const {
  507. return !isThisCapture() && !isVLATypeCapture();
  508. }
  509. bool isCopyCapture() const { return Kind == Cap_ByCopy; }
  510. bool isReferenceCapture() const { return Kind == Cap_ByRef; }
  511. bool isBlockCapture() const { return Kind == Cap_Block; }
  512. bool isVLATypeCapture() const { return Kind == Cap_VLA; }
  513. bool isNested() const { return Nested; }
  514. bool isInvalid() const { return Invalid; }
  515. /// Determine whether this capture is an init-capture.
  516. bool isInitCapture() const;
  517. bool isODRUsed() const { return ODRUsed; }
  518. bool isNonODRUsed() const { return NonODRUsed; }
  519. void markUsed(bool IsODRUse) {
  520. if (IsODRUse)
  521. ODRUsed = true;
  522. else
  523. NonODRUsed = true;
  524. }
  525. VarDecl *getVariable() const {
  526. assert(isVariableCapture());
  527. return CapturedVar;
  528. }
  529. const VariableArrayType *getCapturedVLAType() const {
  530. assert(isVLATypeCapture());
  531. return CapturedVLA;
  532. }
  533. /// Retrieve the location at which this variable was captured.
  534. SourceLocation getLocation() const { return Loc; }
  535. /// Retrieve the source location of the ellipsis, whose presence
  536. /// indicates that the capture is a pack expansion.
  537. SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
  538. /// Retrieve the capture type for this capture, which is effectively
  539. /// the type of the non-static data member in the lambda/block structure
  540. /// that would store this capture.
  541. QualType getCaptureType() const { return CaptureType; }
  542. };
  543. class CapturingScopeInfo : public FunctionScopeInfo {
  544. protected:
  545. CapturingScopeInfo(const CapturingScopeInfo&) = default;
  546. public:
  547. enum ImplicitCaptureStyle {
  548. ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
  549. ImpCap_CapturedRegion
  550. };
  551. ImplicitCaptureStyle ImpCaptureStyle;
  552. CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
  553. : FunctionScopeInfo(Diag), ImpCaptureStyle(Style) {}
  554. /// CaptureMap - A map of captured variables to (index+1) into Captures.
  555. llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
  556. /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
  557. /// zero if 'this' is not captured.
  558. unsigned CXXThisCaptureIndex = 0;
  559. /// Captures - The captures.
  560. SmallVector<Capture, 4> Captures;
  561. /// - Whether the target type of return statements in this context
  562. /// is deduced (e.g. a lambda or block with omitted return type).
  563. bool HasImplicitReturnType = false;
  564. /// ReturnType - The target type of return statements in this context,
  565. /// or null if unknown.
  566. QualType ReturnType;
  567. void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
  568. SourceLocation Loc, SourceLocation EllipsisLoc,
  569. QualType CaptureType, bool Invalid) {
  570. Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
  571. EllipsisLoc, CaptureType, Invalid));
  572. CaptureMap[Var] = Captures.size();
  573. }
  574. void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType,
  575. QualType CaptureType) {
  576. Captures.push_back(Capture(Capture::VLACapture, VLAType,
  577. /*FIXME: IsNested*/ false, Loc, CaptureType));
  578. }
  579. void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
  580. bool ByCopy);
  581. /// Determine whether the C++ 'this' is captured.
  582. bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
  583. /// Retrieve the capture of C++ 'this', if it has been captured.
  584. Capture &getCXXThisCapture() {
  585. assert(isCXXThisCaptured() && "this has not been captured");
  586. return Captures[CXXThisCaptureIndex - 1];
  587. }
  588. /// Determine whether the given variable has been captured.
  589. bool isCaptured(VarDecl *Var) const {
  590. return CaptureMap.count(Var);
  591. }
  592. /// Determine whether the given variable-array type has been captured.
  593. bool isVLATypeCaptured(const VariableArrayType *VAT) const;
  594. /// Retrieve the capture of the given variable, if it has been
  595. /// captured already.
  596. Capture &getCapture(VarDecl *Var) {
  597. assert(isCaptured(Var) && "Variable has not been captured");
  598. return Captures[CaptureMap[Var] - 1];
  599. }
  600. const Capture &getCapture(VarDecl *Var) const {
  601. llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
  602. = CaptureMap.find(Var);
  603. assert(Known != CaptureMap.end() && "Variable has not been captured");
  604. return Captures[Known->second - 1];
  605. }
  606. static bool classof(const FunctionScopeInfo *FSI) {
  607. return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
  608. || FSI->Kind == SK_CapturedRegion;
  609. }
  610. };
  611. /// Retains information about a block that is currently being parsed.
  612. class BlockScopeInfo final : public CapturingScopeInfo {
  613. public:
  614. BlockDecl *TheDecl;
  615. /// TheScope - This is the scope for the block itself, which contains
  616. /// arguments etc.
  617. Scope *TheScope;
  618. /// BlockType - The function type of the block, if one was given.
  619. /// Its return type may be BuiltinType::Dependent.
  620. QualType FunctionType;
  621. BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
  622. : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
  623. TheScope(BlockScope) {
  624. Kind = SK_Block;
  625. }
  626. ~BlockScopeInfo() override;
  627. static bool classof(const FunctionScopeInfo *FSI) {
  628. return FSI->Kind == SK_Block;
  629. }
  630. };
  631. /// Retains information about a captured region.
  632. class CapturedRegionScopeInfo final : public CapturingScopeInfo {
  633. public:
  634. /// The CapturedDecl for this statement.
  635. CapturedDecl *TheCapturedDecl;
  636. /// The captured record type.
  637. RecordDecl *TheRecordDecl;
  638. /// This is the enclosing scope of the captured region.
  639. Scope *TheScope;
  640. /// The implicit parameter for the captured variables.
  641. ImplicitParamDecl *ContextParam;
  642. /// The kind of captured region.
  643. unsigned short CapRegionKind;
  644. unsigned short OpenMPLevel;
  645. unsigned short OpenMPCaptureLevel;
  646. CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
  647. RecordDecl *RD, ImplicitParamDecl *Context,
  648. CapturedRegionKind K, unsigned OpenMPLevel,
  649. unsigned OpenMPCaptureLevel)
  650. : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
  651. TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
  652. ContextParam(Context), CapRegionKind(K), OpenMPLevel(OpenMPLevel),
  653. OpenMPCaptureLevel(OpenMPCaptureLevel) {
  654. Kind = SK_CapturedRegion;
  655. }
  656. ~CapturedRegionScopeInfo() override;
  657. /// A descriptive name for the kind of captured region this is.
  658. StringRef getRegionName() const {
  659. switch (CapRegionKind) {
  660. case CR_Default:
  661. return "default captured statement";
  662. case CR_ObjCAtFinally:
  663. return "Objective-C @finally statement";
  664. case CR_OpenMP:
  665. return "OpenMP region";
  666. }
  667. llvm_unreachable("Invalid captured region kind!");
  668. }
  669. static bool classof(const FunctionScopeInfo *FSI) {
  670. return FSI->Kind == SK_CapturedRegion;
  671. }
  672. };
  673. class LambdaScopeInfo final :
  674. public CapturingScopeInfo, public InventedTemplateParameterInfo {
  675. public:
  676. /// The class that describes the lambda.
  677. CXXRecordDecl *Lambda = nullptr;
  678. /// The lambda's compiler-generated \c operator().
  679. CXXMethodDecl *CallOperator = nullptr;
  680. /// Source range covering the lambda introducer [...].
  681. SourceRange IntroducerRange;
  682. /// Source location of the '&' or '=' specifying the default capture
  683. /// type, if any.
  684. SourceLocation CaptureDefaultLoc;
  685. /// The number of captures in the \c Captures list that are
  686. /// explicit captures.
  687. unsigned NumExplicitCaptures = 0;
  688. /// Whether this is a mutable lambda.
  689. bool Mutable = false;
  690. /// Whether the (empty) parameter list is explicit.
  691. bool ExplicitParams = false;
  692. /// Whether any of the capture expressions requires cleanups.
  693. CleanupInfo Cleanup;
  694. /// Whether the lambda contains an unexpanded parameter pack.
  695. bool ContainsUnexpandedParameterPack = false;
  696. /// Packs introduced by this lambda, if any.
  697. SmallVector<NamedDecl*, 4> LocalPacks;
  698. /// Source range covering the explicit template parameter list (if it exists).
  699. SourceRange ExplicitTemplateParamsRange;
  700. /// The requires-clause immediately following the explicit template parameter
  701. /// list, if any. (Note that there may be another requires-clause included as
  702. /// part of the lambda-declarator.)
  703. ExprResult RequiresClause;
  704. /// If this is a generic lambda, and the template parameter
  705. /// list has been created (from the TemplateParams) then store
  706. /// a reference to it (cache it to avoid reconstructing it).
  707. TemplateParameterList *GLTemplateParameterList = nullptr;
  708. /// Contains all variable-referring-expressions (i.e. DeclRefExprs
  709. /// or MemberExprs) that refer to local variables in a generic lambda
  710. /// or a lambda in a potentially-evaluated-if-used context.
  711. ///
  712. /// Potentially capturable variables of a nested lambda that might need
  713. /// to be captured by the lambda are housed here.
  714. /// This is specifically useful for generic lambdas or
  715. /// lambdas within a potentially evaluated-if-used context.
  716. /// If an enclosing variable is named in an expression of a lambda nested
  717. /// within a generic lambda, we don't always know know whether the variable
  718. /// will truly be odr-used (i.e. need to be captured) by that nested lambda,
  719. /// until its instantiation. But we still need to capture it in the
  720. /// enclosing lambda if all intervening lambdas can capture the variable.
  721. llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
  722. /// Contains all variable-referring-expressions that refer
  723. /// to local variables that are usable as constant expressions and
  724. /// do not involve an odr-use (they may still need to be captured
  725. /// if the enclosing full-expression is instantiation dependent).
  726. llvm::SmallSet<Expr *, 8> NonODRUsedCapturingExprs;
  727. /// A map of explicit capture indices to their introducer source ranges.
  728. llvm::DenseMap<unsigned, SourceRange> ExplicitCaptureRanges;
  729. /// Contains all of the variables defined in this lambda that shadow variables
  730. /// that were defined in parent contexts. Used to avoid warnings when the
  731. /// shadowed variables are uncaptured by this lambda.
  732. struct ShadowedOuterDecl {
  733. const VarDecl *VD;
  734. const VarDecl *ShadowedDecl;
  735. };
  736. llvm::SmallVector<ShadowedOuterDecl, 4> ShadowingDecls;
  737. SourceLocation PotentialThisCaptureLocation;
  738. LambdaScopeInfo(DiagnosticsEngine &Diag)
  739. : CapturingScopeInfo(Diag, ImpCap_None) {
  740. Kind = SK_Lambda;
  741. }
  742. /// Note when all explicit captures have been added.
  743. void finishedExplicitCaptures() {
  744. NumExplicitCaptures = Captures.size();
  745. }
  746. static bool classof(const FunctionScopeInfo *FSI) {
  747. return FSI->Kind == SK_Lambda;
  748. }
  749. /// Is this scope known to be for a generic lambda? (This will be false until
  750. /// we parse a template parameter list or the first 'auto'-typed parameter).
  751. bool isGenericLambda() const {
  752. return !TemplateParams.empty() || GLTemplateParameterList;
  753. }
  754. /// Add a variable that might potentially be captured by the
  755. /// lambda and therefore the enclosing lambdas.
  756. ///
  757. /// This is also used by enclosing lambda's to speculatively capture
  758. /// variables that nested lambda's - depending on their enclosing
  759. /// specialization - might need to capture.
  760. /// Consider:
  761. /// void f(int, int); <-- don't capture
  762. /// void f(const int&, double); <-- capture
  763. /// void foo() {
  764. /// const int x = 10;
  765. /// auto L = [=](auto a) { // capture 'x'
  766. /// return [=](auto b) {
  767. /// f(x, a); // we may or may not need to capture 'x'
  768. /// };
  769. /// };
  770. /// }
  771. void addPotentialCapture(Expr *VarExpr) {
  772. assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr) ||
  773. isa<FunctionParmPackExpr>(VarExpr));
  774. PotentiallyCapturingExprs.push_back(VarExpr);
  775. }
  776. void addPotentialThisCapture(SourceLocation Loc) {
  777. PotentialThisCaptureLocation = Loc;
  778. }
  779. bool hasPotentialThisCapture() const {
  780. return PotentialThisCaptureLocation.isValid();
  781. }
  782. /// Mark a variable's reference in a lambda as non-odr using.
  783. ///
  784. /// For generic lambdas, if a variable is named in a potentially evaluated
  785. /// expression, where the enclosing full expression is dependent then we
  786. /// must capture the variable (given a default capture).
  787. /// This is accomplished by recording all references to variables
  788. /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
  789. /// PotentialCaptures. All such variables have to be captured by that lambda,
  790. /// except for as described below.
  791. /// If that variable is usable as a constant expression and is named in a
  792. /// manner that does not involve its odr-use (e.g. undergoes
  793. /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
  794. /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
  795. /// if we can determine that the full expression is not instantiation-
  796. /// dependent, then we can entirely avoid its capture.
  797. ///
  798. /// const int n = 0;
  799. /// [&] (auto x) {
  800. /// (void)+n + x;
  801. /// };
  802. /// Interestingly, this strategy would involve a capture of n, even though
  803. /// it's obviously not odr-used here, because the full-expression is
  804. /// instantiation-dependent. It could be useful to avoid capturing such
  805. /// variables, even when they are referred to in an instantiation-dependent
  806. /// expression, if we can unambiguously determine that they shall never be
  807. /// odr-used. This would involve removal of the variable-referring-expression
  808. /// from the array of PotentialCaptures during the lvalue-to-rvalue
  809. /// conversions. But per the working draft N3797, (post-chicago 2013) we must
  810. /// capture such variables.
  811. /// Before anyone is tempted to implement a strategy for not-capturing 'n',
  812. /// consider the insightful warning in:
  813. /// /cfe-commits/Week-of-Mon-20131104/092596.html
  814. /// "The problem is that the set of captures for a lambda is part of the ABI
  815. /// (since lambda layout can be made visible through inline functions and the
  816. /// like), and there are no guarantees as to which cases we'll manage to build
  817. /// an lvalue-to-rvalue conversion in, when parsing a template -- some
  818. /// seemingly harmless change elsewhere in Sema could cause us to start or stop
  819. /// building such a node. So we need a rule that anyone can implement and get
  820. /// exactly the same result".
  821. void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
  822. assert(isa<DeclRefExpr>(CapturingVarExpr) ||
  823. isa<MemberExpr>(CapturingVarExpr) ||
  824. isa<FunctionParmPackExpr>(CapturingVarExpr));
  825. NonODRUsedCapturingExprs.insert(CapturingVarExpr);
  826. }
  827. bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
  828. assert(isa<DeclRefExpr>(CapturingVarExpr) ||
  829. isa<MemberExpr>(CapturingVarExpr) ||
  830. isa<FunctionParmPackExpr>(CapturingVarExpr));
  831. return NonODRUsedCapturingExprs.count(CapturingVarExpr);
  832. }
  833. void removePotentialCapture(Expr *E) {
  834. llvm::erase_value(PotentiallyCapturingExprs, E);
  835. }
  836. void clearPotentialCaptures() {
  837. PotentiallyCapturingExprs.clear();
  838. PotentialThisCaptureLocation = SourceLocation();
  839. }
  840. unsigned getNumPotentialVariableCaptures() const {
  841. return PotentiallyCapturingExprs.size();
  842. }
  843. bool hasPotentialCaptures() const {
  844. return getNumPotentialVariableCaptures() ||
  845. PotentialThisCaptureLocation.isValid();
  846. }
  847. void visitPotentialCaptures(
  848. llvm::function_ref<void(VarDecl *, Expr *)> Callback) const;
  849. };
  850. FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
  851. : Base(nullptr, false) {}
  852. FunctionScopeInfo::WeakObjectProfileTy
  853. FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
  854. FunctionScopeInfo::WeakObjectProfileTy Result;
  855. Result.Base.setInt(true);
  856. return Result;
  857. }
  858. template <typename ExprT>
  859. void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
  860. assert(E);
  861. WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
  862. Uses.push_back(WeakUseTy(E, IsRead));
  863. }
  864. inline void CapturingScopeInfo::addThisCapture(bool isNested,
  865. SourceLocation Loc,
  866. QualType CaptureType,
  867. bool ByCopy) {
  868. Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
  869. ByCopy, /*Invalid*/ false));
  870. CXXThisCaptureIndex = Captures.size();
  871. }
  872. } // namespace sema
  873. } // namespace clang
  874. #endif // LLVM_CLANG_SEMA_SCOPEINFO_H
  875. #ifdef __GNUC__
  876. #pragma GCC diagnostic pop
  877. #endif