clang API Documentation
00001 //===--- ScopeInfo.h - Information about a semantic context -----*- C++ -*-===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file defines FunctionScopeInfo and its subclasses, which contain 00011 // information about a single function, block, lambda, or method body. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #ifndef LLVM_CLANG_SEMA_SCOPEINFO_H 00016 #define LLVM_CLANG_SEMA_SCOPEINFO_H 00017 00018 #include "clang/AST/Expr.h" 00019 #include "clang/AST/Type.h" 00020 #include "clang/Basic/CapturedStmt.h" 00021 #include "clang/Basic/PartialDiagnostic.h" 00022 #include "clang/Sema/Ownership.h" 00023 #include "llvm/ADT/DenseMap.h" 00024 #include "llvm/ADT/SmallSet.h" 00025 #include "llvm/ADT/SmallVector.h" 00026 #include <algorithm> 00027 00028 namespace clang { 00029 00030 class Decl; 00031 class BlockDecl; 00032 class CapturedDecl; 00033 class CXXMethodDecl; 00034 class FieldDecl; 00035 class ObjCPropertyDecl; 00036 class IdentifierInfo; 00037 class ImplicitParamDecl; 00038 class LabelDecl; 00039 class ReturnStmt; 00040 class Scope; 00041 class SwitchStmt; 00042 class TemplateTypeParmDecl; 00043 class TemplateParameterList; 00044 class VarDecl; 00045 class ObjCIvarRefExpr; 00046 class ObjCPropertyRefExpr; 00047 class ObjCMessageExpr; 00048 00049 namespace sema { 00050 00051 /// \brief Contains information about the compound statement currently being 00052 /// parsed. 00053 class CompoundScopeInfo { 00054 public: 00055 CompoundScopeInfo() 00056 : HasEmptyLoopBodies(false) { } 00057 00058 /// \brief Whether this compound stamement contains `for' or `while' loops 00059 /// with empty bodies. 00060 bool HasEmptyLoopBodies; 00061 00062 void setHasEmptyLoopBodies() { 00063 HasEmptyLoopBodies = true; 00064 } 00065 }; 00066 00067 class PossiblyUnreachableDiag { 00068 public: 00069 PartialDiagnostic PD; 00070 SourceLocation Loc; 00071 const Stmt *stmt; 00072 00073 PossiblyUnreachableDiag(const PartialDiagnostic &PD, SourceLocation Loc, 00074 const Stmt *stmt) 00075 : PD(PD), Loc(Loc), stmt(stmt) {} 00076 }; 00077 00078 /// \brief Retains information about a function, method, or block that is 00079 /// currently being parsed. 00080 class FunctionScopeInfo { 00081 protected: 00082 enum ScopeKind { 00083 SK_Function, 00084 SK_Block, 00085 SK_Lambda, 00086 SK_CapturedRegion 00087 }; 00088 00089 public: 00090 /// \brief What kind of scope we are describing. 00091 /// 00092 ScopeKind Kind; 00093 00094 /// \brief Whether this function contains a VLA, \@try, try, C++ 00095 /// initializer, or anything else that can't be jumped past. 00096 bool HasBranchProtectedScope; 00097 00098 /// \brief Whether this function contains any switches or direct gotos. 00099 bool HasBranchIntoScope; 00100 00101 /// \brief Whether this function contains any indirect gotos. 00102 bool HasIndirectGoto; 00103 00104 /// \brief Whether a statement was dropped because it was invalid. 00105 bool HasDroppedStmt; 00106 00107 /// A flag that is set when parsing a method that must call super's 00108 /// implementation, such as \c -dealloc, \c -finalize, or any method marked 00109 /// with \c __attribute__((objc_requires_super)). 00110 bool ObjCShouldCallSuper; 00111 00112 /// True when this is a method marked as a designated initializer. 00113 bool ObjCIsDesignatedInit; 00114 /// This starts true for a method marked as designated initializer and will 00115 /// be set to false if there is an invocation to a designated initializer of 00116 /// the super class. 00117 bool ObjCWarnForNoDesignatedInitChain; 00118 00119 /// True when this is an initializer method not marked as a designated 00120 /// initializer within a class that has at least one initializer marked as a 00121 /// designated initializer. 00122 bool ObjCIsSecondaryInit; 00123 /// This starts true for a secondary initializer method and will be set to 00124 /// false if there is an invocation of an initializer on 'self'. 00125 bool ObjCWarnForNoInitDelegation; 00126 00127 /// \brief Used to determine if errors occurred in this function or block. 00128 DiagnosticErrorTrap ErrorTrap; 00129 00130 /// SwitchStack - This is the current set of active switch statements in the 00131 /// block. 00132 SmallVector<SwitchStmt*, 8> SwitchStack; 00133 00134 /// \brief The list of return statements that occur within the function or 00135 /// block, if there is any chance of applying the named return value 00136 /// optimization, or if we need to infer a return type. 00137 SmallVector<ReturnStmt*, 4> Returns; 00138 00139 /// \brief The stack of currently active compound stamement scopes in the 00140 /// function. 00141 SmallVector<CompoundScopeInfo, 4> CompoundScopes; 00142 00143 /// \brief A list of PartialDiagnostics created but delayed within the 00144 /// current function scope. These diagnostics are vetted for reachability 00145 /// prior to being emitted. 00146 SmallVector<PossiblyUnreachableDiag, 4> PossiblyUnreachableDiags; 00147 00148 public: 00149 /// Represents a simple identification of a weak object. 00150 /// 00151 /// Part of the implementation of -Wrepeated-use-of-weak. 00152 /// 00153 /// This is used to determine if two weak accesses refer to the same object. 00154 /// Here are some examples of how various accesses are "profiled": 00155 /// 00156 /// Access Expression | "Base" Decl | "Property" Decl 00157 /// :---------------: | :-----------------: | :------------------------------: 00158 /// self.property | self (VarDecl) | property (ObjCPropertyDecl) 00159 /// self.implicitProp | self (VarDecl) | -implicitProp (ObjCMethodDecl) 00160 /// self->ivar.prop | ivar (ObjCIvarDecl) | prop (ObjCPropertyDecl) 00161 /// cxxObj.obj.prop | obj (FieldDecl) | prop (ObjCPropertyDecl) 00162 /// [self foo].prop | 0 (unknown) | prop (ObjCPropertyDecl) 00163 /// self.prop1.prop2 | prop1 (ObjCPropertyDecl) | prop2 (ObjCPropertyDecl) 00164 /// MyClass.prop | MyClass (ObjCInterfaceDecl) | -prop (ObjCMethodDecl) 00165 /// weakVar | 0 (known) | weakVar (VarDecl) 00166 /// self->weakIvar | self (VarDecl) | weakIvar (ObjCIvarDecl) 00167 /// 00168 /// Objects are identified with only two Decls to make it reasonably fast to 00169 /// compare them. 00170 class WeakObjectProfileTy { 00171 /// The base object decl, as described in the class documentation. 00172 /// 00173 /// The extra flag is "true" if the Base and Property are enough to uniquely 00174 /// identify the object in memory. 00175 /// 00176 /// \sa isExactProfile() 00177 typedef llvm::PointerIntPair<const NamedDecl *, 1, bool> BaseInfoTy; 00178 BaseInfoTy Base; 00179 00180 /// The "property" decl, as described in the class documentation. 00181 /// 00182 /// Note that this may not actually be an ObjCPropertyDecl, e.g. in the 00183 /// case of "implicit" properties (regular methods accessed via dot syntax). 00184 const NamedDecl *Property; 00185 00186 /// Used to find the proper base profile for a given base expression. 00187 static BaseInfoTy getBaseInfo(const Expr *BaseE); 00188 00189 inline WeakObjectProfileTy(); 00190 static inline WeakObjectProfileTy getSentinel(); 00191 00192 public: 00193 WeakObjectProfileTy(const ObjCPropertyRefExpr *RE); 00194 WeakObjectProfileTy(const Expr *Base, const ObjCPropertyDecl *Property); 00195 WeakObjectProfileTy(const DeclRefExpr *RE); 00196 WeakObjectProfileTy(const ObjCIvarRefExpr *RE); 00197 00198 const NamedDecl *getBase() const { return Base.getPointer(); } 00199 const NamedDecl *getProperty() const { return Property; } 00200 00201 /// Returns true if the object base specifies a known object in memory, 00202 /// rather than, say, an instance variable or property of another object. 00203 /// 00204 /// Note that this ignores the effects of aliasing; that is, \c foo.bar is 00205 /// considered an exact profile if \c foo is a local variable, even if 00206 /// another variable \c foo2 refers to the same object as \c foo. 00207 /// 00208 /// For increased precision, accesses with base variables that are 00209 /// properties or ivars of 'self' (e.g. self.prop1.prop2) are considered to 00210 /// be exact, though this is not true for arbitrary variables 00211 /// (foo.prop1.prop2). 00212 bool isExactProfile() const { 00213 return Base.getInt(); 00214 } 00215 00216 bool operator==(const WeakObjectProfileTy &Other) const { 00217 return Base == Other.Base && Property == Other.Property; 00218 } 00219 00220 // For use in DenseMap. 00221 // We can't specialize the usual llvm::DenseMapInfo at the end of the file 00222 // because by that point the DenseMap in FunctionScopeInfo has already been 00223 // instantiated. 00224 class DenseMapInfo { 00225 public: 00226 static inline WeakObjectProfileTy getEmptyKey() { 00227 return WeakObjectProfileTy(); 00228 } 00229 static inline WeakObjectProfileTy getTombstoneKey() { 00230 return WeakObjectProfileTy::getSentinel(); 00231 } 00232 00233 static unsigned getHashValue(const WeakObjectProfileTy &Val) { 00234 typedef std::pair<BaseInfoTy, const NamedDecl *> Pair; 00235 return llvm::DenseMapInfo<Pair>::getHashValue(Pair(Val.Base, 00236 Val.Property)); 00237 } 00238 00239 static bool isEqual(const WeakObjectProfileTy &LHS, 00240 const WeakObjectProfileTy &RHS) { 00241 return LHS == RHS; 00242 } 00243 }; 00244 }; 00245 00246 /// Represents a single use of a weak object. 00247 /// 00248 /// Stores both the expression and whether the access is potentially unsafe 00249 /// (i.e. it could potentially be warned about). 00250 /// 00251 /// Part of the implementation of -Wrepeated-use-of-weak. 00252 class WeakUseTy { 00253 llvm::PointerIntPair<const Expr *, 1, bool> Rep; 00254 public: 00255 WeakUseTy(const Expr *Use, bool IsRead) : Rep(Use, IsRead) {} 00256 00257 const Expr *getUseExpr() const { return Rep.getPointer(); } 00258 bool isUnsafe() const { return Rep.getInt(); } 00259 void markSafe() { Rep.setInt(false); } 00260 00261 bool operator==(const WeakUseTy &Other) const { 00262 return Rep == Other.Rep; 00263 } 00264 }; 00265 00266 /// Used to collect uses of a particular weak object in a function body. 00267 /// 00268 /// Part of the implementation of -Wrepeated-use-of-weak. 00269 typedef SmallVector<WeakUseTy, 4> WeakUseVector; 00270 00271 /// Used to collect all uses of weak objects in a function body. 00272 /// 00273 /// Part of the implementation of -Wrepeated-use-of-weak. 00274 typedef llvm::SmallDenseMap<WeakObjectProfileTy, WeakUseVector, 8, 00275 WeakObjectProfileTy::DenseMapInfo> 00276 WeakObjectUseMap; 00277 00278 private: 00279 /// Used to collect all uses of weak objects in this function body. 00280 /// 00281 /// Part of the implementation of -Wrepeated-use-of-weak. 00282 WeakObjectUseMap WeakObjectUses; 00283 00284 public: 00285 /// Record that a weak object was accessed. 00286 /// 00287 /// Part of the implementation of -Wrepeated-use-of-weak. 00288 template <typename ExprT> 00289 inline void recordUseOfWeak(const ExprT *E, bool IsRead = true); 00290 00291 void recordUseOfWeak(const ObjCMessageExpr *Msg, 00292 const ObjCPropertyDecl *Prop); 00293 00294 /// Record that a given expression is a "safe" access of a weak object (e.g. 00295 /// assigning it to a strong variable.) 00296 /// 00297 /// Part of the implementation of -Wrepeated-use-of-weak. 00298 void markSafeWeakUse(const Expr *E); 00299 00300 const WeakObjectUseMap &getWeakObjectUses() const { 00301 return WeakObjectUses; 00302 } 00303 00304 void setHasBranchIntoScope() { 00305 HasBranchIntoScope = true; 00306 } 00307 00308 void setHasBranchProtectedScope() { 00309 HasBranchProtectedScope = true; 00310 } 00311 00312 void setHasIndirectGoto() { 00313 HasIndirectGoto = true; 00314 } 00315 00316 void setHasDroppedStmt() { 00317 HasDroppedStmt = true; 00318 } 00319 00320 bool NeedsScopeChecking() const { 00321 return !HasDroppedStmt && 00322 (HasIndirectGoto || 00323 (HasBranchProtectedScope && HasBranchIntoScope)); 00324 } 00325 00326 FunctionScopeInfo(DiagnosticsEngine &Diag) 00327 : Kind(SK_Function), 00328 HasBranchProtectedScope(false), 00329 HasBranchIntoScope(false), 00330 HasIndirectGoto(false), 00331 HasDroppedStmt(false), 00332 ObjCShouldCallSuper(false), 00333 ObjCIsDesignatedInit(false), 00334 ObjCWarnForNoDesignatedInitChain(false), 00335 ObjCIsSecondaryInit(false), 00336 ObjCWarnForNoInitDelegation(false), 00337 ErrorTrap(Diag) { } 00338 00339 virtual ~FunctionScopeInfo(); 00340 00341 /// \brief Clear out the information in this function scope, making it 00342 /// suitable for reuse. 00343 void Clear(); 00344 }; 00345 00346 class CapturingScopeInfo : public FunctionScopeInfo { 00347 public: 00348 enum ImplicitCaptureStyle { 00349 ImpCap_None, ImpCap_LambdaByval, ImpCap_LambdaByref, ImpCap_Block, 00350 ImpCap_CapturedRegion 00351 }; 00352 00353 ImplicitCaptureStyle ImpCaptureStyle; 00354 00355 class Capture { 00356 // There are three categories of capture: capturing 'this', capturing 00357 // local variables, and C++1y initialized captures (which can have an 00358 // arbitrary initializer, and don't really capture in the traditional 00359 // sense at all). 00360 // 00361 // There are three ways to capture a local variable: 00362 // - capture by copy in the C++11 sense, 00363 // - capture by reference in the C++11 sense, and 00364 // - __block capture. 00365 // Lambdas explicitly specify capture by copy or capture by reference. 00366 // For blocks, __block capture applies to variables with that annotation, 00367 // variables of reference type are captured by reference, and other 00368 // variables are captured by copy. 00369 enum CaptureKind { 00370 Cap_ByCopy, Cap_ByRef, Cap_Block, Cap_This 00371 }; 00372 00373 /// The variable being captured (if we are not capturing 'this') and whether 00374 /// this is a nested capture. 00375 llvm::PointerIntPair<VarDecl*, 1, bool> VarAndNested; 00376 00377 /// Expression to initialize a field of the given type, and the kind of 00378 /// capture (if this is a capture and not an init-capture). The expression 00379 /// is only required if we are capturing ByVal and the variable's type has 00380 /// a non-trivial copy constructor. 00381 llvm::PointerIntPair<void *, 2, CaptureKind> InitExprAndCaptureKind; 00382 00383 /// \brief The source location at which the first capture occurred. 00384 SourceLocation Loc; 00385 00386 /// \brief The location of the ellipsis that expands a parameter pack. 00387 SourceLocation EllipsisLoc; 00388 00389 /// \brief The type as it was captured, which is in effect the type of the 00390 /// non-static data member that would hold the capture. 00391 QualType CaptureType; 00392 00393 public: 00394 Capture(VarDecl *Var, bool Block, bool ByRef, bool IsNested, 00395 SourceLocation Loc, SourceLocation EllipsisLoc, 00396 QualType CaptureType, Expr *Cpy) 00397 : VarAndNested(Var, IsNested), 00398 InitExprAndCaptureKind(Cpy, Block ? Cap_Block : 00399 ByRef ? Cap_ByRef : Cap_ByCopy), 00400 Loc(Loc), EllipsisLoc(EllipsisLoc), CaptureType(CaptureType) {} 00401 00402 enum IsThisCapture { ThisCapture }; 00403 Capture(IsThisCapture, bool IsNested, SourceLocation Loc, 00404 QualType CaptureType, Expr *Cpy) 00405 : VarAndNested(nullptr, IsNested), 00406 InitExprAndCaptureKind(Cpy, Cap_This), 00407 Loc(Loc), EllipsisLoc(), CaptureType(CaptureType) {} 00408 00409 bool isThisCapture() const { 00410 return InitExprAndCaptureKind.getInt() == Cap_This; 00411 } 00412 bool isVariableCapture() const { 00413 return InitExprAndCaptureKind.getInt() != Cap_This && !isVLATypeCapture(); 00414 } 00415 bool isCopyCapture() const { 00416 return InitExprAndCaptureKind.getInt() == Cap_ByCopy && 00417 !isVLATypeCapture(); 00418 } 00419 bool isReferenceCapture() const { 00420 return InitExprAndCaptureKind.getInt() == Cap_ByRef; 00421 } 00422 bool isBlockCapture() const { 00423 return InitExprAndCaptureKind.getInt() == Cap_Block; 00424 } 00425 bool isVLATypeCapture() const { 00426 return InitExprAndCaptureKind.getInt() == Cap_ByCopy && 00427 getVariable() == nullptr; 00428 } 00429 bool isNested() const { return VarAndNested.getInt(); } 00430 00431 VarDecl *getVariable() const { 00432 return VarAndNested.getPointer(); 00433 } 00434 00435 /// \brief Retrieve the location at which this variable was captured. 00436 SourceLocation getLocation() const { return Loc; } 00437 00438 /// \brief Retrieve the source location of the ellipsis, whose presence 00439 /// indicates that the capture is a pack expansion. 00440 SourceLocation getEllipsisLoc() const { return EllipsisLoc; } 00441 00442 /// \brief Retrieve the capture type for this capture, which is effectively 00443 /// the type of the non-static data member in the lambda/block structure 00444 /// that would store this capture. 00445 QualType getCaptureType() const { return CaptureType; } 00446 00447 Expr *getInitExpr() const { 00448 assert(!isVLATypeCapture() && "no init expression for type capture"); 00449 return static_cast<Expr *>(InitExprAndCaptureKind.getPointer()); 00450 } 00451 }; 00452 00453 CapturingScopeInfo(DiagnosticsEngine &Diag, ImplicitCaptureStyle Style) 00454 : FunctionScopeInfo(Diag), ImpCaptureStyle(Style), CXXThisCaptureIndex(0), 00455 HasImplicitReturnType(false) 00456 {} 00457 00458 /// CaptureMap - A map of captured variables to (index+1) into Captures. 00459 llvm::DenseMap<VarDecl*, unsigned> CaptureMap; 00460 00461 /// CXXThisCaptureIndex - The (index+1) of the capture of 'this'; 00462 /// zero if 'this' is not captured. 00463 unsigned CXXThisCaptureIndex; 00464 00465 /// Captures - The captures. 00466 SmallVector<Capture, 4> Captures; 00467 00468 /// \brief - Whether the target type of return statements in this context 00469 /// is deduced (e.g. a lambda or block with omitted return type). 00470 bool HasImplicitReturnType; 00471 00472 /// ReturnType - The target type of return statements in this context, 00473 /// or null if unknown. 00474 QualType ReturnType; 00475 00476 void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, 00477 SourceLocation Loc, SourceLocation EllipsisLoc, 00478 QualType CaptureType, Expr *Cpy) { 00479 Captures.push_back(Capture(Var, isBlock, isByref, isNested, Loc, 00480 EllipsisLoc, CaptureType, Cpy)); 00481 CaptureMap[Var] = Captures.size(); 00482 } 00483 00484 void addVLATypeCapture(SourceLocation Loc, QualType CaptureType) { 00485 Captures.push_back(Capture(/*Var*/ nullptr, /*isBlock*/ false, 00486 /*isByref*/ false, /*isNested*/ false, Loc, 00487 /*EllipsisLoc*/ SourceLocation(), CaptureType, 00488 /*Cpy*/ nullptr)); 00489 } 00490 00491 void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, 00492 Expr *Cpy); 00493 00494 /// \brief Determine whether the C++ 'this' is captured. 00495 bool isCXXThisCaptured() const { return CXXThisCaptureIndex != 0; } 00496 00497 /// \brief Retrieve the capture of C++ 'this', if it has been captured. 00498 Capture &getCXXThisCapture() { 00499 assert(isCXXThisCaptured() && "this has not been captured"); 00500 return Captures[CXXThisCaptureIndex - 1]; 00501 } 00502 00503 /// \brief Determine whether the given variable has been captured. 00504 bool isCaptured(VarDecl *Var) const { 00505 return CaptureMap.count(Var); 00506 } 00507 00508 /// \brief Determine whether the given variable-array type has been captured. 00509 bool isVLATypeCaptured(const VariableArrayType *VAT) const; 00510 00511 /// \brief Retrieve the capture of the given variable, if it has been 00512 /// captured already. 00513 Capture &getCapture(VarDecl *Var) { 00514 assert(isCaptured(Var) && "Variable has not been captured"); 00515 return Captures[CaptureMap[Var] - 1]; 00516 } 00517 00518 const Capture &getCapture(VarDecl *Var) const { 00519 llvm::DenseMap<VarDecl*, unsigned>::const_iterator Known 00520 = CaptureMap.find(Var); 00521 assert(Known != CaptureMap.end() && "Variable has not been captured"); 00522 return Captures[Known->second - 1]; 00523 } 00524 00525 static bool classof(const FunctionScopeInfo *FSI) { 00526 return FSI->Kind == SK_Block || FSI->Kind == SK_Lambda 00527 || FSI->Kind == SK_CapturedRegion; 00528 } 00529 }; 00530 00531 /// \brief Retains information about a block that is currently being parsed. 00532 class BlockScopeInfo : public CapturingScopeInfo { 00533 public: 00534 BlockDecl *TheDecl; 00535 00536 /// TheScope - This is the scope for the block itself, which contains 00537 /// arguments etc. 00538 Scope *TheScope; 00539 00540 /// BlockType - The function type of the block, if one was given. 00541 /// Its return type may be BuiltinType::Dependent. 00542 QualType FunctionType; 00543 00544 BlockScopeInfo(DiagnosticsEngine &Diag, Scope *BlockScope, BlockDecl *Block) 00545 : CapturingScopeInfo(Diag, ImpCap_Block), TheDecl(Block), 00546 TheScope(BlockScope) 00547 { 00548 Kind = SK_Block; 00549 } 00550 00551 virtual ~BlockScopeInfo(); 00552 00553 static bool classof(const FunctionScopeInfo *FSI) { 00554 return FSI->Kind == SK_Block; 00555 } 00556 }; 00557 00558 /// \brief Retains information about a captured region. 00559 class CapturedRegionScopeInfo: public CapturingScopeInfo { 00560 public: 00561 /// \brief The CapturedDecl for this statement. 00562 CapturedDecl *TheCapturedDecl; 00563 /// \brief The captured record type. 00564 RecordDecl *TheRecordDecl; 00565 /// \brief This is the enclosing scope of the captured region. 00566 Scope *TheScope; 00567 /// \brief The implicit parameter for the captured variables. 00568 ImplicitParamDecl *ContextParam; 00569 /// \brief The kind of captured region. 00570 CapturedRegionKind CapRegionKind; 00571 00572 CapturedRegionScopeInfo(DiagnosticsEngine &Diag, Scope *S, CapturedDecl *CD, 00573 RecordDecl *RD, ImplicitParamDecl *Context, 00574 CapturedRegionKind K) 00575 : CapturingScopeInfo(Diag, ImpCap_CapturedRegion), 00576 TheCapturedDecl(CD), TheRecordDecl(RD), TheScope(S), 00577 ContextParam(Context), CapRegionKind(K) 00578 { 00579 Kind = SK_CapturedRegion; 00580 } 00581 00582 virtual ~CapturedRegionScopeInfo(); 00583 00584 /// \brief A descriptive name for the kind of captured region this is. 00585 StringRef getRegionName() const { 00586 switch (CapRegionKind) { 00587 case CR_Default: 00588 return "default captured statement"; 00589 case CR_OpenMP: 00590 return "OpenMP region"; 00591 } 00592 llvm_unreachable("Invalid captured region kind!"); 00593 } 00594 00595 static bool classof(const FunctionScopeInfo *FSI) { 00596 return FSI->Kind == SK_CapturedRegion; 00597 } 00598 }; 00599 00600 class LambdaScopeInfo : public CapturingScopeInfo { 00601 public: 00602 /// \brief The class that describes the lambda. 00603 CXXRecordDecl *Lambda; 00604 00605 /// \brief The lambda's compiler-generated \c operator(). 00606 CXXMethodDecl *CallOperator; 00607 00608 /// \brief Source range covering the lambda introducer [...]. 00609 SourceRange IntroducerRange; 00610 00611 /// \brief Source location of the '&' or '=' specifying the default capture 00612 /// type, if any. 00613 SourceLocation CaptureDefaultLoc; 00614 00615 /// \brief The number of captures in the \c Captures list that are 00616 /// explicit captures. 00617 unsigned NumExplicitCaptures; 00618 00619 /// \brief Whether this is a mutable lambda. 00620 bool Mutable; 00621 00622 /// \brief Whether the (empty) parameter list is explicit. 00623 bool ExplicitParams; 00624 00625 /// \brief Whether any of the capture expressions requires cleanups. 00626 bool ExprNeedsCleanups; 00627 00628 /// \brief Whether the lambda contains an unexpanded parameter pack. 00629 bool ContainsUnexpandedParameterPack; 00630 00631 /// \brief Variables used to index into by-copy array captures. 00632 SmallVector<VarDecl *, 4> ArrayIndexVars; 00633 00634 /// \brief Offsets into the ArrayIndexVars array at which each capture starts 00635 /// its list of array index variables. 00636 SmallVector<unsigned, 4> ArrayIndexStarts; 00637 00638 /// \brief If this is a generic lambda, use this as the depth of 00639 /// each 'auto' parameter, during initial AST construction. 00640 unsigned AutoTemplateParameterDepth; 00641 00642 /// \brief Store the list of the auto parameters for a generic lambda. 00643 /// If this is a generic lambda, store the list of the auto 00644 /// parameters converted into TemplateTypeParmDecls into a vector 00645 /// that can be used to construct the generic lambda's template 00646 /// parameter list, during initial AST construction. 00647 SmallVector<TemplateTypeParmDecl*, 4> AutoTemplateParams; 00648 00649 /// If this is a generic lambda, and the template parameter 00650 /// list has been created (from the AutoTemplateParams) then 00651 /// store a reference to it (cache it to avoid reconstructing it). 00652 TemplateParameterList *GLTemplateParameterList; 00653 00654 /// \brief Contains all variable-referring-expressions (i.e. DeclRefExprs 00655 /// or MemberExprs) that refer to local variables in a generic lambda 00656 /// or a lambda in a potentially-evaluated-if-used context. 00657 /// 00658 /// Potentially capturable variables of a nested lambda that might need 00659 /// to be captured by the lambda are housed here. 00660 /// This is specifically useful for generic lambdas or 00661 /// lambdas within a a potentially evaluated-if-used context. 00662 /// If an enclosing variable is named in an expression of a lambda nested 00663 /// within a generic lambda, we don't always know know whether the variable 00664 /// will truly be odr-used (i.e. need to be captured) by that nested lambda, 00665 /// until its instantiation. But we still need to capture it in the 00666 /// enclosing lambda if all intervening lambdas can capture the variable. 00667 00668 llvm::SmallVector<Expr*, 4> PotentiallyCapturingExprs; 00669 00670 /// \brief Contains all variable-referring-expressions that refer 00671 /// to local variables that are usable as constant expressions and 00672 /// do not involve an odr-use (they may still need to be captured 00673 /// if the enclosing full-expression is instantiation dependent). 00674 llvm::SmallSet<Expr*, 8> NonODRUsedCapturingExprs; 00675 00676 SourceLocation PotentialThisCaptureLocation; 00677 00678 LambdaScopeInfo(DiagnosticsEngine &Diag) 00679 : CapturingScopeInfo(Diag, ImpCap_None), Lambda(nullptr), 00680 CallOperator(nullptr), NumExplicitCaptures(0), Mutable(false), 00681 ExprNeedsCleanups(false), ContainsUnexpandedParameterPack(false), 00682 AutoTemplateParameterDepth(0), GLTemplateParameterList(nullptr) 00683 { 00684 Kind = SK_Lambda; 00685 } 00686 00687 virtual ~LambdaScopeInfo(); 00688 00689 /// \brief Note when all explicit captures have been added. 00690 void finishedExplicitCaptures() { 00691 NumExplicitCaptures = Captures.size(); 00692 } 00693 00694 static bool classof(const FunctionScopeInfo *FSI) { 00695 return FSI->Kind == SK_Lambda; 00696 } 00697 00698 /// 00699 /// \brief Add a variable that might potentially be captured by the 00700 /// lambda and therefore the enclosing lambdas. 00701 /// 00702 /// This is also used by enclosing lambda's to speculatively capture 00703 /// variables that nested lambda's - depending on their enclosing 00704 /// specialization - might need to capture. 00705 /// Consider: 00706 /// void f(int, int); <-- don't capture 00707 /// void f(const int&, double); <-- capture 00708 /// void foo() { 00709 /// const int x = 10; 00710 /// auto L = [=](auto a) { // capture 'x' 00711 /// return [=](auto b) { 00712 /// f(x, a); // we may or may not need to capture 'x' 00713 /// }; 00714 /// }; 00715 /// } 00716 void addPotentialCapture(Expr *VarExpr) { 00717 assert(isa<DeclRefExpr>(VarExpr) || isa<MemberExpr>(VarExpr)); 00718 PotentiallyCapturingExprs.push_back(VarExpr); 00719 } 00720 00721 void addPotentialThisCapture(SourceLocation Loc) { 00722 PotentialThisCaptureLocation = Loc; 00723 } 00724 bool hasPotentialThisCapture() const { 00725 return PotentialThisCaptureLocation.isValid(); 00726 } 00727 00728 /// \brief Mark a variable's reference in a lambda as non-odr using. 00729 /// 00730 /// For generic lambdas, if a variable is named in a potentially evaluated 00731 /// expression, where the enclosing full expression is dependent then we 00732 /// must capture the variable (given a default capture). 00733 /// This is accomplished by recording all references to variables 00734 /// (DeclRefExprs or MemberExprs) within said nested lambda in its array of 00735 /// PotentialCaptures. All such variables have to be captured by that lambda, 00736 /// except for as described below. 00737 /// If that variable is usable as a constant expression and is named in a 00738 /// manner that does not involve its odr-use (e.g. undergoes 00739 /// lvalue-to-rvalue conversion, or discarded) record that it is so. Upon the 00740 /// act of analyzing the enclosing full expression (ActOnFinishFullExpr) 00741 /// if we can determine that the full expression is not instantiation- 00742 /// dependent, then we can entirely avoid its capture. 00743 /// 00744 /// const int n = 0; 00745 /// [&] (auto x) { 00746 /// (void)+n + x; 00747 /// }; 00748 /// Interestingly, this strategy would involve a capture of n, even though 00749 /// it's obviously not odr-used here, because the full-expression is 00750 /// instantiation-dependent. It could be useful to avoid capturing such 00751 /// variables, even when they are referred to in an instantiation-dependent 00752 /// expression, if we can unambiguously determine that they shall never be 00753 /// odr-used. This would involve removal of the variable-referring-expression 00754 /// from the array of PotentialCaptures during the lvalue-to-rvalue 00755 /// conversions. But per the working draft N3797, (post-chicago 2013) we must 00756 /// capture such variables. 00757 /// Before anyone is tempted to implement a strategy for not-capturing 'n', 00758 /// consider the insightful warning in: 00759 /// /cfe-commits/Week-of-Mon-20131104/092596.html 00760 /// "The problem is that the set of captures for a lambda is part of the ABI 00761 /// (since lambda layout can be made visible through inline functions and the 00762 /// like), and there are no guarantees as to which cases we'll manage to build 00763 /// an lvalue-to-rvalue conversion in, when parsing a template -- some 00764 /// seemingly harmless change elsewhere in Sema could cause us to start or stop 00765 /// building such a node. So we need a rule that anyone can implement and get 00766 /// exactly the same result". 00767 /// 00768 void markVariableExprAsNonODRUsed(Expr *CapturingVarExpr) { 00769 assert(isa<DeclRefExpr>(CapturingVarExpr) 00770 || isa<MemberExpr>(CapturingVarExpr)); 00771 NonODRUsedCapturingExprs.insert(CapturingVarExpr); 00772 } 00773 bool isVariableExprMarkedAsNonODRUsed(Expr *CapturingVarExpr) const { 00774 assert(isa<DeclRefExpr>(CapturingVarExpr) 00775 || isa<MemberExpr>(CapturingVarExpr)); 00776 return NonODRUsedCapturingExprs.count(CapturingVarExpr); 00777 } 00778 void removePotentialCapture(Expr *E) { 00779 PotentiallyCapturingExprs.erase( 00780 std::remove(PotentiallyCapturingExprs.begin(), 00781 PotentiallyCapturingExprs.end(), E), 00782 PotentiallyCapturingExprs.end()); 00783 } 00784 void clearPotentialCaptures() { 00785 PotentiallyCapturingExprs.clear(); 00786 PotentialThisCaptureLocation = SourceLocation(); 00787 } 00788 unsigned getNumPotentialVariableCaptures() const { 00789 return PotentiallyCapturingExprs.size(); 00790 } 00791 00792 bool hasPotentialCaptures() const { 00793 return getNumPotentialVariableCaptures() || 00794 PotentialThisCaptureLocation.isValid(); 00795 } 00796 00797 // When passed the index, returns the VarDecl and Expr associated 00798 // with the index. 00799 void getPotentialVariableCapture(unsigned Idx, VarDecl *&VD, Expr *&E) const; 00800 }; 00801 00802 FunctionScopeInfo::WeakObjectProfileTy::WeakObjectProfileTy() 00803 : Base(nullptr, false), Property(nullptr) {} 00804 00805 FunctionScopeInfo::WeakObjectProfileTy 00806 FunctionScopeInfo::WeakObjectProfileTy::getSentinel() { 00807 FunctionScopeInfo::WeakObjectProfileTy Result; 00808 Result.Base.setInt(true); 00809 return Result; 00810 } 00811 00812 template <typename ExprT> 00813 void FunctionScopeInfo::recordUseOfWeak(const ExprT *E, bool IsRead) { 00814 assert(E); 00815 WeakUseVector &Uses = WeakObjectUses[WeakObjectProfileTy(E)]; 00816 Uses.push_back(WeakUseTy(E, IsRead)); 00817 } 00818 00819 inline void 00820 CapturingScopeInfo::addThisCapture(bool isNested, SourceLocation Loc, 00821 QualType CaptureType, Expr *Cpy) { 00822 Captures.push_back(Capture(Capture::ThisCapture, isNested, Loc, CaptureType, 00823 Cpy)); 00824 CXXThisCaptureIndex = Captures.size(); 00825 00826 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(this)) 00827 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size()); 00828 } 00829 00830 } // end namespace sema 00831 } // end namespace clang 00832 00833 #endif