1 //===--- ScopeInfo.h - Information about a semantic context -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines FunctionScopeInfo and its subclasses, which contain
11 // information about a single function, block, lambda, or method body.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_SEMA_SCOPEINFO_H
16 #define LLVM_CLANG_SEMA_SCOPEINFO_H
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/Type.h"
20 #include "clang/Basic/CapturedStmt.h"
21 #include "clang/Basic/PartialDiagnostic.h"
22 #include "clang/Sema/Ownership.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/SmallVector.h"
35 class ObjCPropertyDecl;
37 class ImplicitParamDecl;
42 class TemplateTypeParmDecl;
43 class TemplateParameterList;
45 class ObjCIvarRefExpr;
46 class ObjCPropertyRefExpr;
47 class ObjCMessageExpr;
51 /// \brief Contains information about the compound statement currently being
53 class CompoundScopeInfo {
56 : HasEmptyLoopBodies(false) { }
58 /// \brief Whether this compound stamement contains `for' or `while' loops
59 /// with empty bodies.
60 bool HasEmptyLoopBodies;
62 void setHasEmptyLoopBodies() {
63 HasEmptyLoopBodies = true;
67 class PossiblyUnreachableDiag {
73 PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
75 : PD(PD), Loc(Loc), stmt(stmt) {}
78 /// \brief Retains information about a function, method, or block that is
79 /// currently being parsed.
80 class FunctionScopeInfo {
90 /// \brief What kind of scope we are describing.
94 /// \brief Whether this function contains a VLA, \@try, try, C++
95 /// initializer, or anything else that can't be jumped past.
96 bool HasBranchProtectedScope : 1;
98 /// \brief Whether this function contains any switches or direct gotos.
99 bool HasBranchIntoScope : 1;
101 /// \brief Whether this function contains any indirect gotos.
102 bool HasIndirectGoto : 1;
104 /// \brief Whether a statement was dropped because it was invalid.
105 bool HasDroppedStmt : 1;
107 /// \brief True if current scope is for OpenMP declare reduction combiner.
108 bool HasOMPDeclareReductionCombiner;
110 /// \brief Whether there is a fallthrough statement in this function.
111 bool HasFallthroughStmt : 1;
113 /// A flag that is set when parsing a method that must call super's
114 /// implementation, such as \c -dealloc, \c -finalize, or any method marked
115 /// with \c __attribute__((objc_requires_super)).
116 bool ObjCShouldCallSuper : 1;
118 /// True when this is a method marked as a designated initializer.
119 bool ObjCIsDesignatedInit : 1;
120 /// This starts true for a method marked as designated initializer and will
121 /// be set to false if there is an invocation to a designated initializer of
123 bool ObjCWarnForNoDesignatedInitChain : 1;
125 /// True when this is an initializer method not marked as a designated
126 /// initializer within a class that has at least one initializer marked as a
127 /// designated initializer.
128 bool ObjCIsSecondaryInit : 1;
129 /// This starts true for a secondary initializer method and will be set to
130 /// false if there is an invocation of an initializer on 'self'.
131 bool ObjCWarnForNoInitDelegation : 1;
133 /// First 'return' statement in the current function.
134 SourceLocation FirstReturnLoc;
136 /// First C++ 'try' statement in the current function.
137 SourceLocation FirstCXXTryLoc;
139 /// First SEH '__try' statement in the current function.
140 SourceLocation FirstSEHTryLoc;
142 /// \brief Used to determine if errors occurred in this function or block.
143 DiagnosticErrorTrap ErrorTrap;
145 /// SwitchStack - This is the current set of active switch statements in the
147 SmallVector<SwitchStmt*, 8> SwitchStack;
149 /// \brief The list of return statements that occur within the function or
150 /// block, if there is any chance of applying the named return value
151 /// optimization, or if we need to infer a return type.
152 SmallVector<ReturnStmt*, 4> Returns;
154 /// \brief The promise object for this coroutine, if any.
155 VarDecl *CoroutinePromise;
157 /// \brief The list of coroutine control flow constructs (co_await, co_yield,
158 /// co_return) that occur within the function or block. Empty if and only if
159 /// this function or block is not (yet known to be) a coroutine.
160 SmallVector<Stmt*, 4> CoroutineStmts;
162 /// \brief The stack of currently active compound stamement scopes in the
164 SmallVector<CompoundScopeInfo, 4> CompoundScopes;
166 /// \brief A list of PartialDiagnostics created but delayed within the
167 /// current function scope. These diagnostics are vetted for reachability
168 /// prior to being emitted.
169 SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
171 /// \brief A list of parameters which have the nonnull attribute and are
172 /// modified in the function.
173 llvm::SmallPtrSet<const ParmVarDecl*, 8> ModifiedNonNullParams;
176 /// Represents a simple identification of a weak object.
178 /// Part of the implementation of -Wrepeated-use-of-weak.
180 /// This is used to determine if two weak accesses refer to the same object.
181 /// Here are some examples of how various accesses are "profiled":
183 /// Access Expression | "Base" Decl | "Property" Decl
184 /// :---------------: | :-----------------: | :------------------------------:
185 /// self.property | self (VarDecl) | property (ObjCPropertyDecl)
186 /// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl)
187 /// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
188 /// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl)
189 /// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl)
190 /// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl)
191 /// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
192 /// MyClass.foo.prop | +foo (ObjCMethodDecl) | -prop (ObjCPropertyDecl)
193 /// weakVar | 0 (known) | weakVar (VarDecl)
194 /// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl)
196 /// Objects are identified with only two Decls to make it reasonably fast to
198 class WeakObjectProfileTy {
199 /// The base object decl, as described in the class documentation.
201 /// The extra flag is "true" if the Base and Property are enough to uniquely
202 /// identify the object in memory.
204 /// \sa isExactProfile()
205 typedef llvm::PointerIntPair<const NamedDecl *, 1, bool> BaseInfoTy;
208 /// The "property" decl, as described in the class documentation.
210 /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
211 /// case of "implicit" properties (regular methods accessed via dot syntax).
212 const NamedDecl *Property;
214 /// Used to find the proper base profile for a given base expression.
215 static BaseInfoTy getBaseInfo(const Expr *BaseE);
217 inline WeakObjectProfileTy();
218 static inline WeakObjectProfileTy getSentinel();
221 WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
222 WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
223 WeakObjectProfileTy(const DeclRefExpr *RE);
224 WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
226 const NamedDecl *getBase() const { return Base.getPointer(); }
227 const NamedDecl *getProperty() const { return Property; }
229 /// Returns true if the object base specifies a known object in memory,
230 /// rather than, say, an instance variable or property of another object.
232 /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
233 /// considered an exact profile if \c foo is a local variable, even if
234 /// another variable \c foo2 refers to the same object as \c foo.
236 /// For increased precision, accesses with base variables that are
237 /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
238 /// be exact, though this is not true for arbitrary variables
239 /// (foo.prop1.prop2).
240 bool isExactProfile() const {
241 return Base.getInt();
244 bool operator==(const WeakObjectProfileTy &Other) const {
245 return Base == Other.Base && Property == Other.Property;
248 // For use in DenseMap.
249 // We can't specialize the usual llvm::DenseMapInfo at the end of the file
250 // because by that point the DenseMap in FunctionScopeInfo has already been
254 static inline WeakObjectProfileTy getEmptyKey() {
255 return WeakObjectProfileTy();
257 static inline WeakObjectProfileTy getTombstoneKey() {
258 return WeakObjectProfileTy::getSentinel();
261 static unsigned getHashValue(const WeakObjectProfileTy &Val) {
262 typedef std::pair<BaseInfoTy, const NamedDecl *> Pair;
263 return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
267 static bool isEqual(const WeakObjectProfileTy &LHS,
268 const WeakObjectProfileTy &RHS) {
274 /// Represents a single use of a weak object.
276 /// Stores both the expression and whether the access is potentially unsafe
277 /// (i.e. it could potentially be warned about).
279 /// Part of the implementation of -Wrepeated-use-of-weak.
281 llvm::PointerIntPair<const Expr *, 1, bool> Rep;
283 WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
285 const Expr *getUseExpr() const { return Rep.getPointer(); }
286 bool isUnsafe() const { return Rep.getInt(); }
287 void markSafe() { Rep.setInt(false); }
289 bool operator==(const WeakUseTy &Other) const {
290 return Rep == Other.Rep;
294 /// Used to collect uses of a particular weak object in a function body.
296 /// Part of the implementation of -Wrepeated-use-of-weak.
297 typedef SmallVector<WeakUseTy, 4> WeakUseVector;
299 /// Used to collect all uses of weak objects in a function body.
301 /// Part of the implementation of -Wrepeated-use-of-weak.
302 typedef llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
303 WeakObjectProfileTy::DenseMapInfo>
307 /// Used to collect all uses of weak objects in this function body.
309 /// Part of the implementation of -Wrepeated-use-of-weak.
310 WeakObjectUseMap WeakObjectUses;
313 FunctionScopeInfo(const FunctionScopeInfo&) = default;
316 /// Record that a weak object was accessed.
318 /// Part of the implementation of -Wrepeated-use-of-weak.
319 template <typename ExprT>
320 inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
322 void recordUseOfWeak(const ObjCMessageExpr *Msg,
323 const ObjCPropertyDecl *Prop);
325 /// Record that a given expression is a "safe" access of a weak object (e.g.
326 /// assigning it to a strong variable.)
328 /// Part of the implementation of -Wrepeated-use-of-weak.
329 void markSafeWeakUse(const Expr *E);
331 const WeakObjectUseMap &getWeakObjectUses() const {
332 return WeakObjectUses;
335 void setHasBranchIntoScope() {
336 HasBranchIntoScope = true;
339 void setHasBranchProtectedScope() {
340 HasBranchProtectedScope = true;
343 void setHasIndirectGoto() {
344 HasIndirectGoto = true;
347 void setHasDroppedStmt() {
348 HasDroppedStmt = true;
351 void setHasOMPDeclareReductionCombiner() {
352 HasOMPDeclareReductionCombiner = true;
355 void setHasFallthroughStmt() {
356 HasFallthroughStmt = true;
359 void setHasCXXTry(SourceLocation TryLoc) {
360 setHasBranchProtectedScope();
361 FirstCXXTryLoc = TryLoc;
364 void setHasSEHTry(SourceLocation TryLoc) {
365 setHasBranchProtectedScope();
366 FirstSEHTryLoc = TryLoc;
369 bool NeedsScopeChecking() const {
370 return !HasDroppedStmt &&
372 (HasBranchProtectedScope && HasBranchIntoScope));
375 FunctionScopeInfo(DiagnosticsEngine &Diag)
377 HasBranchProtectedScope(false),
378 HasBranchIntoScope(false),
379 HasIndirectGoto(false),
380 HasDroppedStmt(false),
381 HasOMPDeclareReductionCombiner(false),
382 HasFallthroughStmt(false),
383 ObjCShouldCallSuper(false),
384 ObjCIsDesignatedInit(false),
385 ObjCWarnForNoDesignatedInitChain(false),
386 ObjCIsSecondaryInit(false),
387 ObjCWarnForNoInitDelegation(false),
390 virtual ~FunctionScopeInfo();
392 /// \brief Clear out the information in this function scope, making it
393 /// suitable for reuse.
397 class CapturingScopeInfo : public FunctionScopeInfo {
399 CapturingScopeInfo(const CapturingScopeInfo&) = default;
402 enum ImplicitCaptureStyle {
403 ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
404 ImpCap_CapturedRegion
407 ImplicitCaptureStyle ImpCaptureStyle;
410 // There are three categories of capture: capturing 'this', capturing
411 // local variables, and C++1y initialized captures (which can have an
412 // arbitrary initializer, and don't really capture in the traditional
415 // There are three ways to capture a local variable:
416 // - capture by copy in the C++11 sense,
417 // - capture by reference in the C++11 sense, and
418 // - __block capture.
419 // Lambdas explicitly specify capture by copy or capture by reference.
420 // For blocks, __block capture applies to variables with that annotation,
421 // variables of reference type are captured by reference, and other
422 // variables are captured by copy.
424 Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_VLA
427 IsNestedCapture = 0x1,
430 /// The variable being captured (if we are not capturing 'this') and whether
431 /// this is a nested capture, and whether we are capturing 'this'
432 llvm::PointerIntPair<VarDecl*, 2> VarAndNestedAndThis;
433 /// Expression to initialize a field of the given type, and the kind of
434 /// capture (if this is a capture and not an init-capture). The expression
435 /// is only required if we are capturing ByVal and the variable's type has
436 /// a non-trivial copy constructor.
437 llvm::PointerIntPair<void *, 2, CaptureKind> InitExprAndCaptureKind;
439 /// \brief The source location at which the first capture occurred.
442 /// \brief The location of the ellipsis that expands a parameter pack.
443 SourceLocation EllipsisLoc;
445 /// \brief The type as it was captured, which is in effect the type of the
446 /// non-static data member that would hold the capture.
447 QualType CaptureType;
450 Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
451 SourceLocation Loc, SourceLocation EllipsisLoc,
452 QualType CaptureType, Expr *Cpy)
453 : VarAndNestedAndThis(Var, IsNested ? IsNestedCapture : 0),
454 InitExprAndCaptureKind(
455 Cpy, !Var ? Cap_VLA : Block ? Cap_Block : ByRef ? Cap_ByRef
457 Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {}
459 enum IsThisCapture { ThisCapture };
460 Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
461 QualType CaptureType, Expr *Cpy, const bool ByCopy)
462 : VarAndNestedAndThis(
463 nullptr, (IsThisCaptured | (IsNested ? IsNestedCapture : 0))),
464 InitExprAndCaptureKind(Cpy, ByCopy ? Cap_ByCopy : Cap_ByRef),
465 Loc(Loc), EllipsisLoc(), CaptureType(CaptureType) {}
467 bool isThisCapture() const {
468 return VarAndNestedAndThis.getInt() & IsThisCaptured;
470 bool isVariableCapture() const {
471 return !isThisCapture() && !isVLATypeCapture();
473 bool isCopyCapture() const {
474 return InitExprAndCaptureKind.getInt() == Cap_ByCopy;
476 bool isReferenceCapture() const {
477 return InitExprAndCaptureKind.getInt() == Cap_ByRef;
479 bool isBlockCapture() const {
480 return InitExprAndCaptureKind.getInt() == Cap_Block;
482 bool isVLATypeCapture() const {
483 return InitExprAndCaptureKind.getInt() == Cap_VLA;
485 bool isNested() const {
486 return VarAndNestedAndThis.getInt() & IsNestedCapture;
489 VarDecl *getVariable() const {
490 return VarAndNestedAndThis.getPointer();
493 /// \brief Retrieve the location at which this variable was captured.
494 SourceLocation getLocation() const { return Loc; }
496 /// \brief Retrieve the source location of the ellipsis, whose presence
497 /// indicates that the capture is a pack expansion.
498 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
500 /// \brief Retrieve the capture type for this capture, which is effectively
501 /// the type of the non-static data member in the lambda/block structure
502 /// that would store this capture.
503 QualType getCaptureType() const { return CaptureType; }
505 Expr *getInitExpr() const {
506 assert(!isVLATypeCapture() && "no init expression for type capture");
507 return static_cast<Expr *>(InitExprAndCaptureKind.getPointer());
511 CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
512 : FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex(0),
513 HasImplicitReturnType(false)
516 /// CaptureMap - A map of captured variables to (index+1) into Captures.
517 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
519 /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
520 /// zero if 'this' is not captured.
521 unsigned CXXThisCaptureIndex;
523 /// Captures - The captures.
524 SmallVector<Capture, 4> Captures;
526 /// \brief - Whether the target type of return statements in this context
527 /// is deduced (e.g. a lambda or block with omitted return type).
528 bool HasImplicitReturnType;
530 /// ReturnType - The target type of return statements in this context,
531 /// or null if unknown.
534 void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
535 SourceLocation Loc, SourceLocation EllipsisLoc,
536 QualType CaptureType, Expr *Cpy) {
537 Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
538 EllipsisLoc, CaptureType, Cpy));
539 CaptureMap[Var] = Captures.size();
542 void addVLATypeCapture(SourceLocation Loc, QualType CaptureType) {
543 Captures.push_back(Capture(/*Var*/ nullptr, /*isBlock*/ false,
544 /*isByref*/ false, /*isNested*/ false, Loc,
545 /*EllipsisLoc*/ SourceLocation(), CaptureType,
549 void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
550 Expr *Cpy, bool ByCopy);
552 /// \brief Determine whether the C++ 'this' is captured.
553 bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
555 /// \brief Retrieve the capture of C++ 'this', if it has been captured.
556 Capture &getCXXThisCapture() {
557 assert(isCXXThisCaptured() && "this has not been captured");
558 return Captures[CXXThisCaptureIndex - 1];
561 /// \brief Determine whether the given variable has been captured.
562 bool isCaptured(VarDecl *Var) const {
563 return CaptureMap.count(Var);
566 /// \brief Determine whether the given variable-array type has been captured.
567 bool isVLATypeCaptured(const VariableArrayType *VAT) const;
569 /// \brief Retrieve the capture of the given variable, if it has been
570 /// captured already.
571 Capture &getCapture(VarDecl *Var) {
572 assert(isCaptured(Var) && "Variable has not been captured");
573 return Captures[CaptureMap[Var] - 1];
576 const Capture &getCapture(VarDecl *Var) const {
577 llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
578 = CaptureMap.find(Var);
579 assert(Known != CaptureMap.end() && "Variable has not been captured");
580 return Captures[Known->second - 1];
583 static bool classof(const FunctionScopeInfo *FSI) {
584 return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
585 || FSI->Kind == SK_CapturedRegion;
589 /// \brief Retains information about a block that is currently being parsed.
590 class BlockScopeInfo final : public CapturingScopeInfo {
594 /// TheScope - This is the scope for the block itself, which contains
598 /// BlockType - The function type of the block, if one was given.
599 /// Its return type may be BuiltinType::Dependent.
600 QualType FunctionType;
602 BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
603 : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
609 ~BlockScopeInfo() override;
611 static bool classof(const FunctionScopeInfo *FSI) {
612 return FSI->Kind == SK_Block;
616 /// \brief Retains information about a captured region.
617 class CapturedRegionScopeInfo final : public CapturingScopeInfo {
619 /// \brief The CapturedDecl for this statement.
620 CapturedDecl *TheCapturedDecl;
621 /// \brief The captured record type.
622 RecordDecl *TheRecordDecl;
623 /// \brief This is the enclosing scope of the captured region.
625 /// \brief The implicit parameter for the captured variables.
626 ImplicitParamDecl *ContextParam;
627 /// \brief The kind of captured region.
628 unsigned short CapRegionKind;
629 unsigned short OpenMPLevel;
631 CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
632 RecordDecl *RD, ImplicitParamDecl *Context,
633 CapturedRegionKind K, unsigned OpenMPLevel)
634 : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
635 TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
636 ContextParam(Context), CapRegionKind(K), OpenMPLevel(OpenMPLevel)
638 Kind = SK_CapturedRegion;
641 ~CapturedRegionScopeInfo() override;
643 /// \brief A descriptive name for the kind of captured region this is.
644 StringRef getRegionName() const {
645 switch (CapRegionKind) {
647 return "default captured statement";
649 return "OpenMP region";
651 llvm_unreachable("Invalid captured region kind!");
654 static bool classof(const FunctionScopeInfo *FSI) {
655 return FSI->Kind == SK_CapturedRegion;
659 class LambdaScopeInfo final : public CapturingScopeInfo {
661 /// \brief The class that describes the lambda.
662 CXXRecordDecl *Lambda;
664 /// \brief The lambda's compiler-generated \c operator().
665 CXXMethodDecl *CallOperator;
667 /// \brief Source range covering the lambda introducer [...].
668 SourceRange IntroducerRange;
670 /// \brief Source location of the '&' or '=' specifying the default capture
672 SourceLocation CaptureDefaultLoc;
674 /// \brief The number of captures in the \c Captures list that are
675 /// explicit captures.
676 unsigned NumExplicitCaptures;
678 /// \brief Whether this is a mutable lambda.
681 /// \brief Whether the (empty) parameter list is explicit.
684 /// \brief Whether any of the capture expressions requires cleanups.
685 bool ExprNeedsCleanups;
687 /// \brief Whether the lambda contains an unexpanded parameter pack.
688 bool ContainsUnexpandedParameterPack;
690 /// \brief If this is a generic lambda, use this as the depth of
691 /// each 'auto' parameter, during initial AST construction.
692 unsigned AutoTemplateParameterDepth;
694 /// \brief Store the list of the auto parameters for a generic lambda.
695 /// If this is a generic lambda, store the list of the auto
696 /// parameters converted into TemplateTypeParmDecls into a vector
697 /// that can be used to construct the generic lambda's template
698 /// parameter list, during initial AST construction.
699 SmallVector<TemplateTypeParmDecl*, 4> AutoTemplateParams;
701 /// If this is a generic lambda, and the template parameter
702 /// list has been created (from the AutoTemplateParams) then
703 /// store a reference to it (cache it to avoid reconstructing it).
704 TemplateParameterList *GLTemplateParameterList;
706 /// \brief Contains all variable-referring-expressions (i.e. DeclRefExprs
707 /// or MemberExprs) that refer to local variables in a generic lambda
708 /// or a lambda in a potentially-evaluated-if-used context.
710 /// Potentially capturable variables of a nested lambda that might need
711 /// to be captured by the lambda are housed here.
712 /// This is specifically useful for generic lambdas or
713 /// lambdas within a a potentially evaluated-if-used context.
714 /// If an enclosing variable is named in an expression of a lambda nested
715 /// within a generic lambda, we don't always know know whether the variable
716 /// will truly be odr-used (i.e. need to be captured) by that nested lambda,
717 /// until its instantiation. But we still need to capture it in the
718 /// enclosing lambda if all intervening lambdas can capture the variable.
720 llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
722 /// \brief 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;
728 SourceLocation PotentialThisCaptureLocation;
730 LambdaScopeInfo(DiagnosticsEngine &Diag)
731 : CapturingScopeInfo(Diag, ImpCap_None), Lambda(nullptr),
732 CallOperator(nullptr), NumExplicitCaptures(0), Mutable(false),
733 ExplicitParams(false), ExprNeedsCleanups(false),
734 ContainsUnexpandedParameterPack(false), AutoTemplateParameterDepth(0),
735 GLTemplateParameterList(nullptr) {
739 /// \brief Note when all explicit captures have been added.
740 void finishedExplicitCaptures() {
741 NumExplicitCaptures = Captures.size();
744 static bool classof(const FunctionScopeInfo *FSI) {
745 return FSI->Kind == SK_Lambda;
749 /// \brief Add a variable that might potentially be captured by the
750 /// lambda and therefore the enclosing lambdas.
752 /// This is also used by enclosing lambda's to speculatively capture
753 /// variables that nested lambda's - depending on their enclosing
754 /// specialization - might need to capture.
756 /// void f(int, int); <-- don't capture
757 /// void f(const int&, double); <-- capture
759 /// const int x = 10;
760 /// auto L = [=](auto a) { // capture 'x'
761 /// return [=](auto b) {
762 /// f(x, a); // we may or may not need to capture 'x'
766 void addPotentialCapture(Expr *VarExpr) {
767 assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr));
768 PotentiallyCapturingExprs.push_back(VarExpr);
771 void addPotentialThisCapture(SourceLocation Loc) {
772 PotentialThisCaptureLocation = Loc;
774 bool hasPotentialThisCapture() const {
775 return PotentialThisCaptureLocation.isValid();
778 /// \brief Mark a variable's reference in a lambda as non-odr using.
780 /// For generic lambdas, if a variable is named in a potentially evaluated
781 /// expression, where the enclosing full expression is dependent then we
782 /// must capture the variable (given a default capture).
783 /// This is accomplished by recording all references to variables
784 /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
785 /// PotentialCaptures. All such variables have to be captured by that lambda,
786 /// except for as described below.
787 /// If that variable is usable as a constant expression and is named in a
788 /// manner that does not involve its odr-use (e.g. undergoes
789 /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
790 /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
791 /// if we can determine that the full expression is not instantiation-
792 /// dependent, then we can entirely avoid its capture.
798 /// Interestingly, this strategy would involve a capture of n, even though
799 /// it's obviously not odr-used here, because the full-expression is
800 /// instantiation-dependent. It could be useful to avoid capturing such
801 /// variables, even when they are referred to in an instantiation-dependent
802 /// expression, if we can unambiguously determine that they shall never be
803 /// odr-used. This would involve removal of the variable-referring-expression
804 /// from the array of PotentialCaptures during the lvalue-to-rvalue
805 /// conversions. But per the working draft N3797, (post-chicago 2013) we must
806 /// capture such variables.
807 /// Before anyone is tempted to implement a strategy for not-capturing 'n',
808 /// consider the insightful warning in:
809 /// /cfe-commits/Week-of-Mon-20131104/092596.html
810 /// "The problem is that the set of captures for a lambda is part of the ABI
811 /// (since lambda layout can be made visible through inline functions and the
812 /// like), and there are no guarantees as to which cases we'll manage to build
813 /// an lvalue-to-rvalue conversion in, when parsing a template -- some
814 /// seemingly harmless change elsewhere in Sema could cause us to start or stop
815 /// building such a node. So we need a rule that anyone can implement and get
816 /// exactly the same result".
818 void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
819 assert(isa<DeclRefExpr>(CapturingVarExpr)
820 || isa<MemberExpr>(CapturingVarExpr));
821 NonODRUsedCapturingExprs.insert(CapturingVarExpr);
823 bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const {
824 assert(isa<DeclRefExpr>(CapturingVarExpr)
825 || isa<MemberExpr>(CapturingVarExpr));
826 return NonODRUsedCapturingExprs.count(CapturingVarExpr);
828 void removePotentialCapture(Expr *E) {
829 PotentiallyCapturingExprs.erase(
830 std::remove(PotentiallyCapturingExprs.begin(),
831 PotentiallyCapturingExprs.end(), E),
832 PotentiallyCapturingExprs.end());
834 void clearPotentialCaptures() {
835 PotentiallyCapturingExprs.clear();
836 PotentialThisCaptureLocation = SourceLocation();
838 unsigned getNumPotentialVariableCaptures() const {
839 return PotentiallyCapturingExprs.size();
842 bool hasPotentialCaptures() const {
843 return getNumPotentialVariableCaptures() ||
844 PotentialThisCaptureLocation.isValid();
847 // When passed the index, returns the VarDecl and Expr associated
849 void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E) const;
852 FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
853 : Base(nullptr, false), Property(nullptr) {}
855 FunctionScopeInfo::WeakObjectProfileTy
856 FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
857 FunctionScopeInfo::WeakObjectProfileTy Result;
858 Result.Base.setInt(true);
862 template <typename ExprT>
863 void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
865 WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
866 Uses.push_back(WeakUseTy(E, IsRead));
870 CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc,
871 QualType CaptureType, Expr *Cpy,
873 Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
875 CXXThisCaptureIndex = Captures.size();
878 } // end namespace sema
879 } // end namespace clang