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_SCOPE_INFO_H
16 #define LLVM_CLANG_SEMA_SCOPE_INFO_H
18 #include "clang/AST/Type.h"
19 #include "clang/Basic/CapturedStmt.h"
20 #include "clang/Basic/PartialDiagnostic.h"
21 #include "clang/Sema/Ownership.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/SmallSet.h"
24 #include "llvm/ADT/SmallVector.h"
34 class ObjCPropertyDecl;
36 class ImplicitParamDecl;
41 class TemplateTypeParmDecl;
42 class TemplateParameterList;
46 class ObjCIvarRefExpr;
47 class ObjCPropertyRefExpr;
48 class ObjCMessageExpr;
52 /// \brief Contains information about the compound statement currently being
54 class CompoundScopeInfo {
57 : HasEmptyLoopBodies(false) { }
59 /// \brief Whether this compound stamement contains `for' or `while' loops
60 /// with empty bodies.
61 bool HasEmptyLoopBodies;
63 void setHasEmptyLoopBodies() {
64 HasEmptyLoopBodies = true;
68 class PossiblyUnreachableDiag {
74 PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc,
76 : PD(PD), Loc(Loc), stmt(stmt) {}
79 /// \brief Retains information about a function, method, or block that is
80 /// currently being parsed.
81 class FunctionScopeInfo {
91 /// \brief What kind of scope we are describing.
95 /// \brief Whether this function contains a VLA, \@try, try, C++
96 /// initializer, or anything else that can't be jumped past.
97 bool HasBranchProtectedScope;
99 /// \brief Whether this function contains any switches or direct gotos.
100 bool HasBranchIntoScope;
102 /// \brief Whether this function contains any indirect gotos.
103 bool HasIndirectGoto;
105 /// \brief Whether a statement was dropped because it was invalid.
108 /// A flag that is set when parsing a method that must call super's
109 /// implementation, such as \c -dealloc, \c -finalize, or any method marked
110 /// with \c __attribute__((objc_requires_super)).
111 bool ObjCShouldCallSuper;
113 /// \brief Used to determine if errors occurred in this function or block.
114 DiagnosticErrorTrap ErrorTrap;
116 /// SwitchStack - This is the current set of active switch statements in the
118 SmallVector<SwitchStmt*, 8> SwitchStack;
120 /// \brief The list of return statements that occur within the function or
121 /// block, if there is any chance of applying the named return value
122 /// optimization, or if we need to infer a return type.
123 SmallVector<ReturnStmt*, 4> Returns;
125 /// \brief The stack of currently active compound stamement scopes in the
127 SmallVector<CompoundScopeInfo, 4> CompoundScopes;
129 /// \brief A list of PartialDiagnostics created but delayed within the
130 /// current function scope. These diagnostics are vetted for reachability
131 /// prior to being emitted.
132 SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags;
135 /// Represents a simple identification of a weak object.
137 /// Part of the implementation of -Wrepeated-use-of-weak.
139 /// This is used to determine if two weak accesses refer to the same object.
140 /// Here are some examples of how various accesses are "profiled":
142 /// Access Expression | "Base" Decl | "Property" Decl
143 /// :---------------: | :-----------------: | :------------------------------:
144 /// self.property | self (VarDecl) | property (ObjCPropertyDecl)
145 /// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl)
146 /// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl)
147 /// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl)
148 /// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl)
149 /// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl)
150 /// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl)
151 /// weakVar | 0 (known) | weakVar (VarDecl)
152 /// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl)
154 /// Objects are identified with only two Decls to make it reasonably fast to
156 class WeakObjectProfileTy {
157 /// The base object decl, as described in the class documentation.
159 /// The extra flag is "true" if the Base and Property are enough to uniquely
160 /// identify the object in memory.
162 /// \sa isExactProfile()
163 typedef llvm::PointerIntPair<const NamedDecl *, 1, bool> BaseInfoTy;
166 /// The "property" decl, as described in the class documentation.
168 /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the
169 /// case of "implicit" properties (regular methods accessed via dot syntax).
170 const NamedDecl *Property;
172 /// Used to find the proper base profile for a given base expression.
173 static BaseInfoTy getBaseInfo(const Expr *BaseE);
175 // For use in DenseMap.
176 friend class DenseMapInfo;
177 inline WeakObjectProfileTy();
178 static inline WeakObjectProfileTy getSentinel();
181 WeakObjectProfileTy(const ObjCPropertyRefExpr *RE);
182 WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property);
183 WeakObjectProfileTy(const DeclRefExpr *RE);
184 WeakObjectProfileTy(const ObjCIvarRefExpr *RE);
186 const NamedDecl *getBase() const { return Base.getPointer(); }
187 const NamedDecl *getProperty() const { return Property; }
189 /// Returns true if the object base specifies a known object in memory,
190 /// rather than, say, an instance variable or property of another object.
192 /// Note that this ignores the effects of aliasing; that is, \c foo.bar is
193 /// considered an exact profile if \c foo is a local variable, even if
194 /// another variable \c foo2 refers to the same object as \c foo.
196 /// For increased precision, accesses with base variables that are
197 /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to
198 /// be exact, though this is not true for arbitrary variables
199 /// (foo.prop1.prop2).
200 bool isExactProfile() const {
201 return Base.getInt();
204 bool operator==(const WeakObjectProfileTy &Other) const {
205 return Base == Other.Base && Property == Other.Property;
208 // For use in DenseMap.
209 // We can't specialize the usual llvm::DenseMapInfo at the end of the file
210 // because by that point the DenseMap in FunctionScopeInfo has already been
214 static inline WeakObjectProfileTy getEmptyKey() {
215 return WeakObjectProfileTy();
217 static inline WeakObjectProfileTy getTombstoneKey() {
218 return WeakObjectProfileTy::getSentinel();
221 static unsigned getHashValue(const WeakObjectProfileTy &Val) {
222 typedef std::pair<BaseInfoTy, const NamedDecl *> Pair;
223 return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base,
227 static bool isEqual(const WeakObjectProfileTy &LHS,
228 const WeakObjectProfileTy &RHS) {
234 /// Represents a single use of a weak object.
236 /// Stores both the expression and whether the access is potentially unsafe
237 /// (i.e. it could potentially be warned about).
239 /// Part of the implementation of -Wrepeated-use-of-weak.
241 llvm::PointerIntPair<const Expr *, 1, bool> Rep;
243 WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {}
245 const Expr *getUseExpr() const { return Rep.getPointer(); }
246 bool isUnsafe() const { return Rep.getInt(); }
247 void markSafe() { Rep.setInt(false); }
249 bool operator==(const WeakUseTy &Other) const {
250 return Rep == Other.Rep;
254 /// Used to collect uses of a particular weak object in a function body.
256 /// Part of the implementation of -Wrepeated-use-of-weak.
257 typedef SmallVector<WeakUseTy, 4> WeakUseVector;
259 /// Used to collect all uses of weak objects in a function body.
261 /// Part of the implementation of -Wrepeated-use-of-weak.
262 typedef llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8,
263 WeakObjectProfileTy::DenseMapInfo>
267 /// Used to collect all uses of weak objects in this function body.
269 /// Part of the implementation of -Wrepeated-use-of-weak.
270 WeakObjectUseMap WeakObjectUses;
273 /// Record that a weak object was accessed.
275 /// Part of the implementation of -Wrepeated-use-of-weak.
276 template <typename ExprT>
277 inline void recordUseOfWeak(const ExprT *E, bool IsRead = true);
279 void recordUseOfWeak(const ObjCMessageExpr *Msg,
280 const ObjCPropertyDecl *Prop);
282 /// Record that a given expression is a "safe" access of a weak object (e.g.
283 /// assigning it to a strong variable.)
285 /// Part of the implementation of -Wrepeated-use-of-weak.
286 void markSafeWeakUse(const Expr *E);
288 const WeakObjectUseMap &getWeakObjectUses() const {
289 return WeakObjectUses;
292 void setHasBranchIntoScope() {
293 HasBranchIntoScope = true;
296 void setHasBranchProtectedScope() {
297 HasBranchProtectedScope = true;
300 void setHasIndirectGoto() {
301 HasIndirectGoto = true;
304 void setHasDroppedStmt() {
305 HasDroppedStmt = true;
308 bool NeedsScopeChecking() const {
309 return !HasDroppedStmt &&
311 (HasBranchProtectedScope && HasBranchIntoScope));
314 FunctionScopeInfo(DiagnosticsEngine &Diag)
316 HasBranchProtectedScope(false),
317 HasBranchIntoScope(false),
318 HasIndirectGoto(false),
319 HasDroppedStmt(false),
320 ObjCShouldCallSuper(false),
323 virtual ~FunctionScopeInfo();
325 /// \brief Clear out the information in this function scope, making it
326 /// suitable for reuse.
330 class CapturingScopeInfo : public FunctionScopeInfo {
332 enum ImplicitCaptureStyle {
333 ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block,
334 ImpCap_CapturedRegion
337 ImplicitCaptureStyle ImpCaptureStyle;
340 // There are three categories of capture: capturing 'this', capturing
341 // local variables, and C++1y initialized captures (which can have an
342 // arbitrary initializer, and don't really capture in the traditional
345 // There are three ways to capture a local variable:
346 // - capture by copy in the C++11 sense,
347 // - capture by reference in the C++11 sense, and
348 // - __block capture.
349 // Lambdas explicitly specify capture by copy or capture by reference.
350 // For blocks, __block capture applies to variables with that annotation,
351 // variables of reference type are captured by reference, and other
352 // variables are captured by copy.
354 Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_This
357 /// The variable being captured (if we are not capturing 'this') and whether
358 /// this is a nested capture.
359 llvm::PointerIntPair<VarDecl*, 1, bool> VarAndNested;
361 /// Expression to initialize a field of the given type, and the kind of
362 /// capture (if this is a capture and not an init-capture). The expression
363 /// is only required if we are capturing ByVal and the variable's type has
364 /// a non-trivial copy constructor.
365 llvm::PointerIntPair<Expr*, 2, CaptureKind> InitExprAndCaptureKind;
367 /// \brief The source location at which the first capture occurred.
370 /// \brief The location of the ellipsis that expands a parameter pack.
371 SourceLocation EllipsisLoc;
373 /// \brief The type as it was captured, which is in effect the type of the
374 /// non-static data member that would hold the capture.
375 QualType CaptureType;
378 Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested,
379 SourceLocation Loc, SourceLocation EllipsisLoc,
380 QualType CaptureType, Expr *Cpy)
381 : VarAndNested(Var, IsNested),
382 InitExprAndCaptureKind(Cpy, Block ? Cap_Block :
383 ByRef ? Cap_ByRef : Cap_ByCopy),
384 Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {}
386 enum IsThisCapture { ThisCapture };
387 Capture(IsThisCapture, bool IsNested, SourceLocation Loc,
388 QualType CaptureType, Expr *Cpy)
389 : VarAndNested(0, IsNested),
390 InitExprAndCaptureKind(Cpy, Cap_This),
391 Loc(Loc), EllipsisLoc(), CaptureType(CaptureType) {}
393 bool isThisCapture() const {
394 return InitExprAndCaptureKind.getInt() == Cap_This;
396 bool isVariableCapture() const {
397 return InitExprAndCaptureKind.getInt() != Cap_This;
399 bool isCopyCapture() const {
400 return InitExprAndCaptureKind.getInt() == Cap_ByCopy;
402 bool isReferenceCapture() const {
403 return InitExprAndCaptureKind.getInt() == Cap_ByRef;
405 bool isBlockCapture() const {
406 return InitExprAndCaptureKind.getInt() == Cap_Block;
408 bool isNested() { return VarAndNested.getInt(); }
410 VarDecl *getVariable() const {
411 return VarAndNested.getPointer();
414 /// \brief Retrieve the location at which this variable was captured.
415 SourceLocation getLocation() const { return Loc; }
417 /// \brief Retrieve the source location of the ellipsis, whose presence
418 /// indicates that the capture is a pack expansion.
419 SourceLocation getEllipsisLoc() const { return EllipsisLoc; }
421 /// \brief Retrieve the capture type for this capture, which is effectively
422 /// the type of the non-static data member in the lambda/block structure
423 /// that would store this capture.
424 QualType getCaptureType() const { return CaptureType; }
426 Expr *getInitExpr() const {
427 return InitExprAndCaptureKind.getPointer();
431 CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style)
432 : FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex(0),
433 HasImplicitReturnType(false)
436 /// CaptureMap - A map of captured variables to (index+1) into Captures.
437 llvm::DenseMap<VarDecl*, unsigned> CaptureMap;
439 /// CXXThisCaptureIndex - The (index+1) of the capture of 'this';
440 /// zero if 'this' is not captured.
441 unsigned CXXThisCaptureIndex;
443 /// Captures - The captures.
444 SmallVector<Capture, 4> Captures;
446 /// \brief - Whether the target type of return statements in this context
447 /// is deduced (e.g. a lambda or block with omitted return type).
448 bool HasImplicitReturnType;
450 /// ReturnType - The target type of return statements in this context,
451 /// or null if unknown.
454 void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested,
455 SourceLocation Loc, SourceLocation EllipsisLoc,
456 QualType CaptureType, Expr *Cpy) {
457 Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc,
458 EllipsisLoc, CaptureType, Cpy));
459 CaptureMap[Var] = Captures.size();
462 void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType,
465 /// \brief Determine whether the C++ 'this' is captured.
466 bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; }
468 /// \brief Retrieve the capture of C++ 'this', if it has been captured.
469 Capture &getCXXThisCapture() {
470 assert(isCXXThisCaptured() && "this has not been captured");
471 return Captures[CXXThisCaptureIndex - 1];
474 /// \brief Determine whether the given variable has been captured.
475 bool isCaptured(VarDecl *Var) const {
476 return CaptureMap.count(Var);
479 /// \brief Retrieve the capture of the given variable, if it has been
480 /// captured already.
481 Capture &getCapture(VarDecl *Var) {
482 assert(isCaptured(Var) && "Variable has not been captured");
483 return Captures[CaptureMap[Var] - 1];
486 const Capture &getCapture(VarDecl *Var) const {
487 llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known
488 = CaptureMap.find(Var);
489 assert(Known != CaptureMap.end() && "Variable has not been captured");
490 return Captures[Known->second - 1];
493 static bool classof(const FunctionScopeInfo *FSI) {
494 return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda
495 || FSI->Kind == SK_CapturedRegion;
499 /// \brief Retains information about a block that is currently being parsed.
500 class BlockScopeInfo : public CapturingScopeInfo {
504 /// TheScope - This is the scope for the block itself, which contains
508 /// BlockType - The function type of the block, if one was given.
509 /// Its return type may be BuiltinType::Dependent.
510 QualType FunctionType;
512 BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block)
513 : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block),
519 virtual ~BlockScopeInfo();
521 static bool classof(const FunctionScopeInfo *FSI) {
522 return FSI->Kind == SK_Block;
526 /// \brief Retains information about a captured region.
527 class CapturedRegionScopeInfo: public CapturingScopeInfo {
529 /// \brief The CapturedDecl for this statement.
530 CapturedDecl *TheCapturedDecl;
531 /// \brief The captured record type.
532 RecordDecl *TheRecordDecl;
533 /// \brief This is the enclosing scope of the captured region.
535 /// \brief The implicit parameter for the captured variables.
536 ImplicitParamDecl *ContextParam;
537 /// \brief The kind of captured region.
538 CapturedRegionKind CapRegionKind;
540 CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD,
541 RecordDecl *RD, ImplicitParamDecl *Context,
542 CapturedRegionKind K)
543 : CapturingScopeInfo(Diag, ImpCap_CapturedRegion),
544 TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S),
545 ContextParam(Context), CapRegionKind(K)
547 Kind = SK_CapturedRegion;
550 virtual ~CapturedRegionScopeInfo();
552 /// \brief A descriptive name for the kind of captured region this is.
553 StringRef getRegionName() const {
554 switch (CapRegionKind) {
556 return "default captured statement";
558 return "OpenMP region";
560 llvm_unreachable("Invalid captured region kind!");
563 static bool classof(const FunctionScopeInfo *FSI) {
564 return FSI->Kind == SK_CapturedRegion;
568 class LambdaScopeInfo : public CapturingScopeInfo {
570 /// \brief The class that describes the lambda.
571 CXXRecordDecl *Lambda;
573 /// \brief The lambda's compiler-generated \c operator().
574 CXXMethodDecl *CallOperator;
576 /// \brief Source range covering the lambda introducer [...].
577 SourceRange IntroducerRange;
579 /// \brief Source location of the '&' or '=' specifying the default capture
581 SourceLocation CaptureDefaultLoc;
583 /// \brief The number of captures in the \c Captures list that are
584 /// explicit captures.
585 unsigned NumExplicitCaptures;
587 /// \brief Whether this is a mutable lambda.
590 /// \brief Whether the (empty) parameter list is explicit.
593 /// \brief Whether any of the capture expressions requires cleanups.
594 bool ExprNeedsCleanups;
596 /// \brief Whether the lambda contains an unexpanded parameter pack.
597 bool ContainsUnexpandedParameterPack;
599 /// \brief Variables used to index into by-copy array captures.
600 SmallVector<VarDecl *, 4> ArrayIndexVars;
602 /// \brief Offsets into the ArrayIndexVars array at which each capture starts
603 /// its list of array index variables.
604 SmallVector<unsigned, 4> ArrayIndexStarts;
606 /// \brief If this is a generic lambda, use this as the depth of
607 /// each 'auto' parameter, during initial AST construction.
608 unsigned AutoTemplateParameterDepth;
610 /// \brief Store the list of the auto parameters for a generic lambda.
611 /// If this is a generic lambda, store the list of the auto
612 /// parameters converted into TemplateTypeParmDecls into a vector
613 /// that can be used to construct the generic lambda's template
614 /// parameter list, during initial AST construction.
615 SmallVector<TemplateTypeParmDecl*, 4> AutoTemplateParams;
617 /// If this is a generic lambda, and the template parameter
618 /// list has been created (from the AutoTemplateParams) then
619 /// store a reference to it (cache it to avoid reconstructing it).
620 TemplateParameterList *GLTemplateParameterList;
622 /// \brief Contains all variable-referring-expressions (i.e. DeclRefExprs
623 /// or MemberExprs) that refer to local variables in a generic lambda
624 /// or a lambda in a potentially-evaluated-if-used context.
626 /// Potentially capturable variables of a nested lambda that might need
627 /// to be captured by the lambda are housed here.
628 /// This is specifically useful for generic lambdas or
629 /// lambdas within a a potentially evaluated-if-used context.
630 /// If an enclosing variable is named in an expression of a lambda nested
631 /// within a generic lambda, we don't always know know whether the variable
632 /// will truly be odr-used (i.e. need to be captured) by that nested lambda,
633 /// until its instantiation. But we still need to capture it in the
634 /// enclosing lambda if all intervening lambdas can capture the variable.
636 llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs;
638 /// \brief Contains all variable-referring-expressions that refer
639 /// to local variables that are usable as constant expressions and
640 /// do not involve an odr-use (they may still need to be captured
641 /// if the enclosing full-expression is instantiation dependent).
642 llvm::SmallSet<Expr*, 8> NonODRUsedCapturingExprs;
644 SourceLocation PotentialThisCaptureLocation;
646 LambdaScopeInfo(DiagnosticsEngine &Diag)
647 : CapturingScopeInfo(Diag, ImpCap_None), Lambda(0),
648 CallOperator(0), NumExplicitCaptures(0), Mutable(false),
649 ExprNeedsCleanups(false), ContainsUnexpandedParameterPack(false),
650 AutoTemplateParameterDepth(0), GLTemplateParameterList(0)
655 virtual ~LambdaScopeInfo();
657 /// \brief Note when all explicit captures have been added.
658 void finishedExplicitCaptures() {
659 NumExplicitCaptures = Captures.size();
662 static bool classof(const FunctionScopeInfo *FSI) {
663 return FSI->Kind == SK_Lambda;
667 /// \brief Add a variable that might potentially be captured by the
668 /// lambda and therefore the enclosing lambdas.
670 /// This is also used by enclosing lambda's to speculatively capture
671 /// variables that nested lambda's - depending on their enclosing
672 /// specialization - might need to capture.
674 /// void f(int, int); <-- don't capture
675 /// void f(const int&, double); <-- capture
677 /// const int x = 10;
678 /// auto L = [=](auto a) { // capture 'x'
679 /// return [=](auto b) {
680 /// f(x, a); // we may or may not need to capture 'x'
684 void addPotentialCapture(Expr *VarExpr) {
685 assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr));
686 PotentiallyCapturingExprs.push_back(VarExpr);
689 void addPotentialThisCapture(SourceLocation Loc) {
690 PotentialThisCaptureLocation = Loc;
692 bool hasPotentialThisCapture() const {
693 return PotentialThisCaptureLocation.isValid();
696 /// \brief Mark a variable's reference in a lambda as non-odr using.
698 /// For generic lambdas, if a variable is named in a potentially evaluated
699 /// expression, where the enclosing full expression is dependent then we
700 /// must capture the variable (given a default capture).
701 /// This is accomplished by recording all references to variables
702 /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of
703 /// PotentialCaptures. All such variables have to be captured by that lambda,
704 /// except for as described below.
705 /// If that variable is usable as a constant expression and is named in a
706 /// manner that does not involve its odr-use (e.g. undergoes
707 /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the
708 /// act of analyzing the enclosing full expression (ActOnFinishFullExpr)
709 /// if we can determine that the full expression is not instantiation-
710 /// dependent, then we can entirely avoid its capture.
712 /// const int n = 0;
\r
716 /// Interestingly, this strategy would involve a capture of n, even though
717 /// it's obviously not odr-used here, because the full-expression is
718 /// instantiation-dependent. It could be useful to avoid capturing such
719 /// variables, even when they are referred to in an instantiation-dependent
720 /// expression, if we can unambiguously determine that they shall never be
721 /// odr-used. This would involve removal of the variable-referring-expression
722 /// from the array of PotentialCaptures during the lvalue-to-rvalue
723 /// conversions. But per the working draft N3797, (post-chicago 2013) we must
724 /// capture such variables.
725 /// Before anyone is tempted to implement a strategy for not-capturing 'n',
726 /// consider the insightful warning in:
727 /// /cfe-commits/Week-of-Mon-20131104/092596.html
728 /// "The problem is that the set of captures for a lambda is part of the ABI
\r
729 /// (since lambda layout can be made visible through inline functions and the
\r
730 /// like), and there are no guarantees as to which cases we'll manage to build
\r
731 /// an lvalue-to-rvalue conversion in, when parsing a template -- some
\r
732 /// seemingly harmless change elsewhere in Sema could cause us to start or stop
\r
733 /// building such a node. So we need a rule that anyone can implement and get
\r
734 /// exactly the same result".
736 void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) {
737 assert(isa<DeclRefExpr>(CapturingVarExpr)
738 || isa<MemberExpr>(CapturingVarExpr));
739 NonODRUsedCapturingExprs.insert(CapturingVarExpr);
741 bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) {
742 assert(isa<DeclRefExpr>(CapturingVarExpr)
743 || isa<MemberExpr>(CapturingVarExpr));
744 return NonODRUsedCapturingExprs.count(CapturingVarExpr);
746 void removePotentialCapture(Expr *E) {
747 PotentiallyCapturingExprs.erase(
748 std::remove(PotentiallyCapturingExprs.begin(),
749 PotentiallyCapturingExprs.end(), E),
750 PotentiallyCapturingExprs.end());
752 void clearPotentialCaptures() {
753 PotentiallyCapturingExprs.clear();
754 PotentialThisCaptureLocation = SourceLocation();
756 unsigned getNumPotentialVariableCaptures() const {
757 return PotentiallyCapturingExprs.size();
760 bool hasPotentialCaptures() const {
761 return getNumPotentialVariableCaptures() ||
762 PotentialThisCaptureLocation.isValid();
765 // When passed the index, returns the VarDecl and Expr associated
767 void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E);
772 FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy()
773 : Base(0, false), Property(0) {}
775 FunctionScopeInfo::WeakObjectProfileTy
776 FunctionScopeInfo::WeakObjectProfileTy::getSentinel() {
777 FunctionScopeInfo::WeakObjectProfileTy Result;
778 Result.Base.setInt(true);
782 template <typename ExprT>
783 void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) {
785 WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)];
786 Uses.push_back(WeakUseTy(E, IsRead));
790 CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc,
791 QualType CaptureType, Expr *Cpy) {
792 Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType,
794 CXXThisCaptureIndex = Captures.size();
796 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(this))
797 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
800 } // end namespace sema
801 } // end namespace clang