Sema.h revision 98ae834a3e289f84f0765d0d0ca7ff22ccaba458
1010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// 2010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// 3010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// The LLVM Compiler Infrastructure 4010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// 5010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// This file is distributed under the University of Illinois Open Source 6010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// License. See LICENSE.TXT for details. 71320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci// 81320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci//===----------------------------------------------------------------------===// 9010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// 10010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// This file defines the Sema class, which performs semantic analysis and 11010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)// builds ASTs. 12f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)// 13010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)//===----------------------------------------------------------------------===// 14010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) 15010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#ifndef LLVM_CLANG_SEMA_SEMA_H 16010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#define LLVM_CLANG_SEMA_SEMA_H 17010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) 18010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Sema/Ownership.h" 191320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Sema/AnalysisBasedWarnings.h" 201320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Sema/IdentifierResolver.h" 211320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Sema/ObjCMethodList.h" 221320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Sema/DeclSpec.h" 23010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Sema/ExternalSemaSource.h" 24010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Sema/LocInfoType.h" 25010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Sema/TypoCorrection.h" 26010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/Sema/Weak.h" 27010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/Expr.h" 28010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/ExprObjC.h" 29010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/DeclarationName.h" 30010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/ExternalASTSource.h" 31010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/TypeLoc.h" 32010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "clang/AST/NSAPI.h" 331320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Lex/ModuleLoader.h" 341320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "clang/Basic/Specifiers.h" 3503b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)#include "clang/Basic/TemplateKinds.h" 3603b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)#include "clang/Basic/TypeTraits.h" 3703b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles)#include "clang/Basic/ExpressionTraits.h" 38010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)#include "llvm/ADT/ArrayRef.h" 391320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/ADT/OwningPtr.h" 401320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/ADT/SmallPtrSet.h" 411320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "llvm/ADT/SmallVector.h" 425f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include <deque> 435f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include <string> 441320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci 451320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccinamespace llvm { 46116680a4aac90f2aa7413d9095a592090648e557Ben Murdoch class APSInt; 475f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) template <typename ValueT> struct DenseMapInfo; 485f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles) template <typename ValueT, typename ValueInfoT> class DenseSet; 49010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class SmallBitVector; 50010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)} 51010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) 52010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles)namespace clang { 53010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class ADLResult; 54010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class ASTConsumer; 55010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class ASTContext; 56010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class ASTMutationListener; 571320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ASTReader; 581320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ASTWriter; 591320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ArrayType; 601320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class AttributeList; 611320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class BlockDecl; 621320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CXXBasePath; 631320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CXXBasePaths; 641320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CXXBindTemporaryExpr; 65010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; 66010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class CXXConstructorDecl; 67f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) class CXXConversionDecl; 68f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles) class CXXDestructorDecl; 6903b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles) class CXXFieldCollector; 7003b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles) class CXXMemberCallExpr; 7103b57e008b61dfcb1fbad3aea950ae0e001748b0Torne (Richard Coles) class CXXMethodDecl; 721320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CXXScopeSpec; 731320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CXXTemporary; 741320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CXXTryStmt; 751320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CallExpr; 761320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ClassTemplateDecl; 771320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ClassTemplatePartialSpecializationDecl; 781320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ClassTemplateSpecializationDecl; 791320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CodeCompleteConsumer; 801320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CodeCompletionAllocator; 811320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CodeCompletionTUInfo; 821320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class CodeCompletionResult; 83010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class Decl; 84010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class DeclAccessPair; 85010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class DeclContext; 86010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class DeclRefExpr; 87010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class DeclaratorDecl; 88010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class DeducedTemplateArgument; 89010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class DependentDiagnostic; 90010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class DesignatedInitExpr; 91010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class Designation; 92010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class EnumConstantDecl; 931320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class Expr; 941320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ExtVectorType; 951320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ExternalSemaSource; 961320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class FormatAttr; 971320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class FriendDecl; 981320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class FunctionDecl; 991320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class FunctionProtoType; 1001320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class FunctionTemplateDecl; 1011320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci class ImplicitConversionSequence; 102010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class InitListExpr; 103010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class InitializationKind; 104010d83a9304c5a91596085d917d248abff47903aTorne (Richard Coles) class InitializationSequence; 105 class InitializedEntity; 106 class IntegerLiteral; 107 class LabelStmt; 108 class LambdaExpr; 109 class LangOptions; 110 class LocalInstantiationScope; 111 class LookupResult; 112 class MacroInfo; 113 class MultiLevelTemplateArgumentList; 114 class NamedDecl; 115 class NonNullAttr; 116 class ObjCCategoryDecl; 117 class ObjCCategoryImplDecl; 118 class ObjCCompatibleAliasDecl; 119 class ObjCContainerDecl; 120 class ObjCImplDecl; 121 class ObjCImplementationDecl; 122 class ObjCInterfaceDecl; 123 class ObjCIvarDecl; 124 template <class T> class ObjCList; 125 class ObjCMessageExpr; 126 class ObjCMethodDecl; 127 class ObjCPropertyDecl; 128 class ObjCProtocolDecl; 129 class OverloadCandidateSet; 130 class OverloadExpr; 131 class ParenListExpr; 132 class ParmVarDecl; 133 class Preprocessor; 134 class PseudoDestructorTypeStorage; 135 class PseudoObjectExpr; 136 class QualType; 137 class StandardConversionSequence; 138 class Stmt; 139 class StringLiteral; 140 class SwitchStmt; 141 class TargetAttributesSema; 142 class TemplateArgument; 143 class TemplateArgumentList; 144 class TemplateArgumentLoc; 145 class TemplateDecl; 146 class TemplateParameterList; 147 class TemplatePartialOrderingContext; 148 class TemplateTemplateParmDecl; 149 class Token; 150 class TypeAliasDecl; 151 class TypedefDecl; 152 class TypedefNameDecl; 153 class TypeLoc; 154 class UnqualifiedId; 155 class UnresolvedLookupExpr; 156 class UnresolvedMemberExpr; 157 class UnresolvedSetImpl; 158 class UnresolvedSetIterator; 159 class UsingDecl; 160 class UsingShadowDecl; 161 class ValueDecl; 162 class VarDecl; 163 class VisibilityAttr; 164 class VisibleDeclConsumer; 165 class IndirectFieldDecl; 166 167namespace sema { 168 class AccessedEntity; 169 class BlockScopeInfo; 170 class CompoundScopeInfo; 171 class DelayedDiagnostic; 172 class DelayedDiagnosticPool; 173 class FunctionScopeInfo; 174 class LambdaScopeInfo; 175 class PossiblyUnreachableDiag; 176 class TemplateDeductionInfo; 177} 178 179// FIXME: No way to easily map from TemplateTypeParmTypes to 180// TemplateTypeParmDecls, so we have this horrible PointerUnion. 181typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, 182 SourceLocation> UnexpandedParameterPack; 183 184/// Sema - This implements semantic analysis and AST building for C. 185class Sema { 186 Sema(const Sema&); // DO NOT IMPLEMENT 187 void operator=(const Sema&); // DO NOT IMPLEMENT 188 mutable const TargetAttributesSema* TheTargetAttributesSema; 189public: 190 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; 191 typedef OpaquePtr<TemplateName> TemplateTy; 192 typedef OpaquePtr<QualType> TypeTy; 193 194 OpenCLOptions OpenCLFeatures; 195 FPOptions FPFeatures; 196 197 const LangOptions &LangOpts; 198 Preprocessor &PP; 199 ASTContext &Context; 200 ASTConsumer &Consumer; 201 DiagnosticsEngine &Diags; 202 SourceManager &SourceMgr; 203 204 /// \brief Flag indicating whether or not to collect detailed statistics. 205 bool CollectStats; 206 207 /// \brief Source of additional semantic information. 208 ExternalSemaSource *ExternalSource; 209 210 /// \brief Code-completion consumer. 211 CodeCompleteConsumer *CodeCompleter; 212 213 /// CurContext - This is the current declaration context of parsing. 214 DeclContext *CurContext; 215 216 /// \brief Generally null except when we temporarily switch decl contexts, 217 /// like in \see ActOnObjCTemporaryExitContainerContext. 218 DeclContext *OriginalLexicalContext; 219 220 /// VAListTagName - The declaration name corresponding to __va_list_tag. 221 /// This is used as part of a hack to omit that class from ADL results. 222 DeclarationName VAListTagName; 223 224 /// PackContext - Manages the stack for #pragma pack. An alignment 225 /// of 0 indicates default alignment. 226 void *PackContext; // Really a "PragmaPackStack*" 227 228 bool MSStructPragmaOn; // True when #pragma ms_struct on 229 230 /// VisContext - Manages the stack for #pragma GCC visibility. 231 void *VisContext; // Really a "PragmaVisStack*" 232 233 /// ExprNeedsCleanups - True if the current evaluation context 234 /// requires cleanups to be run at its conclusion. 235 bool ExprNeedsCleanups; 236 237 /// ExprCleanupObjects - This is the stack of objects requiring 238 /// cleanup that are created by the current full expression. The 239 /// element type here is ExprWithCleanups::Object. 240 SmallVector<BlockDecl*, 8> ExprCleanupObjects; 241 242 llvm::SmallPtrSet<Expr*, 8> MaybeODRUseExprs; 243 244 /// \brief Stack containing information about each of the nested 245 /// function, block, and method scopes that are currently active. 246 /// 247 /// This array is never empty. Clients should ignore the first 248 /// element, which is used to cache a single FunctionScopeInfo 249 /// that's used to parse every top-level function. 250 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; 251 252 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, 253 &ExternalSemaSource::ReadExtVectorDecls, 2, 2> 254 ExtVectorDeclsType; 255 256 /// ExtVectorDecls - This is a list all the extended vector types. This allows 257 /// us to associate a raw vector type with one of the ext_vector type names. 258 /// This is only necessary for issuing pretty diagnostics. 259 ExtVectorDeclsType ExtVectorDecls; 260 261 /// \brief The set of types for which we have already complained about the 262 /// definitions being hidden. 263 /// 264 /// This set is used to suppress redundant diagnostics. 265 llvm::SmallPtrSet<NamedDecl *, 4> HiddenDefinitions; 266 267 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. 268 OwningPtr<CXXFieldCollector> FieldCollector; 269 270 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; 271 272 /// PureVirtualClassDiagSet - a set of class declarations which we have 273 /// emitted a list of pure virtual functions. Used to prevent emitting the 274 /// same list more than once. 275 OwningPtr<RecordDeclSetTy> PureVirtualClassDiagSet; 276 277 /// ParsingInitForAutoVars - a set of declarations with auto types for which 278 /// we are currently parsing the initializer. 279 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; 280 281 /// \brief A mapping from external names to the most recent 282 /// locally-scoped external declaration with that name. 283 /// 284 /// This map contains external declarations introduced in local 285 /// scoped, e.g., 286 /// 287 /// \code 288 /// void f() { 289 /// void foo(int, int); 290 /// } 291 /// \endcode 292 /// 293 /// Here, the name "foo" will be associated with the declaration on 294 /// "foo" within f. This name is not visible outside of 295 /// "f". However, we still find it in two cases: 296 /// 297 /// - If we are declaring another external with the name "foo", we 298 /// can find "foo" as a previous declaration, so that the types 299 /// of this external declaration can be checked for 300 /// compatibility. 301 /// 302 /// - If we would implicitly declare "foo" (e.g., due to a call to 303 /// "foo" in C when no prototype or definition is visible), then 304 /// we find this declaration of "foo" and complain that it is 305 /// not visible. 306 llvm::DenseMap<DeclarationName, NamedDecl *> LocallyScopedExternalDecls; 307 308 /// \brief Look for a locally scoped external declaration by the given name. 309 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator 310 findLocallyScopedExternalDecl(DeclarationName Name); 311 312 typedef LazyVector<VarDecl *, ExternalSemaSource, 313 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> 314 TentativeDefinitionsType; 315 316 /// \brief All the tentative definitions encountered in the TU. 317 TentativeDefinitionsType TentativeDefinitions; 318 319 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, 320 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> 321 UnusedFileScopedDeclsType; 322 323 /// \brief The set of file scoped decls seen so far that have not been used 324 /// and must warn if not used. Only contains the first declaration. 325 UnusedFileScopedDeclsType UnusedFileScopedDecls; 326 327 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, 328 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> 329 DelegatingCtorDeclsType; 330 331 /// \brief All the delegating constructors seen so far in the file, used for 332 /// cycle detection at the end of the TU. 333 DelegatingCtorDeclsType DelegatingCtorDecls; 334 335 /// \brief All the destructors seen during a class definition that had their 336 /// exception spec computation delayed because it depended on an unparsed 337 /// exception spec. 338 SmallVector<CXXDestructorDecl*, 2> DelayedDestructorExceptionSpecs; 339 340 /// \brief All the overriding destructors seen during a class definition 341 /// (there could be multiple due to nested classes) that had their exception 342 /// spec checks delayed, plus the overridden destructor. 343 SmallVector<std::pair<const CXXDestructorDecl*, 344 const CXXDestructorDecl*>, 2> 345 DelayedDestructorExceptionSpecChecks; 346 347 /// \brief Callback to the parser to parse templated functions when needed. 348 typedef void LateTemplateParserCB(void *P, const FunctionDecl *FD); 349 LateTemplateParserCB *LateTemplateParser; 350 void *OpaqueParser; 351 352 void SetLateTemplateParser(LateTemplateParserCB *LTP, void *P) { 353 LateTemplateParser = LTP; 354 OpaqueParser = P; 355 } 356 357 class DelayedDiagnostics; 358 359 class DelayedDiagnosticsState { 360 sema::DelayedDiagnosticPool *SavedPool; 361 friend class Sema::DelayedDiagnostics; 362 }; 363 typedef DelayedDiagnosticsState ParsingDeclState; 364 typedef DelayedDiagnosticsState ProcessingContextState; 365 366 /// A class which encapsulates the logic for delaying diagnostics 367 /// during parsing and other processing. 368 class DelayedDiagnostics { 369 /// \brief The current pool of diagnostics into which delayed 370 /// diagnostics should go. 371 sema::DelayedDiagnosticPool *CurPool; 372 373 public: 374 DelayedDiagnostics() : CurPool(0) {} 375 376 /// Adds a delayed diagnostic. 377 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h 378 379 /// Determines whether diagnostics should be delayed. 380 bool shouldDelayDiagnostics() { return CurPool != 0; } 381 382 /// Returns the current delayed-diagnostics pool. 383 sema::DelayedDiagnosticPool *getCurrentPool() const { 384 return CurPool; 385 } 386 387 /// Enter a new scope. Access and deprecation diagnostics will be 388 /// collected in this pool. 389 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { 390 DelayedDiagnosticsState state; 391 state.SavedPool = CurPool; 392 CurPool = &pool; 393 return state; 394 } 395 396 /// Leave a delayed-diagnostic state that was previously pushed. 397 /// Do not emit any of the diagnostics. This is performed as part 398 /// of the bookkeeping of popping a pool "properly". 399 void popWithoutEmitting(DelayedDiagnosticsState state) { 400 CurPool = state.SavedPool; 401 } 402 403 /// Enter a new scope where access and deprecation diagnostics are 404 /// not delayed. 405 DelayedDiagnosticsState pushUndelayed() { 406 DelayedDiagnosticsState state; 407 state.SavedPool = CurPool; 408 CurPool = 0; 409 return state; 410 } 411 412 /// Undo a previous pushUndelayed(). 413 void popUndelayed(DelayedDiagnosticsState state) { 414 assert(CurPool == NULL); 415 CurPool = state.SavedPool; 416 } 417 } DelayedDiagnostics; 418 419 /// A RAII object to temporarily push a declaration context. 420 class ContextRAII { 421 private: 422 Sema &S; 423 DeclContext *SavedContext; 424 ProcessingContextState SavedContextState; 425 QualType SavedCXXThisTypeOverride; 426 427 public: 428 ContextRAII(Sema &S, DeclContext *ContextToPush) 429 : S(S), SavedContext(S.CurContext), 430 SavedContextState(S.DelayedDiagnostics.pushUndelayed()), 431 SavedCXXThisTypeOverride(S.CXXThisTypeOverride) 432 { 433 assert(ContextToPush && "pushing null context"); 434 S.CurContext = ContextToPush; 435 } 436 437 void pop() { 438 if (!SavedContext) return; 439 S.CurContext = SavedContext; 440 S.DelayedDiagnostics.popUndelayed(SavedContextState); 441 S.CXXThisTypeOverride = SavedCXXThisTypeOverride; 442 SavedContext = 0; 443 } 444 445 ~ContextRAII() { 446 pop(); 447 } 448 }; 449 450 /// WeakUndeclaredIdentifiers - Identifiers contained in 451 /// #pragma weak before declared. rare. may alias another 452 /// identifier, declared or undeclared 453 llvm::DenseMap<IdentifierInfo*,WeakInfo> WeakUndeclaredIdentifiers; 454 455 /// ExtnameUndeclaredIdentifiers - Identifiers contained in 456 /// #pragma redefine_extname before declared. Used in Solaris system headers 457 /// to define functions that occur in multiple standards to call the version 458 /// in the currently selected standard. 459 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; 460 461 462 /// \brief Load weak undeclared identifiers from the external source. 463 void LoadExternalWeakUndeclaredIdentifiers(); 464 465 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by 466 /// #pragma weak during processing of other Decls. 467 /// I couldn't figure out a clean way to generate these in-line, so 468 /// we store them here and handle separately -- which is a hack. 469 /// It would be best to refactor this. 470 SmallVector<Decl*,2> WeakTopLevelDecl; 471 472 IdentifierResolver IdResolver; 473 474 /// Translation Unit Scope - useful to Objective-C actions that need 475 /// to lookup file scope declarations in the "ordinary" C decl namespace. 476 /// For example, user-defined classes, built-in "id" type, etc. 477 Scope *TUScope; 478 479 /// \brief The C++ "std" namespace, where the standard library resides. 480 LazyDeclPtr StdNamespace; 481 482 /// \brief The C++ "std::bad_alloc" class, which is defined by the C++ 483 /// standard library. 484 LazyDeclPtr StdBadAlloc; 485 486 /// \brief The C++ "std::initializer_list" template, which is defined in 487 /// <initializer_list>. 488 ClassTemplateDecl *StdInitializerList; 489 490 /// \brief The C++ "type_info" declaration, which is defined in <typeinfo>. 491 RecordDecl *CXXTypeInfoDecl; 492 493 /// \brief The MSVC "_GUID" struct, which is defined in MSVC header files. 494 RecordDecl *MSVCGuidDecl; 495 496 /// \brief Caches identifiers/selectors for NSFoundation APIs. 497 llvm::OwningPtr<NSAPI> NSAPIObj; 498 499 /// \brief The declaration of the Objective-C NSNumber class. 500 ObjCInterfaceDecl *NSNumberDecl; 501 502 /// \brief Pointer to NSNumber type (NSNumber *). 503 QualType NSNumberPointer; 504 505 /// \brief The Objective-C NSNumber methods used to create NSNumber literals. 506 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; 507 508 /// \brief The declaration of the Objective-C NSString class. 509 ObjCInterfaceDecl *NSStringDecl; 510 511 /// \brief Pointer to NSString type (NSString *). 512 QualType NSStringPointer; 513 514 /// \brief The declaration of the stringWithUTF8String: method. 515 ObjCMethodDecl *StringWithUTF8StringMethod; 516 517 /// \brief The declaration of the Objective-C NSArray class. 518 ObjCInterfaceDecl *NSArrayDecl; 519 520 /// \brief The declaration of the arrayWithObjects:count: method. 521 ObjCMethodDecl *ArrayWithObjectsMethod; 522 523 /// \brief The declaration of the Objective-C NSDictionary class. 524 ObjCInterfaceDecl *NSDictionaryDecl; 525 526 /// \brief The declaration of the dictionaryWithObjects:forKeys:count: method. 527 ObjCMethodDecl *DictionaryWithObjectsMethod; 528 529 /// \brief id<NSCopying> type. 530 QualType QIDNSCopying; 531 532 /// A flag to remember whether the implicit forms of operator new and delete 533 /// have been declared. 534 bool GlobalNewDeleteDeclared; 535 536 /// A flag that is set when parsing a -dealloc method and no [super dealloc] 537 /// call was found yet. 538 bool ObjCShouldCallSuperDealloc; 539 /// A flag that is set when parsing a -finalize method and no [super finalize] 540 /// call was found yet. 541 bool ObjCShouldCallSuperFinalize; 542 543 /// \brief Describes how the expressions currently being parsed are 544 /// evaluated at run-time, if at all. 545 enum ExpressionEvaluationContext { 546 /// \brief The current expression and its subexpressions occur within an 547 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of 548 /// \c sizeof, where the type of the expression may be significant but 549 /// no code will be generated to evaluate the value of the expression at 550 /// run time. 551 Unevaluated, 552 553 /// \brief The current context is "potentially evaluated" in C++11 terms, 554 /// but the expression is evaluated at compile-time (like the values of 555 /// cases in a switch statment). 556 ConstantEvaluated, 557 558 /// \brief The current expression is potentially evaluated at run time, 559 /// which means that code may be generated to evaluate the value of the 560 /// expression at run time. 561 PotentiallyEvaluated, 562 563 /// \brief The current expression is potentially evaluated, but any 564 /// declarations referenced inside that expression are only used if 565 /// in fact the current expression is used. 566 /// 567 /// This value is used when parsing default function arguments, for which 568 /// we would like to provide diagnostics (e.g., passing non-POD arguments 569 /// through varargs) but do not want to mark declarations as "referenced" 570 /// until the default argument is used. 571 PotentiallyEvaluatedIfUsed 572 }; 573 574 /// \brief Data structure used to record current or nested 575 /// expression evaluation contexts. 576 struct ExpressionEvaluationContextRecord { 577 /// \brief The expression evaluation context. 578 ExpressionEvaluationContext Context; 579 580 /// \brief Whether the enclosing context needed a cleanup. 581 bool ParentNeedsCleanups; 582 583 /// \brief Whether we are in a decltype expression. 584 bool IsDecltype; 585 586 /// \brief The number of active cleanup objects when we entered 587 /// this expression evaluation context. 588 unsigned NumCleanupObjects; 589 590 llvm::SmallPtrSet<Expr*, 8> SavedMaybeODRUseExprs; 591 592 /// \brief The lambdas that are present within this context, if it 593 /// is indeed an unevaluated context. 594 llvm::SmallVector<LambdaExpr *, 2> Lambdas; 595 596 /// \brief The declaration that provides context for the lambda expression 597 /// if the normal declaration context does not suffice, e.g., in a 598 /// default function argument. 599 Decl *LambdaContextDecl; 600 601 /// \brief The context information used to mangle lambda expressions 602 /// within this context. 603 /// 604 /// This mangling information is allocated lazily, since most contexts 605 /// do not have lambda expressions. 606 LambdaMangleContext *LambdaMangle; 607 608 /// \brief If we are processing a decltype type, a set of call expressions 609 /// for which we have deferred checking the completeness of the return type. 610 llvm::SmallVector<CallExpr*, 8> DelayedDecltypeCalls; 611 612 /// \brief If we are processing a decltype type, a set of temporary binding 613 /// expressions for which we have deferred checking the destructor. 614 llvm::SmallVector<CXXBindTemporaryExpr*, 8> DelayedDecltypeBinds; 615 616 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, 617 unsigned NumCleanupObjects, 618 bool ParentNeedsCleanups, 619 Decl *LambdaContextDecl, 620 bool IsDecltype) 621 : Context(Context), ParentNeedsCleanups(ParentNeedsCleanups), 622 IsDecltype(IsDecltype), NumCleanupObjects(NumCleanupObjects), 623 LambdaContextDecl(LambdaContextDecl), LambdaMangle() { } 624 625 ~ExpressionEvaluationContextRecord() { 626 delete LambdaMangle; 627 } 628 629 /// \brief Retrieve the mangling context for lambdas. 630 LambdaMangleContext &getLambdaMangleContext() { 631 assert(LambdaContextDecl && "Need to have a lambda context declaration"); 632 if (!LambdaMangle) 633 LambdaMangle = new LambdaMangleContext; 634 return *LambdaMangle; 635 } 636 }; 637 638 /// A stack of expression evaluation contexts. 639 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; 640 641 /// SpecialMemberOverloadResult - The overloading result for a special member 642 /// function. 643 /// 644 /// This is basically a wrapper around PointerIntPair. The lowest bits of the 645 /// integer are used to determine whether overload resolution succeeded. 646 class SpecialMemberOverloadResult : public llvm::FastFoldingSetNode { 647 public: 648 enum Kind { 649 NoMemberOrDeleted, 650 Ambiguous, 651 Success 652 }; 653 654 private: 655 llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; 656 657 public: 658 SpecialMemberOverloadResult(const llvm::FoldingSetNodeID &ID) 659 : FastFoldingSetNode(ID) 660 {} 661 662 CXXMethodDecl *getMethod() const { return Pair.getPointer(); } 663 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } 664 665 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } 666 void setKind(Kind K) { Pair.setInt(K); } 667 }; 668 669 /// \brief A cache of special member function overload resolution results 670 /// for C++ records. 671 llvm::FoldingSet<SpecialMemberOverloadResult> SpecialMemberCache; 672 673 /// \brief The kind of translation unit we are processing. 674 /// 675 /// When we're processing a complete translation unit, Sema will perform 676 /// end-of-translation-unit semantic tasks (such as creating 677 /// initializers for tentative definitions in C) once parsing has 678 /// completed. Modules and precompiled headers perform different kinds of 679 /// checks. 680 TranslationUnitKind TUKind; 681 682 llvm::BumpPtrAllocator BumpAlloc; 683 684 /// \brief The number of SFINAE diagnostics that have been trapped. 685 unsigned NumSFINAEErrors; 686 687 typedef llvm::DenseMap<ParmVarDecl *, SmallVector<ParmVarDecl *, 1> > 688 UnparsedDefaultArgInstantiationsMap; 689 690 /// \brief A mapping from parameters with unparsed default arguments to the 691 /// set of instantiations of each parameter. 692 /// 693 /// This mapping is a temporary data structure used when parsing 694 /// nested class templates or nested classes of class templates, 695 /// where we might end up instantiating an inner class before the 696 /// default arguments of its methods have been parsed. 697 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; 698 699 // Contains the locations of the beginning of unparsed default 700 // argument locations. 701 llvm::DenseMap<ParmVarDecl *,SourceLocation> UnparsedDefaultArgLocs; 702 703 /// UndefinedInternals - all the used, undefined objects with 704 /// internal linkage in this translation unit. 705 llvm::DenseMap<NamedDecl*, SourceLocation> UndefinedInternals; 706 707 typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; 708 typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; 709 710 /// Method Pool - allows efficient lookup when typechecking messages to "id". 711 /// We need to maintain a list, since selectors can have differing signatures 712 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% 713 /// of selectors are "overloaded"). 714 GlobalMethodPool MethodPool; 715 716 /// Method selectors used in a @selector expression. Used for implementation 717 /// of -Wselector. 718 llvm::DenseMap<Selector, SourceLocation> ReferencedSelectors; 719 720 void ReadMethodPool(Selector Sel); 721 722 /// Private Helper predicate to check for 'self'. 723 bool isSelfExpr(Expr *RExpr); 724 725 /// \brief Cause the active diagnostic on the DiagosticsEngine to be 726 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and 727 /// should not be used elsewhere. 728 void EmitCurrentDiagnostic(unsigned DiagID); 729 730public: 731 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, 732 TranslationUnitKind TUKind = TU_Complete, 733 CodeCompleteConsumer *CompletionConsumer = 0); 734 ~Sema(); 735 736 /// \brief Perform initialization that occurs after the parser has been 737 /// initialized but before it parses anything. 738 void Initialize(); 739 740 const LangOptions &getLangOpts() const { return LangOpts; } 741 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } 742 FPOptions &getFPOptions() { return FPFeatures; } 743 744 DiagnosticsEngine &getDiagnostics() const { return Diags; } 745 SourceManager &getSourceManager() const { return SourceMgr; } 746 const TargetAttributesSema &getTargetAttributesSema() const; 747 Preprocessor &getPreprocessor() const { return PP; } 748 ASTContext &getASTContext() const { return Context; } 749 ASTConsumer &getASTConsumer() const { return Consumer; } 750 ASTMutationListener *getASTMutationListener() const; 751 752 void PrintStats() const; 753 754 /// \brief Helper class that creates diagnostics with optional 755 /// template instantiation stacks. 756 /// 757 /// This class provides a wrapper around the basic DiagnosticBuilder 758 /// class that emits diagnostics. SemaDiagnosticBuilder is 759 /// responsible for emitting the diagnostic (as DiagnosticBuilder 760 /// does) and, if the diagnostic comes from inside a template 761 /// instantiation, printing the template instantiation stack as 762 /// well. 763 class SemaDiagnosticBuilder : public DiagnosticBuilder { 764 Sema &SemaRef; 765 unsigned DiagID; 766 767 public: 768 SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) 769 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } 770 771 ~SemaDiagnosticBuilder() { 772 // If we aren't active, there is nothing to do. 773 if (!isActive()) return; 774 775 // Otherwise, we need to emit the diagnostic. First flush the underlying 776 // DiagnosticBuilder data, and clear the diagnostic builder itself so it 777 // won't emit the diagnostic in its own destructor. 778 // 779 // This seems wasteful, in that as written the DiagnosticBuilder dtor will 780 // do its own needless checks to see if the diagnostic needs to be 781 // emitted. However, because we take care to ensure that the builder 782 // objects never escape, a sufficiently smart compiler will be able to 783 // eliminate that code. 784 FlushCounts(); 785 Clear(); 786 787 // Dispatch to Sema to emit the diagnostic. 788 SemaRef.EmitCurrentDiagnostic(DiagID); 789 } 790 }; 791 792 /// \brief Emit a diagnostic. 793 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { 794 DiagnosticBuilder DB = Diags.Report(Loc, DiagID); 795 return SemaDiagnosticBuilder(DB, *this, DiagID); 796 } 797 798 /// \brief Emit a partial diagnostic. 799 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); 800 801 /// \brief Build a partial diagnostic. 802 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h 803 804 bool findMacroSpelling(SourceLocation &loc, StringRef name); 805 806 /// \brief Get a string to suggest for zero-initialization of a type. 807 std::string getFixItZeroInitializerForType(QualType T) const; 808 std::string getFixItZeroLiteralForType(QualType T) const; 809 810 ExprResult Owned(Expr* E) { return E; } 811 ExprResult Owned(ExprResult R) { return R; } 812 StmtResult Owned(Stmt* S) { return S; } 813 814 void ActOnEndOfTranslationUnit(); 815 816 void CheckDelegatingCtorCycles(); 817 818 Scope *getScopeForContext(DeclContext *Ctx); 819 820 void PushFunctionScope(); 821 void PushBlockScope(Scope *BlockScope, BlockDecl *Block); 822 void PushLambdaScope(CXXRecordDecl *Lambda, CXXMethodDecl *CallOperator); 823 void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP =0, 824 const Decl *D = 0, const BlockExpr *blkExpr = 0); 825 826 sema::FunctionScopeInfo *getCurFunction() const { 827 return FunctionScopes.back(); 828 } 829 830 void PushCompoundScope(); 831 void PopCompoundScope(); 832 833 sema::CompoundScopeInfo &getCurCompoundScope() const; 834 835 bool hasAnyUnrecoverableErrorsInThisFunction() const; 836 837 /// \brief Retrieve the current block, if any. 838 sema::BlockScopeInfo *getCurBlock(); 839 840 /// \brief Retrieve the current lambda expression, if any. 841 sema::LambdaScopeInfo *getCurLambda(); 842 843 /// WeakTopLevelDeclDecls - access to #pragma weak-generated Decls 844 SmallVector<Decl*,2> &WeakTopLevelDecls() { return WeakTopLevelDecl; } 845 846 //===--------------------------------------------------------------------===// 847 // Type Analysis / Processing: SemaType.cpp. 848 // 849 850 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs); 851 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVR) { 852 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR)); 853 } 854 QualType BuildPointerType(QualType T, 855 SourceLocation Loc, DeclarationName Entity); 856 QualType BuildReferenceType(QualType T, bool LValueRef, 857 SourceLocation Loc, DeclarationName Entity); 858 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 859 Expr *ArraySize, unsigned Quals, 860 SourceRange Brackets, DeclarationName Entity); 861 QualType BuildExtVectorType(QualType T, Expr *ArraySize, 862 SourceLocation AttrLoc); 863 QualType BuildFunctionType(QualType T, 864 QualType *ParamTypes, unsigned NumParamTypes, 865 bool Variadic, bool HasTrailingReturn, 866 unsigned Quals, RefQualifierKind RefQualifier, 867 SourceLocation Loc, DeclarationName Entity, 868 FunctionType::ExtInfo Info); 869 QualType BuildMemberPointerType(QualType T, QualType Class, 870 SourceLocation Loc, 871 DeclarationName Entity); 872 QualType BuildBlockPointerType(QualType T, 873 SourceLocation Loc, DeclarationName Entity); 874 QualType BuildParenType(QualType T); 875 QualType BuildAtomicType(QualType T, SourceLocation Loc); 876 877 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); 878 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); 879 TypeSourceInfo *GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 880 TypeSourceInfo *ReturnTypeInfo); 881 882 /// \brief Package the given type and TSI into a ParsedType. 883 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); 884 DeclarationNameInfo GetNameForDeclarator(Declarator &D); 885 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); 886 static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = 0); 887 CanThrowResult canThrow(const Expr *E); 888 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, 889 const FunctionProtoType *FPT); 890 bool CheckSpecifiedExceptionType(QualType T, const SourceRange &Range); 891 bool CheckDistantExceptionSpec(QualType T); 892 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); 893 bool CheckEquivalentExceptionSpec( 894 const FunctionProtoType *Old, SourceLocation OldLoc, 895 const FunctionProtoType *New, SourceLocation NewLoc); 896 bool CheckEquivalentExceptionSpec( 897 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 898 const FunctionProtoType *Old, SourceLocation OldLoc, 899 const FunctionProtoType *New, SourceLocation NewLoc, 900 bool *MissingExceptionSpecification = 0, 901 bool *MissingEmptyExceptionSpecification = 0, 902 bool AllowNoexceptAllMatchWithNoSpec = false, 903 bool IsOperatorNew = false); 904 bool CheckExceptionSpecSubset( 905 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, 906 const FunctionProtoType *Superset, SourceLocation SuperLoc, 907 const FunctionProtoType *Subset, SourceLocation SubLoc); 908 bool CheckParamExceptionSpec(const PartialDiagnostic & NoteID, 909 const FunctionProtoType *Target, SourceLocation TargetLoc, 910 const FunctionProtoType *Source, SourceLocation SourceLoc); 911 912 TypeResult ActOnTypeName(Scope *S, Declarator &D); 913 914 /// \brief The parser has parsed the context-sensitive type 'instancetype' 915 /// in an Objective-C message declaration. Return the appropriate type. 916 ParsedType ActOnObjCInstanceType(SourceLocation Loc); 917 918 /// \brief Abstract class used to diagnose incomplete types. 919 struct TypeDiagnoser { 920 bool Suppressed; 921 922 TypeDiagnoser(bool Suppressed = false) : Suppressed(Suppressed) { } 923 924 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; 925 virtual ~TypeDiagnoser() {} 926 }; 927 928 static int getPrintable(int I) { return I; } 929 static unsigned getPrintable(unsigned I) { return I; } 930 static bool getPrintable(bool B) { return B; } 931 static const char * getPrintable(const char *S) { return S; } 932 static StringRef getPrintable(StringRef S) { return S; } 933 static const std::string &getPrintable(const std::string &S) { return S; } 934 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { 935 return II; 936 } 937 static DeclarationName getPrintable(DeclarationName N) { return N; } 938 static QualType getPrintable(QualType T) { return T; } 939 static SourceRange getPrintable(SourceRange R) { return R; } 940 static SourceRange getPrintable(SourceLocation L) { return L; } 941 static SourceRange getPrintable(Expr *E) { return E->getSourceRange(); } 942 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} 943 944 template<typename T1> 945 class BoundTypeDiagnoser1 : public TypeDiagnoser { 946 unsigned DiagID; 947 const T1 &Arg1; 948 949 public: 950 BoundTypeDiagnoser1(unsigned DiagID, const T1 &Arg1) 951 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1) { } 952 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 953 if (Suppressed) return; 954 S.Diag(Loc, DiagID) << getPrintable(Arg1) << T; 955 } 956 957 virtual ~BoundTypeDiagnoser1() { } 958 }; 959 960 template<typename T1, typename T2> 961 class BoundTypeDiagnoser2 : public TypeDiagnoser { 962 unsigned DiagID; 963 const T1 &Arg1; 964 const T2 &Arg2; 965 966 public: 967 BoundTypeDiagnoser2(unsigned DiagID, const T1 &Arg1, 968 const T2 &Arg2) 969 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), 970 Arg2(Arg2) { } 971 972 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 973 if (Suppressed) return; 974 S.Diag(Loc, DiagID) << getPrintable(Arg1) << getPrintable(Arg2) << T; 975 } 976 977 virtual ~BoundTypeDiagnoser2() { } 978 }; 979 980 template<typename T1, typename T2, typename T3> 981 class BoundTypeDiagnoser3 : public TypeDiagnoser { 982 unsigned DiagID; 983 const T1 &Arg1; 984 const T2 &Arg2; 985 const T3 &Arg3; 986 987 public: 988 BoundTypeDiagnoser3(unsigned DiagID, const T1 &Arg1, 989 const T2 &Arg2, const T3 &Arg3) 990 : TypeDiagnoser(DiagID == 0), DiagID(DiagID), Arg1(Arg1), 991 Arg2(Arg2), Arg3(Arg3) { } 992 993 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 994 if (Suppressed) return; 995 S.Diag(Loc, DiagID) 996 << getPrintable(Arg1) << getPrintable(Arg2) << getPrintable(Arg3) << T; 997 } 998 999 virtual ~BoundTypeDiagnoser3() { } 1000 }; 1001 1002 bool RequireCompleteType(SourceLocation Loc, QualType T, 1003 TypeDiagnoser &Diagnoser); 1004 bool RequireCompleteType(SourceLocation Loc, QualType T, 1005 unsigned DiagID); 1006 1007 template<typename T1> 1008 bool RequireCompleteType(SourceLocation Loc, QualType T, 1009 unsigned DiagID, const T1 &Arg1) { 1010 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1011 return RequireCompleteType(Loc, T, Diagnoser); 1012 } 1013 1014 template<typename T1, typename T2> 1015 bool RequireCompleteType(SourceLocation Loc, QualType T, 1016 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { 1017 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1018 return RequireCompleteType(Loc, T, Diagnoser); 1019 } 1020 1021 template<typename T1, typename T2, typename T3> 1022 bool RequireCompleteType(SourceLocation Loc, QualType T, 1023 unsigned DiagID, const T1 &Arg1, const T2 &Arg2, 1024 const T3 &Arg3) { 1025 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1026 Arg3); 1027 return RequireCompleteType(Loc, T, Diagnoser); 1028 } 1029 1030 bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); 1031 bool RequireCompleteExprType(Expr *E, unsigned DiagID); 1032 1033 template<typename T1> 1034 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1) { 1035 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1036 return RequireCompleteExprType(E, Diagnoser); 1037 } 1038 1039 template<typename T1, typename T2> 1040 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, 1041 const T2 &Arg2) { 1042 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1043 return RequireCompleteExprType(E, Diagnoser); 1044 } 1045 1046 template<typename T1, typename T2, typename T3> 1047 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const T1 &Arg1, 1048 const T2 &Arg2, const T3 &Arg3) { 1049 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1050 Arg3); 1051 return RequireCompleteExprType(E, Diagnoser); 1052 } 1053 1054 bool RequireLiteralType(SourceLocation Loc, QualType T, 1055 TypeDiagnoser &Diagnoser); 1056 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); 1057 1058 template<typename T1> 1059 bool RequireLiteralType(SourceLocation Loc, QualType T, 1060 unsigned DiagID, const T1 &Arg1) { 1061 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 1062 return RequireLiteralType(Loc, T, Diagnoser); 1063 } 1064 1065 template<typename T1, typename T2> 1066 bool RequireLiteralType(SourceLocation Loc, QualType T, 1067 unsigned DiagID, const T1 &Arg1, const T2 &Arg2) { 1068 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 1069 return RequireLiteralType(Loc, T, Diagnoser); 1070 } 1071 1072 template<typename T1, typename T2, typename T3> 1073 bool RequireLiteralType(SourceLocation Loc, QualType T, 1074 unsigned DiagID, const T1 &Arg1, const T2 &Arg2, 1075 const T3 &Arg3) { 1076 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, 1077 Arg3); 1078 return RequireLiteralType(Loc, T, Diagnoser); 1079 } 1080 1081 QualType getElaboratedType(ElaboratedTypeKeyword Keyword, 1082 const CXXScopeSpec &SS, QualType T); 1083 1084 QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); 1085 QualType BuildDecltypeType(Expr *E, SourceLocation Loc); 1086 QualType BuildUnaryTransformType(QualType BaseType, 1087 UnaryTransformType::UTTKind UKind, 1088 SourceLocation Loc); 1089 1090 //===--------------------------------------------------------------------===// 1091 // Symbol table / Decl tracking callbacks: SemaDecl.cpp. 1092 // 1093 1094 /// List of decls defined in a function prototype. This contains EnumConstants 1095 /// that incorrectly end up in translation unit scope because there is no 1096 /// function to pin them on. ActOnFunctionDeclarator reads this list and patches 1097 /// them into the FunctionDecl. 1098 std::vector<NamedDecl*> DeclsInPrototypeScope; 1099 /// Nonzero if we are currently parsing a function declarator. This is a counter 1100 /// as opposed to a boolean so we can deal with nested function declarators 1101 /// such as: 1102 /// void f(void (*g)(), ...) 1103 unsigned InFunctionDeclarator; 1104 1105 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = 0); 1106 1107 void DiagnoseUseOfUnimplementedSelectors(); 1108 1109 ParsedType getTypeName(IdentifierInfo &II, SourceLocation NameLoc, 1110 Scope *S, CXXScopeSpec *SS = 0, 1111 bool isClassName = false, 1112 bool HasTrailingDot = false, 1113 ParsedType ObjectType = ParsedType(), 1114 bool IsCtorOrDtorName = false, 1115 bool WantNontrivialTypeSourceInfo = false, 1116 IdentifierInfo **CorrectedII = 0); 1117 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); 1118 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); 1119 bool DiagnoseUnknownTypeName(const IdentifierInfo &II, 1120 SourceLocation IILoc, 1121 Scope *S, 1122 CXXScopeSpec *SS, 1123 ParsedType &SuggestedType); 1124 1125 /// \brief Describes the result of the name lookup and resolution performed 1126 /// by \c ClassifyName(). 1127 enum NameClassificationKind { 1128 NC_Unknown, 1129 NC_Error, 1130 NC_Keyword, 1131 NC_Type, 1132 NC_Expression, 1133 NC_NestedNameSpecifier, 1134 NC_TypeTemplate, 1135 NC_FunctionTemplate 1136 }; 1137 1138 class NameClassification { 1139 NameClassificationKind Kind; 1140 ExprResult Expr; 1141 TemplateName Template; 1142 ParsedType Type; 1143 const IdentifierInfo *Keyword; 1144 1145 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} 1146 1147 public: 1148 NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} 1149 1150 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} 1151 1152 NameClassification(const IdentifierInfo *Keyword) 1153 : Kind(NC_Keyword), Keyword(Keyword) { } 1154 1155 static NameClassification Error() { 1156 return NameClassification(NC_Error); 1157 } 1158 1159 static NameClassification Unknown() { 1160 return NameClassification(NC_Unknown); 1161 } 1162 1163 static NameClassification NestedNameSpecifier() { 1164 return NameClassification(NC_NestedNameSpecifier); 1165 } 1166 1167 static NameClassification TypeTemplate(TemplateName Name) { 1168 NameClassification Result(NC_TypeTemplate); 1169 Result.Template = Name; 1170 return Result; 1171 } 1172 1173 static NameClassification FunctionTemplate(TemplateName Name) { 1174 NameClassification Result(NC_FunctionTemplate); 1175 Result.Template = Name; 1176 return Result; 1177 } 1178 1179 NameClassificationKind getKind() const { return Kind; } 1180 1181 ParsedType getType() const { 1182 assert(Kind == NC_Type); 1183 return Type; 1184 } 1185 1186 ExprResult getExpression() const { 1187 assert(Kind == NC_Expression); 1188 return Expr; 1189 } 1190 1191 TemplateName getTemplateName() const { 1192 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 1193 return Template; 1194 } 1195 1196 TemplateNameKind getTemplateNameKind() const { 1197 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate); 1198 return Kind == NC_TypeTemplate? TNK_Type_template : TNK_Function_template; 1199 } 1200}; 1201 1202 /// \brief Perform name lookup on the given name, classifying it based on 1203 /// the results of name lookup and the following token. 1204 /// 1205 /// This routine is used by the parser to resolve identifiers and help direct 1206 /// parsing. When the identifier cannot be found, this routine will attempt 1207 /// to correct the typo and classify based on the resulting name. 1208 /// 1209 /// \param S The scope in which we're performing name lookup. 1210 /// 1211 /// \param SS The nested-name-specifier that precedes the name. 1212 /// 1213 /// \param Name The identifier. If typo correction finds an alternative name, 1214 /// this pointer parameter will be updated accordingly. 1215 /// 1216 /// \param NameLoc The location of the identifier. 1217 /// 1218 /// \param NextToken The token following the identifier. Used to help 1219 /// disambiguate the name. 1220 NameClassification ClassifyName(Scope *S, 1221 CXXScopeSpec &SS, 1222 IdentifierInfo *&Name, 1223 SourceLocation NameLoc, 1224 const Token &NextToken); 1225 1226 Decl *ActOnDeclarator(Scope *S, Declarator &D); 1227 1228 Decl *HandleDeclarator(Scope *S, Declarator &D, 1229 MultiTemplateParamsArg TemplateParameterLists); 1230 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, 1231 const LookupResult &Previous, 1232 Scope *S); 1233 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); 1234 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, 1235 DeclarationName Name, 1236 SourceLocation Loc); 1237 void DiagnoseFunctionSpecifiers(Declarator& D); 1238 void CheckShadow(Scope *S, VarDecl *D, const LookupResult& R); 1239 void CheckShadow(Scope *S, VarDecl *D); 1240 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); 1241 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); 1242 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1243 TypeSourceInfo *TInfo, 1244 LookupResult &Previous); 1245 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, 1246 LookupResult &Previous, bool &Redeclaration); 1247 NamedDecl* ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1248 TypeSourceInfo *TInfo, 1249 LookupResult &Previous, 1250 MultiTemplateParamsArg TemplateParamLists); 1251 // Returns true if the variable declaration is a redeclaration 1252 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); 1253 void CheckCompleteVariableDeclaration(VarDecl *var); 1254 void ActOnStartFunctionDeclarator(); 1255 void ActOnEndFunctionDeclarator(); 1256 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, 1257 TypeSourceInfo *TInfo, 1258 LookupResult &Previous, 1259 MultiTemplateParamsArg TemplateParamLists, 1260 bool &AddToScope); 1261 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1262 1263 bool CheckConstexprFunctionDecl(const FunctionDecl *FD); 1264 bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); 1265 1266 void DiagnoseHiddenVirtualMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); 1267 // Returns true if the function declaration is a redeclaration 1268 bool CheckFunctionDeclaration(Scope *S, 1269 FunctionDecl *NewFD, LookupResult &Previous, 1270 bool IsExplicitSpecialization); 1271 void CheckMain(FunctionDecl *FD, const DeclSpec &D); 1272 Decl *ActOnParamDeclarator(Scope *S, Declarator &D); 1273 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, 1274 SourceLocation Loc, 1275 QualType T); 1276 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, 1277 SourceLocation NameLoc, IdentifierInfo *Name, 1278 QualType T, TypeSourceInfo *TSInfo, 1279 StorageClass SC, StorageClass SCAsWritten); 1280 void ActOnParamDefaultArgument(Decl *param, 1281 SourceLocation EqualLoc, 1282 Expr *defarg); 1283 void ActOnParamUnparsedDefaultArgument(Decl *param, 1284 SourceLocation EqualLoc, 1285 SourceLocation ArgLoc); 1286 void ActOnParamDefaultArgumentError(Decl *param); 1287 bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, 1288 SourceLocation EqualLoc); 1289 1290 void CheckSelfReference(Decl *OrigDecl, Expr *E); 1291 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit, 1292 bool TypeMayContainAuto); 1293 void ActOnUninitializedDecl(Decl *dcl, bool TypeMayContainAuto); 1294 void ActOnInitializerError(Decl *Dcl); 1295 void ActOnCXXForRangeDecl(Decl *D); 1296 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); 1297 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); 1298 void FinalizeDeclaration(Decl *D); 1299 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, 1300 Decl **Group, 1301 unsigned NumDecls); 1302 DeclGroupPtrTy BuildDeclaratorGroup(Decl **Group, unsigned NumDecls, 1303 bool TypeMayContainAuto = true); 1304 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, 1305 SourceLocation LocAfterDecls); 1306 void CheckForFunctionRedefinition(FunctionDecl *FD); 1307 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D); 1308 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D); 1309 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); 1310 1311 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); 1312 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); 1313 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); 1314 1315 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an 1316 /// attribute for which parsing is delayed. 1317 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); 1318 1319 /// \brief Diagnose any unused parameters in the given sequence of 1320 /// ParmVarDecl pointers. 1321 void DiagnoseUnusedParameters(ParmVarDecl * const *Begin, 1322 ParmVarDecl * const *End); 1323 1324 /// \brief Diagnose whether the size of parameters or return value of a 1325 /// function or obj-c method definition is pass-by-value and larger than a 1326 /// specified threshold. 1327 void DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Begin, 1328 ParmVarDecl * const *End, 1329 QualType ReturnTy, 1330 NamedDecl *D); 1331 1332 void DiagnoseInvalidJumps(Stmt *Body); 1333 Decl *ActOnFileScopeAsmDecl(Expr *expr, 1334 SourceLocation AsmLoc, 1335 SourceLocation RParenLoc); 1336 1337 /// \brief The parser has processed a module import declaration. 1338 /// 1339 /// \param AtLoc The location of the '@' symbol, if any. 1340 /// 1341 /// \param ImportLoc The location of the 'import' keyword. 1342 /// 1343 /// \param Path The module access path. 1344 DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, 1345 ModuleIdPath Path); 1346 1347 /// \brief Retrieve a suitable printing policy. 1348 PrintingPolicy getPrintingPolicy() const { 1349 return getPrintingPolicy(Context, PP); 1350 } 1351 1352 /// \brief Retrieve a suitable printing policy. 1353 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, 1354 const Preprocessor &PP); 1355 1356 /// Scope actions. 1357 void ActOnPopScope(SourceLocation Loc, Scope *S); 1358 void ActOnTranslationUnitScope(Scope *S); 1359 1360 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1361 DeclSpec &DS); 1362 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, 1363 DeclSpec &DS, 1364 MultiTemplateParamsArg TemplateParams); 1365 1366 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, 1367 AccessSpecifier AS, 1368 RecordDecl *Record); 1369 1370 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, 1371 RecordDecl *Record); 1372 1373 bool isAcceptableTagRedeclaration(const TagDecl *Previous, 1374 TagTypeKind NewTag, bool isDefinition, 1375 SourceLocation NewTagLoc, 1376 const IdentifierInfo &Name); 1377 1378 enum TagUseKind { 1379 TUK_Reference, // Reference to a tag: 'struct foo *X;' 1380 TUK_Declaration, // Fwd decl of a tag: 'struct foo;' 1381 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' 1382 TUK_Friend // Friend declaration: 'friend struct foo;' 1383 }; 1384 1385 Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, 1386 SourceLocation KWLoc, CXXScopeSpec &SS, 1387 IdentifierInfo *Name, SourceLocation NameLoc, 1388 AttributeList *Attr, AccessSpecifier AS, 1389 SourceLocation ModulePrivateLoc, 1390 MultiTemplateParamsArg TemplateParameterLists, 1391 bool &OwnedDecl, bool &IsDependent, 1392 SourceLocation ScopedEnumKWLoc, 1393 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType); 1394 1395 Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, 1396 unsigned TagSpec, SourceLocation TagLoc, 1397 CXXScopeSpec &SS, 1398 IdentifierInfo *Name, SourceLocation NameLoc, 1399 AttributeList *Attr, 1400 MultiTemplateParamsArg TempParamLists); 1401 1402 TypeResult ActOnDependentTag(Scope *S, 1403 unsigned TagSpec, 1404 TagUseKind TUK, 1405 const CXXScopeSpec &SS, 1406 IdentifierInfo *Name, 1407 SourceLocation TagLoc, 1408 SourceLocation NameLoc); 1409 1410 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 1411 IdentifierInfo *ClassName, 1412 SmallVectorImpl<Decl *> &Decls); 1413 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, 1414 Declarator &D, Expr *BitfieldWidth); 1415 1416 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, 1417 Declarator &D, Expr *BitfieldWidth, bool HasInit, 1418 AccessSpecifier AS); 1419 1420 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, 1421 TypeSourceInfo *TInfo, 1422 RecordDecl *Record, SourceLocation Loc, 1423 bool Mutable, Expr *BitfieldWidth, bool HasInit, 1424 SourceLocation TSSL, 1425 AccessSpecifier AS, NamedDecl *PrevDecl, 1426 Declarator *D = 0); 1427 1428 enum CXXSpecialMember { 1429 CXXDefaultConstructor, 1430 CXXCopyConstructor, 1431 CXXMoveConstructor, 1432 CXXCopyAssignment, 1433 CXXMoveAssignment, 1434 CXXDestructor, 1435 CXXInvalid 1436 }; 1437 bool CheckNontrivialField(FieldDecl *FD); 1438 void DiagnoseNontrivial(const RecordType* Record, CXXSpecialMember mem); 1439 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); 1440 void ActOnLastBitfield(SourceLocation DeclStart, 1441 SmallVectorImpl<Decl *> &AllIvarDecls); 1442 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, 1443 Declarator &D, Expr *BitfieldWidth, 1444 tok::ObjCKeywordKind visibility); 1445 1446 // This is used for both record definitions and ObjC interface declarations. 1447 void ActOnFields(Scope* S, SourceLocation RecLoc, Decl *TagDecl, 1448 llvm::ArrayRef<Decl *> Fields, 1449 SourceLocation LBrac, SourceLocation RBrac, 1450 AttributeList *AttrList); 1451 1452 /// ActOnTagStartDefinition - Invoked when we have entered the 1453 /// scope of a tag's definition (e.g., for an enumeration, class, 1454 /// struct, or union). 1455 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); 1456 1457 Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); 1458 1459 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a 1460 /// C++ record definition's base-specifiers clause and are starting its 1461 /// member declarations. 1462 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, 1463 SourceLocation FinalLoc, 1464 SourceLocation LBraceLoc); 1465 1466 /// ActOnTagFinishDefinition - Invoked once we have finished parsing 1467 /// the definition of a tag (enumeration, class, struct, or union). 1468 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, 1469 SourceLocation RBraceLoc); 1470 1471 void ActOnObjCContainerFinishDefinition(); 1472 1473 /// \brief Invoked when we must temporarily exit the objective-c container 1474 /// scope for parsing/looking-up C constructs. 1475 /// 1476 /// Must be followed by a call to \see ActOnObjCReenterContainerContext 1477 void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); 1478 void ActOnObjCReenterContainerContext(DeclContext *DC); 1479 1480 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable 1481 /// error parsing the definition of a tag. 1482 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); 1483 1484 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, 1485 EnumConstantDecl *LastEnumConst, 1486 SourceLocation IdLoc, 1487 IdentifierInfo *Id, 1488 Expr *val); 1489 bool CheckEnumUnderlyingType(TypeSourceInfo *TI); 1490 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, 1491 QualType EnumUnderlyingTy, const EnumDecl *Prev); 1492 1493 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, 1494 SourceLocation IdLoc, IdentifierInfo *Id, 1495 AttributeList *Attrs, 1496 SourceLocation EqualLoc, Expr *Val); 1497 void ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc, 1498 SourceLocation RBraceLoc, Decl *EnumDecl, 1499 Decl **Elements, unsigned NumElements, 1500 Scope *S, AttributeList *Attr); 1501 1502 DeclContext *getContainingDC(DeclContext *DC); 1503 1504 /// Set the current declaration context until it gets popped. 1505 void PushDeclContext(Scope *S, DeclContext *DC); 1506 void PopDeclContext(); 1507 1508 /// EnterDeclaratorContext - Used when we must lookup names in the context 1509 /// of a declarator's nested name specifier. 1510 void EnterDeclaratorContext(Scope *S, DeclContext *DC); 1511 void ExitDeclaratorContext(Scope *S); 1512 1513 /// Push the parameters of D, which must be a function, into scope. 1514 void ActOnReenterFunctionContext(Scope* S, Decl* D); 1515 void ActOnExitFunctionContext(); 1516 1517 DeclContext *getFunctionLevelDeclContext(); 1518 1519 /// getCurFunctionDecl - If inside of a function body, this returns a pointer 1520 /// to the function decl for the function being parsed. If we're currently 1521 /// in a 'block', this returns the containing context. 1522 FunctionDecl *getCurFunctionDecl(); 1523 1524 /// getCurMethodDecl - If inside of a method body, this returns a pointer to 1525 /// the method decl for the method being parsed. If we're currently 1526 /// in a 'block', this returns the containing context. 1527 ObjCMethodDecl *getCurMethodDecl(); 1528 1529 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method 1530 /// or C function we're in, otherwise return null. If we're currently 1531 /// in a 'block', this returns the containing context. 1532 NamedDecl *getCurFunctionOrMethodDecl(); 1533 1534 /// Add this decl to the scope shadowed decl chains. 1535 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); 1536 1537 /// \brief Make the given externally-produced declaration visible at the 1538 /// top level scope. 1539 /// 1540 /// \param D The externally-produced declaration to push. 1541 /// 1542 /// \param Name The name of the externally-produced declaration. 1543 void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); 1544 1545 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true 1546 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns 1547 /// true if 'D' belongs to the given declaration context. 1548 /// 1549 /// \param ExplicitInstantiationOrSpecialization When true, we are checking 1550 /// whether the declaration is in scope for the purposes of explicit template 1551 /// instantiation or specialization. The default is false. 1552 bool isDeclInScope(NamedDecl *&D, DeclContext *Ctx, Scope *S = 0, 1553 bool ExplicitInstantiationOrSpecialization = false); 1554 1555 /// Finds the scope corresponding to the given decl context, if it 1556 /// happens to be an enclosing scope. Otherwise return NULL. 1557 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); 1558 1559 /// Subroutines of ActOnDeclarator(). 1560 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, 1561 TypeSourceInfo *TInfo); 1562 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); 1563 1564 /// Attribute merging methods. Return true if a new attribute was added. 1565 bool mergeAvailabilityAttr(Decl *D, SourceRange Range, bool Inherited, 1566 IdentifierInfo *Platform, VersionTuple Introduced, 1567 VersionTuple Deprecated, VersionTuple Obsoleted, 1568 bool IsUnavailable, StringRef Message); 1569 bool mergeVisibilityAttr(Decl *D, SourceRange Range, 1570 bool Inherited, VisibilityAttr::VisibilityType Vis); 1571 bool mergeDLLImportAttr(Decl *D, SourceRange Range, bool Inherited); 1572 bool mergeDLLExportAttr(Decl *D, SourceRange Range, bool Inherited); 1573 bool mergeDeclAttribute(Decl *New, InheritableAttr *Attr); 1574 1575 void mergeDeclAttributes(Decl *New, Decl *Old, bool MergeDeprecation = true); 1576 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1577 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S); 1578 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 1579 Scope *S); 1580 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 1581 void MergeVarDecl(VarDecl *New, LookupResult &OldDecls); 1582 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old); 1583 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1584 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 1585 1586 // AssignmentAction - This is used by all the assignment diagnostic functions 1587 // to represent what is actually causing the operation 1588 enum AssignmentAction { 1589 AA_Assigning, 1590 AA_Passing, 1591 AA_Returning, 1592 AA_Converting, 1593 AA_Initializing, 1594 AA_Sending, 1595 AA_Casting 1596 }; 1597 1598 /// C++ Overloading. 1599 enum OverloadKind { 1600 /// This is a legitimate overload: the existing declarations are 1601 /// functions or function templates with different signatures. 1602 Ovl_Overload, 1603 1604 /// This is not an overload because the signature exactly matches 1605 /// an existing declaration. 1606 Ovl_Match, 1607 1608 /// This is not an overload because the lookup results contain a 1609 /// non-function. 1610 Ovl_NonFunction 1611 }; 1612 OverloadKind CheckOverload(Scope *S, 1613 FunctionDecl *New, 1614 const LookupResult &OldDecls, 1615 NamedDecl *&OldDecl, 1616 bool IsForUsingDecl); 1617 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 1618 1619 /// \brief Checks availability of the function depending on the current 1620 /// function context.Inside an unavailable function,unavailability is ignored. 1621 /// 1622 /// \returns true if \arg FD is unavailable and current context is inside 1623 /// an available function, false otherwise. 1624 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 1625 1626 ImplicitConversionSequence 1627 TryImplicitConversion(Expr *From, QualType ToType, 1628 bool SuppressUserConversions, 1629 bool AllowExplicit, 1630 bool InOverloadResolution, 1631 bool CStyle, 1632 bool AllowObjCWritebackConversion); 1633 1634 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 1635 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 1636 bool IsComplexPromotion(QualType FromType, QualType ToType); 1637 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1638 bool InOverloadResolution, 1639 QualType& ConvertedType, bool &IncompatibleObjC); 1640 bool isObjCPointerConversion(QualType FromType, QualType ToType, 1641 QualType& ConvertedType, bool &IncompatibleObjC); 1642 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 1643 QualType &ConvertedType); 1644 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 1645 QualType& ConvertedType); 1646 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 1647 const FunctionProtoType *NewType, 1648 unsigned *ArgPos = 0); 1649 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 1650 QualType FromType, QualType ToType); 1651 1652 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 1653 bool CheckPointerConversion(Expr *From, QualType ToType, 1654 CastKind &Kind, 1655 CXXCastPath& BasePath, 1656 bool IgnoreBaseAccess); 1657 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 1658 bool InOverloadResolution, 1659 QualType &ConvertedType); 1660 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 1661 CastKind &Kind, 1662 CXXCastPath &BasePath, 1663 bool IgnoreBaseAccess); 1664 bool IsQualificationConversion(QualType FromType, QualType ToType, 1665 bool CStyle, bool &ObjCLifetimeConversion); 1666 bool IsNoReturnConversion(QualType FromType, QualType ToType, 1667 QualType &ResultTy); 1668 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 1669 1670 1671 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1672 const VarDecl *NRVOCandidate, 1673 QualType ResultType, 1674 Expr *Value, 1675 bool AllowNRVO = true); 1676 1677 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 1678 ExprResult Init); 1679 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 1680 SourceLocation EqualLoc, 1681 ExprResult Init, 1682 bool TopLevelOfInitList = false, 1683 bool AllowExplicit = false); 1684 ExprResult PerformObjectArgumentInitialization(Expr *From, 1685 NestedNameSpecifier *Qualifier, 1686 NamedDecl *FoundDecl, 1687 CXXMethodDecl *Method); 1688 1689 ExprResult PerformContextuallyConvertToBool(Expr *From); 1690 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 1691 1692 /// Contexts in which a converted constant expression is required. 1693 enum CCEKind { 1694 CCEK_CaseValue, ///< Expression in a case label. 1695 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 1696 CCEK_TemplateArg ///< Value of a non-type template parameter. 1697 }; 1698 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 1699 llvm::APSInt &Value, CCEKind CCE); 1700 1701 /// \brief Abstract base class used to diagnose problems that occur while 1702 /// trying to convert an expression to integral or enumeration type. 1703 class ICEConvertDiagnoser { 1704 public: 1705 bool Suppress; 1706 bool SuppressConversion; 1707 1708 ICEConvertDiagnoser(bool Suppress = false, 1709 bool SuppressConversion = false) 1710 : Suppress(Suppress), SuppressConversion(SuppressConversion) { } 1711 1712 /// \brief Emits a diagnostic complaining that the expression does not have 1713 /// integral or enumeration type. 1714 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1715 QualType T) = 0; 1716 1717 /// \brief Emits a diagnostic when the expression has incomplete class type. 1718 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 1719 QualType T) = 0; 1720 1721 /// \brief Emits a diagnostic when the only matching conversion function 1722 /// is explicit. 1723 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 1724 QualType T, 1725 QualType ConvTy) = 0; 1726 1727 /// \brief Emits a note for the explicit conversion function. 1728 virtual DiagnosticBuilder 1729 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 1730 1731 /// \brief Emits a diagnostic when there are multiple possible conversion 1732 /// functions. 1733 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 1734 QualType T) = 0; 1735 1736 /// \brief Emits a note for one of the candidate conversions. 1737 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 1738 QualType ConvTy) = 0; 1739 1740 /// \brief Emits a diagnostic when we picked a conversion function 1741 /// (for cases when we are not allowed to pick a conversion function). 1742 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 1743 QualType T, 1744 QualType ConvTy) = 0; 1745 1746 virtual ~ICEConvertDiagnoser() {} 1747 }; 1748 1749 ExprResult 1750 ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE, 1751 ICEConvertDiagnoser &Diagnoser, 1752 bool AllowScopedEnumerations); 1753 1754 enum ObjCSubscriptKind { 1755 OS_Array, 1756 OS_Dictionary, 1757 OS_Error 1758 }; 1759 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 1760 1761 ExprResult PerformObjectMemberConversion(Expr *From, 1762 NestedNameSpecifier *Qualifier, 1763 NamedDecl *FoundDecl, 1764 NamedDecl *Member); 1765 1766 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 1767 // TODO: make this is a typesafe union. 1768 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 1769 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 1770 1771 void AddOverloadCandidate(FunctionDecl *Function, 1772 DeclAccessPair FoundDecl, 1773 llvm::ArrayRef<Expr *> Args, 1774 OverloadCandidateSet& CandidateSet, 1775 bool SuppressUserConversions = false, 1776 bool PartialOverloading = false, 1777 bool AllowExplicit = false); 1778 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 1779 llvm::ArrayRef<Expr *> Args, 1780 OverloadCandidateSet& CandidateSet, 1781 bool SuppressUserConversions = false, 1782 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 1783 void AddMethodCandidate(DeclAccessPair FoundDecl, 1784 QualType ObjectType, 1785 Expr::Classification ObjectClassification, 1786 Expr **Args, unsigned NumArgs, 1787 OverloadCandidateSet& CandidateSet, 1788 bool SuppressUserConversion = false); 1789 void AddMethodCandidate(CXXMethodDecl *Method, 1790 DeclAccessPair FoundDecl, 1791 CXXRecordDecl *ActingContext, QualType ObjectType, 1792 Expr::Classification ObjectClassification, 1793 llvm::ArrayRef<Expr *> Args, 1794 OverloadCandidateSet& CandidateSet, 1795 bool SuppressUserConversions = false); 1796 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 1797 DeclAccessPair FoundDecl, 1798 CXXRecordDecl *ActingContext, 1799 TemplateArgumentListInfo *ExplicitTemplateArgs, 1800 QualType ObjectType, 1801 Expr::Classification ObjectClassification, 1802 llvm::ArrayRef<Expr *> Args, 1803 OverloadCandidateSet& CandidateSet, 1804 bool SuppressUserConversions = false); 1805 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 1806 DeclAccessPair FoundDecl, 1807 TemplateArgumentListInfo *ExplicitTemplateArgs, 1808 llvm::ArrayRef<Expr *> Args, 1809 OverloadCandidateSet& CandidateSet, 1810 bool SuppressUserConversions = false); 1811 void AddConversionCandidate(CXXConversionDecl *Conversion, 1812 DeclAccessPair FoundDecl, 1813 CXXRecordDecl *ActingContext, 1814 Expr *From, QualType ToType, 1815 OverloadCandidateSet& CandidateSet); 1816 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 1817 DeclAccessPair FoundDecl, 1818 CXXRecordDecl *ActingContext, 1819 Expr *From, QualType ToType, 1820 OverloadCandidateSet &CandidateSet); 1821 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 1822 DeclAccessPair FoundDecl, 1823 CXXRecordDecl *ActingContext, 1824 const FunctionProtoType *Proto, 1825 Expr *Object, llvm::ArrayRef<Expr*> Args, 1826 OverloadCandidateSet& CandidateSet); 1827 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 1828 SourceLocation OpLoc, 1829 Expr **Args, unsigned NumArgs, 1830 OverloadCandidateSet& CandidateSet, 1831 SourceRange OpRange = SourceRange()); 1832 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 1833 Expr **Args, unsigned NumArgs, 1834 OverloadCandidateSet& CandidateSet, 1835 bool IsAssignmentOperator = false, 1836 unsigned NumContextualBoolArguments = 0); 1837 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 1838 SourceLocation OpLoc, 1839 Expr **Args, unsigned NumArgs, 1840 OverloadCandidateSet& CandidateSet); 1841 void AddArgumentDependentLookupCandidates(DeclarationName Name, 1842 bool Operator, SourceLocation Loc, 1843 llvm::ArrayRef<Expr *> Args, 1844 TemplateArgumentListInfo *ExplicitTemplateArgs, 1845 OverloadCandidateSet& CandidateSet, 1846 bool PartialOverloading = false, 1847 bool StdNamespaceIsAssociated = false); 1848 1849 // Emit as a 'note' the specific overload candidate 1850 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType()); 1851 1852 // Emit as a series of 'note's all template and non-templates 1853 // identified by the expression Expr 1854 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType()); 1855 1856 // [PossiblyAFunctionType] --> [Return] 1857 // NonFunctionType --> NonFunctionType 1858 // R (A) --> R(A) 1859 // R (*)(A) --> R (A) 1860 // R (&)(A) --> R (A) 1861 // R (S::*)(A) --> R (A) 1862 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 1863 1864 FunctionDecl * 1865 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 1866 QualType TargetType, 1867 bool Complain, 1868 DeclAccessPair &Found, 1869 bool *pHadMultipleCandidates = 0); 1870 1871 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 1872 bool Complain = false, 1873 DeclAccessPair* Found = 0); 1874 1875 bool ResolveAndFixSingleFunctionTemplateSpecialization( 1876 ExprResult &SrcExpr, 1877 bool DoFunctionPointerConverion = false, 1878 bool Complain = false, 1879 const SourceRange& OpRangeForComplaining = SourceRange(), 1880 QualType DestTypeForComplaining = QualType(), 1881 unsigned DiagIDForComplaining = 0); 1882 1883 1884 Expr *FixOverloadedFunctionReference(Expr *E, 1885 DeclAccessPair FoundDecl, 1886 FunctionDecl *Fn); 1887 ExprResult FixOverloadedFunctionReference(ExprResult, 1888 DeclAccessPair FoundDecl, 1889 FunctionDecl *Fn); 1890 1891 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 1892 llvm::ArrayRef<Expr *> Args, 1893 OverloadCandidateSet &CandidateSet, 1894 bool PartialOverloading = false); 1895 1896 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 1897 UnresolvedLookupExpr *ULE, 1898 SourceLocation LParenLoc, 1899 Expr **Args, unsigned NumArgs, 1900 SourceLocation RParenLoc, 1901 Expr *ExecConfig, 1902 bool AllowTypoCorrection=true); 1903 1904 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 1905 unsigned Opc, 1906 const UnresolvedSetImpl &Fns, 1907 Expr *input); 1908 1909 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 1910 unsigned Opc, 1911 const UnresolvedSetImpl &Fns, 1912 Expr *LHS, Expr *RHS); 1913 1914 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 1915 SourceLocation RLoc, 1916 Expr *Base,Expr *Idx); 1917 1918 ExprResult 1919 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 1920 SourceLocation LParenLoc, Expr **Args, 1921 unsigned NumArgs, SourceLocation RParenLoc); 1922 ExprResult 1923 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 1924 Expr **Args, unsigned NumArgs, 1925 SourceLocation RParenLoc); 1926 1927 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 1928 SourceLocation OpLoc); 1929 1930 /// CheckCallReturnType - Checks that a call expression's return type is 1931 /// complete. Returns true on failure. The location passed in is the location 1932 /// that best represents the call. 1933 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 1934 CallExpr *CE, FunctionDecl *FD); 1935 1936 /// Helpers for dealing with blocks and functions. 1937 bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd, 1938 bool CheckParameterNames); 1939 void CheckCXXDefaultArguments(FunctionDecl *FD); 1940 void CheckExtraCXXDefaultArguments(Declarator &D); 1941 Scope *getNonFieldDeclScope(Scope *S); 1942 1943 /// \name Name lookup 1944 /// 1945 /// These routines provide name lookup that is used during semantic 1946 /// analysis to resolve the various kinds of names (identifiers, 1947 /// overloaded operator names, constructor names, etc.) into zero or 1948 /// more declarations within a particular scope. The major entry 1949 /// points are LookupName, which performs unqualified name lookup, 1950 /// and LookupQualifiedName, which performs qualified name lookup. 1951 /// 1952 /// All name lookup is performed based on some specific criteria, 1953 /// which specify what names will be visible to name lookup and how 1954 /// far name lookup should work. These criteria are important both 1955 /// for capturing language semantics (certain lookups will ignore 1956 /// certain names, for example) and for performance, since name 1957 /// lookup is often a bottleneck in the compilation of C++. Name 1958 /// lookup criteria is specified via the LookupCriteria enumeration. 1959 /// 1960 /// The results of name lookup can vary based on the kind of name 1961 /// lookup performed, the current language, and the translation 1962 /// unit. In C, for example, name lookup will either return nothing 1963 /// (no entity found) or a single declaration. In C++, name lookup 1964 /// can additionally refer to a set of overloaded functions or 1965 /// result in an ambiguity. All of the possible results of name 1966 /// lookup are captured by the LookupResult class, which provides 1967 /// the ability to distinguish among them. 1968 //@{ 1969 1970 /// @brief Describes the kind of name lookup to perform. 1971 enum LookupNameKind { 1972 /// Ordinary name lookup, which finds ordinary names (functions, 1973 /// variables, typedefs, etc.) in C and most kinds of names 1974 /// (functions, variables, members, types, etc.) in C++. 1975 LookupOrdinaryName = 0, 1976 /// Tag name lookup, which finds the names of enums, classes, 1977 /// structs, and unions. 1978 LookupTagName, 1979 /// Label name lookup. 1980 LookupLabel, 1981 /// Member name lookup, which finds the names of 1982 /// class/struct/union members. 1983 LookupMemberName, 1984 /// Look up of an operator name (e.g., operator+) for use with 1985 /// operator overloading. This lookup is similar to ordinary name 1986 /// lookup, but will ignore any declarations that are class members. 1987 LookupOperatorName, 1988 /// Look up of a name that precedes the '::' scope resolution 1989 /// operator in C++. This lookup completely ignores operator, object, 1990 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 1991 LookupNestedNameSpecifierName, 1992 /// Look up a namespace name within a C++ using directive or 1993 /// namespace alias definition, ignoring non-namespace names (C++ 1994 /// [basic.lookup.udir]p1). 1995 LookupNamespaceName, 1996 /// Look up all declarations in a scope with the given name, 1997 /// including resolved using declarations. This is appropriate 1998 /// for checking redeclarations for a using declaration. 1999 LookupUsingDeclName, 2000 /// Look up an ordinary name that is going to be redeclared as a 2001 /// name with linkage. This lookup ignores any declarations that 2002 /// are outside of the current scope unless they have linkage. See 2003 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 2004 LookupRedeclarationWithLinkage, 2005 /// Look up the name of an Objective-C protocol. 2006 LookupObjCProtocolName, 2007 /// Look up implicit 'self' parameter of an objective-c method. 2008 LookupObjCImplicitSelfParam, 2009 /// \brief Look up any declaration with any name. 2010 LookupAnyName 2011 }; 2012 2013 /// \brief Specifies whether (or how) name lookup is being performed for a 2014 /// redeclaration (vs. a reference). 2015 enum RedeclarationKind { 2016 /// \brief The lookup is a reference to this name that is not for the 2017 /// purpose of redeclaring the name. 2018 NotForRedeclaration = 0, 2019 /// \brief The lookup results will be used for redeclaration of a name, 2020 /// if an entity by that name already exists. 2021 ForRedeclaration 2022 }; 2023 2024 /// \brief The possible outcomes of name lookup for a literal operator. 2025 enum LiteralOperatorLookupResult { 2026 /// \brief The lookup resulted in an error. 2027 LOLR_Error, 2028 /// \brief The lookup found a single 'cooked' literal operator, which 2029 /// expects a normal literal to be built and passed to it. 2030 LOLR_Cooked, 2031 /// \brief The lookup found a single 'raw' literal operator, which expects 2032 /// a string literal containing the spelling of the literal token. 2033 LOLR_Raw, 2034 /// \brief The lookup found an overload set of literal operator templates, 2035 /// which expect the characters of the spelling of the literal token to be 2036 /// passed as a non-type template argument pack. 2037 LOLR_Template 2038 }; 2039 2040 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 2041 CXXSpecialMember SM, 2042 bool ConstArg, 2043 bool VolatileArg, 2044 bool RValueThis, 2045 bool ConstThis, 2046 bool VolatileThis); 2047 2048private: 2049 bool CppLookupName(LookupResult &R, Scope *S); 2050 2051 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 2052 // 2053 // The boolean value will be true to indicate that the namespace was loaded 2054 // from an AST/PCH file, or false otherwise. 2055 llvm::DenseMap<NamespaceDecl*, bool> KnownNamespaces; 2056 2057 /// \brief Whether we have already loaded known namespaces from an extenal 2058 /// source. 2059 bool LoadedExternalKnownNamespaces; 2060 2061public: 2062 /// \brief Look up a name, looking for a single declaration. Return 2063 /// null if the results were absent, ambiguous, or overloaded. 2064 /// 2065 /// It is preferable to use the elaborated form and explicitly handle 2066 /// ambiguity and overloaded. 2067 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 2068 SourceLocation Loc, 2069 LookupNameKind NameKind, 2070 RedeclarationKind Redecl 2071 = NotForRedeclaration); 2072 bool LookupName(LookupResult &R, Scope *S, 2073 bool AllowBuiltinCreation = false); 2074 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2075 bool InUnqualifiedLookup = false); 2076 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2077 bool AllowBuiltinCreation = false, 2078 bool EnteringContext = false); 2079 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 2080 RedeclarationKind Redecl 2081 = NotForRedeclaration); 2082 2083 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2084 QualType T1, QualType T2, 2085 UnresolvedSetImpl &Functions); 2086 2087 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 2088 SourceLocation GnuLabelLoc = SourceLocation()); 2089 2090 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 2091 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 2092 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 2093 unsigned Quals); 2094 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 2095 bool RValueThis, unsigned ThisQuals); 2096 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class); 2097 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, bool RValueThis, 2098 unsigned ThisQuals); 2099 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 2100 2101 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 2102 ArrayRef<QualType> ArgTys, 2103 bool AllowRawAndTemplate); 2104 2105 void ArgumentDependentLookup(DeclarationName Name, bool Operator, 2106 SourceLocation Loc, 2107 llvm::ArrayRef<Expr *> Args, 2108 ADLResult &Functions, 2109 bool StdNamespaceIsAssociated = false); 2110 2111 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2112 VisibleDeclConsumer &Consumer, 2113 bool IncludeGlobalScope = true); 2114 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2115 VisibleDeclConsumer &Consumer, 2116 bool IncludeGlobalScope = true); 2117 2118 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 2119 Sema::LookupNameKind LookupKind, 2120 Scope *S, CXXScopeSpec *SS, 2121 CorrectionCandidateCallback &CCC, 2122 DeclContext *MemberContext = 0, 2123 bool EnteringContext = false, 2124 const ObjCObjectPointerType *OPT = 0); 2125 2126 void FindAssociatedClassesAndNamespaces(llvm::ArrayRef<Expr *> Args, 2127 AssociatedNamespaceSet &AssociatedNamespaces, 2128 AssociatedClassSet &AssociatedClasses); 2129 2130 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 2131 bool ConsiderLinkage, 2132 bool ExplicitInstantiationOrSpecialization); 2133 2134 bool DiagnoseAmbiguousLookup(LookupResult &Result); 2135 //@} 2136 2137 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 2138 SourceLocation IdLoc, 2139 bool TypoCorrection = false); 2140 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2141 Scope *S, bool ForRedeclaration, 2142 SourceLocation Loc); 2143 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 2144 Scope *S); 2145 void AddKnownFunctionAttributes(FunctionDecl *FD); 2146 2147 // More parsing and symbol table subroutines. 2148 2149 // Decl attributes - this routine is the top level dispatcher. 2150 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD, 2151 bool NonInheritable = true, bool Inheritable = true); 2152 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 2153 bool NonInheritable = true, bool Inheritable = true); 2154 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 2155 const AttributeList *AttrList); 2156 2157 void checkUnusedDeclAttributes(Declarator &D); 2158 2159 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 2160 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC); 2161 bool CheckNoReturnAttr(const AttributeList &attr); 2162 2163 /// \brief Stmt attributes - this routine is the top level dispatcher. 2164 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs, 2165 SourceRange Range); 2166 2167 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 2168 bool &IncompleteImpl, unsigned DiagID); 2169 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 2170 ObjCMethodDecl *MethodDecl, 2171 bool IsProtocolMethodDecl); 2172 2173 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2174 ObjCMethodDecl *Overridden, 2175 bool IsProtocolMethodDecl); 2176 2177 /// WarnExactTypedMethods - This routine issues a warning if method 2178 /// implementation declaration matches exactly that of its declaration. 2179 void WarnExactTypedMethods(ObjCMethodDecl *Method, 2180 ObjCMethodDecl *MethodDecl, 2181 bool IsProtocolMethodDecl); 2182 2183 bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl, 2184 ObjCInterfaceDecl *IDecl); 2185 2186 typedef llvm::DenseSet<Selector, llvm::DenseMapInfo<Selector> > SelectorSet; 2187 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 2188 2189 /// CheckProtocolMethodDefs - This routine checks unimplemented 2190 /// methods declared in protocol, and those referenced by it. 2191 /// \param IDecl - Used for checking for methods which may have been 2192 /// inherited. 2193 void CheckProtocolMethodDefs(SourceLocation ImpLoc, 2194 ObjCProtocolDecl *PDecl, 2195 bool& IncompleteImpl, 2196 const SelectorSet &InsMap, 2197 const SelectorSet &ClsMap, 2198 ObjCContainerDecl *CDecl); 2199 2200 /// CheckImplementationIvars - This routine checks if the instance variables 2201 /// listed in the implelementation match those listed in the interface. 2202 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2203 ObjCIvarDecl **Fields, unsigned nIvars, 2204 SourceLocation Loc); 2205 2206 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 2207 /// remains unimplemented in the class or category @implementation. 2208 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2209 ObjCContainerDecl* IDecl, 2210 bool IncompleteImpl = false); 2211 2212 /// DiagnoseUnimplementedProperties - This routine warns on those properties 2213 /// which must be implemented by this implementation. 2214 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 2215 ObjCContainerDecl *CDecl, 2216 const SelectorSet &InsMap); 2217 2218 /// DefaultSynthesizeProperties - This routine default synthesizes all 2219 /// properties which must be synthesized in class's @implementation. 2220 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 2221 ObjCInterfaceDecl *IDecl); 2222 void DefaultSynthesizeProperties(Scope *S, Decl *D); 2223 2224 /// CollectImmediateProperties - This routine collects all properties in 2225 /// the class and its conforming protocols; but not those it its super class. 2226 void CollectImmediateProperties(ObjCContainerDecl *CDecl, 2227 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap, 2228 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap); 2229 2230 2231 /// LookupPropertyDecl - Looks up a property in the current class and all 2232 /// its protocols. 2233 ObjCPropertyDecl *LookupPropertyDecl(const ObjCContainerDecl *CDecl, 2234 IdentifierInfo *II); 2235 2236 /// Called by ActOnProperty to handle @property declarations in 2237 //// class extensions. 2238 Decl *HandlePropertyInClassExtension(Scope *S, 2239 SourceLocation AtLoc, 2240 SourceLocation LParenLoc, 2241 FieldDeclarator &FD, 2242 Selector GetterSel, 2243 Selector SetterSel, 2244 const bool isAssign, 2245 const bool isReadWrite, 2246 const unsigned Attributes, 2247 const unsigned AttributesAsWritten, 2248 bool *isOverridingProperty, 2249 TypeSourceInfo *T, 2250 tok::ObjCKeywordKind MethodImplKind); 2251 2252 /// Called by ActOnProperty and HandlePropertyInClassExtension to 2253 /// handle creating the ObjcPropertyDecl for a category or @interface. 2254 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 2255 ObjCContainerDecl *CDecl, 2256 SourceLocation AtLoc, 2257 SourceLocation LParenLoc, 2258 FieldDeclarator &FD, 2259 Selector GetterSel, 2260 Selector SetterSel, 2261 const bool isAssign, 2262 const bool isReadWrite, 2263 const unsigned Attributes, 2264 const unsigned AttributesAsWritten, 2265 TypeSourceInfo *T, 2266 tok::ObjCKeywordKind MethodImplKind, 2267 DeclContext *lexicalDC = 0); 2268 2269 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 2270 /// warning) when atomic property has one but not the other user-declared 2271 /// setter or getter. 2272 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 2273 ObjCContainerDecl* IDecl); 2274 2275 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 2276 2277 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 2278 2279 enum MethodMatchStrategy { 2280 MMS_loose, 2281 MMS_strict 2282 }; 2283 2284 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 2285 /// true, or false, accordingly. 2286 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 2287 const ObjCMethodDecl *PrevMethod, 2288 MethodMatchStrategy strategy = MMS_strict); 2289 2290 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 2291 /// or protocol against those declared in their implementations. 2292 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 2293 const SelectorSet &ClsMap, 2294 SelectorSet &InsMapSeen, 2295 SelectorSet &ClsMapSeen, 2296 ObjCImplDecl* IMPDecl, 2297 ObjCContainerDecl* IDecl, 2298 bool &IncompleteImpl, 2299 bool ImmediateClass, 2300 bool WarnCategoryMethodImpl=false); 2301 2302 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2303 /// category matches with those implemented in its primary class and 2304 /// warns each time an exact match is found. 2305 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 2306 2307 /// \brief Add the given method to the list of globally-known methods. 2308 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 2309 2310private: 2311 /// AddMethodToGlobalPool - Add an instance or factory method to the global 2312 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 2313 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 2314 2315 /// LookupMethodInGlobalPool - Returns the instance or factory method and 2316 /// optionally warns if there are multiple signatures. 2317 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2318 bool receiverIdOrClass, 2319 bool warn, bool instance); 2320 2321public: 2322 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 2323 /// unit are added to a global pool. This allows us to efficiently associate 2324 /// a selector with a method declaraation for purposes of typechecking 2325 /// messages sent to "id" (where the class of the object is unknown). 2326 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2327 AddMethodToGlobalPool(Method, impl, /*instance*/true); 2328 } 2329 2330 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 2331 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2332 AddMethodToGlobalPool(Method, impl, /*instance*/false); 2333 } 2334 2335 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 2336 /// pool. 2337 void AddAnyMethodToGlobalPool(Decl *D); 2338 2339 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 2340 /// there are multiple signatures. 2341 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 2342 bool receiverIdOrClass=false, 2343 bool warn=true) { 2344 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2345 warn, /*instance*/true); 2346 } 2347 2348 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 2349 /// there are multiple signatures. 2350 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 2351 bool receiverIdOrClass=false, 2352 bool warn=true) { 2353 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2354 warn, /*instance*/false); 2355 } 2356 2357 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 2358 /// implementation. 2359 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 2360 2361 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 2362 /// initialization. 2363 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 2364 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 2365 2366 //===--------------------------------------------------------------------===// 2367 // Statement Parsing Callbacks: SemaStmt.cpp. 2368public: 2369 class FullExprArg { 2370 public: 2371 FullExprArg(Sema &actions) : E(0) { } 2372 2373 // FIXME: The const_cast here is ugly. RValue references would make this 2374 // much nicer (or we could duplicate a bunch of the move semantics 2375 // emulation code from Ownership.h). 2376 FullExprArg(const FullExprArg& Other) : E(Other.E) {} 2377 2378 ExprResult release() { 2379 return move(E); 2380 } 2381 2382 Expr *get() const { return E; } 2383 2384 Expr *operator->() { 2385 return E; 2386 } 2387 2388 private: 2389 // FIXME: No need to make the entire Sema class a friend when it's just 2390 // Sema::MakeFullExpr that needs access to the constructor below. 2391 friend class Sema; 2392 2393 explicit FullExprArg(Expr *expr) : E(expr) {} 2394 2395 Expr *E; 2396 }; 2397 2398 FullExprArg MakeFullExpr(Expr *Arg) { 2399 return FullExprArg(ActOnFinishFullExpr(Arg).release()); 2400 } 2401 2402 StmtResult ActOnExprStmt(FullExprArg Expr); 2403 2404 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 2405 bool HasLeadingEmptyMacro = false); 2406 2407 void ActOnStartOfCompoundStmt(); 2408 void ActOnFinishOfCompoundStmt(); 2409 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 2410 MultiStmtArg Elts, 2411 bool isStmtExpr); 2412 2413 /// \brief A RAII object to enter scope of a compound statement. 2414 class CompoundScopeRAII { 2415 public: 2416 CompoundScopeRAII(Sema &S): S(S) { 2417 S.ActOnStartOfCompoundStmt(); 2418 } 2419 2420 ~CompoundScopeRAII() { 2421 S.ActOnFinishOfCompoundStmt(); 2422 } 2423 2424 private: 2425 Sema &S; 2426 }; 2427 2428 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 2429 SourceLocation StartLoc, 2430 SourceLocation EndLoc); 2431 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 2432 StmtResult ActOnForEachLValueExpr(Expr *E); 2433 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 2434 SourceLocation DotDotDotLoc, Expr *RHSVal, 2435 SourceLocation ColonLoc); 2436 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 2437 2438 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 2439 SourceLocation ColonLoc, 2440 Stmt *SubStmt, Scope *CurScope); 2441 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 2442 SourceLocation ColonLoc, Stmt *SubStmt); 2443 2444 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, const AttrVec &Attrs, 2445 Stmt *SubStmt); 2446 2447 StmtResult ActOnIfStmt(SourceLocation IfLoc, 2448 FullExprArg CondVal, Decl *CondVar, 2449 Stmt *ThenVal, 2450 SourceLocation ElseLoc, Stmt *ElseVal); 2451 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 2452 Expr *Cond, 2453 Decl *CondVar); 2454 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 2455 Stmt *Switch, Stmt *Body); 2456 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 2457 FullExprArg Cond, 2458 Decl *CondVar, Stmt *Body); 2459 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 2460 SourceLocation WhileLoc, 2461 SourceLocation CondLParen, Expr *Cond, 2462 SourceLocation CondRParen); 2463 2464 StmtResult ActOnForStmt(SourceLocation ForLoc, 2465 SourceLocation LParenLoc, 2466 Stmt *First, FullExprArg Second, 2467 Decl *SecondVar, 2468 FullExprArg Third, 2469 SourceLocation RParenLoc, 2470 Stmt *Body); 2471 ExprResult ActOnObjCForCollectionOperand(SourceLocation forLoc, 2472 Expr *collection); 2473 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 2474 SourceLocation LParenLoc, 2475 Stmt *First, Expr *Second, 2476 SourceLocation RParenLoc, Stmt *Body); 2477 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, 2478 SourceLocation LParenLoc, Stmt *LoopVar, 2479 SourceLocation ColonLoc, Expr *Collection, 2480 SourceLocation RParenLoc); 2481 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 2482 SourceLocation ColonLoc, 2483 Stmt *RangeDecl, Stmt *BeginEndDecl, 2484 Expr *Cond, Expr *Inc, 2485 Stmt *LoopVarDecl, 2486 SourceLocation RParenLoc); 2487 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 2488 2489 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 2490 SourceLocation LabelLoc, 2491 LabelDecl *TheDecl); 2492 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 2493 SourceLocation StarLoc, 2494 Expr *DestExp); 2495 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 2496 StmtResult ActOnBreakStmt(SourceLocation GotoLoc, Scope *CurScope); 2497 2498 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 2499 bool AllowFunctionParameters); 2500 2501 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2502 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2503 2504 StmtResult ActOnAsmStmt(SourceLocation AsmLoc, 2505 bool IsSimple, bool IsVolatile, 2506 unsigned NumOutputs, unsigned NumInputs, 2507 IdentifierInfo **Names, 2508 MultiExprArg Constraints, 2509 MultiExprArg Exprs, 2510 Expr *AsmString, 2511 MultiExprArg Clobbers, 2512 SourceLocation RParenLoc, 2513 bool MSAsm = false); 2514 2515 2516 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 2517 SourceLocation StartLoc, 2518 SourceLocation IdLoc, IdentifierInfo *Id, 2519 bool Invalid = false); 2520 2521 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 2522 2523 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 2524 Decl *Parm, Stmt *Body); 2525 2526 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 2527 2528 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2529 MultiStmtArg Catch, Stmt *Finally); 2530 2531 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2532 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2533 Scope *CurScope); 2534 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 2535 Expr *operand); 2536 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2537 Expr *SynchExpr, 2538 Stmt *SynchBody); 2539 2540 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 2541 2542 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2543 SourceLocation StartLoc, 2544 SourceLocation IdLoc, 2545 IdentifierInfo *Id); 2546 2547 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2548 2549 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2550 Decl *ExDecl, Stmt *HandlerBlock); 2551 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2552 MultiStmtArg Handlers); 2553 2554 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2555 SourceLocation TryLoc, 2556 Stmt *TryBlock, 2557 Stmt *Handler); 2558 2559 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2560 Expr *FilterExpr, 2561 Stmt *Block); 2562 2563 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2564 Stmt *Block); 2565 2566 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2567 2568 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2569 2570 /// \brief If it's a file scoped decl that must warn if not used, keep track 2571 /// of it. 2572 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2573 2574 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2575 /// whose result is unused, warn. 2576 void DiagnoseUnusedExprResult(const Stmt *S); 2577 void DiagnoseUnusedDecl(const NamedDecl *ND); 2578 2579 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 2580 /// statement as a \p Body, and it is located on the same line. 2581 /// 2582 /// This helps prevent bugs due to typos, such as: 2583 /// if (condition); 2584 /// do_stuff(); 2585 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 2586 const Stmt *Body, 2587 unsigned DiagID); 2588 2589 /// Warn if a for/while loop statement \p S, which is followed by 2590 /// \p PossibleBody, has a suspicious null statement as a body. 2591 void DiagnoseEmptyLoopBody(const Stmt *S, 2592 const Stmt *PossibleBody); 2593 2594 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 2595 return DelayedDiagnostics.push(pool); 2596 } 2597 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 2598 2599 typedef ProcessingContextState ParsingClassState; 2600 ParsingClassState PushParsingClass() { 2601 return DelayedDiagnostics.pushUndelayed(); 2602 } 2603 void PopParsingClass(ParsingClassState state) { 2604 DelayedDiagnostics.popUndelayed(state); 2605 } 2606 2607 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 2608 2609 void EmitDeprecationWarning(NamedDecl *D, StringRef Message, 2610 SourceLocation Loc, 2611 const ObjCInterfaceDecl *UnknownObjCClass=0); 2612 2613 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2614 2615 bool makeUnavailableInSystemHeader(SourceLocation loc, 2616 StringRef message); 2617 2618 //===--------------------------------------------------------------------===// 2619 // Expression Parsing Callbacks: SemaExpr.cpp. 2620 2621 bool CanUseDecl(NamedDecl *D); 2622 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 2623 const ObjCInterfaceDecl *UnknownObjCClass=0); 2624 void NoteDeletedFunction(FunctionDecl *FD); 2625 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 2626 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 2627 ObjCMethodDecl *Getter, 2628 SourceLocation Loc); 2629 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 2630 Expr **Args, unsigned NumArgs); 2631 2632 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 2633 Decl *LambdaContextDecl = 0, 2634 bool IsDecltype = false); 2635 2636 void PopExpressionEvaluationContext(); 2637 2638 void DiscardCleanupsInEvaluationContext(); 2639 2640 ExprResult TranformToPotentiallyEvaluated(Expr *E); 2641 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 2642 2643 ExprResult ActOnConstantExpression(ExprResult Res); 2644 2645 // Functions for marking a declaration referenced. These functions also 2646 // contain the relevant logic for marking if a reference to a function or 2647 // variable is an odr-use (in the C++11 sense). There are separate variants 2648 // for expressions referring to a decl; these exist because odr-use marking 2649 // needs to be delayed for some constant variables when we build one of the 2650 // named expressions. 2651 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D); 2652 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func); 2653 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 2654 void MarkDeclRefReferenced(DeclRefExpr *E); 2655 void MarkMemberReferenced(MemberExpr *E); 2656 2657 void UpdateMarkingForLValueToRValue(Expr *E); 2658 void CleanupVarDeclMarking(); 2659 2660 enum TryCaptureKind { 2661 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 2662 }; 2663 2664 /// \brief Try to capture the given variable. 2665 /// 2666 /// \param Var The variable to capture. 2667 /// 2668 /// \param Loc The location at which the capture occurs. 2669 /// 2670 /// \param Kind The kind of capture, which may be implicit (for either a 2671 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 2672 /// 2673 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 2674 /// an explicit lambda capture. 2675 /// 2676 /// \param BuildAndDiagnose Whether we are actually supposed to add the 2677 /// captures or diagnose errors. If false, this routine merely check whether 2678 /// the capture can occur without performing the capture itself or complaining 2679 /// if the variable cannot be captured. 2680 /// 2681 /// \param CaptureType Will be set to the type of the field used to capture 2682 /// this variable in the innermost block or lambda. Only valid when the 2683 /// variable can be captured. 2684 /// 2685 /// \param DeclRefType Will be set to the type of a refernce to the capture 2686 /// from within the current scope. Only valid when the variable can be 2687 /// captured. 2688 /// 2689 /// \returns true if an error occurred (i.e., the variable cannot be 2690 /// captured) and false if the capture succeeded. 2691 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 2692 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 2693 QualType &CaptureType, 2694 QualType &DeclRefType); 2695 2696 /// \brief Try to capture the given variable. 2697 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 2698 TryCaptureKind Kind = TryCapture_Implicit, 2699 SourceLocation EllipsisLoc = SourceLocation()); 2700 2701 /// \brief Given a variable, determine the type that a reference to that 2702 /// variable will have in the given scope. 2703 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 2704 2705 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 2706 void MarkDeclarationsReferencedInExpr(Expr *E, 2707 bool SkipLocalVariables = false); 2708 2709 /// \brief Try to recover by turning the given expression into a 2710 /// call. Returns true if recovery was attempted or an error was 2711 /// emitted; this may also leave the ExprResult invalid. 2712 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 2713 bool ForceComplain = false, 2714 bool (*IsPlausibleResult)(QualType) = 0); 2715 2716 /// \brief Figure out if an expression could be turned into a call. 2717 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 2718 UnresolvedSetImpl &NonTemplateOverloads); 2719 2720 /// \brief Conditionally issue a diagnostic based on the current 2721 /// evaluation context. 2722 /// 2723 /// \param stmt - If stmt is non-null, delay reporting the diagnostic until 2724 /// the function body is parsed, and then do a basic reachability analysis to 2725 /// determine if the statement is reachable. If it is unreachable, the 2726 /// diagnostic will not be emitted. 2727 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 2728 const PartialDiagnostic &PD); 2729 2730 // Primary Expressions. 2731 SourceRange getExprRange(Expr *E) const; 2732 2733 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2734 SourceLocation TemplateKWLoc, 2735 UnqualifiedId &Id, 2736 bool HasTrailingLParen, bool IsAddressOfOperand, 2737 CorrectionCandidateCallback *CCC = 0); 2738 2739 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 2740 TemplateArgumentListInfo &Buffer, 2741 DeclarationNameInfo &NameInfo, 2742 const TemplateArgumentListInfo *&TemplateArgs); 2743 2744 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2745 CorrectionCandidateCallback &CCC, 2746 TemplateArgumentListInfo *ExplicitTemplateArgs = 0, 2747 llvm::ArrayRef<Expr *> Args = llvm::ArrayRef<Expr *>()); 2748 2749 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 2750 IdentifierInfo *II, 2751 bool AllowBuiltinCreation=false); 2752 2753 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 2754 SourceLocation TemplateKWLoc, 2755 const DeclarationNameInfo &NameInfo, 2756 bool isAddressOfOperand, 2757 const TemplateArgumentListInfo *TemplateArgs); 2758 2759 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2760 ExprValueKind VK, 2761 SourceLocation Loc, 2762 const CXXScopeSpec *SS = 0); 2763 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2764 ExprValueKind VK, 2765 const DeclarationNameInfo &NameInfo, 2766 const CXXScopeSpec *SS = 0); 2767 ExprResult 2768 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 2769 SourceLocation nameLoc, 2770 IndirectFieldDecl *indirectField, 2771 Expr *baseObjectExpr = 0, 2772 SourceLocation opLoc = SourceLocation()); 2773 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 2774 SourceLocation TemplateKWLoc, 2775 LookupResult &R, 2776 const TemplateArgumentListInfo *TemplateArgs); 2777 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 2778 SourceLocation TemplateKWLoc, 2779 LookupResult &R, 2780 const TemplateArgumentListInfo *TemplateArgs, 2781 bool IsDefiniteInstance); 2782 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 2783 const LookupResult &R, 2784 bool HasTrailingLParen); 2785 2786 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 2787 const DeclarationNameInfo &NameInfo); 2788 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 2789 SourceLocation TemplateKWLoc, 2790 const DeclarationNameInfo &NameInfo, 2791 const TemplateArgumentListInfo *TemplateArgs); 2792 2793 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2794 LookupResult &R, 2795 bool NeedsADL); 2796 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 2797 const DeclarationNameInfo &NameInfo, 2798 NamedDecl *D); 2799 2800 ExprResult BuildLiteralOperatorCall(LookupResult &R, 2801 DeclarationNameInfo &SuffixInfo, 2802 ArrayRef<Expr*> Args, 2803 SourceLocation LitEndLoc, 2804 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 2805 2806 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 2807 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 2808 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0); 2809 ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0); 2810 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 2811 ExprResult ActOnParenListExpr(SourceLocation L, 2812 SourceLocation R, 2813 MultiExprArg Val); 2814 2815 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 2816 /// fragments (e.g. "foo" "bar" L"baz"). 2817 ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 2818 Scope *UDLScope = 0); 2819 2820 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 2821 SourceLocation DefaultLoc, 2822 SourceLocation RParenLoc, 2823 Expr *ControllingExpr, 2824 MultiTypeArg ArgTypes, 2825 MultiExprArg ArgExprs); 2826 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 2827 SourceLocation DefaultLoc, 2828 SourceLocation RParenLoc, 2829 Expr *ControllingExpr, 2830 TypeSourceInfo **Types, 2831 Expr **Exprs, 2832 unsigned NumAssocs); 2833 2834 // Binary/Unary Operators. 'Tok' is the token for the operator. 2835 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 2836 Expr *InputExpr); 2837 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 2838 UnaryOperatorKind Opc, Expr *Input); 2839 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 2840 tok::TokenKind Op, Expr *Input); 2841 2842 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 2843 SourceLocation OpLoc, 2844 UnaryExprOrTypeTrait ExprKind, 2845 SourceRange R); 2846 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 2847 UnaryExprOrTypeTrait ExprKind); 2848 ExprResult 2849 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 2850 UnaryExprOrTypeTrait ExprKind, 2851 bool IsType, void *TyOrEx, 2852 const SourceRange &ArgRange); 2853 2854 ExprResult CheckPlaceholderExpr(Expr *E); 2855 bool CheckVecStepExpr(Expr *E); 2856 2857 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 2858 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 2859 SourceRange ExprRange, 2860 UnaryExprOrTypeTrait ExprKind); 2861 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 2862 SourceLocation OpLoc, 2863 IdentifierInfo &Name, 2864 SourceLocation NameLoc, 2865 SourceLocation RParenLoc); 2866 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 2867 tok::TokenKind Kind, Expr *Input); 2868 2869 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 2870 Expr *Idx, SourceLocation RLoc); 2871 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 2872 Expr *Idx, SourceLocation RLoc); 2873 2874 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2875 SourceLocation OpLoc, bool IsArrow, 2876 CXXScopeSpec &SS, 2877 SourceLocation TemplateKWLoc, 2878 NamedDecl *FirstQualifierInScope, 2879 const DeclarationNameInfo &NameInfo, 2880 const TemplateArgumentListInfo *TemplateArgs); 2881 2882 // This struct is for use by ActOnMemberAccess to allow 2883 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 2884 // changing the access operator from a '.' to a '->' (to see if that is the 2885 // change needed to fix an error about an unknown member, e.g. when the class 2886 // defines a custom operator->). 2887 struct ActOnMemberAccessExtraArgs { 2888 Scope *S; 2889 UnqualifiedId &Id; 2890 Decl *ObjCImpDecl; 2891 bool HasTrailingLParen; 2892 }; 2893 2894 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 2895 SourceLocation OpLoc, bool IsArrow, 2896 const CXXScopeSpec &SS, 2897 SourceLocation TemplateKWLoc, 2898 NamedDecl *FirstQualifierInScope, 2899 LookupResult &R, 2900 const TemplateArgumentListInfo *TemplateArgs, 2901 bool SuppressQualifierCheck = false, 2902 ActOnMemberAccessExtraArgs *ExtraArgs = 0); 2903 2904 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 2905 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 2906 bool &IsArrow, SourceLocation OpLoc, 2907 CXXScopeSpec &SS, 2908 Decl *ObjCImpDecl, 2909 bool HasTemplateArgs); 2910 2911 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 2912 const CXXScopeSpec &SS, 2913 const LookupResult &R); 2914 2915 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 2916 bool IsArrow, SourceLocation OpLoc, 2917 const CXXScopeSpec &SS, 2918 SourceLocation TemplateKWLoc, 2919 NamedDecl *FirstQualifierInScope, 2920 const DeclarationNameInfo &NameInfo, 2921 const TemplateArgumentListInfo *TemplateArgs); 2922 2923 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 2924 SourceLocation OpLoc, 2925 tok::TokenKind OpKind, 2926 CXXScopeSpec &SS, 2927 SourceLocation TemplateKWLoc, 2928 UnqualifiedId &Member, 2929 Decl *ObjCImpDecl, 2930 bool HasTrailingLParen); 2931 2932 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 2933 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 2934 FunctionDecl *FDecl, 2935 const FunctionProtoType *Proto, 2936 Expr **Args, unsigned NumArgs, 2937 SourceLocation RParenLoc, 2938 bool ExecConfig = false); 2939 void CheckStaticArrayArgument(SourceLocation CallLoc, 2940 ParmVarDecl *Param, 2941 const Expr *ArgExpr); 2942 2943 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 2944 /// This provides the location of the left/right parens and a list of comma 2945 /// locations. 2946 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 2947 MultiExprArg ArgExprs, SourceLocation RParenLoc, 2948 Expr *ExecConfig = 0, bool IsExecConfig = false); 2949 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 2950 SourceLocation LParenLoc, 2951 Expr **Args, unsigned NumArgs, 2952 SourceLocation RParenLoc, 2953 Expr *Config = 0, 2954 bool IsExecConfig = false); 2955 2956 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 2957 MultiExprArg ExecConfig, 2958 SourceLocation GGGLoc); 2959 2960 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 2961 Declarator &D, ParsedType &Ty, 2962 SourceLocation RParenLoc, Expr *CastExpr); 2963 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 2964 TypeSourceInfo *Ty, 2965 SourceLocation RParenLoc, 2966 Expr *Op); 2967 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 2968 2969 /// \brief Build an altivec or OpenCL literal. 2970 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 2971 SourceLocation RParenLoc, Expr *E, 2972 TypeSourceInfo *TInfo); 2973 2974 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 2975 2976 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 2977 ParsedType Ty, 2978 SourceLocation RParenLoc, 2979 Expr *InitExpr); 2980 2981 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 2982 TypeSourceInfo *TInfo, 2983 SourceLocation RParenLoc, 2984 Expr *LiteralExpr); 2985 2986 ExprResult ActOnInitList(SourceLocation LBraceLoc, 2987 MultiExprArg InitArgList, 2988 SourceLocation RBraceLoc); 2989 2990 ExprResult ActOnDesignatedInitializer(Designation &Desig, 2991 SourceLocation Loc, 2992 bool GNUSyntax, 2993 ExprResult Init); 2994 2995 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 2996 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 2997 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 2998 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 2999 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 3000 Expr *LHSExpr, Expr *RHSExpr); 3001 3002 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3003 /// in the case of a the GNU conditional expr extension. 3004 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 3005 SourceLocation ColonLoc, 3006 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 3007 3008 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3009 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 3010 LabelDecl *TheDecl); 3011 3012 void ActOnStartStmtExpr(); 3013 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 3014 SourceLocation RPLoc); // "({..})" 3015 void ActOnStmtExprError(); 3016 3017 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 3018 struct OffsetOfComponent { 3019 SourceLocation LocStart, LocEnd; 3020 bool isBrackets; // true if [expr], false if .ident 3021 union { 3022 IdentifierInfo *IdentInfo; 3023 Expr *E; 3024 } U; 3025 }; 3026 3027 /// __builtin_offsetof(type, a.b[123][456].c) 3028 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 3029 TypeSourceInfo *TInfo, 3030 OffsetOfComponent *CompPtr, 3031 unsigned NumComponents, 3032 SourceLocation RParenLoc); 3033 ExprResult ActOnBuiltinOffsetOf(Scope *S, 3034 SourceLocation BuiltinLoc, 3035 SourceLocation TypeLoc, 3036 ParsedType ParsedArgTy, 3037 OffsetOfComponent *CompPtr, 3038 unsigned NumComponents, 3039 SourceLocation RParenLoc); 3040 3041 // __builtin_choose_expr(constExpr, expr1, expr2) 3042 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 3043 Expr *CondExpr, Expr *LHSExpr, 3044 Expr *RHSExpr, SourceLocation RPLoc); 3045 3046 // __builtin_va_arg(expr, type) 3047 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 3048 SourceLocation RPLoc); 3049 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 3050 TypeSourceInfo *TInfo, SourceLocation RPLoc); 3051 3052 // __null 3053 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 3054 3055 bool CheckCaseExpression(Expr *E); 3056 3057 /// \brief Describes the result of an "if-exists" condition check. 3058 enum IfExistsResult { 3059 /// \brief The symbol exists. 3060 IER_Exists, 3061 3062 /// \brief The symbol does not exist. 3063 IER_DoesNotExist, 3064 3065 /// \brief The name is a dependent name, so the results will differ 3066 /// from one instantiation to the next. 3067 IER_Dependent, 3068 3069 /// \brief An error occurred. 3070 IER_Error 3071 }; 3072 3073 IfExistsResult 3074 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 3075 const DeclarationNameInfo &TargetNameInfo); 3076 3077 IfExistsResult 3078 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 3079 bool IsIfExists, CXXScopeSpec &SS, 3080 UnqualifiedId &Name); 3081 3082 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 3083 bool IsIfExists, 3084 NestedNameSpecifierLoc QualifierLoc, 3085 DeclarationNameInfo NameInfo, 3086 Stmt *Nested); 3087 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 3088 bool IsIfExists, 3089 CXXScopeSpec &SS, UnqualifiedId &Name, 3090 Stmt *Nested); 3091 3092 //===------------------------- "Block" Extension ------------------------===// 3093 3094 /// ActOnBlockStart - This callback is invoked when a block literal is 3095 /// started. 3096 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 3097 3098 /// ActOnBlockArguments - This callback allows processing of block arguments. 3099 /// If there are no arguments, this is still invoked. 3100 void ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope); 3101 3102 /// ActOnBlockError - If there is an error parsing a block, this callback 3103 /// is invoked to pop the information about the block from the action impl. 3104 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 3105 3106 /// ActOnBlockStmtExpr - This is called when the body of a block statement 3107 /// literal was successfully completed. ^(int x){...} 3108 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 3109 Scope *CurScope); 3110 3111 //===---------------------------- OpenCL Features -----------------------===// 3112 3113 /// __builtin_astype(...) 3114 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3115 SourceLocation BuiltinLoc, 3116 SourceLocation RParenLoc); 3117 3118 //===---------------------------- C++ Features --------------------------===// 3119 3120 // Act on C++ namespaces 3121 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 3122 SourceLocation NamespaceLoc, 3123 SourceLocation IdentLoc, 3124 IdentifierInfo *Ident, 3125 SourceLocation LBrace, 3126 AttributeList *AttrList); 3127 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 3128 3129 NamespaceDecl *getStdNamespace() const; 3130 NamespaceDecl *getOrCreateStdNamespace(); 3131 3132 CXXRecordDecl *getStdBadAlloc() const; 3133 3134 /// \brief Tests whether Ty is an instance of std::initializer_list and, if 3135 /// it is and Element is not NULL, assigns the element type to Element. 3136 bool isStdInitializerList(QualType Ty, QualType *Element); 3137 3138 /// \brief Looks for the std::initializer_list template and instantiates it 3139 /// with Element, or emits an error if it's not found. 3140 /// 3141 /// \returns The instantiated template, or null on error. 3142 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 3143 3144 /// \brief Determine whether Ctor is an initializer-list constructor, as 3145 /// defined in [dcl.init.list]p2. 3146 bool isInitListConstructor(const CXXConstructorDecl *Ctor); 3147 3148 Decl *ActOnUsingDirective(Scope *CurScope, 3149 SourceLocation UsingLoc, 3150 SourceLocation NamespcLoc, 3151 CXXScopeSpec &SS, 3152 SourceLocation IdentLoc, 3153 IdentifierInfo *NamespcName, 3154 AttributeList *AttrList); 3155 3156 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 3157 3158 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 3159 SourceLocation NamespaceLoc, 3160 SourceLocation AliasLoc, 3161 IdentifierInfo *Alias, 3162 CXXScopeSpec &SS, 3163 SourceLocation IdentLoc, 3164 IdentifierInfo *Ident); 3165 3166 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 3167 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 3168 const LookupResult &PreviousDecls); 3169 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 3170 NamedDecl *Target); 3171 3172 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3173 bool isTypeName, 3174 const CXXScopeSpec &SS, 3175 SourceLocation NameLoc, 3176 const LookupResult &Previous); 3177 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 3178 const CXXScopeSpec &SS, 3179 SourceLocation NameLoc); 3180 3181 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3182 SourceLocation UsingLoc, 3183 CXXScopeSpec &SS, 3184 const DeclarationNameInfo &NameInfo, 3185 AttributeList *AttrList, 3186 bool IsInstantiation, 3187 bool IsTypeName, 3188 SourceLocation TypenameLoc); 3189 3190 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 3191 3192 Decl *ActOnUsingDeclaration(Scope *CurScope, 3193 AccessSpecifier AS, 3194 bool HasUsingKeyword, 3195 SourceLocation UsingLoc, 3196 CXXScopeSpec &SS, 3197 UnqualifiedId &Name, 3198 AttributeList *AttrList, 3199 bool IsTypeName, 3200 SourceLocation TypenameLoc); 3201 Decl *ActOnAliasDeclaration(Scope *CurScope, 3202 AccessSpecifier AS, 3203 MultiTemplateParamsArg TemplateParams, 3204 SourceLocation UsingLoc, 3205 UnqualifiedId &Name, 3206 TypeResult Type); 3207 3208 /// InitializeVarWithConstructor - Creates an CXXConstructExpr 3209 /// and sets it as the initializer for the the passed in VarDecl. 3210 bool InitializeVarWithConstructor(VarDecl *VD, 3211 CXXConstructorDecl *Constructor, 3212 MultiExprArg Exprs, 3213 bool HadMultipleCandidates); 3214 3215 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 3216 /// including handling of its default argument expressions. 3217 /// 3218 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 3219 ExprResult 3220 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3221 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 3222 bool HadMultipleCandidates, bool RequiresZeroInit, 3223 unsigned ConstructKind, SourceRange ParenRange); 3224 3225 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 3226 // the constructor can be elidable? 3227 ExprResult 3228 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3229 CXXConstructorDecl *Constructor, bool Elidable, 3230 MultiExprArg Exprs, bool HadMultipleCandidates, 3231 bool RequiresZeroInit, unsigned ConstructKind, 3232 SourceRange ParenRange); 3233 3234 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 3235 /// the default expr if needed. 3236 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3237 FunctionDecl *FD, 3238 ParmVarDecl *Param); 3239 3240 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 3241 /// constructed variable. 3242 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 3243 3244 /// \brief Helper class that collects exception specifications for 3245 /// implicitly-declared special member functions. 3246 class ImplicitExceptionSpecification { 3247 // Pointer to allow copying 3248 Sema *Self; 3249 // We order exception specifications thus: 3250 // noexcept is the most restrictive, but is only used in C++0x. 3251 // throw() comes next. 3252 // Then a throw(collected exceptions) 3253 // Finally no specification. 3254 // throw(...) is used instead if any called function uses it. 3255 // 3256 // If this exception specification cannot be known yet (for instance, 3257 // because this is the exception specification for a defaulted default 3258 // constructor and we haven't finished parsing the deferred parts of the 3259 // class yet), the C++0x standard does not specify how to behave. We 3260 // record this as an 'unknown' exception specification, which overrules 3261 // any other specification (even 'none', to keep this rule simple). 3262 ExceptionSpecificationType ComputedEST; 3263 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3264 SmallVector<QualType, 4> Exceptions; 3265 3266 void ClearExceptions() { 3267 ExceptionsSeen.clear(); 3268 Exceptions.clear(); 3269 } 3270 3271 public: 3272 explicit ImplicitExceptionSpecification(Sema &Self) 3273 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 3274 if (!Self.Context.getLangOpts().CPlusPlus0x) 3275 ComputedEST = EST_DynamicNone; 3276 } 3277 3278 /// \brief Get the computed exception specification type. 3279 ExceptionSpecificationType getExceptionSpecType() const { 3280 assert(ComputedEST != EST_ComputedNoexcept && 3281 "noexcept(expr) should not be a possible result"); 3282 return ComputedEST; 3283 } 3284 3285 /// \brief The number of exceptions in the exception specification. 3286 unsigned size() const { return Exceptions.size(); } 3287 3288 /// \brief The set of exceptions in the exception specification. 3289 const QualType *data() const { return Exceptions.data(); } 3290 3291 /// \brief Integrate another called method into the collected data. 3292 void CalledDecl(SourceLocation CallLoc, CXXMethodDecl *Method); 3293 3294 /// \brief Integrate an invoked expression into the collected data. 3295 void CalledExpr(Expr *E); 3296 3297 /// \brief Specify that the exception specification can't be detemined yet. 3298 void SetDelayed() { 3299 ClearExceptions(); 3300 ComputedEST = EST_Delayed; 3301 } 3302 3303 FunctionProtoType::ExtProtoInfo getEPI() const { 3304 FunctionProtoType::ExtProtoInfo EPI; 3305 EPI.ExceptionSpecType = getExceptionSpecType(); 3306 EPI.NumExceptions = size(); 3307 EPI.Exceptions = data(); 3308 return EPI; 3309 } 3310 }; 3311 3312 /// \brief Determine what sort of exception specification a defaulted 3313 /// copy constructor of a class will have. 3314 ImplicitExceptionSpecification 3315 ComputeDefaultedDefaultCtorExceptionSpec(CXXRecordDecl *ClassDecl); 3316 3317 /// \brief Determine what sort of exception specification a defaulted 3318 /// default constructor of a class will have, and whether the parameter 3319 /// will be const. 3320 std::pair<ImplicitExceptionSpecification, bool> 3321 ComputeDefaultedCopyCtorExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 3322 3323 /// \brief Determine what sort of exception specification a defautled 3324 /// copy assignment operator of a class will have, and whether the 3325 /// parameter will be const. 3326 std::pair<ImplicitExceptionSpecification, bool> 3327 ComputeDefaultedCopyAssignmentExceptionSpecAndConst(CXXRecordDecl *ClassDecl); 3328 3329 /// \brief Determine what sort of exception specification a defaulted move 3330 /// constructor of a class will have. 3331 ImplicitExceptionSpecification 3332 ComputeDefaultedMoveCtorExceptionSpec(CXXRecordDecl *ClassDecl); 3333 3334 /// \brief Determine what sort of exception specification a defaulted move 3335 /// assignment operator of a class will have. 3336 ImplicitExceptionSpecification 3337 ComputeDefaultedMoveAssignmentExceptionSpec(CXXRecordDecl *ClassDecl); 3338 3339 /// \brief Determine what sort of exception specification a defaulted 3340 /// destructor of a class will have. 3341 ImplicitExceptionSpecification 3342 ComputeDefaultedDtorExceptionSpec(CXXRecordDecl *ClassDecl); 3343 3344 /// \brief Check the given exception-specification and update the 3345 /// extended prototype information with the results. 3346 void checkExceptionSpecification(ExceptionSpecificationType EST, 3347 ArrayRef<ParsedType> DynamicExceptions, 3348 ArrayRef<SourceRange> DynamicExceptionRanges, 3349 Expr *NoexceptExpr, 3350 llvm::SmallVectorImpl<QualType> &Exceptions, 3351 FunctionProtoType::ExtProtoInfo &EPI); 3352 3353 /// \brief Determine if a special member function should have a deleted 3354 /// definition when it is defaulted. 3355 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 3356 bool Diagnose = false); 3357 3358 /// \brief Declare the implicit default constructor for the given class. 3359 /// 3360 /// \param ClassDecl The class declaration into which the implicit 3361 /// default constructor will be added. 3362 /// 3363 /// \returns The implicitly-declared default constructor. 3364 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 3365 CXXRecordDecl *ClassDecl); 3366 3367 /// DefineImplicitDefaultConstructor - Checks for feasibility of 3368 /// defining this constructor as the default constructor. 3369 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3370 CXXConstructorDecl *Constructor); 3371 3372 /// \brief Declare the implicit destructor for the given class. 3373 /// 3374 /// \param ClassDecl The class declaration into which the implicit 3375 /// destructor will be added. 3376 /// 3377 /// \returns The implicitly-declared destructor. 3378 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 3379 3380 /// DefineImplicitDestructor - Checks for feasibility of 3381 /// defining this destructor as the default destructor. 3382 void DefineImplicitDestructor(SourceLocation CurrentLocation, 3383 CXXDestructorDecl *Destructor); 3384 3385 /// \brief Build an exception spec for destructors that don't have one. 3386 /// 3387 /// C++11 says that user-defined destructors with no exception spec get one 3388 /// that looks as if the destructor was implicitly declared. 3389 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 3390 CXXDestructorDecl *Destructor, 3391 bool WasDelayed = false); 3392 3393 /// \brief Declare all inherited constructors for the given class. 3394 /// 3395 /// \param ClassDecl The class declaration into which the inherited 3396 /// constructors will be added. 3397 void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl); 3398 3399 /// \brief Declare the implicit copy constructor for the given class. 3400 /// 3401 /// \param ClassDecl The class declaration into which the implicit 3402 /// copy constructor will be added. 3403 /// 3404 /// \returns The implicitly-declared copy constructor. 3405 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 3406 3407 /// DefineImplicitCopyConstructor - Checks for feasibility of 3408 /// defining this constructor as the copy constructor. 3409 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3410 CXXConstructorDecl *Constructor); 3411 3412 /// \brief Declare the implicit move constructor for the given class. 3413 /// 3414 /// \param ClassDecl The Class declaration into which the implicit 3415 /// move constructor will be added. 3416 /// 3417 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 3418 /// declared. 3419 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 3420 3421 /// DefineImplicitMoveConstructor - Checks for feasibility of 3422 /// defining this constructor as the move constructor. 3423 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 3424 CXXConstructorDecl *Constructor); 3425 3426 /// \brief Declare the implicit copy assignment operator for the given class. 3427 /// 3428 /// \param ClassDecl The class declaration into which the implicit 3429 /// copy assignment operator will be added. 3430 /// 3431 /// \returns The implicitly-declared copy assignment operator. 3432 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 3433 3434 /// \brief Defines an implicitly-declared copy assignment operator. 3435 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 3436 CXXMethodDecl *MethodDecl); 3437 3438 /// \brief Declare the implicit move assignment operator for the given class. 3439 /// 3440 /// \param ClassDecl The Class declaration into which the implicit 3441 /// move assignment operator will be added. 3442 /// 3443 /// \returns The implicitly-declared move assignment operator, or NULL if it 3444 /// wasn't declared. 3445 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 3446 3447 /// \brief Defines an implicitly-declared move assignment operator. 3448 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 3449 CXXMethodDecl *MethodDecl); 3450 3451 /// \brief Force the declaration of any implicitly-declared members of this 3452 /// class. 3453 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 3454 3455 /// \brief Determine whether the given function is an implicitly-deleted 3456 /// special member function. 3457 bool isImplicitlyDeleted(FunctionDecl *FD); 3458 3459 /// \brief Check whether 'this' shows up in the type of a static member 3460 /// function after the (naturally empty) cv-qualifier-seq would be. 3461 /// 3462 /// \returns true if an error occurred. 3463 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 3464 3465 /// \brief Whether this' shows up in the exception specification of a static 3466 /// member function. 3467 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 3468 3469 /// \brief Check whether 'this' shows up in the attributes of the given 3470 /// static member function. 3471 /// 3472 /// \returns true if an error occurred. 3473 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 3474 3475 /// MaybeBindToTemporary - If the passed in expression has a record type with 3476 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 3477 /// it simply returns the passed in expression. 3478 ExprResult MaybeBindToTemporary(Expr *E); 3479 3480 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 3481 MultiExprArg ArgsPtr, 3482 SourceLocation Loc, 3483 ASTOwningVector<Expr*> &ConvertedArgs, 3484 bool AllowExplicit = false); 3485 3486 ParsedType getDestructorName(SourceLocation TildeLoc, 3487 IdentifierInfo &II, SourceLocation NameLoc, 3488 Scope *S, CXXScopeSpec &SS, 3489 ParsedType ObjectType, 3490 bool EnteringContext); 3491 3492 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType); 3493 3494 // Checks that reinterpret casts don't have undefined behavior. 3495 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 3496 bool IsDereference, SourceRange Range); 3497 3498 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 3499 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 3500 tok::TokenKind Kind, 3501 SourceLocation LAngleBracketLoc, 3502 Declarator &D, 3503 SourceLocation RAngleBracketLoc, 3504 SourceLocation LParenLoc, 3505 Expr *E, 3506 SourceLocation RParenLoc); 3507 3508 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 3509 tok::TokenKind Kind, 3510 TypeSourceInfo *Ty, 3511 Expr *E, 3512 SourceRange AngleBrackets, 3513 SourceRange Parens); 3514 3515 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3516 SourceLocation TypeidLoc, 3517 TypeSourceInfo *Operand, 3518 SourceLocation RParenLoc); 3519 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3520 SourceLocation TypeidLoc, 3521 Expr *Operand, 3522 SourceLocation RParenLoc); 3523 3524 /// ActOnCXXTypeid - Parse typeid( something ). 3525 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 3526 SourceLocation LParenLoc, bool isType, 3527 void *TyOrExpr, 3528 SourceLocation RParenLoc); 3529 3530 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3531 SourceLocation TypeidLoc, 3532 TypeSourceInfo *Operand, 3533 SourceLocation RParenLoc); 3534 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3535 SourceLocation TypeidLoc, 3536 Expr *Operand, 3537 SourceLocation RParenLoc); 3538 3539 /// ActOnCXXUuidof - Parse __uuidof( something ). 3540 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 3541 SourceLocation LParenLoc, bool isType, 3542 void *TyOrExpr, 3543 SourceLocation RParenLoc); 3544 3545 3546 //// ActOnCXXThis - Parse 'this' pointer. 3547 ExprResult ActOnCXXThis(SourceLocation loc); 3548 3549 /// \brief Try to retrieve the type of the 'this' pointer. 3550 /// 3551 /// \param Capture If true, capture 'this' in this context. 3552 /// 3553 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 3554 QualType getCurrentThisType(); 3555 3556 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the 3557 /// current context not being a non-static member function. In such cases, 3558 /// this provides the type used for 'this'. 3559 QualType CXXThisTypeOverride; 3560 3561 /// \brief RAII object used to temporarily allow the C++ 'this' expression 3562 /// to be used, with the given qualifiers on the current class type. 3563 class CXXThisScopeRAII { 3564 Sema &S; 3565 QualType OldCXXThisTypeOverride; 3566 bool Enabled; 3567 3568 public: 3569 /// \brief Introduce a new scope where 'this' may be allowed (when enabled), 3570 /// using the given declaration (which is either a class template or a 3571 /// class) along with the given qualifiers. 3572 /// along with the qualifiers placed on '*this'. 3573 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, 3574 bool Enabled = true); 3575 3576 ~CXXThisScopeRAII(); 3577 }; 3578 3579 /// \brief Make sure the value of 'this' is actually available in the current 3580 /// context, if it is a potentially evaluated context. 3581 /// 3582 /// \param Loc The location at which the capture of 'this' occurs. 3583 /// 3584 /// \param Explicit Whether 'this' is explicitly captured in a lambda 3585 /// capture list. 3586 void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false); 3587 3588 /// \brief Determine whether the given type is the type of *this that is used 3589 /// outside of the body of a member function for a type that is currently 3590 /// being defined. 3591 bool isThisOutsideMemberFunctionBody(QualType BaseType); 3592 3593 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 3594 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3595 3596 3597 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 3598 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3599 3600 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 3601 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 3602 3603 //// ActOnCXXThrow - Parse throw expressions. 3604 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 3605 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 3606 bool IsThrownVarInScope); 3607 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 3608 bool IsThrownVarInScope); 3609 3610 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 3611 /// Can be interpreted either as function-style casting ("int(x)") 3612 /// or class type construction ("ClassType(x,y,z)") 3613 /// or creation of a value-initialized type ("int()"). 3614 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 3615 SourceLocation LParenLoc, 3616 MultiExprArg Exprs, 3617 SourceLocation RParenLoc); 3618 3619 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 3620 SourceLocation LParenLoc, 3621 MultiExprArg Exprs, 3622 SourceLocation RParenLoc); 3623 3624 /// ActOnCXXNew - Parsed a C++ 'new' expression. 3625 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 3626 SourceLocation PlacementLParen, 3627 MultiExprArg PlacementArgs, 3628 SourceLocation PlacementRParen, 3629 SourceRange TypeIdParens, Declarator &D, 3630 Expr *Initializer); 3631 ExprResult BuildCXXNew(SourceLocation StartLoc, bool UseGlobal, 3632 SourceLocation PlacementLParen, 3633 MultiExprArg PlacementArgs, 3634 SourceLocation PlacementRParen, 3635 SourceRange TypeIdParens, 3636 QualType AllocType, 3637 TypeSourceInfo *AllocTypeInfo, 3638 Expr *ArraySize, 3639 SourceRange DirectInitRange, 3640 Expr *Initializer, 3641 bool TypeMayContainAuto = true); 3642 3643 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 3644 SourceRange R); 3645 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 3646 bool UseGlobal, QualType AllocType, bool IsArray, 3647 Expr **PlaceArgs, unsigned NumPlaceArgs, 3648 FunctionDecl *&OperatorNew, 3649 FunctionDecl *&OperatorDelete); 3650 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 3651 DeclarationName Name, Expr** Args, 3652 unsigned NumArgs, DeclContext *Ctx, 3653 bool AllowMissing, FunctionDecl *&Operator, 3654 bool Diagnose = true); 3655 void DeclareGlobalNewDelete(); 3656 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 3657 QualType Argument, 3658 bool addMallocAttr = false); 3659 3660 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3661 DeclarationName Name, FunctionDecl* &Operator, 3662 bool Diagnose = true); 3663 3664 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 3665 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 3666 bool UseGlobal, bool ArrayForm, 3667 Expr *Operand); 3668 3669 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 3670 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 3671 SourceLocation StmtLoc, 3672 bool ConvertToBoolean); 3673 3674 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 3675 Expr *Operand, SourceLocation RParen); 3676 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3677 SourceLocation RParen); 3678 3679 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 3680 /// pseudo-functions. 3681 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 3682 SourceLocation KWLoc, 3683 ParsedType Ty, 3684 SourceLocation RParen); 3685 3686 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 3687 SourceLocation KWLoc, 3688 TypeSourceInfo *T, 3689 SourceLocation RParen); 3690 3691 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 3692 /// pseudo-functions. 3693 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 3694 SourceLocation KWLoc, 3695 ParsedType LhsTy, 3696 ParsedType RhsTy, 3697 SourceLocation RParen); 3698 3699 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3700 SourceLocation KWLoc, 3701 TypeSourceInfo *LhsT, 3702 TypeSourceInfo *RhsT, 3703 SourceLocation RParen); 3704 3705 /// \brief Parsed one of the type trait support pseudo-functions. 3706 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3707 ArrayRef<ParsedType> Args, 3708 SourceLocation RParenLoc); 3709 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3710 ArrayRef<TypeSourceInfo *> Args, 3711 SourceLocation RParenLoc); 3712 3713 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 3714 /// pseudo-functions. 3715 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3716 SourceLocation KWLoc, 3717 ParsedType LhsTy, 3718 Expr *DimExpr, 3719 SourceLocation RParen); 3720 3721 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 3722 SourceLocation KWLoc, 3723 TypeSourceInfo *TSInfo, 3724 Expr *DimExpr, 3725 SourceLocation RParen); 3726 3727 /// ActOnExpressionTrait - Parsed one of the unary type trait support 3728 /// pseudo-functions. 3729 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 3730 SourceLocation KWLoc, 3731 Expr *Queried, 3732 SourceLocation RParen); 3733 3734 ExprResult BuildExpressionTrait(ExpressionTrait OET, 3735 SourceLocation KWLoc, 3736 Expr *Queried, 3737 SourceLocation RParen); 3738 3739 ExprResult ActOnStartCXXMemberReference(Scope *S, 3740 Expr *Base, 3741 SourceLocation OpLoc, 3742 tok::TokenKind OpKind, 3743 ParsedType &ObjectType, 3744 bool &MayBePseudoDestructor); 3745 3746 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 3747 3748 ExprResult BuildPseudoDestructorExpr(Expr *Base, 3749 SourceLocation OpLoc, 3750 tok::TokenKind OpKind, 3751 const CXXScopeSpec &SS, 3752 TypeSourceInfo *ScopeType, 3753 SourceLocation CCLoc, 3754 SourceLocation TildeLoc, 3755 PseudoDestructorTypeStorage DestroyedType, 3756 bool HasTrailingLParen); 3757 3758 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3759 SourceLocation OpLoc, 3760 tok::TokenKind OpKind, 3761 CXXScopeSpec &SS, 3762 UnqualifiedId &FirstTypeName, 3763 SourceLocation CCLoc, 3764 SourceLocation TildeLoc, 3765 UnqualifiedId &SecondTypeName, 3766 bool HasTrailingLParen); 3767 3768 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3769 SourceLocation OpLoc, 3770 tok::TokenKind OpKind, 3771 SourceLocation TildeLoc, 3772 const DeclSpec& DS, 3773 bool HasTrailingLParen); 3774 3775 /// MaybeCreateExprWithCleanups - If the current full-expression 3776 /// requires any cleanups, surround it with a ExprWithCleanups node. 3777 /// Otherwise, just returns the passed-in expression. 3778 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 3779 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 3780 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 3781 3782 ExprResult ActOnFinishFullExpr(Expr *Expr); 3783 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 3784 3785 // Marks SS invalid if it represents an incomplete type. 3786 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 3787 3788 DeclContext *computeDeclContext(QualType T); 3789 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 3790 bool EnteringContext = false); 3791 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 3792 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 3793 bool isUnknownSpecialization(const CXXScopeSpec &SS); 3794 3795 /// \brief The parser has parsed a global nested-name-specifier '::'. 3796 /// 3797 /// \param S The scope in which this nested-name-specifier occurs. 3798 /// 3799 /// \param CCLoc The location of the '::'. 3800 /// 3801 /// \param SS The nested-name-specifier, which will be updated in-place 3802 /// to reflect the parsed nested-name-specifier. 3803 /// 3804 /// \returns true if an error occurred, false otherwise. 3805 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 3806 CXXScopeSpec &SS); 3807 3808 bool isAcceptableNestedNameSpecifier(NamedDecl *SD); 3809 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 3810 3811 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 3812 SourceLocation IdLoc, 3813 IdentifierInfo &II, 3814 ParsedType ObjectType); 3815 3816 bool BuildCXXNestedNameSpecifier(Scope *S, 3817 IdentifierInfo &Identifier, 3818 SourceLocation IdentifierLoc, 3819 SourceLocation CCLoc, 3820 QualType ObjectType, 3821 bool EnteringContext, 3822 CXXScopeSpec &SS, 3823 NamedDecl *ScopeLookupResult, 3824 bool ErrorRecoveryLookup); 3825 3826 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 3827 /// 3828 /// \param S The scope in which this nested-name-specifier occurs. 3829 /// 3830 /// \param Identifier The identifier preceding the '::'. 3831 /// 3832 /// \param IdentifierLoc The location of the identifier. 3833 /// 3834 /// \param CCLoc The location of the '::'. 3835 /// 3836 /// \param ObjectType The type of the object, if we're parsing 3837 /// nested-name-specifier in a member access expression. 3838 /// 3839 /// \param EnteringContext Whether we're entering the context nominated by 3840 /// this nested-name-specifier. 3841 /// 3842 /// \param SS The nested-name-specifier, which is both an input 3843 /// parameter (the nested-name-specifier before this type) and an 3844 /// output parameter (containing the full nested-name-specifier, 3845 /// including this new type). 3846 /// 3847 /// \returns true if an error occurred, false otherwise. 3848 bool ActOnCXXNestedNameSpecifier(Scope *S, 3849 IdentifierInfo &Identifier, 3850 SourceLocation IdentifierLoc, 3851 SourceLocation CCLoc, 3852 ParsedType ObjectType, 3853 bool EnteringContext, 3854 CXXScopeSpec &SS); 3855 3856 ExprResult ActOnDecltypeExpression(Expr *E); 3857 3858 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 3859 const DeclSpec &DS, 3860 SourceLocation ColonColonLoc); 3861 3862 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 3863 IdentifierInfo &Identifier, 3864 SourceLocation IdentifierLoc, 3865 SourceLocation ColonLoc, 3866 ParsedType ObjectType, 3867 bool EnteringContext); 3868 3869 /// \brief The parser has parsed a nested-name-specifier 3870 /// 'template[opt] template-name < template-args >::'. 3871 /// 3872 /// \param S The scope in which this nested-name-specifier occurs. 3873 /// 3874 /// \param SS The nested-name-specifier, which is both an input 3875 /// parameter (the nested-name-specifier before this type) and an 3876 /// output parameter (containing the full nested-name-specifier, 3877 /// including this new type). 3878 /// 3879 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 3880 /// \param TemplateName The template name. 3881 /// \param TemplateNameLoc The location of the template name. 3882 /// \param LAngleLoc The location of the opening angle bracket ('<'). 3883 /// \param TemplateArgs The template arguments. 3884 /// \param RAngleLoc The location of the closing angle bracket ('>'). 3885 /// \param CCLoc The location of the '::'. 3886 /// 3887 /// \param EnteringContext Whether we're entering the context of the 3888 /// nested-name-specifier. 3889 /// 3890 /// 3891 /// \returns true if an error occurred, false otherwise. 3892 bool ActOnCXXNestedNameSpecifier(Scope *S, 3893 CXXScopeSpec &SS, 3894 SourceLocation TemplateKWLoc, 3895 TemplateTy Template, 3896 SourceLocation TemplateNameLoc, 3897 SourceLocation LAngleLoc, 3898 ASTTemplateArgsPtr TemplateArgs, 3899 SourceLocation RAngleLoc, 3900 SourceLocation CCLoc, 3901 bool EnteringContext); 3902 3903 /// \brief Given a C++ nested-name-specifier, produce an annotation value 3904 /// that the parser can use later to reconstruct the given 3905 /// nested-name-specifier. 3906 /// 3907 /// \param SS A nested-name-specifier. 3908 /// 3909 /// \returns A pointer containing all of the information in the 3910 /// nested-name-specifier \p SS. 3911 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 3912 3913 /// \brief Given an annotation pointer for a nested-name-specifier, restore 3914 /// the nested-name-specifier structure. 3915 /// 3916 /// \param Annotation The annotation pointer, produced by 3917 /// \c SaveNestedNameSpecifierAnnotation(). 3918 /// 3919 /// \param AnnotationRange The source range corresponding to the annotation. 3920 /// 3921 /// \param SS The nested-name-specifier that will be updated with the contents 3922 /// of the annotation pointer. 3923 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 3924 SourceRange AnnotationRange, 3925 CXXScopeSpec &SS); 3926 3927 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3928 3929 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 3930 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 3931 /// After this method is called, according to [C++ 3.4.3p3], names should be 3932 /// looked up in the declarator-id's scope, until the declarator is parsed and 3933 /// ActOnCXXExitDeclaratorScope is called. 3934 /// The 'SS' should be a non-empty valid CXXScopeSpec. 3935 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 3936 3937 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 3938 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 3939 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 3940 /// Used to indicate that names should revert to being looked up in the 3941 /// defining scope. 3942 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 3943 3944 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 3945 /// initializer for the declaration 'Dcl'. 3946 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 3947 /// static data member of class X, names should be looked up in the scope of 3948 /// class X. 3949 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 3950 3951 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 3952 /// initializer for the declaration 'Dcl'. 3953 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 3954 3955 /// \brief Create a new lambda closure type. 3956 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 3957 bool KnownDependent = false); 3958 3959 /// \brief Start the definition of a lambda expression. 3960 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 3961 SourceRange IntroducerRange, 3962 TypeSourceInfo *MethodType, 3963 SourceLocation EndLoc, 3964 llvm::ArrayRef<ParmVarDecl *> Params, 3965 llvm::Optional<unsigned> ManglingNumber 3966 = llvm::Optional<unsigned>(), 3967 Decl *ContextDecl = 0); 3968 3969 /// \brief Introduce the scope for a lambda expression. 3970 sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator, 3971 SourceRange IntroducerRange, 3972 LambdaCaptureDefault CaptureDefault, 3973 bool ExplicitParams, 3974 bool ExplicitResultType, 3975 bool Mutable); 3976 3977 /// \brief Note that we have finished the explicit captures for the 3978 /// given lambda. 3979 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 3980 3981 /// \brief Introduce the lambda parameters into scope. 3982 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); 3983 3984 /// ActOnStartOfLambdaDefinition - This is called just before we start 3985 /// parsing the body of a lambda; it analyzes the explicit captures and 3986 /// arguments, and sets up various data-structures for the body of the 3987 /// lambda. 3988 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 3989 Declarator &ParamInfo, Scope *CurScope); 3990 3991 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 3992 /// is invoked to pop the information about the lambda. 3993 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 3994 bool IsInstantiation = false); 3995 3996 /// ActOnLambdaExpr - This is called when the body of a lambda expression 3997 /// was successfully completed. 3998 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 3999 Scope *CurScope, 4000 bool IsInstantiation = false); 4001 4002 /// \brief Define the "body" of the conversion from a lambda object to a 4003 /// function pointer. 4004 /// 4005 /// This routine doesn't actually define a sensible body; rather, it fills 4006 /// in the initialization expression needed to copy the lambda object into 4007 /// the block, and IR generation actually generates the real body of the 4008 /// block pointer conversion. 4009 void DefineImplicitLambdaToFunctionPointerConversion( 4010 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 4011 4012 /// \brief Define the "body" of the conversion from a lambda object to a 4013 /// block pointer. 4014 /// 4015 /// This routine doesn't actually define a sensible body; rather, it fills 4016 /// in the initialization expression needed to copy the lambda object into 4017 /// the block, and IR generation actually generates the real body of the 4018 /// block pointer conversion. 4019 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 4020 CXXConversionDecl *Conv); 4021 4022 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 4023 SourceLocation ConvLocation, 4024 CXXConversionDecl *Conv, 4025 Expr *Src); 4026 4027 // ParseObjCStringLiteral - Parse Objective-C string literals. 4028 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 4029 Expr **Strings, 4030 unsigned NumStrings); 4031 4032 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 4033 4034 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 4035 /// numeric literal expression. Type of the expression will be "NSNumber *" 4036 /// or "id" if NSNumber is unavailable. 4037 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 4038 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 4039 bool Value); 4040 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 4041 4042 // BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 4043 // '@' prefixed parenthesized expression. The type of the expression will 4044 // either be "NSNumber *" or "NSString *" depending on the type of 4045 // ValueType, which is allowed to be a built-in numeric type or 4046 // "char *" or "const char *". 4047 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 4048 4049 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 4050 Expr *IndexExpr, 4051 ObjCMethodDecl *getterMethod, 4052 ObjCMethodDecl *setterMethod); 4053 4054 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 4055 ObjCDictionaryElement *Elements, 4056 unsigned NumElements); 4057 4058 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 4059 TypeSourceInfo *EncodedTypeInfo, 4060 SourceLocation RParenLoc); 4061 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 4062 CXXConversionDecl *Method, 4063 bool HadMultipleCandidates); 4064 4065 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 4066 SourceLocation EncodeLoc, 4067 SourceLocation LParenLoc, 4068 ParsedType Ty, 4069 SourceLocation RParenLoc); 4070 4071 // ParseObjCSelectorExpression - Build selector expression for @selector 4072 ExprResult ParseObjCSelectorExpression(Selector Sel, 4073 SourceLocation AtLoc, 4074 SourceLocation SelLoc, 4075 SourceLocation LParenLoc, 4076 SourceLocation RParenLoc); 4077 4078 // ParseObjCProtocolExpression - Build protocol expression for @protocol 4079 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 4080 SourceLocation AtLoc, 4081 SourceLocation ProtoLoc, 4082 SourceLocation LParenLoc, 4083 SourceLocation RParenLoc); 4084 4085 //===--------------------------------------------------------------------===// 4086 // C++ Declarations 4087 // 4088 Decl *ActOnStartLinkageSpecification(Scope *S, 4089 SourceLocation ExternLoc, 4090 SourceLocation LangLoc, 4091 StringRef Lang, 4092 SourceLocation LBraceLoc); 4093 Decl *ActOnFinishLinkageSpecification(Scope *S, 4094 Decl *LinkageSpec, 4095 SourceLocation RBraceLoc); 4096 4097 4098 //===--------------------------------------------------------------------===// 4099 // C++ Classes 4100 // 4101 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 4102 const CXXScopeSpec *SS = 0); 4103 4104 bool ActOnAccessSpecifier(AccessSpecifier Access, 4105 SourceLocation ASLoc, 4106 SourceLocation ColonLoc, 4107 AttributeList *Attrs = 0); 4108 4109 Decl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 4110 Declarator &D, 4111 MultiTemplateParamsArg TemplateParameterLists, 4112 Expr *BitfieldWidth, const VirtSpecifiers &VS, 4113 bool HasDeferredInit); 4114 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, 4115 Expr *Init); 4116 4117 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4118 Scope *S, 4119 CXXScopeSpec &SS, 4120 IdentifierInfo *MemberOrBase, 4121 ParsedType TemplateTypeTy, 4122 const DeclSpec &DS, 4123 SourceLocation IdLoc, 4124 SourceLocation LParenLoc, 4125 Expr **Args, unsigned NumArgs, 4126 SourceLocation RParenLoc, 4127 SourceLocation EllipsisLoc); 4128 4129 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4130 Scope *S, 4131 CXXScopeSpec &SS, 4132 IdentifierInfo *MemberOrBase, 4133 ParsedType TemplateTypeTy, 4134 const DeclSpec &DS, 4135 SourceLocation IdLoc, 4136 Expr *InitList, 4137 SourceLocation EllipsisLoc); 4138 4139 MemInitResult BuildMemInitializer(Decl *ConstructorD, 4140 Scope *S, 4141 CXXScopeSpec &SS, 4142 IdentifierInfo *MemberOrBase, 4143 ParsedType TemplateTypeTy, 4144 const DeclSpec &DS, 4145 SourceLocation IdLoc, 4146 Expr *Init, 4147 SourceLocation EllipsisLoc); 4148 4149 MemInitResult BuildMemberInitializer(ValueDecl *Member, 4150 Expr *Init, 4151 SourceLocation IdLoc); 4152 4153 MemInitResult BuildBaseInitializer(QualType BaseType, 4154 TypeSourceInfo *BaseTInfo, 4155 Expr *Init, 4156 CXXRecordDecl *ClassDecl, 4157 SourceLocation EllipsisLoc); 4158 4159 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 4160 Expr *Init, 4161 CXXRecordDecl *ClassDecl); 4162 4163 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4164 CXXCtorInitializer *Initializer); 4165 4166 bool SetCtorInitializers(CXXConstructorDecl *Constructor, 4167 CXXCtorInitializer **Initializers, 4168 unsigned NumInitializers, bool AnyErrors); 4169 4170 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 4171 4172 4173 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 4174 /// mark all the non-trivial destructors of its members and bases as 4175 /// referenced. 4176 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 4177 CXXRecordDecl *Record); 4178 4179 /// \brief The list of classes whose vtables have been used within 4180 /// this translation unit, and the source locations at which the 4181 /// first use occurred. 4182 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 4183 4184 /// \brief The list of vtables that are required but have not yet been 4185 /// materialized. 4186 SmallVector<VTableUse, 16> VTableUses; 4187 4188 /// \brief The set of classes whose vtables have been used within 4189 /// this translation unit, and a bit that will be true if the vtable is 4190 /// required to be emitted (otherwise, it should be emitted only if needed 4191 /// by code generation). 4192 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 4193 4194 /// \brief Load any externally-stored vtable uses. 4195 void LoadExternalVTableUses(); 4196 4197 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 4198 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 4199 DynamicClassesType; 4200 4201 /// \brief A list of all of the dynamic classes in this translation 4202 /// unit. 4203 DynamicClassesType DynamicClasses; 4204 4205 /// \brief Note that the vtable for the given class was used at the 4206 /// given location. 4207 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 4208 bool DefinitionRequired = false); 4209 4210 /// MarkVirtualMembersReferenced - Will mark all members of the given 4211 /// CXXRecordDecl referenced. 4212 void MarkVirtualMembersReferenced(SourceLocation Loc, 4213 const CXXRecordDecl *RD); 4214 4215 /// \brief Define all of the vtables that have been used in this 4216 /// translation unit and reference any virtual members used by those 4217 /// vtables. 4218 /// 4219 /// \returns true if any work was done, false otherwise. 4220 bool DefineUsedVTables(); 4221 4222 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 4223 4224 void ActOnMemInitializers(Decl *ConstructorDecl, 4225 SourceLocation ColonLoc, 4226 CXXCtorInitializer **MemInits, 4227 unsigned NumMemInits, 4228 bool AnyErrors); 4229 4230 void CheckCompletedCXXClass(CXXRecordDecl *Record); 4231 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4232 Decl *TagDecl, 4233 SourceLocation LBrac, 4234 SourceLocation RBrac, 4235 AttributeList *AttrList); 4236 void ActOnFinishCXXMemberDecls(); 4237 4238 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 4239 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 4240 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 4241 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4242 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 4243 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 4244 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4245 void ActOnFinishDelayedMemberInitializers(Decl *Record); 4246 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true); 4247 bool IsInsideALocalClassWithinATemplateFunction(); 4248 4249 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4250 Expr *AssertExpr, 4251 Expr *AssertMessageExpr, 4252 SourceLocation RParenLoc); 4253 4254 FriendDecl *CheckFriendTypeDecl(SourceLocation Loc, 4255 SourceLocation FriendLoc, 4256 TypeSourceInfo *TSInfo); 4257 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 4258 MultiTemplateParamsArg TemplateParams); 4259 Decl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 4260 MultiTemplateParamsArg TemplateParams); 4261 4262 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 4263 StorageClass& SC); 4264 void CheckConstructor(CXXConstructorDecl *Constructor); 4265 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 4266 StorageClass& SC); 4267 bool CheckDestructor(CXXDestructorDecl *Destructor); 4268 void CheckConversionDeclarator(Declarator &D, QualType &R, 4269 StorageClass& SC); 4270 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 4271 4272 void CheckExplicitlyDefaultedMethods(CXXRecordDecl *Record); 4273 void CheckExplicitlyDefaultedDefaultConstructor(CXXConstructorDecl *Ctor); 4274 void CheckExplicitlyDefaultedCopyConstructor(CXXConstructorDecl *Ctor); 4275 void CheckExplicitlyDefaultedCopyAssignment(CXXMethodDecl *Method); 4276 void CheckExplicitlyDefaultedMoveConstructor(CXXConstructorDecl *Ctor); 4277 void CheckExplicitlyDefaultedMoveAssignment(CXXMethodDecl *Method); 4278 void CheckExplicitlyDefaultedDestructor(CXXDestructorDecl *Dtor); 4279 4280 //===--------------------------------------------------------------------===// 4281 // C++ Derived Classes 4282 // 4283 4284 /// ActOnBaseSpecifier - Parsed a base specifier 4285 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 4286 SourceRange SpecifierRange, 4287 bool Virtual, AccessSpecifier Access, 4288 TypeSourceInfo *TInfo, 4289 SourceLocation EllipsisLoc); 4290 4291 BaseResult ActOnBaseSpecifier(Decl *classdecl, 4292 SourceRange SpecifierRange, 4293 bool Virtual, AccessSpecifier Access, 4294 ParsedType basetype, 4295 SourceLocation BaseLoc, 4296 SourceLocation EllipsisLoc); 4297 4298 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 4299 unsigned NumBases); 4300 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 4301 unsigned NumBases); 4302 4303 bool IsDerivedFrom(QualType Derived, QualType Base); 4304 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 4305 4306 // FIXME: I don't like this name. 4307 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 4308 4309 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 4310 4311 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4312 SourceLocation Loc, SourceRange Range, 4313 CXXCastPath *BasePath = 0, 4314 bool IgnoreAccess = false); 4315 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4316 unsigned InaccessibleBaseID, 4317 unsigned AmbigiousBaseConvID, 4318 SourceLocation Loc, SourceRange Range, 4319 DeclarationName Name, 4320 CXXCastPath *BasePath); 4321 4322 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 4323 4324 /// CheckOverridingFunctionReturnType - Checks whether the return types are 4325 /// covariant, according to C++ [class.virtual]p5. 4326 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4327 const CXXMethodDecl *Old); 4328 4329 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 4330 /// spec is a subset of base spec. 4331 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4332 const CXXMethodDecl *Old); 4333 4334 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 4335 4336 /// CheckOverrideControl - Check C++0x override control semantics. 4337 void CheckOverrideControl(const Decl *D); 4338 4339 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 4340 /// overrides a virtual member function marked 'final', according to 4341 /// C++0x [class.virtual]p3. 4342 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 4343 const CXXMethodDecl *Old); 4344 4345 4346 //===--------------------------------------------------------------------===// 4347 // C++ Access Control 4348 // 4349 4350 enum AccessResult { 4351 AR_accessible, 4352 AR_inaccessible, 4353 AR_dependent, 4354 AR_delayed 4355 }; 4356 4357 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 4358 NamedDecl *PrevMemberDecl, 4359 AccessSpecifier LexicalAS); 4360 4361 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 4362 DeclAccessPair FoundDecl); 4363 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 4364 DeclAccessPair FoundDecl); 4365 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 4366 SourceRange PlacementRange, 4367 CXXRecordDecl *NamingClass, 4368 DeclAccessPair FoundDecl, 4369 bool Diagnose = true); 4370 AccessResult CheckConstructorAccess(SourceLocation Loc, 4371 CXXConstructorDecl *D, 4372 const InitializedEntity &Entity, 4373 AccessSpecifier Access, 4374 bool IsCopyBindingRefToTemp = false); 4375 AccessResult CheckConstructorAccess(SourceLocation Loc, 4376 CXXConstructorDecl *D, 4377 const InitializedEntity &Entity, 4378 AccessSpecifier Access, 4379 const PartialDiagnostic &PDiag); 4380 AccessResult CheckDestructorAccess(SourceLocation Loc, 4381 CXXDestructorDecl *Dtor, 4382 const PartialDiagnostic &PDiag, 4383 QualType objectType = QualType()); 4384 AccessResult CheckDirectMemberAccess(SourceLocation Loc, 4385 NamedDecl *D, 4386 const PartialDiagnostic &PDiag); 4387 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 4388 Expr *ObjectExpr, 4389 Expr *ArgExpr, 4390 DeclAccessPair FoundDecl); 4391 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 4392 DeclAccessPair FoundDecl); 4393 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 4394 QualType Base, QualType Derived, 4395 const CXXBasePath &Path, 4396 unsigned DiagID, 4397 bool ForceCheck = false, 4398 bool ForceUnprivileged = false); 4399 void CheckLookupAccess(const LookupResult &R); 4400 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); 4401 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, 4402 AccessSpecifier access, 4403 QualType objectType); 4404 4405 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 4406 const MultiLevelTemplateArgumentList &TemplateArgs); 4407 void PerformDependentDiagnostics(const DeclContext *Pattern, 4408 const MultiLevelTemplateArgumentList &TemplateArgs); 4409 4410 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4411 4412 /// \brief When true, access checking violations are treated as SFINAE 4413 /// failures rather than hard errors. 4414 bool AccessCheckingSFINAE; 4415 4416 enum AbstractDiagSelID { 4417 AbstractNone = -1, 4418 AbstractReturnType, 4419 AbstractParamType, 4420 AbstractVariableType, 4421 AbstractFieldType, 4422 AbstractArrayType 4423 }; 4424 4425 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4426 TypeDiagnoser &Diagnoser); 4427 template<typename T1> 4428 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4429 unsigned DiagID, 4430 const T1 &Arg1) { 4431 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 4432 return RequireNonAbstractType(Loc, T, Diagnoser); 4433 } 4434 4435 template<typename T1, typename T2> 4436 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4437 unsigned DiagID, 4438 const T1 &Arg1, const T2 &Arg2) { 4439 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 4440 return RequireNonAbstractType(Loc, T, Diagnoser); 4441 } 4442 4443 template<typename T1, typename T2, typename T3> 4444 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4445 unsigned DiagID, 4446 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { 4447 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); 4448 return RequireNonAbstractType(Loc, T, Diagnoser); 4449 } 4450 4451 void DiagnoseAbstractType(const CXXRecordDecl *RD); 4452 4453 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 4454 AbstractDiagSelID SelID = AbstractNone); 4455 4456 //===--------------------------------------------------------------------===// 4457 // C++ Overloaded Operators [C++ 13.5] 4458 // 4459 4460 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 4461 4462 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 4463 4464 //===--------------------------------------------------------------------===// 4465 // C++ Templates [C++ 14] 4466 // 4467 void FilterAcceptableTemplateNames(LookupResult &R, 4468 bool AllowFunctionTemplates = true); 4469 bool hasAnyAcceptableTemplateNames(LookupResult &R, 4470 bool AllowFunctionTemplates = true); 4471 4472 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 4473 QualType ObjectType, bool EnteringContext, 4474 bool &MemberOfUnknownSpecialization); 4475 4476 TemplateNameKind isTemplateName(Scope *S, 4477 CXXScopeSpec &SS, 4478 bool hasTemplateKeyword, 4479 UnqualifiedId &Name, 4480 ParsedType ObjectType, 4481 bool EnteringContext, 4482 TemplateTy &Template, 4483 bool &MemberOfUnknownSpecialization); 4484 4485 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 4486 SourceLocation IILoc, 4487 Scope *S, 4488 const CXXScopeSpec *SS, 4489 TemplateTy &SuggestedTemplate, 4490 TemplateNameKind &SuggestedKind); 4491 4492 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 4493 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 4494 4495 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 4496 SourceLocation EllipsisLoc, 4497 SourceLocation KeyLoc, 4498 IdentifierInfo *ParamName, 4499 SourceLocation ParamNameLoc, 4500 unsigned Depth, unsigned Position, 4501 SourceLocation EqualLoc, 4502 ParsedType DefaultArg); 4503 4504 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 4505 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 4506 unsigned Depth, 4507 unsigned Position, 4508 SourceLocation EqualLoc, 4509 Expr *DefaultArg); 4510 Decl *ActOnTemplateTemplateParameter(Scope *S, 4511 SourceLocation TmpLoc, 4512 TemplateParameterList *Params, 4513 SourceLocation EllipsisLoc, 4514 IdentifierInfo *ParamName, 4515 SourceLocation ParamNameLoc, 4516 unsigned Depth, 4517 unsigned Position, 4518 SourceLocation EqualLoc, 4519 ParsedTemplateArgument DefaultArg); 4520 4521 TemplateParameterList * 4522 ActOnTemplateParameterList(unsigned Depth, 4523 SourceLocation ExportLoc, 4524 SourceLocation TemplateLoc, 4525 SourceLocation LAngleLoc, 4526 Decl **Params, unsigned NumParams, 4527 SourceLocation RAngleLoc); 4528 4529 /// \brief The context in which we are checking a template parameter 4530 /// list. 4531 enum TemplateParamListContext { 4532 TPC_ClassTemplate, 4533 TPC_FunctionTemplate, 4534 TPC_ClassTemplateMember, 4535 TPC_FriendFunctionTemplate, 4536 TPC_FriendFunctionTemplateDefinition, 4537 TPC_TypeAliasTemplate 4538 }; 4539 4540 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 4541 TemplateParameterList *OldParams, 4542 TemplateParamListContext TPC); 4543 TemplateParameterList * 4544 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 4545 SourceLocation DeclLoc, 4546 const CXXScopeSpec &SS, 4547 TemplateParameterList **ParamLists, 4548 unsigned NumParamLists, 4549 bool IsFriend, 4550 bool &IsExplicitSpecialization, 4551 bool &Invalid); 4552 4553 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 4554 SourceLocation KWLoc, CXXScopeSpec &SS, 4555 IdentifierInfo *Name, SourceLocation NameLoc, 4556 AttributeList *Attr, 4557 TemplateParameterList *TemplateParams, 4558 AccessSpecifier AS, 4559 SourceLocation ModulePrivateLoc, 4560 unsigned NumOuterTemplateParamLists, 4561 TemplateParameterList **OuterTemplateParamLists); 4562 4563 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 4564 TemplateArgumentListInfo &Out); 4565 4566 void NoteAllFoundTemplates(TemplateName Name); 4567 4568 QualType CheckTemplateIdType(TemplateName Template, 4569 SourceLocation TemplateLoc, 4570 TemplateArgumentListInfo &TemplateArgs); 4571 4572 TypeResult 4573 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4574 TemplateTy Template, SourceLocation TemplateLoc, 4575 SourceLocation LAngleLoc, 4576 ASTTemplateArgsPtr TemplateArgs, 4577 SourceLocation RAngleLoc, 4578 bool IsCtorOrDtorName = false); 4579 4580 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 4581 /// such as \c class T::template apply<U>. 4582 /// 4583 /// \param TUK 4584 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 4585 TypeSpecifierType TagSpec, 4586 SourceLocation TagLoc, 4587 CXXScopeSpec &SS, 4588 SourceLocation TemplateKWLoc, 4589 TemplateTy TemplateD, 4590 SourceLocation TemplateLoc, 4591 SourceLocation LAngleLoc, 4592 ASTTemplateArgsPtr TemplateArgsIn, 4593 SourceLocation RAngleLoc); 4594 4595 4596 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 4597 SourceLocation TemplateKWLoc, 4598 LookupResult &R, 4599 bool RequiresADL, 4600 const TemplateArgumentListInfo *TemplateArgs); 4601 4602 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 4603 SourceLocation TemplateKWLoc, 4604 const DeclarationNameInfo &NameInfo, 4605 const TemplateArgumentListInfo *TemplateArgs); 4606 4607 TemplateNameKind ActOnDependentTemplateName(Scope *S, 4608 CXXScopeSpec &SS, 4609 SourceLocation TemplateKWLoc, 4610 UnqualifiedId &Name, 4611 ParsedType ObjectType, 4612 bool EnteringContext, 4613 TemplateTy &Template); 4614 4615 DeclResult 4616 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 4617 SourceLocation KWLoc, 4618 SourceLocation ModulePrivateLoc, 4619 CXXScopeSpec &SS, 4620 TemplateTy Template, 4621 SourceLocation TemplateNameLoc, 4622 SourceLocation LAngleLoc, 4623 ASTTemplateArgsPtr TemplateArgs, 4624 SourceLocation RAngleLoc, 4625 AttributeList *Attr, 4626 MultiTemplateParamsArg TemplateParameterLists); 4627 4628 Decl *ActOnTemplateDeclarator(Scope *S, 4629 MultiTemplateParamsArg TemplateParameterLists, 4630 Declarator &D); 4631 4632 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 4633 MultiTemplateParamsArg TemplateParameterLists, 4634 Declarator &D); 4635 4636 bool 4637 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 4638 TemplateSpecializationKind NewTSK, 4639 NamedDecl *PrevDecl, 4640 TemplateSpecializationKind PrevTSK, 4641 SourceLocation PrevPtOfInstantiation, 4642 bool &SuppressNew); 4643 4644 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 4645 const TemplateArgumentListInfo &ExplicitTemplateArgs, 4646 LookupResult &Previous); 4647 4648 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 4649 TemplateArgumentListInfo *ExplicitTemplateArgs, 4650 LookupResult &Previous); 4651 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 4652 4653 DeclResult 4654 ActOnExplicitInstantiation(Scope *S, 4655 SourceLocation ExternLoc, 4656 SourceLocation TemplateLoc, 4657 unsigned TagSpec, 4658 SourceLocation KWLoc, 4659 const CXXScopeSpec &SS, 4660 TemplateTy Template, 4661 SourceLocation TemplateNameLoc, 4662 SourceLocation LAngleLoc, 4663 ASTTemplateArgsPtr TemplateArgs, 4664 SourceLocation RAngleLoc, 4665 AttributeList *Attr); 4666 4667 DeclResult 4668 ActOnExplicitInstantiation(Scope *S, 4669 SourceLocation ExternLoc, 4670 SourceLocation TemplateLoc, 4671 unsigned TagSpec, 4672 SourceLocation KWLoc, 4673 CXXScopeSpec &SS, 4674 IdentifierInfo *Name, 4675 SourceLocation NameLoc, 4676 AttributeList *Attr); 4677 4678 DeclResult ActOnExplicitInstantiation(Scope *S, 4679 SourceLocation ExternLoc, 4680 SourceLocation TemplateLoc, 4681 Declarator &D); 4682 4683 TemplateArgumentLoc 4684 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 4685 SourceLocation TemplateLoc, 4686 SourceLocation RAngleLoc, 4687 Decl *Param, 4688 SmallVectorImpl<TemplateArgument> &Converted); 4689 4690 /// \brief Specifies the context in which a particular template 4691 /// argument is being checked. 4692 enum CheckTemplateArgumentKind { 4693 /// \brief The template argument was specified in the code or was 4694 /// instantiated with some deduced template arguments. 4695 CTAK_Specified, 4696 4697 /// \brief The template argument was deduced via template argument 4698 /// deduction. 4699 CTAK_Deduced, 4700 4701 /// \brief The template argument was deduced from an array bound 4702 /// via template argument deduction. 4703 CTAK_DeducedFromArrayBound 4704 }; 4705 4706 bool CheckTemplateArgument(NamedDecl *Param, 4707 const TemplateArgumentLoc &Arg, 4708 NamedDecl *Template, 4709 SourceLocation TemplateLoc, 4710 SourceLocation RAngleLoc, 4711 unsigned ArgumentPackIndex, 4712 SmallVectorImpl<TemplateArgument> &Converted, 4713 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4714 4715 /// \brief Check that the given template arguments can be be provided to 4716 /// the given template, converting the arguments along the way. 4717 /// 4718 /// \param Template The template to which the template arguments are being 4719 /// provided. 4720 /// 4721 /// \param TemplateLoc The location of the template name in the source. 4722 /// 4723 /// \param TemplateArgs The list of template arguments. If the template is 4724 /// a template template parameter, this function may extend the set of 4725 /// template arguments to also include substituted, defaulted template 4726 /// arguments. 4727 /// 4728 /// \param PartialTemplateArgs True if the list of template arguments is 4729 /// intentionally partial, e.g., because we're checking just the initial 4730 /// set of template arguments. 4731 /// 4732 /// \param Converted Will receive the converted, canonicalized template 4733 /// arguments. 4734 /// 4735 /// 4736 /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate 4737 /// when the template arguments contain a pack expansion that is being 4738 /// expanded into a fixed parameter list. 4739 /// 4740 /// \returns True if an error occurred, false otherwise. 4741 bool CheckTemplateArgumentList(TemplateDecl *Template, 4742 SourceLocation TemplateLoc, 4743 TemplateArgumentListInfo &TemplateArgs, 4744 bool PartialTemplateArgs, 4745 SmallVectorImpl<TemplateArgument> &Converted, 4746 bool *ExpansionIntoFixedList = 0); 4747 4748 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 4749 const TemplateArgumentLoc &Arg, 4750 SmallVectorImpl<TemplateArgument> &Converted); 4751 4752 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 4753 TypeSourceInfo *Arg); 4754 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 4755 QualType InstantiatedParamType, Expr *Arg, 4756 TemplateArgument &Converted, 4757 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4758 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 4759 const TemplateArgumentLoc &Arg); 4760 4761 ExprResult 4762 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 4763 QualType ParamType, 4764 SourceLocation Loc); 4765 ExprResult 4766 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 4767 SourceLocation Loc); 4768 4769 /// \brief Enumeration describing how template parameter lists are compared 4770 /// for equality. 4771 enum TemplateParameterListEqualKind { 4772 /// \brief We are matching the template parameter lists of two templates 4773 /// that might be redeclarations. 4774 /// 4775 /// \code 4776 /// template<typename T> struct X; 4777 /// template<typename T> struct X; 4778 /// \endcode 4779 TPL_TemplateMatch, 4780 4781 /// \brief We are matching the template parameter lists of two template 4782 /// template parameters as part of matching the template parameter lists 4783 /// of two templates that might be redeclarations. 4784 /// 4785 /// \code 4786 /// template<template<int I> class TT> struct X; 4787 /// template<template<int Value> class Other> struct X; 4788 /// \endcode 4789 TPL_TemplateTemplateParmMatch, 4790 4791 /// \brief We are matching the template parameter lists of a template 4792 /// template argument against the template parameter lists of a template 4793 /// template parameter. 4794 /// 4795 /// \code 4796 /// template<template<int Value> class Metafun> struct X; 4797 /// template<int Value> struct integer_c; 4798 /// X<integer_c> xic; 4799 /// \endcode 4800 TPL_TemplateTemplateArgumentMatch 4801 }; 4802 4803 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 4804 TemplateParameterList *Old, 4805 bool Complain, 4806 TemplateParameterListEqualKind Kind, 4807 SourceLocation TemplateArgLoc 4808 = SourceLocation()); 4809 4810 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 4811 4812 /// \brief Called when the parser has parsed a C++ typename 4813 /// specifier, e.g., "typename T::type". 4814 /// 4815 /// \param S The scope in which this typename type occurs. 4816 /// \param TypenameLoc the location of the 'typename' keyword 4817 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4818 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 4819 /// \param IdLoc the location of the identifier. 4820 TypeResult 4821 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4822 const CXXScopeSpec &SS, const IdentifierInfo &II, 4823 SourceLocation IdLoc); 4824 4825 /// \brief Called when the parser has parsed a C++ typename 4826 /// specifier that ends in a template-id, e.g., 4827 /// "typename MetaFun::template apply<T1, T2>". 4828 /// 4829 /// \param S The scope in which this typename type occurs. 4830 /// \param TypenameLoc the location of the 'typename' keyword 4831 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 4832 /// \param TemplateLoc the location of the 'template' keyword, if any. 4833 /// \param TemplateName The template name. 4834 /// \param TemplateNameLoc The location of the template name. 4835 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4836 /// \param TemplateArgs The template arguments. 4837 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4838 TypeResult 4839 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 4840 const CXXScopeSpec &SS, 4841 SourceLocation TemplateLoc, 4842 TemplateTy Template, 4843 SourceLocation TemplateNameLoc, 4844 SourceLocation LAngleLoc, 4845 ASTTemplateArgsPtr TemplateArgs, 4846 SourceLocation RAngleLoc); 4847 4848 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 4849 SourceLocation KeywordLoc, 4850 NestedNameSpecifierLoc QualifierLoc, 4851 const IdentifierInfo &II, 4852 SourceLocation IILoc); 4853 4854 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 4855 SourceLocation Loc, 4856 DeclarationName Name); 4857 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 4858 4859 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 4860 bool RebuildTemplateParamsInCurrentInstantiation( 4861 TemplateParameterList *Params); 4862 4863 std::string 4864 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4865 const TemplateArgumentList &Args); 4866 4867 std::string 4868 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 4869 const TemplateArgument *Args, 4870 unsigned NumArgs); 4871 4872 //===--------------------------------------------------------------------===// 4873 // C++ Variadic Templates (C++0x [temp.variadic]) 4874 //===--------------------------------------------------------------------===// 4875 4876 /// \brief The context in which an unexpanded parameter pack is 4877 /// being diagnosed. 4878 /// 4879 /// Note that the values of this enumeration line up with the first 4880 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 4881 enum UnexpandedParameterPackContext { 4882 /// \brief An arbitrary expression. 4883 UPPC_Expression = 0, 4884 4885 /// \brief The base type of a class type. 4886 UPPC_BaseType, 4887 4888 /// \brief The type of an arbitrary declaration. 4889 UPPC_DeclarationType, 4890 4891 /// \brief The type of a data member. 4892 UPPC_DataMemberType, 4893 4894 /// \brief The size of a bit-field. 4895 UPPC_BitFieldWidth, 4896 4897 /// \brief The expression in a static assertion. 4898 UPPC_StaticAssertExpression, 4899 4900 /// \brief The fixed underlying type of an enumeration. 4901 UPPC_FixedUnderlyingType, 4902 4903 /// \brief The enumerator value. 4904 UPPC_EnumeratorValue, 4905 4906 /// \brief A using declaration. 4907 UPPC_UsingDeclaration, 4908 4909 /// \brief A friend declaration. 4910 UPPC_FriendDeclaration, 4911 4912 /// \brief A declaration qualifier. 4913 UPPC_DeclarationQualifier, 4914 4915 /// \brief An initializer. 4916 UPPC_Initializer, 4917 4918 /// \brief A default argument. 4919 UPPC_DefaultArgument, 4920 4921 /// \brief The type of a non-type template parameter. 4922 UPPC_NonTypeTemplateParameterType, 4923 4924 /// \brief The type of an exception. 4925 UPPC_ExceptionType, 4926 4927 /// \brief Partial specialization. 4928 UPPC_PartialSpecialization, 4929 4930 /// \brief Microsoft __if_exists. 4931 UPPC_IfExists, 4932 4933 /// \brief Microsoft __if_not_exists. 4934 UPPC_IfNotExists 4935}; 4936 4937 /// \brief Diagnose unexpanded parameter packs. 4938 /// 4939 /// \param Loc The location at which we should emit the diagnostic. 4940 /// 4941 /// \param UPPC The context in which we are diagnosing unexpanded 4942 /// parameter packs. 4943 /// 4944 /// \param Unexpanded the set of unexpanded parameter packs. 4945 void DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 4946 UnexpandedParameterPackContext UPPC, 4947 ArrayRef<UnexpandedParameterPack> Unexpanded); 4948 4949 /// \brief If the given type contains an unexpanded parameter pack, 4950 /// diagnose the error. 4951 /// 4952 /// \param Loc The source location where a diagnostc should be emitted. 4953 /// 4954 /// \param T The type that is being checked for unexpanded parameter 4955 /// packs. 4956 /// 4957 /// \returns true if an error occurred, false otherwise. 4958 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 4959 UnexpandedParameterPackContext UPPC); 4960 4961 /// \brief If the given expression contains an unexpanded parameter 4962 /// pack, diagnose the error. 4963 /// 4964 /// \param E The expression that is being checked for unexpanded 4965 /// parameter packs. 4966 /// 4967 /// \returns true if an error occurred, false otherwise. 4968 bool DiagnoseUnexpandedParameterPack(Expr *E, 4969 UnexpandedParameterPackContext UPPC = UPPC_Expression); 4970 4971 /// \brief If the given nested-name-specifier contains an unexpanded 4972 /// parameter pack, diagnose the error. 4973 /// 4974 /// \param SS The nested-name-specifier that is being checked for 4975 /// unexpanded parameter packs. 4976 /// 4977 /// \returns true if an error occurred, false otherwise. 4978 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 4979 UnexpandedParameterPackContext UPPC); 4980 4981 /// \brief If the given name contains an unexpanded parameter pack, 4982 /// diagnose the error. 4983 /// 4984 /// \param NameInfo The name (with source location information) that 4985 /// is being checked for unexpanded parameter packs. 4986 /// 4987 /// \returns true if an error occurred, false otherwise. 4988 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 4989 UnexpandedParameterPackContext UPPC); 4990 4991 /// \brief If the given template name contains an unexpanded parameter pack, 4992 /// diagnose the error. 4993 /// 4994 /// \param Loc The location of the template name. 4995 /// 4996 /// \param Template The template name that is being checked for unexpanded 4997 /// parameter packs. 4998 /// 4999 /// \returns true if an error occurred, false otherwise. 5000 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 5001 TemplateName Template, 5002 UnexpandedParameterPackContext UPPC); 5003 5004 /// \brief If the given template argument contains an unexpanded parameter 5005 /// pack, diagnose the error. 5006 /// 5007 /// \param Arg The template argument that is being checked for unexpanded 5008 /// parameter packs. 5009 /// 5010 /// \returns true if an error occurred, false otherwise. 5011 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 5012 UnexpandedParameterPackContext UPPC); 5013 5014 /// \brief Collect the set of unexpanded parameter packs within the given 5015 /// template argument. 5016 /// 5017 /// \param Arg The template argument that will be traversed to find 5018 /// unexpanded parameter packs. 5019 void collectUnexpandedParameterPacks(TemplateArgument Arg, 5020 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5021 5022 /// \brief Collect the set of unexpanded parameter packs within the given 5023 /// template argument. 5024 /// 5025 /// \param Arg The template argument that will be traversed to find 5026 /// unexpanded parameter packs. 5027 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 5028 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5029 5030 /// \brief Collect the set of unexpanded parameter packs within the given 5031 /// type. 5032 /// 5033 /// \param T The type that will be traversed to find 5034 /// unexpanded parameter packs. 5035 void collectUnexpandedParameterPacks(QualType T, 5036 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5037 5038 /// \brief Collect the set of unexpanded parameter packs within the given 5039 /// type. 5040 /// 5041 /// \param TL The type that will be traversed to find 5042 /// unexpanded parameter packs. 5043 void collectUnexpandedParameterPacks(TypeLoc TL, 5044 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5045 5046 /// \brief Collect the set of unexpanded parameter packs within the given 5047 /// nested-name-specifier. 5048 /// 5049 /// \param SS The nested-name-specifier that will be traversed to find 5050 /// unexpanded parameter packs. 5051 void collectUnexpandedParameterPacks(CXXScopeSpec &SS, 5052 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5053 5054 /// \brief Collect the set of unexpanded parameter packs within the given 5055 /// name. 5056 /// 5057 /// \param NameInfo The name that will be traversed to find 5058 /// unexpanded parameter packs. 5059 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 5060 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5061 5062 /// \brief Invoked when parsing a template argument followed by an 5063 /// ellipsis, which creates a pack expansion. 5064 /// 5065 /// \param Arg The template argument preceding the ellipsis, which 5066 /// may already be invalid. 5067 /// 5068 /// \param EllipsisLoc The location of the ellipsis. 5069 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 5070 SourceLocation EllipsisLoc); 5071 5072 /// \brief Invoked when parsing a type followed by an ellipsis, which 5073 /// creates a pack expansion. 5074 /// 5075 /// \param Type The type preceding the ellipsis, which will become 5076 /// the pattern of the pack expansion. 5077 /// 5078 /// \param EllipsisLoc The location of the ellipsis. 5079 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 5080 5081 /// \brief Construct a pack expansion type from the pattern of the pack 5082 /// expansion. 5083 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 5084 SourceLocation EllipsisLoc, 5085 llvm::Optional<unsigned> NumExpansions); 5086 5087 /// \brief Construct a pack expansion type from the pattern of the pack 5088 /// expansion. 5089 QualType CheckPackExpansion(QualType Pattern, 5090 SourceRange PatternRange, 5091 SourceLocation EllipsisLoc, 5092 llvm::Optional<unsigned> NumExpansions); 5093 5094 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5095 /// creates a pack expansion. 5096 /// 5097 /// \param Pattern The expression preceding the ellipsis, which will become 5098 /// the pattern of the pack expansion. 5099 /// 5100 /// \param EllipsisLoc The location of the ellipsis. 5101 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 5102 5103 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5104 /// creates a pack expansion. 5105 /// 5106 /// \param Pattern The expression preceding the ellipsis, which will become 5107 /// the pattern of the pack expansion. 5108 /// 5109 /// \param EllipsisLoc The location of the ellipsis. 5110 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 5111 llvm::Optional<unsigned> NumExpansions); 5112 5113 /// \brief Determine whether we could expand a pack expansion with the 5114 /// given set of parameter packs into separate arguments by repeatedly 5115 /// transforming the pattern. 5116 /// 5117 /// \param EllipsisLoc The location of the ellipsis that identifies the 5118 /// pack expansion. 5119 /// 5120 /// \param PatternRange The source range that covers the entire pattern of 5121 /// the pack expansion. 5122 /// 5123 /// \param Unexpanded The set of unexpanded parameter packs within the 5124 /// pattern. 5125 /// 5126 /// \param NumUnexpanded The number of unexpanded parameter packs in 5127 /// \p Unexpanded. 5128 /// 5129 /// \param ShouldExpand Will be set to \c true if the transformer should 5130 /// expand the corresponding pack expansions into separate arguments. When 5131 /// set, \c NumExpansions must also be set. 5132 /// 5133 /// \param RetainExpansion Whether the caller should add an unexpanded 5134 /// pack expansion after all of the expanded arguments. This is used 5135 /// when extending explicitly-specified template argument packs per 5136 /// C++0x [temp.arg.explicit]p9. 5137 /// 5138 /// \param NumExpansions The number of separate arguments that will be in 5139 /// the expanded form of the corresponding pack expansion. This is both an 5140 /// input and an output parameter, which can be set by the caller if the 5141 /// number of expansions is known a priori (e.g., due to a prior substitution) 5142 /// and will be set by the callee when the number of expansions is known. 5143 /// The callee must set this value when \c ShouldExpand is \c true; it may 5144 /// set this value in other cases. 5145 /// 5146 /// \returns true if an error occurred (e.g., because the parameter packs 5147 /// are to be instantiated with arguments of different lengths), false 5148 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 5149 /// must be set. 5150 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 5151 SourceRange PatternRange, 5152 llvm::ArrayRef<UnexpandedParameterPack> Unexpanded, 5153 const MultiLevelTemplateArgumentList &TemplateArgs, 5154 bool &ShouldExpand, 5155 bool &RetainExpansion, 5156 llvm::Optional<unsigned> &NumExpansions); 5157 5158 /// \brief Determine the number of arguments in the given pack expansion 5159 /// type. 5160 /// 5161 /// This routine already assumes that the pack expansion type can be 5162 /// expanded and that the number of arguments in the expansion is 5163 /// consistent across all of the unexpanded parameter packs in its pattern. 5164 unsigned getNumArgumentsInExpansion(QualType T, 5165 const MultiLevelTemplateArgumentList &TemplateArgs); 5166 5167 /// \brief Determine whether the given declarator contains any unexpanded 5168 /// parameter packs. 5169 /// 5170 /// This routine is used by the parser to disambiguate function declarators 5171 /// with an ellipsis prior to the ')', e.g., 5172 /// 5173 /// \code 5174 /// void f(T...); 5175 /// \endcode 5176 /// 5177 /// To determine whether we have an (unnamed) function parameter pack or 5178 /// a variadic function. 5179 /// 5180 /// \returns true if the declarator contains any unexpanded parameter packs, 5181 /// false otherwise. 5182 bool containsUnexpandedParameterPacks(Declarator &D); 5183 5184 //===--------------------------------------------------------------------===// 5185 // C++ Template Argument Deduction (C++ [temp.deduct]) 5186 //===--------------------------------------------------------------------===// 5187 5188 /// \brief Describes the result of template argument deduction. 5189 /// 5190 /// The TemplateDeductionResult enumeration describes the result of 5191 /// template argument deduction, as returned from 5192 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 5193 /// structure provides additional information about the results of 5194 /// template argument deduction, e.g., the deduced template argument 5195 /// list (if successful) or the specific template parameters or 5196 /// deduced arguments that were involved in the failure. 5197 enum TemplateDeductionResult { 5198 /// \brief Template argument deduction was successful. 5199 TDK_Success = 0, 5200 /// \brief Template argument deduction exceeded the maximum template 5201 /// instantiation depth (which has already been diagnosed). 5202 TDK_InstantiationDepth, 5203 /// \brief Template argument deduction did not deduce a value 5204 /// for every template parameter. 5205 TDK_Incomplete, 5206 /// \brief Template argument deduction produced inconsistent 5207 /// deduced values for the given template parameter. 5208 TDK_Inconsistent, 5209 /// \brief Template argument deduction failed due to inconsistent 5210 /// cv-qualifiers on a template parameter type that would 5211 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 5212 /// but were given a non-const "X". 5213 TDK_Underqualified, 5214 /// \brief Substitution of the deduced template argument values 5215 /// resulted in an error. 5216 TDK_SubstitutionFailure, 5217 /// \brief Substitution of the deduced template argument values 5218 /// into a non-deduced context produced a type or value that 5219 /// produces a type that does not match the original template 5220 /// arguments provided. 5221 TDK_NonDeducedMismatch, 5222 /// \brief When performing template argument deduction for a function 5223 /// template, there were too many call arguments. 5224 TDK_TooManyArguments, 5225 /// \brief When performing template argument deduction for a function 5226 /// template, there were too few call arguments. 5227 TDK_TooFewArguments, 5228 /// \brief The explicitly-specified template arguments were not valid 5229 /// template arguments for the given template. 5230 TDK_InvalidExplicitArguments, 5231 /// \brief The arguments included an overloaded function name that could 5232 /// not be resolved to a suitable function. 5233 TDK_FailedOverloadResolution 5234 }; 5235 5236 TemplateDeductionResult 5237 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 5238 const TemplateArgumentList &TemplateArgs, 5239 sema::TemplateDeductionInfo &Info); 5240 5241 TemplateDeductionResult 5242 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5243 TemplateArgumentListInfo &ExplicitTemplateArgs, 5244 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5245 SmallVectorImpl<QualType> &ParamTypes, 5246 QualType *FunctionType, 5247 sema::TemplateDeductionInfo &Info); 5248 5249 /// brief A function argument from which we performed template argument 5250 // deduction for a call. 5251 struct OriginalCallArg { 5252 OriginalCallArg(QualType OriginalParamType, 5253 unsigned ArgIdx, 5254 QualType OriginalArgType) 5255 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 5256 OriginalArgType(OriginalArgType) { } 5257 5258 QualType OriginalParamType; 5259 unsigned ArgIdx; 5260 QualType OriginalArgType; 5261 }; 5262 5263 TemplateDeductionResult 5264 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 5265 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5266 unsigned NumExplicitlySpecified, 5267 FunctionDecl *&Specialization, 5268 sema::TemplateDeductionInfo &Info, 5269 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0); 5270 5271 TemplateDeductionResult 5272 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5273 TemplateArgumentListInfo *ExplicitTemplateArgs, 5274 llvm::ArrayRef<Expr *> Args, 5275 FunctionDecl *&Specialization, 5276 sema::TemplateDeductionInfo &Info); 5277 5278 TemplateDeductionResult 5279 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5280 TemplateArgumentListInfo *ExplicitTemplateArgs, 5281 QualType ArgFunctionType, 5282 FunctionDecl *&Specialization, 5283 sema::TemplateDeductionInfo &Info); 5284 5285 TemplateDeductionResult 5286 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5287 QualType ToType, 5288 CXXConversionDecl *&Specialization, 5289 sema::TemplateDeductionInfo &Info); 5290 5291 TemplateDeductionResult 5292 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5293 TemplateArgumentListInfo *ExplicitTemplateArgs, 5294 FunctionDecl *&Specialization, 5295 sema::TemplateDeductionInfo &Info); 5296 5297 /// \brief Result type of DeduceAutoType. 5298 enum DeduceAutoResult { 5299 DAR_Succeeded, 5300 DAR_Failed, 5301 DAR_FailedAlreadyDiagnosed 5302 }; 5303 5304 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, 5305 TypeSourceInfo *&Result); 5306 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 5307 5308 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 5309 FunctionTemplateDecl *FT2, 5310 SourceLocation Loc, 5311 TemplatePartialOrderingContext TPOC, 5312 unsigned NumCallArguments); 5313 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, 5314 UnresolvedSetIterator SEnd, 5315 TemplatePartialOrderingContext TPOC, 5316 unsigned NumCallArguments, 5317 SourceLocation Loc, 5318 const PartialDiagnostic &NoneDiag, 5319 const PartialDiagnostic &AmbigDiag, 5320 const PartialDiagnostic &CandidateDiag, 5321 bool Complain = true, 5322 QualType TargetType = QualType()); 5323 5324 ClassTemplatePartialSpecializationDecl * 5325 getMoreSpecializedPartialSpecialization( 5326 ClassTemplatePartialSpecializationDecl *PS1, 5327 ClassTemplatePartialSpecializationDecl *PS2, 5328 SourceLocation Loc); 5329 5330 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 5331 bool OnlyDeduced, 5332 unsigned Depth, 5333 llvm::SmallBitVector &Used); 5334 void MarkDeducedTemplateParameters(FunctionTemplateDecl *FunctionTemplate, 5335 llvm::SmallBitVector &Deduced) { 5336 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 5337 } 5338 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 5339 FunctionTemplateDecl *FunctionTemplate, 5340 llvm::SmallBitVector &Deduced); 5341 5342 //===--------------------------------------------------------------------===// 5343 // C++ Template Instantiation 5344 // 5345 5346 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 5347 const TemplateArgumentList *Innermost = 0, 5348 bool RelativeToPrimary = false, 5349 const FunctionDecl *Pattern = 0); 5350 5351 /// \brief A template instantiation that is currently in progress. 5352 struct ActiveTemplateInstantiation { 5353 /// \brief The kind of template instantiation we are performing 5354 enum InstantiationKind { 5355 /// We are instantiating a template declaration. The entity is 5356 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 5357 TemplateInstantiation, 5358 5359 /// We are instantiating a default argument for a template 5360 /// parameter. The Entity is the template, and 5361 /// TemplateArgs/NumTemplateArguments provides the template 5362 /// arguments as specified. 5363 /// FIXME: Use a TemplateArgumentList 5364 DefaultTemplateArgumentInstantiation, 5365 5366 /// We are instantiating a default argument for a function. 5367 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 5368 /// provides the template arguments as specified. 5369 DefaultFunctionArgumentInstantiation, 5370 5371 /// We are substituting explicit template arguments provided for 5372 /// a function template. The entity is a FunctionTemplateDecl. 5373 ExplicitTemplateArgumentSubstitution, 5374 5375 /// We are substituting template argument determined as part of 5376 /// template argument deduction for either a class template 5377 /// partial specialization or a function template. The 5378 /// Entity is either a ClassTemplatePartialSpecializationDecl or 5379 /// a FunctionTemplateDecl. 5380 DeducedTemplateArgumentSubstitution, 5381 5382 /// We are substituting prior template arguments into a new 5383 /// template parameter. The template parameter itself is either a 5384 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 5385 PriorTemplateArgumentSubstitution, 5386 5387 /// We are checking the validity of a default template argument that 5388 /// has been used when naming a template-id. 5389 DefaultTemplateArgumentChecking, 5390 5391 /// We are instantiating the exception specification for a function 5392 /// template which was deferred until it was needed. 5393 ExceptionSpecInstantiation 5394 } Kind; 5395 5396 /// \brief The point of instantiation within the source code. 5397 SourceLocation PointOfInstantiation; 5398 5399 /// \brief The template (or partial specialization) in which we are 5400 /// performing the instantiation, for substitutions of prior template 5401 /// arguments. 5402 NamedDecl *Template; 5403 5404 /// \brief The entity that is being instantiated. 5405 uintptr_t Entity; 5406 5407 /// \brief The list of template arguments we are substituting, if they 5408 /// are not part of the entity. 5409 const TemplateArgument *TemplateArgs; 5410 5411 /// \brief The number of template arguments in TemplateArgs. 5412 unsigned NumTemplateArgs; 5413 5414 /// \brief The template deduction info object associated with the 5415 /// substitution or checking of explicit or deduced template arguments. 5416 sema::TemplateDeductionInfo *DeductionInfo; 5417 5418 /// \brief The source range that covers the construct that cause 5419 /// the instantiation, e.g., the template-id that causes a class 5420 /// template instantiation. 5421 SourceRange InstantiationRange; 5422 5423 ActiveTemplateInstantiation() 5424 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 5425 NumTemplateArgs(0), DeductionInfo(0) {} 5426 5427 /// \brief Determines whether this template is an actual instantiation 5428 /// that should be counted toward the maximum instantiation depth. 5429 bool isInstantiationRecord() const; 5430 5431 friend bool operator==(const ActiveTemplateInstantiation &X, 5432 const ActiveTemplateInstantiation &Y) { 5433 if (X.Kind != Y.Kind) 5434 return false; 5435 5436 if (X.Entity != Y.Entity) 5437 return false; 5438 5439 switch (X.Kind) { 5440 case TemplateInstantiation: 5441 case ExceptionSpecInstantiation: 5442 return true; 5443 5444 case PriorTemplateArgumentSubstitution: 5445 case DefaultTemplateArgumentChecking: 5446 if (X.Template != Y.Template) 5447 return false; 5448 5449 // Fall through 5450 5451 case DefaultTemplateArgumentInstantiation: 5452 case ExplicitTemplateArgumentSubstitution: 5453 case DeducedTemplateArgumentSubstitution: 5454 case DefaultFunctionArgumentInstantiation: 5455 return X.TemplateArgs == Y.TemplateArgs; 5456 5457 } 5458 5459 llvm_unreachable("Invalid InstantiationKind!"); 5460 } 5461 5462 friend bool operator!=(const ActiveTemplateInstantiation &X, 5463 const ActiveTemplateInstantiation &Y) { 5464 return !(X == Y); 5465 } 5466 }; 5467 5468 /// \brief List of active template instantiations. 5469 /// 5470 /// This vector is treated as a stack. As one template instantiation 5471 /// requires another template instantiation, additional 5472 /// instantiations are pushed onto the stack up to a 5473 /// user-configurable limit LangOptions::InstantiationDepth. 5474 SmallVector<ActiveTemplateInstantiation, 16> 5475 ActiveTemplateInstantiations; 5476 5477 /// \brief Whether we are in a SFINAE context that is not associated with 5478 /// template instantiation. 5479 /// 5480 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 5481 /// of a template instantiation or template argument deduction. 5482 bool InNonInstantiationSFINAEContext; 5483 5484 /// \brief The number of ActiveTemplateInstantiation entries in 5485 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 5486 /// therefore, should not be counted as part of the instantiation depth. 5487 unsigned NonInstantiationEntries; 5488 5489 /// \brief The last template from which a template instantiation 5490 /// error or warning was produced. 5491 /// 5492 /// This value is used to suppress printing of redundant template 5493 /// instantiation backtraces when there are multiple errors in the 5494 /// same instantiation. FIXME: Does this belong in Sema? It's tough 5495 /// to implement it anywhere else. 5496 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 5497 5498 /// \brief The current index into pack expansion arguments that will be 5499 /// used for substitution of parameter packs. 5500 /// 5501 /// The pack expansion index will be -1 to indicate that parameter packs 5502 /// should be instantiated as themselves. Otherwise, the index specifies 5503 /// which argument within the parameter pack will be used for substitution. 5504 int ArgumentPackSubstitutionIndex; 5505 5506 /// \brief RAII object used to change the argument pack substitution index 5507 /// within a \c Sema object. 5508 /// 5509 /// See \c ArgumentPackSubstitutionIndex for more information. 5510 class ArgumentPackSubstitutionIndexRAII { 5511 Sema &Self; 5512 int OldSubstitutionIndex; 5513 5514 public: 5515 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 5516 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 5517 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 5518 } 5519 5520 ~ArgumentPackSubstitutionIndexRAII() { 5521 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 5522 } 5523 }; 5524 5525 friend class ArgumentPackSubstitutionRAII; 5526 5527 /// \brief The stack of calls expression undergoing template instantiation. 5528 /// 5529 /// The top of this stack is used by a fixit instantiating unresolved 5530 /// function calls to fix the AST to match the textual change it prints. 5531 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 5532 5533 /// \brief For each declaration that involved template argument deduction, the 5534 /// set of diagnostics that were suppressed during that template argument 5535 /// deduction. 5536 /// 5537 /// FIXME: Serialize this structure to the AST file. 5538 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 5539 SuppressedDiagnostics; 5540 5541 /// \brief A stack object to be created when performing template 5542 /// instantiation. 5543 /// 5544 /// Construction of an object of type \c InstantiatingTemplate 5545 /// pushes the current instantiation onto the stack of active 5546 /// instantiations. If the size of this stack exceeds the maximum 5547 /// number of recursive template instantiations, construction 5548 /// produces an error and evaluates true. 5549 /// 5550 /// Destruction of this object will pop the named instantiation off 5551 /// the stack. 5552 struct InstantiatingTemplate { 5553 /// \brief Note that we are instantiating a class template, 5554 /// function template, or a member thereof. 5555 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5556 Decl *Entity, 5557 SourceRange InstantiationRange = SourceRange()); 5558 5559 struct ExceptionSpecification {}; 5560 /// \brief Note that we are instantiating an exception specification 5561 /// of a function template. 5562 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5563 FunctionDecl *Entity, ExceptionSpecification, 5564 SourceRange InstantiationRange = SourceRange()); 5565 5566 /// \brief Note that we are instantiating a default argument in a 5567 /// template-id. 5568 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5569 TemplateDecl *Template, 5570 const TemplateArgument *TemplateArgs, 5571 unsigned NumTemplateArgs, 5572 SourceRange InstantiationRange = SourceRange()); 5573 5574 /// \brief Note that we are instantiating a default argument in a 5575 /// template-id. 5576 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5577 FunctionTemplateDecl *FunctionTemplate, 5578 const TemplateArgument *TemplateArgs, 5579 unsigned NumTemplateArgs, 5580 ActiveTemplateInstantiation::InstantiationKind Kind, 5581 sema::TemplateDeductionInfo &DeductionInfo, 5582 SourceRange InstantiationRange = SourceRange()); 5583 5584 /// \brief Note that we are instantiating as part of template 5585 /// argument deduction for a class template partial 5586 /// specialization. 5587 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5588 ClassTemplatePartialSpecializationDecl *PartialSpec, 5589 const TemplateArgument *TemplateArgs, 5590 unsigned NumTemplateArgs, 5591 sema::TemplateDeductionInfo &DeductionInfo, 5592 SourceRange InstantiationRange = SourceRange()); 5593 5594 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5595 ParmVarDecl *Param, 5596 const TemplateArgument *TemplateArgs, 5597 unsigned NumTemplateArgs, 5598 SourceRange InstantiationRange = SourceRange()); 5599 5600 /// \brief Note that we are substituting prior template arguments into a 5601 /// non-type or template template parameter. 5602 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5603 NamedDecl *Template, 5604 NonTypeTemplateParmDecl *Param, 5605 const TemplateArgument *TemplateArgs, 5606 unsigned NumTemplateArgs, 5607 SourceRange InstantiationRange); 5608 5609 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5610 NamedDecl *Template, 5611 TemplateTemplateParmDecl *Param, 5612 const TemplateArgument *TemplateArgs, 5613 unsigned NumTemplateArgs, 5614 SourceRange InstantiationRange); 5615 5616 /// \brief Note that we are checking the default template argument 5617 /// against the template parameter for a given template-id. 5618 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5619 TemplateDecl *Template, 5620 NamedDecl *Param, 5621 const TemplateArgument *TemplateArgs, 5622 unsigned NumTemplateArgs, 5623 SourceRange InstantiationRange); 5624 5625 5626 /// \brief Note that we have finished instantiating this template. 5627 void Clear(); 5628 5629 ~InstantiatingTemplate() { Clear(); } 5630 5631 /// \brief Determines whether we have exceeded the maximum 5632 /// recursive template instantiations. 5633 operator bool() const { return Invalid; } 5634 5635 private: 5636 Sema &SemaRef; 5637 bool Invalid; 5638 bool SavedInNonInstantiationSFINAEContext; 5639 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 5640 SourceRange InstantiationRange); 5641 5642 InstantiatingTemplate(const InstantiatingTemplate&); // not implemented 5643 5644 InstantiatingTemplate& 5645 operator=(const InstantiatingTemplate&); // not implemented 5646 }; 5647 5648 void PrintInstantiationStack(); 5649 5650 /// \brief Determines whether we are currently in a context where 5651 /// template argument substitution failures are not considered 5652 /// errors. 5653 /// 5654 /// \returns An empty \c llvm::Optional if we're not in a SFINAE context. 5655 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 5656 /// template-deduction context object, which can be used to capture 5657 /// diagnostics that will be suppressed. 5658 llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 5659 5660 /// \brief RAII class used to determine whether SFINAE has 5661 /// trapped any errors that occur during template argument 5662 /// deduction.` 5663 class SFINAETrap { 5664 Sema &SemaRef; 5665 unsigned PrevSFINAEErrors; 5666 bool PrevInNonInstantiationSFINAEContext; 5667 bool PrevAccessCheckingSFINAE; 5668 5669 public: 5670 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 5671 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 5672 PrevInNonInstantiationSFINAEContext( 5673 SemaRef.InNonInstantiationSFINAEContext), 5674 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 5675 { 5676 if (!SemaRef.isSFINAEContext()) 5677 SemaRef.InNonInstantiationSFINAEContext = true; 5678 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 5679 } 5680 5681 ~SFINAETrap() { 5682 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 5683 SemaRef.InNonInstantiationSFINAEContext 5684 = PrevInNonInstantiationSFINAEContext; 5685 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 5686 } 5687 5688 /// \brief Determine whether any SFINAE errors have been trapped. 5689 bool hasErrorOccurred() const { 5690 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 5691 } 5692 }; 5693 5694 /// \brief The current instantiation scope used to store local 5695 /// variables. 5696 LocalInstantiationScope *CurrentInstantiationScope; 5697 5698 /// \brief The number of typos corrected by CorrectTypo. 5699 unsigned TyposCorrected; 5700 5701 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> 5702 UnqualifiedTyposCorrectedMap; 5703 5704 /// \brief A cache containing the results of typo correction for unqualified 5705 /// name lookup. 5706 /// 5707 /// The string is the string that we corrected to (which may be empty, if 5708 /// there was no correction), while the boolean will be true when the 5709 /// string represents a keyword. 5710 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 5711 5712 /// \brief Worker object for performing CFG-based warnings. 5713 sema::AnalysisBasedWarnings AnalysisWarnings; 5714 5715 /// \brief An entity for which implicit template instantiation is required. 5716 /// 5717 /// The source location associated with the declaration is the first place in 5718 /// the source code where the declaration was "used". It is not necessarily 5719 /// the point of instantiation (which will be either before or after the 5720 /// namespace-scope declaration that triggered this implicit instantiation), 5721 /// However, it is the location that diagnostics should generally refer to, 5722 /// because users will need to know what code triggered the instantiation. 5723 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 5724 5725 /// \brief The queue of implicit template instantiations that are required 5726 /// but have not yet been performed. 5727 std::deque<PendingImplicitInstantiation> PendingInstantiations; 5728 5729 /// \brief The queue of implicit template instantiations that are required 5730 /// and must be performed within the current local scope. 5731 /// 5732 /// This queue is only used for member functions of local classes in 5733 /// templates, which must be instantiated in the same scope as their 5734 /// enclosing function, so that they can reference function-local 5735 /// types, static variables, enumerators, etc. 5736 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 5737 5738 void PerformPendingInstantiations(bool LocalOnly = false); 5739 5740 TypeSourceInfo *SubstType(TypeSourceInfo *T, 5741 const MultiLevelTemplateArgumentList &TemplateArgs, 5742 SourceLocation Loc, DeclarationName Entity); 5743 5744 QualType SubstType(QualType T, 5745 const MultiLevelTemplateArgumentList &TemplateArgs, 5746 SourceLocation Loc, DeclarationName Entity); 5747 5748 TypeSourceInfo *SubstType(TypeLoc TL, 5749 const MultiLevelTemplateArgumentList &TemplateArgs, 5750 SourceLocation Loc, DeclarationName Entity); 5751 5752 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 5753 const MultiLevelTemplateArgumentList &TemplateArgs, 5754 SourceLocation Loc, 5755 DeclarationName Entity, 5756 CXXRecordDecl *ThisContext, 5757 unsigned ThisTypeQuals); 5758 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 5759 const MultiLevelTemplateArgumentList &TemplateArgs, 5760 int indexAdjustment, 5761 llvm::Optional<unsigned> NumExpansions, 5762 bool ExpectParameterPack); 5763 bool SubstParmTypes(SourceLocation Loc, 5764 ParmVarDecl **Params, unsigned NumParams, 5765 const MultiLevelTemplateArgumentList &TemplateArgs, 5766 SmallVectorImpl<QualType> &ParamTypes, 5767 SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 5768 ExprResult SubstExpr(Expr *E, 5769 const MultiLevelTemplateArgumentList &TemplateArgs); 5770 5771 /// \brief Substitute the given template arguments into a list of 5772 /// expressions, expanding pack expansions if required. 5773 /// 5774 /// \param Exprs The list of expressions to substitute into. 5775 /// 5776 /// \param NumExprs The number of expressions in \p Exprs. 5777 /// 5778 /// \param IsCall Whether this is some form of call, in which case 5779 /// default arguments will be dropped. 5780 /// 5781 /// \param TemplateArgs The set of template arguments to substitute. 5782 /// 5783 /// \param Outputs Will receive all of the substituted arguments. 5784 /// 5785 /// \returns true if an error occurred, false otherwise. 5786 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 5787 const MultiLevelTemplateArgumentList &TemplateArgs, 5788 SmallVectorImpl<Expr *> &Outputs); 5789 5790 StmtResult SubstStmt(Stmt *S, 5791 const MultiLevelTemplateArgumentList &TemplateArgs); 5792 5793 Decl *SubstDecl(Decl *D, DeclContext *Owner, 5794 const MultiLevelTemplateArgumentList &TemplateArgs); 5795 5796 ExprResult SubstInitializer(Expr *E, 5797 const MultiLevelTemplateArgumentList &TemplateArgs, 5798 bool CXXDirectInit); 5799 5800 bool 5801 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 5802 CXXRecordDecl *Pattern, 5803 const MultiLevelTemplateArgumentList &TemplateArgs); 5804 5805 bool 5806 InstantiateClass(SourceLocation PointOfInstantiation, 5807 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 5808 const MultiLevelTemplateArgumentList &TemplateArgs, 5809 TemplateSpecializationKind TSK, 5810 bool Complain = true); 5811 5812 bool InstantiateEnum(SourceLocation PointOfInstantiation, 5813 EnumDecl *Instantiation, EnumDecl *Pattern, 5814 const MultiLevelTemplateArgumentList &TemplateArgs, 5815 TemplateSpecializationKind TSK); 5816 5817 struct LateInstantiatedAttribute { 5818 const Attr *TmplAttr; 5819 LocalInstantiationScope *Scope; 5820 Decl *NewDecl; 5821 5822 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 5823 Decl *D) 5824 : TmplAttr(A), Scope(S), NewDecl(D) 5825 { } 5826 }; 5827 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 5828 5829 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 5830 const Decl *Pattern, Decl *Inst, 5831 LateInstantiatedAttrVec *LateAttrs = 0, 5832 LocalInstantiationScope *OuterMostScope = 0); 5833 5834 bool 5835 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 5836 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5837 TemplateSpecializationKind TSK, 5838 bool Complain = true); 5839 5840 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 5841 CXXRecordDecl *Instantiation, 5842 const MultiLevelTemplateArgumentList &TemplateArgs, 5843 TemplateSpecializationKind TSK); 5844 5845 void InstantiateClassTemplateSpecializationMembers( 5846 SourceLocation PointOfInstantiation, 5847 ClassTemplateSpecializationDecl *ClassTemplateSpec, 5848 TemplateSpecializationKind TSK); 5849 5850 NestedNameSpecifierLoc 5851 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 5852 const MultiLevelTemplateArgumentList &TemplateArgs); 5853 5854 DeclarationNameInfo 5855 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 5856 const MultiLevelTemplateArgumentList &TemplateArgs); 5857 TemplateName 5858 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 5859 SourceLocation Loc, 5860 const MultiLevelTemplateArgumentList &TemplateArgs); 5861 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 5862 TemplateArgumentListInfo &Result, 5863 const MultiLevelTemplateArgumentList &TemplateArgs); 5864 5865 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 5866 FunctionDecl *Function); 5867 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 5868 FunctionDecl *Function, 5869 bool Recursive = false, 5870 bool DefinitionRequired = false); 5871 void InstantiateStaticDataMemberDefinition( 5872 SourceLocation PointOfInstantiation, 5873 VarDecl *Var, 5874 bool Recursive = false, 5875 bool DefinitionRequired = false); 5876 5877 void InstantiateMemInitializers(CXXConstructorDecl *New, 5878 const CXXConstructorDecl *Tmpl, 5879 const MultiLevelTemplateArgumentList &TemplateArgs); 5880 5881 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 5882 const MultiLevelTemplateArgumentList &TemplateArgs); 5883 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 5884 const MultiLevelTemplateArgumentList &TemplateArgs); 5885 5886 // Objective-C declarations. 5887 enum ObjCContainerKind { 5888 OCK_None = -1, 5889 OCK_Interface = 0, 5890 OCK_Protocol, 5891 OCK_Category, 5892 OCK_ClassExtension, 5893 OCK_Implementation, 5894 OCK_CategoryImplementation 5895 }; 5896 ObjCContainerKind getObjCContainerKind() const; 5897 5898 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 5899 IdentifierInfo *ClassName, 5900 SourceLocation ClassLoc, 5901 IdentifierInfo *SuperName, 5902 SourceLocation SuperLoc, 5903 Decl * const *ProtoRefs, 5904 unsigned NumProtoRefs, 5905 const SourceLocation *ProtoLocs, 5906 SourceLocation EndProtoLoc, 5907 AttributeList *AttrList); 5908 5909 Decl *ActOnCompatiblityAlias( 5910 SourceLocation AtCompatibilityAliasLoc, 5911 IdentifierInfo *AliasName, SourceLocation AliasLocation, 5912 IdentifierInfo *ClassName, SourceLocation ClassLocation); 5913 5914 bool CheckForwardProtocolDeclarationForCircularDependency( 5915 IdentifierInfo *PName, 5916 SourceLocation &PLoc, SourceLocation PrevLoc, 5917 const ObjCList<ObjCProtocolDecl> &PList); 5918 5919 Decl *ActOnStartProtocolInterface( 5920 SourceLocation AtProtoInterfaceLoc, 5921 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 5922 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 5923 const SourceLocation *ProtoLocs, 5924 SourceLocation EndProtoLoc, 5925 AttributeList *AttrList); 5926 5927 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 5928 IdentifierInfo *ClassName, 5929 SourceLocation ClassLoc, 5930 IdentifierInfo *CategoryName, 5931 SourceLocation CategoryLoc, 5932 Decl * const *ProtoRefs, 5933 unsigned NumProtoRefs, 5934 const SourceLocation *ProtoLocs, 5935 SourceLocation EndProtoLoc); 5936 5937 Decl *ActOnStartClassImplementation( 5938 SourceLocation AtClassImplLoc, 5939 IdentifierInfo *ClassName, SourceLocation ClassLoc, 5940 IdentifierInfo *SuperClassname, 5941 SourceLocation SuperClassLoc); 5942 5943 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 5944 IdentifierInfo *ClassName, 5945 SourceLocation ClassLoc, 5946 IdentifierInfo *CatName, 5947 SourceLocation CatLoc); 5948 5949 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 5950 ArrayRef<Decl *> Decls); 5951 5952 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 5953 IdentifierInfo **IdentList, 5954 SourceLocation *IdentLocs, 5955 unsigned NumElts); 5956 5957 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 5958 const IdentifierLocPair *IdentList, 5959 unsigned NumElts, 5960 AttributeList *attrList); 5961 5962 void FindProtocolDeclaration(bool WarnOnDeclarations, 5963 const IdentifierLocPair *ProtocolId, 5964 unsigned NumProtocols, 5965 SmallVectorImpl<Decl *> &Protocols); 5966 5967 /// Ensure attributes are consistent with type. 5968 /// \param [in, out] Attributes The attributes to check; they will 5969 /// be modified to be consistent with \arg PropertyTy. 5970 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 5971 SourceLocation Loc, 5972 unsigned &Attributes); 5973 5974 /// Process the specified property declaration and create decls for the 5975 /// setters and getters as needed. 5976 /// \param property The property declaration being processed 5977 /// \param DC The semantic container for the property 5978 /// \param redeclaredProperty Declaration for property if redeclared 5979 /// in class extension. 5980 /// \param lexicalDC Container for redeclaredProperty. 5981 void ProcessPropertyDecl(ObjCPropertyDecl *property, 5982 ObjCContainerDecl *DC, 5983 ObjCPropertyDecl *redeclaredProperty = 0, 5984 ObjCContainerDecl *lexicalDC = 0); 5985 5986 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 5987 ObjCPropertyDecl *SuperProperty, 5988 const IdentifierInfo *Name); 5989 void ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl); 5990 5991 5992 void CompareProperties(Decl *CDecl, Decl *MergeProtocols); 5993 5994 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 5995 ObjCInterfaceDecl *ID); 5996 5997 void MatchOneProtocolPropertiesInClass(Decl *CDecl, 5998 ObjCProtocolDecl *PDecl); 5999 6000 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 6001 Decl **allMethods = 0, unsigned allNum = 0, 6002 Decl **allProperties = 0, unsigned pNum = 0, 6003 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0); 6004 6005 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 6006 SourceLocation LParenLoc, 6007 FieldDeclarator &FD, ObjCDeclSpec &ODS, 6008 Selector GetterSel, Selector SetterSel, 6009 bool *OverridingProperty, 6010 tok::ObjCKeywordKind MethodImplKind, 6011 DeclContext *lexicalDC = 0); 6012 6013 Decl *ActOnPropertyImplDecl(Scope *S, 6014 SourceLocation AtLoc, 6015 SourceLocation PropertyLoc, 6016 bool ImplKind, 6017 IdentifierInfo *PropertyId, 6018 IdentifierInfo *PropertyIvar, 6019 SourceLocation PropertyIvarLoc); 6020 6021 enum ObjCSpecialMethodKind { 6022 OSMK_None, 6023 OSMK_Alloc, 6024 OSMK_New, 6025 OSMK_Copy, 6026 OSMK_RetainingInit, 6027 OSMK_NonRetainingInit 6028 }; 6029 6030 struct ObjCArgInfo { 6031 IdentifierInfo *Name; 6032 SourceLocation NameLoc; 6033 // The Type is null if no type was specified, and the DeclSpec is invalid 6034 // in this case. 6035 ParsedType Type; 6036 ObjCDeclSpec DeclSpec; 6037 6038 /// ArgAttrs - Attribute list for this argument. 6039 AttributeList *ArgAttrs; 6040 }; 6041 6042 Decl *ActOnMethodDeclaration( 6043 Scope *S, 6044 SourceLocation BeginLoc, // location of the + or -. 6045 SourceLocation EndLoc, // location of the ; or {. 6046 tok::TokenKind MethodType, 6047 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 6048 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 6049 // optional arguments. The number of types/arguments is obtained 6050 // from the Sel.getNumArgs(). 6051 ObjCArgInfo *ArgInfo, 6052 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 6053 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 6054 bool isVariadic, bool MethodDefinition); 6055 6056 // Helper method for ActOnClassMethod/ActOnInstanceMethod. 6057 // Will search "local" class/category implementations for a method decl. 6058 // Will also search in class's root looking for instance method. 6059 // Returns 0 if no method is found. 6060 ObjCMethodDecl *LookupPrivateClassMethod(Selector Sel, 6061 ObjCInterfaceDecl *CDecl); 6062 ObjCMethodDecl *LookupPrivateInstanceMethod(Selector Sel, 6063 ObjCInterfaceDecl *ClassDecl); 6064 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 6065 const ObjCObjectPointerType *OPT, 6066 bool IsInstance); 6067 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 6068 bool IsInstance); 6069 6070 bool inferObjCARCLifetime(ValueDecl *decl); 6071 6072 ExprResult 6073 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 6074 Expr *BaseExpr, 6075 SourceLocation OpLoc, 6076 DeclarationName MemberName, 6077 SourceLocation MemberLoc, 6078 SourceLocation SuperLoc, QualType SuperType, 6079 bool Super); 6080 6081 ExprResult 6082 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 6083 IdentifierInfo &propertyName, 6084 SourceLocation receiverNameLoc, 6085 SourceLocation propertyNameLoc); 6086 6087 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 6088 6089 /// \brief Describes the kind of message expression indicated by a message 6090 /// send that starts with an identifier. 6091 enum ObjCMessageKind { 6092 /// \brief The message is sent to 'super'. 6093 ObjCSuperMessage, 6094 /// \brief The message is an instance message. 6095 ObjCInstanceMessage, 6096 /// \brief The message is a class message, and the identifier is a type 6097 /// name. 6098 ObjCClassMessage 6099 }; 6100 6101 ObjCMessageKind getObjCMessageKind(Scope *S, 6102 IdentifierInfo *Name, 6103 SourceLocation NameLoc, 6104 bool IsSuper, 6105 bool HasTrailingDot, 6106 ParsedType &ReceiverType); 6107 6108 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 6109 Selector Sel, 6110 SourceLocation LBracLoc, 6111 ArrayRef<SourceLocation> SelectorLocs, 6112 SourceLocation RBracLoc, 6113 MultiExprArg Args); 6114 6115 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 6116 QualType ReceiverType, 6117 SourceLocation SuperLoc, 6118 Selector Sel, 6119 ObjCMethodDecl *Method, 6120 SourceLocation LBracLoc, 6121 ArrayRef<SourceLocation> SelectorLocs, 6122 SourceLocation RBracLoc, 6123 MultiExprArg Args, 6124 bool isImplicit = false); 6125 6126 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 6127 bool isSuperReceiver, 6128 SourceLocation Loc, 6129 Selector Sel, 6130 ObjCMethodDecl *Method, 6131 MultiExprArg Args); 6132 6133 ExprResult ActOnClassMessage(Scope *S, 6134 ParsedType Receiver, 6135 Selector Sel, 6136 SourceLocation LBracLoc, 6137 ArrayRef<SourceLocation> SelectorLocs, 6138 SourceLocation RBracLoc, 6139 MultiExprArg Args); 6140 6141 ExprResult BuildInstanceMessage(Expr *Receiver, 6142 QualType ReceiverType, 6143 SourceLocation SuperLoc, 6144 Selector Sel, 6145 ObjCMethodDecl *Method, 6146 SourceLocation LBracLoc, 6147 ArrayRef<SourceLocation> SelectorLocs, 6148 SourceLocation RBracLoc, 6149 MultiExprArg Args, 6150 bool isImplicit = false); 6151 6152 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 6153 QualType ReceiverType, 6154 SourceLocation Loc, 6155 Selector Sel, 6156 ObjCMethodDecl *Method, 6157 MultiExprArg Args); 6158 6159 ExprResult ActOnInstanceMessage(Scope *S, 6160 Expr *Receiver, 6161 Selector Sel, 6162 SourceLocation LBracLoc, 6163 ArrayRef<SourceLocation> SelectorLocs, 6164 SourceLocation RBracLoc, 6165 MultiExprArg Args); 6166 6167 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 6168 ObjCBridgeCastKind Kind, 6169 SourceLocation BridgeKeywordLoc, 6170 TypeSourceInfo *TSInfo, 6171 Expr *SubExpr); 6172 6173 ExprResult ActOnObjCBridgedCast(Scope *S, 6174 SourceLocation LParenLoc, 6175 ObjCBridgeCastKind Kind, 6176 SourceLocation BridgeKeywordLoc, 6177 ParsedType Type, 6178 SourceLocation RParenLoc, 6179 Expr *SubExpr); 6180 6181 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 6182 6183 /// \brief Check whether the given new method is a valid override of the 6184 /// given overridden method, and set any properties that should be inherited. 6185 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 6186 const ObjCMethodDecl *Overridden, 6187 bool IsImplementation); 6188 6189 /// \brief Describes the compatibility of a result type with its method. 6190 enum ResultTypeCompatibilityKind { 6191 RTC_Compatible, 6192 RTC_Incompatible, 6193 RTC_Unknown 6194 }; 6195 6196 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 6197 ObjCInterfaceDecl *CurrentClass, 6198 ResultTypeCompatibilityKind RTC); 6199 6200 enum PragmaOptionsAlignKind { 6201 POAK_Native, // #pragma options align=native 6202 POAK_Natural, // #pragma options align=natural 6203 POAK_Packed, // #pragma options align=packed 6204 POAK_Power, // #pragma options align=power 6205 POAK_Mac68k, // #pragma options align=mac68k 6206 POAK_Reset // #pragma options align=reset 6207 }; 6208 6209 /// ActOnPragmaOptionsAlign - Called on well formed #pragma options align. 6210 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 6211 SourceLocation PragmaLoc, 6212 SourceLocation KindLoc); 6213 6214 enum PragmaPackKind { 6215 PPK_Default, // #pragma pack([n]) 6216 PPK_Show, // #pragma pack(show), only supported by MSVC. 6217 PPK_Push, // #pragma pack(push, [identifier], [n]) 6218 PPK_Pop // #pragma pack(pop, [identifier], [n]) 6219 }; 6220 6221 enum PragmaMSStructKind { 6222 PMSST_OFF, // #pragms ms_struct off 6223 PMSST_ON // #pragms ms_struct on 6224 }; 6225 6226 /// ActOnPragmaPack - Called on well formed #pragma pack(...). 6227 void ActOnPragmaPack(PragmaPackKind Kind, 6228 IdentifierInfo *Name, 6229 Expr *Alignment, 6230 SourceLocation PragmaLoc, 6231 SourceLocation LParenLoc, 6232 SourceLocation RParenLoc); 6233 6234 /// ActOnPragmaMSStruct - Called on well formed #pragms ms_struct [on|off]. 6235 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 6236 6237 /// ActOnPragmaUnused - Called on well-formed '#pragma unused'. 6238 void ActOnPragmaUnused(const Token &Identifier, 6239 Scope *curScope, 6240 SourceLocation PragmaLoc); 6241 6242 /// ActOnPragmaVisibility - Called on well formed #pragma GCC visibility... . 6243 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 6244 SourceLocation PragmaLoc); 6245 6246 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6247 SourceLocation Loc); 6248 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 6249 6250 /// ActOnPragmaWeakID - Called on well formed #pragma weak ident. 6251 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 6252 SourceLocation PragmaLoc, 6253 SourceLocation WeakNameLoc); 6254 6255 /// ActOnPragmaRedefineExtname - Called on well formed 6256 /// #pragma redefine_extname oldname newname. 6257 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 6258 IdentifierInfo* AliasName, 6259 SourceLocation PragmaLoc, 6260 SourceLocation WeakNameLoc, 6261 SourceLocation AliasNameLoc); 6262 6263 /// ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident. 6264 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 6265 IdentifierInfo* AliasName, 6266 SourceLocation PragmaLoc, 6267 SourceLocation WeakNameLoc, 6268 SourceLocation AliasNameLoc); 6269 6270 /// ActOnPragmaFPContract - Called on well formed 6271 /// #pragma {STDC,OPENCL} FP_CONTRACT 6272 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 6273 6274 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 6275 /// a the record decl, to handle '#pragma pack' and '#pragma options align'. 6276 void AddAlignmentAttributesForRecord(RecordDecl *RD); 6277 6278 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 6279 void AddMsStructLayoutForRecord(RecordDecl *RD); 6280 6281 /// FreePackedContext - Deallocate and null out PackContext. 6282 void FreePackedContext(); 6283 6284 /// PushNamespaceVisibilityAttr - Note that we've entered a 6285 /// namespace with a visibility attribute. 6286 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 6287 SourceLocation Loc); 6288 6289 /// AddPushedVisibilityAttribute - If '#pragma GCC visibility' was used, 6290 /// add an appropriate visibility attribute. 6291 void AddPushedVisibilityAttribute(Decl *RD); 6292 6293 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 6294 /// for '#pragma GCC visibility' and visibility attributes on namespaces. 6295 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 6296 6297 /// FreeVisContext - Deallocate and null out VisContext. 6298 void FreeVisContext(); 6299 6300 /// AddCFAuditedAttribute - Check whether we're currently within 6301 /// '#pragma clang arc_cf_code_audited' and, if so, consider adding 6302 /// the appropriate attribute. 6303 void AddCFAuditedAttribute(Decl *D); 6304 6305 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 6306 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E); 6307 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T); 6308 6309 /// \brief The kind of conversion being performed. 6310 enum CheckedConversionKind { 6311 /// \brief An implicit conversion. 6312 CCK_ImplicitConversion, 6313 /// \brief A C-style cast. 6314 CCK_CStyleCast, 6315 /// \brief A functional-style cast. 6316 CCK_FunctionalCast, 6317 /// \brief A cast other than a C-style cast. 6318 CCK_OtherCast 6319 }; 6320 6321 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 6322 /// cast. If there is already an implicit cast, merge into the existing one. 6323 /// If isLvalue, the result of the cast is an lvalue. 6324 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 6325 ExprValueKind VK = VK_RValue, 6326 const CXXCastPath *BasePath = 0, 6327 CheckedConversionKind CCK 6328 = CCK_ImplicitConversion); 6329 6330 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 6331 /// to the conversion from scalar type ScalarTy to the Boolean type. 6332 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 6333 6334 /// IgnoredValueConversions - Given that an expression's result is 6335 /// syntactically ignored, perform any conversions that are 6336 /// required. 6337 ExprResult IgnoredValueConversions(Expr *E); 6338 6339 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 6340 // functions and arrays to their respective pointers (C99 6.3.2.1). 6341 ExprResult UsualUnaryConversions(Expr *E); 6342 6343 // DefaultFunctionArrayConversion - converts functions and arrays 6344 // to their respective pointers (C99 6.3.2.1). 6345 ExprResult DefaultFunctionArrayConversion(Expr *E); 6346 6347 // DefaultFunctionArrayLvalueConversion - converts functions and 6348 // arrays to their respective pointers and performs the 6349 // lvalue-to-rvalue conversion. 6350 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 6351 6352 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 6353 // the operand. This is DefaultFunctionArrayLvalueConversion, 6354 // except that it assumes the operand isn't of function or array 6355 // type. 6356 ExprResult DefaultLvalueConversion(Expr *E); 6357 6358 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 6359 // do not have a prototype. Integer promotions are performed on each 6360 // argument, and arguments that have type float are promoted to double. 6361 ExprResult DefaultArgumentPromotion(Expr *E); 6362 6363 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 6364 enum VariadicCallType { 6365 VariadicFunction, 6366 VariadicBlock, 6367 VariadicMethod, 6368 VariadicConstructor, 6369 VariadicDoesNotApply 6370 }; 6371 6372 /// GatherArgumentsForCall - Collector argument expressions for various 6373 /// form of call prototypes. 6374 bool GatherArgumentsForCall(SourceLocation CallLoc, 6375 FunctionDecl *FDecl, 6376 const FunctionProtoType *Proto, 6377 unsigned FirstProtoArg, 6378 Expr **Args, unsigned NumArgs, 6379 SmallVector<Expr *, 8> &AllArgs, 6380 VariadicCallType CallType = VariadicDoesNotApply, 6381 bool AllowExplicit = false); 6382 6383 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 6384 // will warn if the resulting type is not a POD type. 6385 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 6386 FunctionDecl *FDecl); 6387 6388 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 6389 // operands and then handles various conversions that are common to binary 6390 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 6391 // routine returns the first non-arithmetic type found. The client is 6392 // responsible for emitting appropriate error diagnostics. 6393 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 6394 bool IsCompAssign = false); 6395 6396 /// AssignConvertType - All of the 'assignment' semantic checks return this 6397 /// enum to indicate whether the assignment was allowed. These checks are 6398 /// done for simple assignments, as well as initialization, return from 6399 /// function, argument passing, etc. The query is phrased in terms of a 6400 /// source and destination type. 6401 enum AssignConvertType { 6402 /// Compatible - the types are compatible according to the standard. 6403 Compatible, 6404 6405 /// PointerToInt - The assignment converts a pointer to an int, which we 6406 /// accept as an extension. 6407 PointerToInt, 6408 6409 /// IntToPointer - The assignment converts an int to a pointer, which we 6410 /// accept as an extension. 6411 IntToPointer, 6412 6413 /// FunctionVoidPointer - The assignment is between a function pointer and 6414 /// void*, which the standard doesn't allow, but we accept as an extension. 6415 FunctionVoidPointer, 6416 6417 /// IncompatiblePointer - The assignment is between two pointers types that 6418 /// are not compatible, but we accept them as an extension. 6419 IncompatiblePointer, 6420 6421 /// IncompatiblePointer - The assignment is between two pointers types which 6422 /// point to integers which have a different sign, but are otherwise 6423 /// identical. This is a subset of the above, but broken out because it's by 6424 /// far the most common case of incompatible pointers. 6425 IncompatiblePointerSign, 6426 6427 /// CompatiblePointerDiscardsQualifiers - The assignment discards 6428 /// c/v/r qualifiers, which we accept as an extension. 6429 CompatiblePointerDiscardsQualifiers, 6430 6431 /// IncompatiblePointerDiscardsQualifiers - The assignment 6432 /// discards qualifiers that we don't permit to be discarded, 6433 /// like address spaces. 6434 IncompatiblePointerDiscardsQualifiers, 6435 6436 /// IncompatibleNestedPointerQualifiers - The assignment is between two 6437 /// nested pointer types, and the qualifiers other than the first two 6438 /// levels differ e.g. char ** -> const char **, but we accept them as an 6439 /// extension. 6440 IncompatibleNestedPointerQualifiers, 6441 6442 /// IncompatibleVectors - The assignment is between two vector types that 6443 /// have the same size, which we accept as an extension. 6444 IncompatibleVectors, 6445 6446 /// IntToBlockPointer - The assignment converts an int to a block 6447 /// pointer. We disallow this. 6448 IntToBlockPointer, 6449 6450 /// IncompatibleBlockPointer - The assignment is between two block 6451 /// pointers types that are not compatible. 6452 IncompatibleBlockPointer, 6453 6454 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 6455 /// id type and something else (that is incompatible with it). For example, 6456 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 6457 IncompatibleObjCQualifiedId, 6458 6459 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 6460 /// object with __weak qualifier. 6461 IncompatibleObjCWeakRef, 6462 6463 /// Incompatible - We reject this conversion outright, it is invalid to 6464 /// represent it in the AST. 6465 Incompatible 6466 }; 6467 6468 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 6469 /// assignment conversion type specified by ConvTy. This returns true if the 6470 /// conversion was invalid or false if the conversion was accepted. 6471 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 6472 SourceLocation Loc, 6473 QualType DstType, QualType SrcType, 6474 Expr *SrcExpr, AssignmentAction Action, 6475 bool *Complained = 0); 6476 6477 /// CheckAssignmentConstraints - Perform type checking for assignment, 6478 /// argument passing, variable initialization, and function return values. 6479 /// C99 6.5.16. 6480 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 6481 QualType LHSType, 6482 QualType RHSType); 6483 6484 /// Check assignment constraints and prepare for a conversion of the 6485 /// RHS to the LHS type. 6486 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 6487 ExprResult &RHS, 6488 CastKind &Kind); 6489 6490 // CheckSingleAssignmentConstraints - Currently used by 6491 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 6492 // this routine performs the default function/array converions. 6493 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 6494 ExprResult &RHS, 6495 bool Diagnose = true); 6496 6497 // \brief If the lhs type is a transparent union, check whether we 6498 // can initialize the transparent union with the given expression. 6499 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 6500 ExprResult &RHS); 6501 6502 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 6503 6504 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 6505 6506 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6507 AssignmentAction Action, 6508 bool AllowExplicit = false); 6509 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6510 AssignmentAction Action, 6511 bool AllowExplicit, 6512 ImplicitConversionSequence& ICS); 6513 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6514 const ImplicitConversionSequence& ICS, 6515 AssignmentAction Action, 6516 CheckedConversionKind CCK 6517 = CCK_ImplicitConversion); 6518 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6519 const StandardConversionSequence& SCS, 6520 AssignmentAction Action, 6521 CheckedConversionKind CCK); 6522 6523 /// the following "Check" methods will return a valid/converted QualType 6524 /// or a null QualType (indicating an error diagnostic was issued). 6525 6526 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 6527 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6528 ExprResult &RHS); 6529 QualType CheckPointerToMemberOperands( // C++ 5.5 6530 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 6531 SourceLocation OpLoc, bool isIndirect); 6532 QualType CheckMultiplyDivideOperands( // C99 6.5.5 6533 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 6534 bool IsDivide); 6535 QualType CheckRemainderOperands( // C99 6.5.5 6536 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6537 bool IsCompAssign = false); 6538 QualType CheckAdditionOperands( // C99 6.5.6 6539 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6540 QualType* CompLHSTy = 0); 6541 QualType CheckSubtractionOperands( // C99 6.5.6 6542 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6543 QualType* CompLHSTy = 0); 6544 QualType CheckShiftOperands( // C99 6.5.7 6545 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6546 bool IsCompAssign = false); 6547 QualType CheckCompareOperands( // C99 6.5.8/9 6548 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 6549 bool isRelational); 6550 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 6551 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6552 bool IsCompAssign = false); 6553 QualType CheckLogicalOperands( // C99 6.5.[13,14] 6554 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 6555 // CheckAssignmentOperands is used for both simple and compound assignment. 6556 // For simple assignment, pass both expressions and a null converted type. 6557 // For compound assignment, pass both expressions and the converted type. 6558 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 6559 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 6560 6561 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 6562 UnaryOperatorKind Opcode, Expr *Op); 6563 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 6564 BinaryOperatorKind Opcode, 6565 Expr *LHS, Expr *RHS); 6566 ExprResult checkPseudoObjectRValue(Expr *E); 6567 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 6568 6569 QualType CheckConditionalOperands( // C99 6.5.15 6570 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 6571 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 6572 QualType CXXCheckConditionalOperands( // C++ 5.16 6573 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 6574 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 6575 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 6576 bool *NonStandardCompositeType = 0); 6577 QualType FindCompositePointerType(SourceLocation Loc, 6578 ExprResult &E1, ExprResult &E2, 6579 bool *NonStandardCompositeType = 0) { 6580 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 6581 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, 6582 NonStandardCompositeType); 6583 E1 = Owned(E1Tmp); 6584 E2 = Owned(E2Tmp); 6585 return Composite; 6586 } 6587 6588 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6589 SourceLocation QuestionLoc); 6590 6591 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6592 SourceLocation QuestionLoc); 6593 6594 /// type checking for vector binary operators. 6595 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6596 SourceLocation Loc, bool IsCompAssign); 6597 QualType GetSignedVectorType(QualType V); 6598 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 6599 SourceLocation Loc, bool isRelational); 6600 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 6601 SourceLocation Loc); 6602 6603 /// type checking declaration initializers (C99 6.7.8) 6604 bool CheckForConstantInitializer(Expr *e, QualType t); 6605 6606 // type checking C++ declaration initializers (C++ [dcl.init]). 6607 6608 /// ReferenceCompareResult - Expresses the result of comparing two 6609 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 6610 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 6611 enum ReferenceCompareResult { 6612 /// Ref_Incompatible - The two types are incompatible, so direct 6613 /// reference binding is not possible. 6614 Ref_Incompatible = 0, 6615 /// Ref_Related - The two types are reference-related, which means 6616 /// that their unqualified forms (T1 and T2) are either the same 6617 /// or T1 is a base class of T2. 6618 Ref_Related, 6619 /// Ref_Compatible_With_Added_Qualification - The two types are 6620 /// reference-compatible with added qualification, meaning that 6621 /// they are reference-compatible and the qualifiers on T1 (cv1) 6622 /// are greater than the qualifiers on T2 (cv2). 6623 Ref_Compatible_With_Added_Qualification, 6624 /// Ref_Compatible - The two types are reference-compatible and 6625 /// have equivalent qualifiers (cv1 == cv2). 6626 Ref_Compatible 6627 }; 6628 6629 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 6630 QualType T1, QualType T2, 6631 bool &DerivedToBase, 6632 bool &ObjCConversion, 6633 bool &ObjCLifetimeConversion); 6634 6635 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 6636 Expr *CastExpr, CastKind &CastKind, 6637 ExprValueKind &VK, CXXCastPath &Path); 6638 6639 /// \brief Force an expression with unknown-type to an expression of the 6640 /// given type. 6641 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 6642 6643 // CheckVectorCast - check type constraints for vectors. 6644 // Since vectors are an extension, there are no C standard reference for this. 6645 // We allow casting between vectors and integer datatypes of the same size. 6646 // returns true if the cast is invalid 6647 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6648 CastKind &Kind); 6649 6650 // CheckExtVectorCast - check type constraints for extended vectors. 6651 // Since vectors are an extension, there are no C standard reference for this. 6652 // We allow casting between vectors and integer datatypes of the same size, 6653 // or vectors and the element type of that vector. 6654 // returns the cast expr 6655 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 6656 CastKind &Kind); 6657 6658 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 6659 SourceLocation LParenLoc, 6660 Expr *CastExpr, 6661 SourceLocation RParenLoc); 6662 6663 enum ARCConversionResult { ACR_okay, ACR_unbridged }; 6664 6665 /// \brief Checks for invalid conversions and casts between 6666 /// retainable pointers and other pointer kinds. 6667 ARCConversionResult CheckObjCARCConversion(SourceRange castRange, 6668 QualType castType, Expr *&op, 6669 CheckedConversionKind CCK); 6670 6671 Expr *stripARCUnbridgedCast(Expr *e); 6672 void diagnoseARCUnbridgedCast(Expr *e); 6673 6674 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 6675 QualType ExprType); 6676 6677 /// checkRetainCycles - Check whether an Objective-C message send 6678 /// might create an obvious retain cycle. 6679 void checkRetainCycles(ObjCMessageExpr *msg); 6680 void checkRetainCycles(Expr *receiver, Expr *argument); 6681 6682 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 6683 /// to weak/__unsafe_unretained type. 6684 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 6685 6686 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 6687 /// to weak/__unsafe_unretained expression. 6688 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 6689 6690 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 6691 /// \param Method - May be null. 6692 /// \param [out] ReturnType - The return type of the send. 6693 /// \return true iff there were any incompatible types. 6694 bool CheckMessageArgumentTypes(QualType ReceiverType, 6695 Expr **Args, unsigned NumArgs, Selector Sel, 6696 ObjCMethodDecl *Method, bool isClassMessage, 6697 bool isSuperMessage, 6698 SourceLocation lbrac, SourceLocation rbrac, 6699 QualType &ReturnType, ExprValueKind &VK); 6700 6701 /// \brief Determine the result of a message send expression based on 6702 /// the type of the receiver, the method expected to receive the message, 6703 /// and the form of the message send. 6704 QualType getMessageSendResultType(QualType ReceiverType, 6705 ObjCMethodDecl *Method, 6706 bool isClassMessage, bool isSuperMessage); 6707 6708 /// \brief If the given expression involves a message send to a method 6709 /// with a related result type, emit a note describing what happened. 6710 void EmitRelatedResultTypeNote(const Expr *E); 6711 6712 /// CheckBooleanCondition - Diagnose problems involving the use of 6713 /// the given expression as a boolean condition (e.g. in an if 6714 /// statement). Also performs the standard function and array 6715 /// decays, possibly changing the input variable. 6716 /// 6717 /// \param Loc - A location associated with the condition, e.g. the 6718 /// 'if' keyword. 6719 /// \return true iff there were any errors 6720 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 6721 6722 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 6723 Expr *SubExpr); 6724 6725 /// DiagnoseAssignmentAsCondition - Given that an expression is 6726 /// being used as a boolean condition, warn if it's an assignment. 6727 void DiagnoseAssignmentAsCondition(Expr *E); 6728 6729 /// \brief Redundant parentheses over an equality comparison can indicate 6730 /// that the user intended an assignment used as condition. 6731 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 6732 6733 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 6734 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 6735 6736 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 6737 /// the specified width and sign. If an overflow occurs, detect it and emit 6738 /// the specified diagnostic. 6739 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 6740 unsigned NewWidth, bool NewSign, 6741 SourceLocation Loc, unsigned DiagID); 6742 6743 /// Checks that the Objective-C declaration is declared in the global scope. 6744 /// Emits an error and marks the declaration as invalid if it's not declared 6745 /// in the global scope. 6746 bool CheckObjCDeclScope(Decl *D); 6747 6748 /// \brief Abstract base class used for diagnosing integer constant 6749 /// expression violations. 6750 class VerifyICEDiagnoser { 6751 public: 6752 bool Suppress; 6753 6754 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 6755 6756 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 6757 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); 6758 virtual ~VerifyICEDiagnoser() { } 6759 }; 6760 6761 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 6762 /// and reports the appropriate diagnostics. Returns false on success. 6763 /// Can optionally return the value of the expression. 6764 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 6765 VerifyICEDiagnoser &Diagnoser, 6766 bool AllowFold = true); 6767 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 6768 unsigned DiagID, 6769 bool AllowFold = true); 6770 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0); 6771 6772 /// VerifyBitField - verifies that a bit field expression is an ICE and has 6773 /// the correct width, and that the field type is valid. 6774 /// Returns false on success. 6775 /// Can optionally return whether the bit-field is of width 0 6776 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 6777 QualType FieldTy, Expr *BitWidth, 6778 bool *ZeroWidth = 0); 6779 6780 enum CUDAFunctionTarget { 6781 CFT_Device, 6782 CFT_Global, 6783 CFT_Host, 6784 CFT_HostDevice 6785 }; 6786 6787 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 6788 6789 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget, 6790 CUDAFunctionTarget CalleeTarget); 6791 6792 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) { 6793 return CheckCUDATarget(IdentifyCUDATarget(Caller), 6794 IdentifyCUDATarget(Callee)); 6795 } 6796 6797 /// \name Code completion 6798 //@{ 6799 /// \brief Describes the context in which code completion occurs. 6800 enum ParserCompletionContext { 6801 /// \brief Code completion occurs at top-level or namespace context. 6802 PCC_Namespace, 6803 /// \brief Code completion occurs within a class, struct, or union. 6804 PCC_Class, 6805 /// \brief Code completion occurs within an Objective-C interface, protocol, 6806 /// or category. 6807 PCC_ObjCInterface, 6808 /// \brief Code completion occurs within an Objective-C implementation or 6809 /// category implementation 6810 PCC_ObjCImplementation, 6811 /// \brief Code completion occurs within the list of instance variables 6812 /// in an Objective-C interface, protocol, category, or implementation. 6813 PCC_ObjCInstanceVariableList, 6814 /// \brief Code completion occurs following one or more template 6815 /// headers. 6816 PCC_Template, 6817 /// \brief Code completion occurs following one or more template 6818 /// headers within a class. 6819 PCC_MemberTemplate, 6820 /// \brief Code completion occurs within an expression. 6821 PCC_Expression, 6822 /// \brief Code completion occurs within a statement, which may 6823 /// also be an expression or a declaration. 6824 PCC_Statement, 6825 /// \brief Code completion occurs at the beginning of the 6826 /// initialization statement (or expression) in a for loop. 6827 PCC_ForInit, 6828 /// \brief Code completion occurs within the condition of an if, 6829 /// while, switch, or for statement. 6830 PCC_Condition, 6831 /// \brief Code completion occurs within the body of a function on a 6832 /// recovery path, where we do not have a specific handle on our position 6833 /// in the grammar. 6834 PCC_RecoveryInFunction, 6835 /// \brief Code completion occurs where only a type is permitted. 6836 PCC_Type, 6837 /// \brief Code completion occurs in a parenthesized expression, which 6838 /// might also be a type cast. 6839 PCC_ParenthesizedExpression, 6840 /// \brief Code completion occurs within a sequence of declaration 6841 /// specifiers within a function, method, or block. 6842 PCC_LocalDeclarationSpecifiers 6843 }; 6844 6845 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 6846 void CodeCompleteOrdinaryName(Scope *S, 6847 ParserCompletionContext CompletionContext); 6848 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 6849 bool AllowNonIdentifiers, 6850 bool AllowNestedNameSpecifiers); 6851 6852 struct CodeCompleteExpressionData; 6853 void CodeCompleteExpression(Scope *S, 6854 const CodeCompleteExpressionData &Data); 6855 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 6856 SourceLocation OpLoc, 6857 bool IsArrow); 6858 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 6859 void CodeCompleteTag(Scope *S, unsigned TagSpec); 6860 void CodeCompleteTypeQualifiers(DeclSpec &DS); 6861 void CodeCompleteCase(Scope *S); 6862 void CodeCompleteCall(Scope *S, Expr *Fn, llvm::ArrayRef<Expr *> Args); 6863 void CodeCompleteInitializer(Scope *S, Decl *D); 6864 void CodeCompleteReturn(Scope *S); 6865 void CodeCompleteAfterIf(Scope *S); 6866 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 6867 6868 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 6869 bool EnteringContext); 6870 void CodeCompleteUsing(Scope *S); 6871 void CodeCompleteUsingDirective(Scope *S); 6872 void CodeCompleteNamespaceDecl(Scope *S); 6873 void CodeCompleteNamespaceAliasDecl(Scope *S); 6874 void CodeCompleteOperatorName(Scope *S); 6875 void CodeCompleteConstructorInitializer(Decl *Constructor, 6876 CXXCtorInitializer** Initializers, 6877 unsigned NumInitializers); 6878 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 6879 bool AfterAmpersand); 6880 6881 void CodeCompleteObjCAtDirective(Scope *S); 6882 void CodeCompleteObjCAtVisibility(Scope *S); 6883 void CodeCompleteObjCAtStatement(Scope *S); 6884 void CodeCompleteObjCAtExpression(Scope *S); 6885 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 6886 void CodeCompleteObjCPropertyGetter(Scope *S); 6887 void CodeCompleteObjCPropertySetter(Scope *S); 6888 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 6889 bool IsParameter); 6890 void CodeCompleteObjCMessageReceiver(Scope *S); 6891 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 6892 IdentifierInfo **SelIdents, 6893 unsigned NumSelIdents, 6894 bool AtArgumentExpression); 6895 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 6896 IdentifierInfo **SelIdents, 6897 unsigned NumSelIdents, 6898 bool AtArgumentExpression, 6899 bool IsSuper = false); 6900 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 6901 IdentifierInfo **SelIdents, 6902 unsigned NumSelIdents, 6903 bool AtArgumentExpression, 6904 ObjCInterfaceDecl *Super = 0); 6905 void CodeCompleteObjCForCollection(Scope *S, 6906 DeclGroupPtrTy IterationVar); 6907 void CodeCompleteObjCSelector(Scope *S, 6908 IdentifierInfo **SelIdents, 6909 unsigned NumSelIdents); 6910 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 6911 unsigned NumProtocols); 6912 void CodeCompleteObjCProtocolDecl(Scope *S); 6913 void CodeCompleteObjCInterfaceDecl(Scope *S); 6914 void CodeCompleteObjCSuperclass(Scope *S, 6915 IdentifierInfo *ClassName, 6916 SourceLocation ClassNameLoc); 6917 void CodeCompleteObjCImplementationDecl(Scope *S); 6918 void CodeCompleteObjCInterfaceCategory(Scope *S, 6919 IdentifierInfo *ClassName, 6920 SourceLocation ClassNameLoc); 6921 void CodeCompleteObjCImplementationCategory(Scope *S, 6922 IdentifierInfo *ClassName, 6923 SourceLocation ClassNameLoc); 6924 void CodeCompleteObjCPropertyDefinition(Scope *S); 6925 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 6926 IdentifierInfo *PropertyName); 6927 void CodeCompleteObjCMethodDecl(Scope *S, 6928 bool IsInstanceMethod, 6929 ParsedType ReturnType); 6930 void CodeCompleteObjCMethodDeclSelector(Scope *S, 6931 bool IsInstanceMethod, 6932 bool AtParameterName, 6933 ParsedType ReturnType, 6934 IdentifierInfo **SelIdents, 6935 unsigned NumSelIdents); 6936 void CodeCompletePreprocessorDirective(bool InConditional); 6937 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 6938 void CodeCompletePreprocessorMacroName(bool IsDefinition); 6939 void CodeCompletePreprocessorExpression(); 6940 void CodeCompletePreprocessorMacroArgument(Scope *S, 6941 IdentifierInfo *Macro, 6942 MacroInfo *MacroInfo, 6943 unsigned Argument); 6944 void CodeCompleteNaturalLanguage(); 6945 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 6946 CodeCompletionTUInfo &CCTUInfo, 6947 SmallVectorImpl<CodeCompletionResult> &Results); 6948 //@} 6949 6950 //===--------------------------------------------------------------------===// 6951 // Extra semantic analysis beyond the C type system 6952 6953public: 6954 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 6955 unsigned ByteNo) const; 6956 6957private: 6958 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 6959 const ArraySubscriptExpr *ASE=0, 6960 bool AllowOnePastEnd=true, bool IndexNegated=false); 6961 void CheckArrayAccess(const Expr *E); 6962 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall); 6963 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 6964 Expr **Args, unsigned NumArgs); 6965 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall); 6966 6967 bool CheckObjCString(Expr *Arg); 6968 6969 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6970 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 6971 6972 bool SemaBuiltinVAStart(CallExpr *TheCall); 6973 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 6974 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 6975 6976public: 6977 // Used by C++ template instantiation. 6978 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 6979 6980private: 6981 bool SemaBuiltinPrefetch(CallExpr *TheCall); 6982 bool SemaBuiltinObjectSize(CallExpr *TheCall); 6983 bool SemaBuiltinLongjmp(CallExpr *TheCall); 6984 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 6985 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 6986 AtomicExpr::AtomicOp Op); 6987 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6988 llvm::APSInt &Result); 6989 6990 enum FormatStringType { 6991 FST_Scanf, 6992 FST_Printf, 6993 FST_NSString, 6994 FST_Strftime, 6995 FST_Strfmon, 6996 FST_Kprintf, 6997 FST_Unknown 6998 }; 6999 static FormatStringType GetFormatStringType(const FormatAttr *Format); 7000 bool SemaCheckStringLiteral(const Expr *E, Expr **Args, unsigned NumArgs, 7001 bool HasVAListArg, unsigned format_idx, 7002 unsigned firstDataArg, FormatStringType Type, 7003 bool inFunctionCall = true); 7004 7005 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 7006 Expr **Args, unsigned NumArgs, bool HasVAListArg, 7007 unsigned format_idx, unsigned firstDataArg, 7008 FormatStringType Type, bool inFunctionCall); 7009 7010 void CheckFormatArguments(const FormatAttr *Format, CallExpr *TheCall); 7011 void CheckFormatArguments(const FormatAttr *Format, Expr **Args, 7012 unsigned NumArgs, bool IsCXXMember, 7013 SourceLocation Loc, SourceRange Range); 7014 void CheckFormatArguments(Expr **Args, unsigned NumArgs, 7015 bool HasVAListArg, unsigned format_idx, 7016 unsigned firstDataArg, FormatStringType Type, 7017 SourceLocation Loc, SourceRange range); 7018 7019 void CheckNonNullArguments(const NonNullAttr *NonNull, 7020 const Expr * const *ExprArgs, 7021 SourceLocation CallSiteLoc); 7022 7023 void CheckMemaccessArguments(const CallExpr *Call, 7024 unsigned BId, 7025 IdentifierInfo *FnName); 7026 7027 void CheckStrlcpycatArguments(const CallExpr *Call, 7028 IdentifierInfo *FnName); 7029 7030 void CheckStrncatArguments(const CallExpr *Call, 7031 IdentifierInfo *FnName); 7032 7033 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 7034 SourceLocation ReturnLoc); 7035 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 7036 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 7037 7038 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 7039 Expr *Init); 7040 7041 /// \brief The parser's current scope. 7042 /// 7043 /// The parser maintains this state here. 7044 Scope *CurScope; 7045 7046protected: 7047 friend class Parser; 7048 friend class InitializationSequence; 7049 friend class ASTReader; 7050 friend class ASTWriter; 7051 7052public: 7053 /// \brief Retrieve the parser's current scope. 7054 /// 7055 /// This routine must only be used when it is certain that semantic analysis 7056 /// and the parser are in precisely the same context, which is not the case 7057 /// when, e.g., we are performing any kind of template instantiation. 7058 /// Therefore, the only safe places to use this scope are in the parser 7059 /// itself and in routines directly invoked from the parser and *never* from 7060 /// template substitution or instantiation. 7061 Scope *getCurScope() const { return CurScope; } 7062 7063 Decl *getObjCDeclContext() const; 7064 7065 DeclContext *getCurLexicalContext() const { 7066 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 7067 } 7068 7069 AvailabilityResult getCurContextAvailability() const; 7070}; 7071 7072/// \brief RAII object that enters a new expression evaluation context. 7073class EnterExpressionEvaluationContext { 7074 Sema &Actions; 7075 7076public: 7077 EnterExpressionEvaluationContext(Sema &Actions, 7078 Sema::ExpressionEvaluationContext NewContext, 7079 Decl *LambdaContextDecl = 0, 7080 bool IsDecltype = false) 7081 : Actions(Actions) { 7082 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 7083 IsDecltype); 7084 } 7085 7086 ~EnterExpressionEvaluationContext() { 7087 Actions.PopExpressionEvaluationContext(); 7088 } 7089}; 7090 7091} // end namespace clang 7092 7093#endif 7094