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