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