Sema.h revision d4c3d66be70ae2d0bd828329022dc428cc277a1c
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 TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 1691 TypeVisibilityAttr::VisibilityType Vis, 1692 unsigned AttrSpellingListIndex); 1693 VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, 1694 VisibilityAttr::VisibilityType Vis, 1695 unsigned AttrSpellingListIndex); 1696 DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, 1697 unsigned AttrSpellingListIndex); 1698 DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, 1699 unsigned AttrSpellingListIndex); 1700 FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, StringRef Format, 1701 int FormatIdx, int FirstArg, 1702 unsigned AttrSpellingListIndex); 1703 SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, 1704 unsigned AttrSpellingListIndex); 1705 bool mergeDeclAttribute(NamedDecl *New, InheritableAttr *Attr, 1706 bool Override); 1707 1708 /// \brief Describes the kind of merge to perform for availability 1709 /// attributes (including "deprecated", "unavailable", and "availability"). 1710 enum AvailabilityMergeKind { 1711 /// \brief Don't merge availability attributes at all. 1712 AMK_None, 1713 /// \brief Merge availability attributes for a redeclaration, which requires 1714 /// an exact match. 1715 AMK_Redeclaration, 1716 /// \brief Merge availability attributes for an override, which requires 1717 /// an exact match or a weakening of constraints. 1718 AMK_Override 1719 }; 1720 1721 void mergeDeclAttributes(NamedDecl *New, Decl *Old, 1722 AvailabilityMergeKind AMK = AMK_Redeclaration); 1723 void MergeTypedefNameDecl(TypedefNameDecl *New, LookupResult &OldDecls); 1724 bool MergeFunctionDecl(FunctionDecl *New, Decl *Old, Scope *S); 1725 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, 1726 Scope *S); 1727 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); 1728 void MergeVarDecl(VarDecl *New, LookupResult &OldDecls); 1729 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old); 1730 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); 1731 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); 1732 1733 // AssignmentAction - This is used by all the assignment diagnostic functions 1734 // to represent what is actually causing the operation 1735 enum AssignmentAction { 1736 AA_Assigning, 1737 AA_Passing, 1738 AA_Returning, 1739 AA_Converting, 1740 AA_Initializing, 1741 AA_Sending, 1742 AA_Casting 1743 }; 1744 1745 /// C++ Overloading. 1746 enum OverloadKind { 1747 /// This is a legitimate overload: the existing declarations are 1748 /// functions or function templates with different signatures. 1749 Ovl_Overload, 1750 1751 /// This is not an overload because the signature exactly matches 1752 /// an existing declaration. 1753 Ovl_Match, 1754 1755 /// This is not an overload because the lookup results contain a 1756 /// non-function. 1757 Ovl_NonFunction 1758 }; 1759 OverloadKind CheckOverload(Scope *S, 1760 FunctionDecl *New, 1761 const LookupResult &OldDecls, 1762 NamedDecl *&OldDecl, 1763 bool IsForUsingDecl); 1764 bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl); 1765 1766 /// \brief Checks availability of the function depending on the current 1767 /// function context.Inside an unavailable function,unavailability is ignored. 1768 /// 1769 /// \returns true if \p FD is unavailable and current context is inside 1770 /// an available function, false otherwise. 1771 bool isFunctionConsideredUnavailable(FunctionDecl *FD); 1772 1773 ImplicitConversionSequence 1774 TryImplicitConversion(Expr *From, QualType ToType, 1775 bool SuppressUserConversions, 1776 bool AllowExplicit, 1777 bool InOverloadResolution, 1778 bool CStyle, 1779 bool AllowObjCWritebackConversion); 1780 1781 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); 1782 bool IsFloatingPointPromotion(QualType FromType, QualType ToType); 1783 bool IsComplexPromotion(QualType FromType, QualType ToType); 1784 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1785 bool InOverloadResolution, 1786 QualType& ConvertedType, bool &IncompatibleObjC); 1787 bool isObjCPointerConversion(QualType FromType, QualType ToType, 1788 QualType& ConvertedType, bool &IncompatibleObjC); 1789 bool isObjCWritebackConversion(QualType FromType, QualType ToType, 1790 QualType &ConvertedType); 1791 bool IsBlockPointerConversion(QualType FromType, QualType ToType, 1792 QualType& ConvertedType); 1793 bool FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 1794 const FunctionProtoType *NewType, 1795 unsigned *ArgPos = 0); 1796 void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 1797 QualType FromType, QualType ToType); 1798 1799 CastKind PrepareCastToObjCObjectPointer(ExprResult &E); 1800 bool CheckPointerConversion(Expr *From, QualType ToType, 1801 CastKind &Kind, 1802 CXXCastPath& BasePath, 1803 bool IgnoreBaseAccess); 1804 bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, 1805 bool InOverloadResolution, 1806 QualType &ConvertedType); 1807 bool CheckMemberPointerConversion(Expr *From, QualType ToType, 1808 CastKind &Kind, 1809 CXXCastPath &BasePath, 1810 bool IgnoreBaseAccess); 1811 bool IsQualificationConversion(QualType FromType, QualType ToType, 1812 bool CStyle, bool &ObjCLifetimeConversion); 1813 bool IsNoReturnConversion(QualType FromType, QualType ToType, 1814 QualType &ResultTy); 1815 bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); 1816 1817 1818 ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, 1819 const VarDecl *NRVOCandidate, 1820 QualType ResultType, 1821 Expr *Value, 1822 bool AllowNRVO = true); 1823 1824 bool CanPerformCopyInitialization(const InitializedEntity &Entity, 1825 ExprResult Init); 1826 ExprResult PerformCopyInitialization(const InitializedEntity &Entity, 1827 SourceLocation EqualLoc, 1828 ExprResult Init, 1829 bool TopLevelOfInitList = false, 1830 bool AllowExplicit = false); 1831 ExprResult PerformObjectArgumentInitialization(Expr *From, 1832 NestedNameSpecifier *Qualifier, 1833 NamedDecl *FoundDecl, 1834 CXXMethodDecl *Method); 1835 1836 ExprResult PerformContextuallyConvertToBool(Expr *From); 1837 ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); 1838 1839 /// Contexts in which a converted constant expression is required. 1840 enum CCEKind { 1841 CCEK_CaseValue, ///< Expression in a case label. 1842 CCEK_Enumerator, ///< Enumerator value with fixed underlying type. 1843 CCEK_TemplateArg ///< Value of a non-type template parameter. 1844 }; 1845 ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, 1846 llvm::APSInt &Value, CCEKind CCE); 1847 1848 /// \brief Abstract base class used to diagnose problems that occur while 1849 /// trying to convert an expression to integral or enumeration type. 1850 class ICEConvertDiagnoser { 1851 public: 1852 bool Suppress; 1853 bool SuppressConversion; 1854 1855 ICEConvertDiagnoser(bool Suppress = false, 1856 bool SuppressConversion = false) 1857 : Suppress(Suppress), SuppressConversion(SuppressConversion) { } 1858 1859 /// \brief Emits a diagnostic complaining that the expression does not have 1860 /// integral or enumeration type. 1861 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 1862 QualType T) = 0; 1863 1864 /// \brief Emits a diagnostic when the expression has incomplete class type. 1865 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 1866 QualType T) = 0; 1867 1868 /// \brief Emits a diagnostic when the only matching conversion function 1869 /// is explicit. 1870 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 1871 QualType T, 1872 QualType ConvTy) = 0; 1873 1874 /// \brief Emits a note for the explicit conversion function. 1875 virtual DiagnosticBuilder 1876 noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; 1877 1878 /// \brief Emits a diagnostic when there are multiple possible conversion 1879 /// functions. 1880 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 1881 QualType T) = 0; 1882 1883 /// \brief Emits a note for one of the candidate conversions. 1884 virtual DiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 1885 QualType ConvTy) = 0; 1886 1887 /// \brief Emits a diagnostic when we picked a conversion function 1888 /// (for cases when we are not allowed to pick a conversion function). 1889 virtual DiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, 1890 QualType T, 1891 QualType ConvTy) = 0; 1892 1893 virtual ~ICEConvertDiagnoser() {} 1894 }; 1895 1896 ExprResult 1897 ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *FromE, 1898 ICEConvertDiagnoser &Diagnoser, 1899 bool AllowScopedEnumerations); 1900 1901 enum ObjCSubscriptKind { 1902 OS_Array, 1903 OS_Dictionary, 1904 OS_Error 1905 }; 1906 ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); 1907 1908 // Note that LK_String is intentionally after the other literals, as 1909 // this is used for diagnostics logic. 1910 enum ObjCLiteralKind { 1911 LK_Array, 1912 LK_Dictionary, 1913 LK_Numeric, 1914 LK_Boxed, 1915 LK_String, 1916 LK_Block, 1917 LK_None 1918 }; 1919 ObjCLiteralKind CheckLiteralKind(Expr *FromE); 1920 1921 ExprResult PerformObjectMemberConversion(Expr *From, 1922 NestedNameSpecifier *Qualifier, 1923 NamedDecl *FoundDecl, 1924 NamedDecl *Member); 1925 1926 // Members have to be NamespaceDecl* or TranslationUnitDecl*. 1927 // TODO: make this is a typesafe union. 1928 typedef llvm::SmallPtrSet<DeclContext *, 16> AssociatedNamespaceSet; 1929 typedef llvm::SmallPtrSet<CXXRecordDecl *, 16> AssociatedClassSet; 1930 1931 void AddOverloadCandidate(FunctionDecl *Function, 1932 DeclAccessPair FoundDecl, 1933 ArrayRef<Expr *> Args, 1934 OverloadCandidateSet& CandidateSet, 1935 bool SuppressUserConversions = false, 1936 bool PartialOverloading = false, 1937 bool AllowExplicit = false); 1938 void AddFunctionCandidates(const UnresolvedSetImpl &Functions, 1939 ArrayRef<Expr *> Args, 1940 OverloadCandidateSet& CandidateSet, 1941 bool SuppressUserConversions = false, 1942 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 1943 void AddMethodCandidate(DeclAccessPair FoundDecl, 1944 QualType ObjectType, 1945 Expr::Classification ObjectClassification, 1946 Expr **Args, unsigned NumArgs, 1947 OverloadCandidateSet& CandidateSet, 1948 bool SuppressUserConversion = false); 1949 void AddMethodCandidate(CXXMethodDecl *Method, 1950 DeclAccessPair FoundDecl, 1951 CXXRecordDecl *ActingContext, QualType ObjectType, 1952 Expr::Classification ObjectClassification, 1953 ArrayRef<Expr *> Args, 1954 OverloadCandidateSet& CandidateSet, 1955 bool SuppressUserConversions = false); 1956 void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 1957 DeclAccessPair FoundDecl, 1958 CXXRecordDecl *ActingContext, 1959 TemplateArgumentListInfo *ExplicitTemplateArgs, 1960 QualType ObjectType, 1961 Expr::Classification ObjectClassification, 1962 ArrayRef<Expr *> Args, 1963 OverloadCandidateSet& CandidateSet, 1964 bool SuppressUserConversions = false); 1965 void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 1966 DeclAccessPair FoundDecl, 1967 TemplateArgumentListInfo *ExplicitTemplateArgs, 1968 ArrayRef<Expr *> Args, 1969 OverloadCandidateSet& CandidateSet, 1970 bool SuppressUserConversions = false); 1971 void AddConversionCandidate(CXXConversionDecl *Conversion, 1972 DeclAccessPair FoundDecl, 1973 CXXRecordDecl *ActingContext, 1974 Expr *From, QualType ToType, 1975 OverloadCandidateSet& CandidateSet); 1976 void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 1977 DeclAccessPair FoundDecl, 1978 CXXRecordDecl *ActingContext, 1979 Expr *From, QualType ToType, 1980 OverloadCandidateSet &CandidateSet); 1981 void AddSurrogateCandidate(CXXConversionDecl *Conversion, 1982 DeclAccessPair FoundDecl, 1983 CXXRecordDecl *ActingContext, 1984 const FunctionProtoType *Proto, 1985 Expr *Object, ArrayRef<Expr *> Args, 1986 OverloadCandidateSet& CandidateSet); 1987 void AddMemberOperatorCandidates(OverloadedOperatorKind Op, 1988 SourceLocation OpLoc, 1989 Expr **Args, unsigned NumArgs, 1990 OverloadCandidateSet& CandidateSet, 1991 SourceRange OpRange = SourceRange()); 1992 void AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 1993 Expr **Args, unsigned NumArgs, 1994 OverloadCandidateSet& CandidateSet, 1995 bool IsAssignmentOperator = false, 1996 unsigned NumContextualBoolArguments = 0); 1997 void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 1998 SourceLocation OpLoc, 1999 Expr **Args, unsigned NumArgs, 2000 OverloadCandidateSet& CandidateSet); 2001 void AddArgumentDependentLookupCandidates(DeclarationName Name, 2002 bool Operator, SourceLocation Loc, 2003 ArrayRef<Expr *> Args, 2004 TemplateArgumentListInfo *ExplicitTemplateArgs, 2005 OverloadCandidateSet& CandidateSet, 2006 bool PartialOverloading = false); 2007 2008 // Emit as a 'note' the specific overload candidate 2009 void NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType = QualType()); 2010 2011 // Emit as a series of 'note's all template and non-templates 2012 // identified by the expression Expr 2013 void NoteAllOverloadCandidates(Expr* E, QualType DestType = QualType()); 2014 2015 // [PossiblyAFunctionType] --> [Return] 2016 // NonFunctionType --> NonFunctionType 2017 // R (A) --> R(A) 2018 // R (*)(A) --> R (A) 2019 // R (&)(A) --> R (A) 2020 // R (S::*)(A) --> R (A) 2021 QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); 2022 2023 FunctionDecl * 2024 ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 2025 QualType TargetType, 2026 bool Complain, 2027 DeclAccessPair &Found, 2028 bool *pHadMultipleCandidates = 0); 2029 2030 FunctionDecl *ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 2031 bool Complain = false, 2032 DeclAccessPair* Found = 0); 2033 2034 bool ResolveAndFixSingleFunctionTemplateSpecialization( 2035 ExprResult &SrcExpr, 2036 bool DoFunctionPointerConverion = false, 2037 bool Complain = false, 2038 const SourceRange& OpRangeForComplaining = SourceRange(), 2039 QualType DestTypeForComplaining = QualType(), 2040 unsigned DiagIDForComplaining = 0); 2041 2042 2043 Expr *FixOverloadedFunctionReference(Expr *E, 2044 DeclAccessPair FoundDecl, 2045 FunctionDecl *Fn); 2046 ExprResult FixOverloadedFunctionReference(ExprResult, 2047 DeclAccessPair FoundDecl, 2048 FunctionDecl *Fn); 2049 2050 void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 2051 ArrayRef<Expr *> Args, 2052 OverloadCandidateSet &CandidateSet, 2053 bool PartialOverloading = false); 2054 2055 // An enum used to represent the different possible results of building a 2056 // range-based for loop. 2057 enum ForRangeStatus { 2058 FRS_Success, 2059 FRS_NoViableFunction, 2060 FRS_DiagnosticIssued 2061 }; 2062 2063 // An enum to represent whether something is dealing with a call to begin() 2064 // or a call to end() in a range-based for loop. 2065 enum BeginEndFunction { 2066 BEF_begin, 2067 BEF_end 2068 }; 2069 2070 ForRangeStatus BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 2071 SourceLocation RangeLoc, 2072 VarDecl *Decl, 2073 BeginEndFunction BEF, 2074 const DeclarationNameInfo &NameInfo, 2075 LookupResult &MemberLookup, 2076 OverloadCandidateSet *CandidateSet, 2077 Expr *Range, ExprResult *CallExpr); 2078 2079 ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, 2080 UnresolvedLookupExpr *ULE, 2081 SourceLocation LParenLoc, 2082 Expr **Args, unsigned NumArgs, 2083 SourceLocation RParenLoc, 2084 Expr *ExecConfig, 2085 bool AllowTypoCorrection=true); 2086 2087 bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, 2088 Expr **Args, unsigned NumArgs, 2089 SourceLocation RParenLoc, 2090 OverloadCandidateSet *CandidateSet, 2091 ExprResult *Result); 2092 2093 ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, 2094 unsigned Opc, 2095 const UnresolvedSetImpl &Fns, 2096 Expr *input); 2097 2098 ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, 2099 unsigned Opc, 2100 const UnresolvedSetImpl &Fns, 2101 Expr *LHS, Expr *RHS); 2102 2103 ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 2104 SourceLocation RLoc, 2105 Expr *Base,Expr *Idx); 2106 2107 ExprResult 2108 BuildCallToMemberFunction(Scope *S, Expr *MemExpr, 2109 SourceLocation LParenLoc, Expr **Args, 2110 unsigned NumArgs, SourceLocation RParenLoc); 2111 ExprResult 2112 BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, 2113 Expr **Args, unsigned NumArgs, 2114 SourceLocation RParenLoc); 2115 2116 ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, 2117 SourceLocation OpLoc); 2118 2119 /// CheckCallReturnType - Checks that a call expression's return type is 2120 /// complete. Returns true on failure. The location passed in is the location 2121 /// that best represents the call. 2122 bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, 2123 CallExpr *CE, FunctionDecl *FD); 2124 2125 /// Helpers for dealing with blocks and functions. 2126 bool CheckParmsForFunctionDef(ParmVarDecl **Param, ParmVarDecl **ParamEnd, 2127 bool CheckParameterNames); 2128 void CheckCXXDefaultArguments(FunctionDecl *FD); 2129 void CheckExtraCXXDefaultArguments(Declarator &D); 2130 Scope *getNonFieldDeclScope(Scope *S); 2131 2132 /// \name Name lookup 2133 /// 2134 /// These routines provide name lookup that is used during semantic 2135 /// analysis to resolve the various kinds of names (identifiers, 2136 /// overloaded operator names, constructor names, etc.) into zero or 2137 /// more declarations within a particular scope. The major entry 2138 /// points are LookupName, which performs unqualified name lookup, 2139 /// and LookupQualifiedName, which performs qualified name lookup. 2140 /// 2141 /// All name lookup is performed based on some specific criteria, 2142 /// which specify what names will be visible to name lookup and how 2143 /// far name lookup should work. These criteria are important both 2144 /// for capturing language semantics (certain lookups will ignore 2145 /// certain names, for example) and for performance, since name 2146 /// lookup is often a bottleneck in the compilation of C++. Name 2147 /// lookup criteria is specified via the LookupCriteria enumeration. 2148 /// 2149 /// The results of name lookup can vary based on the kind of name 2150 /// lookup performed, the current language, and the translation 2151 /// unit. In C, for example, name lookup will either return nothing 2152 /// (no entity found) or a single declaration. In C++, name lookup 2153 /// can additionally refer to a set of overloaded functions or 2154 /// result in an ambiguity. All of the possible results of name 2155 /// lookup are captured by the LookupResult class, which provides 2156 /// the ability to distinguish among them. 2157 //@{ 2158 2159 /// @brief Describes the kind of name lookup to perform. 2160 enum LookupNameKind { 2161 /// Ordinary name lookup, which finds ordinary names (functions, 2162 /// variables, typedefs, etc.) in C and most kinds of names 2163 /// (functions, variables, members, types, etc.) in C++. 2164 LookupOrdinaryName = 0, 2165 /// Tag name lookup, which finds the names of enums, classes, 2166 /// structs, and unions. 2167 LookupTagName, 2168 /// Label name lookup. 2169 LookupLabel, 2170 /// Member name lookup, which finds the names of 2171 /// class/struct/union members. 2172 LookupMemberName, 2173 /// Look up of an operator name (e.g., operator+) for use with 2174 /// operator overloading. This lookup is similar to ordinary name 2175 /// lookup, but will ignore any declarations that are class members. 2176 LookupOperatorName, 2177 /// Look up of a name that precedes the '::' scope resolution 2178 /// operator in C++. This lookup completely ignores operator, object, 2179 /// function, and enumerator names (C++ [basic.lookup.qual]p1). 2180 LookupNestedNameSpecifierName, 2181 /// Look up a namespace name within a C++ using directive or 2182 /// namespace alias definition, ignoring non-namespace names (C++ 2183 /// [basic.lookup.udir]p1). 2184 LookupNamespaceName, 2185 /// Look up all declarations in a scope with the given name, 2186 /// including resolved using declarations. This is appropriate 2187 /// for checking redeclarations for a using declaration. 2188 LookupUsingDeclName, 2189 /// Look up an ordinary name that is going to be redeclared as a 2190 /// name with linkage. This lookup ignores any declarations that 2191 /// are outside of the current scope unless they have linkage. See 2192 /// C99 6.2.2p4-5 and C++ [basic.link]p6. 2193 LookupRedeclarationWithLinkage, 2194 /// Look up the name of an Objective-C protocol. 2195 LookupObjCProtocolName, 2196 /// Look up implicit 'self' parameter of an objective-c method. 2197 LookupObjCImplicitSelfParam, 2198 /// \brief Look up any declaration with any name. 2199 LookupAnyName 2200 }; 2201 2202 /// \brief Specifies whether (or how) name lookup is being performed for a 2203 /// redeclaration (vs. a reference). 2204 enum RedeclarationKind { 2205 /// \brief The lookup is a reference to this name that is not for the 2206 /// purpose of redeclaring the name. 2207 NotForRedeclaration = 0, 2208 /// \brief The lookup results will be used for redeclaration of a name, 2209 /// if an entity by that name already exists. 2210 ForRedeclaration 2211 }; 2212 2213 /// \brief The possible outcomes of name lookup for a literal operator. 2214 enum LiteralOperatorLookupResult { 2215 /// \brief The lookup resulted in an error. 2216 LOLR_Error, 2217 /// \brief The lookup found a single 'cooked' literal operator, which 2218 /// expects a normal literal to be built and passed to it. 2219 LOLR_Cooked, 2220 /// \brief The lookup found a single 'raw' literal operator, which expects 2221 /// a string literal containing the spelling of the literal token. 2222 LOLR_Raw, 2223 /// \brief The lookup found an overload set of literal operator templates, 2224 /// which expect the characters of the spelling of the literal token to be 2225 /// passed as a non-type template argument pack. 2226 LOLR_Template 2227 }; 2228 2229 SpecialMemberOverloadResult *LookupSpecialMember(CXXRecordDecl *D, 2230 CXXSpecialMember SM, 2231 bool ConstArg, 2232 bool VolatileArg, 2233 bool RValueThis, 2234 bool ConstThis, 2235 bool VolatileThis); 2236 2237private: 2238 bool CppLookupName(LookupResult &R, Scope *S); 2239 2240 // \brief The set of known/encountered (unique, canonicalized) NamespaceDecls. 2241 // 2242 // The boolean value will be true to indicate that the namespace was loaded 2243 // from an AST/PCH file, or false otherwise. 2244 llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; 2245 2246 /// \brief Whether we have already loaded known namespaces from an extenal 2247 /// source. 2248 bool LoadedExternalKnownNamespaces; 2249 2250public: 2251 /// \brief Look up a name, looking for a single declaration. Return 2252 /// null if the results were absent, ambiguous, or overloaded. 2253 /// 2254 /// It is preferable to use the elaborated form and explicitly handle 2255 /// ambiguity and overloaded. 2256 NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, 2257 SourceLocation Loc, 2258 LookupNameKind NameKind, 2259 RedeclarationKind Redecl 2260 = NotForRedeclaration); 2261 bool LookupName(LookupResult &R, Scope *S, 2262 bool AllowBuiltinCreation = false); 2263 bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, 2264 bool InUnqualifiedLookup = false); 2265 bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, 2266 bool AllowBuiltinCreation = false, 2267 bool EnteringContext = false); 2268 ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, 2269 RedeclarationKind Redecl 2270 = NotForRedeclaration); 2271 2272 void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, 2273 QualType T1, QualType T2, 2274 UnresolvedSetImpl &Functions); 2275 2276 LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, 2277 SourceLocation GnuLabelLoc = SourceLocation()); 2278 2279 DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); 2280 CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); 2281 CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, 2282 unsigned Quals); 2283 CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, 2284 bool RValueThis, unsigned ThisQuals); 2285 CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, 2286 unsigned Quals); 2287 CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, 2288 bool RValueThis, unsigned ThisQuals); 2289 CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); 2290 2291 LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, 2292 ArrayRef<QualType> ArgTys, 2293 bool AllowRawAndTemplate); 2294 bool isKnownName(StringRef name); 2295 2296 void ArgumentDependentLookup(DeclarationName Name, bool Operator, 2297 SourceLocation Loc, 2298 ArrayRef<Expr *> Args, 2299 ADLResult &Functions); 2300 2301 void LookupVisibleDecls(Scope *S, LookupNameKind Kind, 2302 VisibleDeclConsumer &Consumer, 2303 bool IncludeGlobalScope = true); 2304 void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, 2305 VisibleDeclConsumer &Consumer, 2306 bool IncludeGlobalScope = true); 2307 2308 TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, 2309 Sema::LookupNameKind LookupKind, 2310 Scope *S, CXXScopeSpec *SS, 2311 CorrectionCandidateCallback &CCC, 2312 DeclContext *MemberContext = 0, 2313 bool EnteringContext = false, 2314 const ObjCObjectPointerType *OPT = 0); 2315 2316 void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, 2317 ArrayRef<Expr *> Args, 2318 AssociatedNamespaceSet &AssociatedNamespaces, 2319 AssociatedClassSet &AssociatedClasses); 2320 2321 void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, 2322 bool ConsiderLinkage, 2323 bool ExplicitInstantiationOrSpecialization); 2324 2325 bool DiagnoseAmbiguousLookup(LookupResult &Result); 2326 //@} 2327 2328 ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, 2329 SourceLocation IdLoc, 2330 bool TypoCorrection = false); 2331 NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, 2332 Scope *S, bool ForRedeclaration, 2333 SourceLocation Loc); 2334 NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, 2335 Scope *S); 2336 void AddKnownFunctionAttributes(FunctionDecl *FD); 2337 2338 // More parsing and symbol table subroutines. 2339 2340 // Decl attributes - this routine is the top level dispatcher. 2341 void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD, 2342 bool NonInheritable = true, 2343 bool Inheritable = true); 2344 void ProcessDeclAttributeList(Scope *S, Decl *D, const AttributeList *AL, 2345 bool NonInheritable = true, 2346 bool Inheritable = true, 2347 bool IncludeCXX11Attributes = true); 2348 bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 2349 const AttributeList *AttrList); 2350 2351 void checkUnusedDeclAttributes(Declarator &D); 2352 2353 bool CheckRegparmAttr(const AttributeList &attr, unsigned &value); 2354 bool CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 2355 const FunctionDecl *FD = 0); 2356 bool CheckNoReturnAttr(const AttributeList &attr); 2357 void CheckAlignasUnderalignment(Decl *D); 2358 2359 /// \brief Stmt attributes - this routine is the top level dispatcher. 2360 StmtResult ProcessStmtAttributes(Stmt *Stmt, AttributeList *Attrs, 2361 SourceRange Range); 2362 2363 void WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 2364 bool &IncompleteImpl, unsigned DiagID); 2365 void WarnConflictingTypedMethods(ObjCMethodDecl *Method, 2366 ObjCMethodDecl *MethodDecl, 2367 bool IsProtocolMethodDecl); 2368 2369 void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2370 ObjCMethodDecl *Overridden, 2371 bool IsProtocolMethodDecl); 2372 2373 /// WarnExactTypedMethods - This routine issues a warning if method 2374 /// implementation declaration matches exactly that of its declaration. 2375 void WarnExactTypedMethods(ObjCMethodDecl *Method, 2376 ObjCMethodDecl *MethodDecl, 2377 bool IsProtocolMethodDecl); 2378 2379 bool isPropertyReadonly(ObjCPropertyDecl *PropertyDecl, 2380 ObjCInterfaceDecl *IDecl); 2381 2382 typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; 2383 typedef llvm::DenseMap<Selector, ObjCMethodDecl*> ProtocolsMethodsMap; 2384 2385 /// CheckProtocolMethodDefs - This routine checks unimplemented 2386 /// methods declared in protocol, and those referenced by it. 2387 void CheckProtocolMethodDefs(SourceLocation ImpLoc, 2388 ObjCProtocolDecl *PDecl, 2389 bool& IncompleteImpl, 2390 const SelectorSet &InsMap, 2391 const SelectorSet &ClsMap, 2392 ObjCContainerDecl *CDecl); 2393 2394 /// CheckImplementationIvars - This routine checks if the instance variables 2395 /// listed in the implelementation match those listed in the interface. 2396 void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 2397 ObjCIvarDecl **Fields, unsigned nIvars, 2398 SourceLocation Loc); 2399 2400 /// ImplMethodsVsClassMethods - This is main routine to warn if any method 2401 /// remains unimplemented in the class or category \@implementation. 2402 void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2403 ObjCContainerDecl* IDecl, 2404 bool IncompleteImpl = false); 2405 2406 /// DiagnoseUnimplementedProperties - This routine warns on those properties 2407 /// which must be implemented by this implementation. 2408 void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 2409 ObjCContainerDecl *CDecl, 2410 const SelectorSet &InsMap); 2411 2412 /// DefaultSynthesizeProperties - This routine default synthesizes all 2413 /// properties which must be synthesized in the class's \@implementation. 2414 void DefaultSynthesizeProperties (Scope *S, ObjCImplDecl* IMPDecl, 2415 ObjCInterfaceDecl *IDecl); 2416 void DefaultSynthesizeProperties(Scope *S, Decl *D); 2417 2418 /// CollectImmediateProperties - This routine collects all properties in 2419 /// the class and its conforming protocols; but not those it its super class. 2420 void CollectImmediateProperties(ObjCContainerDecl *CDecl, 2421 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap, 2422 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& SuperPropMap); 2423 2424 /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 2425 /// an ivar synthesized for 'Method' and 'Method' is a property accessor 2426 /// declared in class 'IFace'. 2427 bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 2428 ObjCMethodDecl *Method, ObjCIvarDecl *IV); 2429 2430 /// Called by ActOnProperty to handle \@property declarations in 2431 /// class extensions. 2432 ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, 2433 SourceLocation AtLoc, 2434 SourceLocation LParenLoc, 2435 FieldDeclarator &FD, 2436 Selector GetterSel, 2437 Selector SetterSel, 2438 const bool isAssign, 2439 const bool isReadWrite, 2440 const unsigned Attributes, 2441 const unsigned AttributesAsWritten, 2442 bool *isOverridingProperty, 2443 TypeSourceInfo *T, 2444 tok::ObjCKeywordKind MethodImplKind); 2445 2446 /// Called by ActOnProperty and HandlePropertyInClassExtension to 2447 /// handle creating the ObjcPropertyDecl for a category or \@interface. 2448 ObjCPropertyDecl *CreatePropertyDecl(Scope *S, 2449 ObjCContainerDecl *CDecl, 2450 SourceLocation AtLoc, 2451 SourceLocation LParenLoc, 2452 FieldDeclarator &FD, 2453 Selector GetterSel, 2454 Selector SetterSel, 2455 const bool isAssign, 2456 const bool isReadWrite, 2457 const unsigned Attributes, 2458 const unsigned AttributesAsWritten, 2459 TypeSourceInfo *T, 2460 tok::ObjCKeywordKind MethodImplKind, 2461 DeclContext *lexicalDC = 0); 2462 2463 /// AtomicPropertySetterGetterRules - This routine enforces the rule (via 2464 /// warning) when atomic property has one but not the other user-declared 2465 /// setter or getter. 2466 void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, 2467 ObjCContainerDecl* IDecl); 2468 2469 void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); 2470 2471 void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); 2472 2473 enum MethodMatchStrategy { 2474 MMS_loose, 2475 MMS_strict 2476 }; 2477 2478 /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns 2479 /// true, or false, accordingly. 2480 bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, 2481 const ObjCMethodDecl *PrevMethod, 2482 MethodMatchStrategy strategy = MMS_strict); 2483 2484 /// MatchAllMethodDeclarations - Check methods declaraed in interface or 2485 /// or protocol against those declared in their implementations. 2486 void MatchAllMethodDeclarations(const SelectorSet &InsMap, 2487 const SelectorSet &ClsMap, 2488 SelectorSet &InsMapSeen, 2489 SelectorSet &ClsMapSeen, 2490 ObjCImplDecl* IMPDecl, 2491 ObjCContainerDecl* IDecl, 2492 bool &IncompleteImpl, 2493 bool ImmediateClass, 2494 bool WarnCategoryMethodImpl=false); 2495 2496 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2497 /// category matches with those implemented in its primary class and 2498 /// warns each time an exact match is found. 2499 void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); 2500 2501 /// \brief Add the given method to the list of globally-known methods. 2502 void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); 2503 2504private: 2505 /// AddMethodToGlobalPool - Add an instance or factory method to the global 2506 /// pool. See descriptoin of AddInstanceMethodToGlobalPool. 2507 void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); 2508 2509 /// LookupMethodInGlobalPool - Returns the instance or factory method and 2510 /// optionally warns if there are multiple signatures. 2511 ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, 2512 bool receiverIdOrClass, 2513 bool warn, bool instance); 2514 2515public: 2516 /// AddInstanceMethodToGlobalPool - All instance methods in a translation 2517 /// unit are added to a global pool. This allows us to efficiently associate 2518 /// a selector with a method declaraation for purposes of typechecking 2519 /// messages sent to "id" (where the class of the object is unknown). 2520 void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2521 AddMethodToGlobalPool(Method, impl, /*instance*/true); 2522 } 2523 2524 /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. 2525 void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { 2526 AddMethodToGlobalPool(Method, impl, /*instance*/false); 2527 } 2528 2529 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 2530 /// pool. 2531 void AddAnyMethodToGlobalPool(Decl *D); 2532 2533 /// LookupInstanceMethodInGlobalPool - Returns the method and warns if 2534 /// there are multiple signatures. 2535 ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, 2536 bool receiverIdOrClass=false, 2537 bool warn=true) { 2538 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2539 warn, /*instance*/true); 2540 } 2541 2542 /// LookupFactoryMethodInGlobalPool - Returns the method and warns if 2543 /// there are multiple signatures. 2544 ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, 2545 bool receiverIdOrClass=false, 2546 bool warn=true) { 2547 return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, 2548 warn, /*instance*/false); 2549 } 2550 2551 /// LookupImplementedMethodInGlobalPool - Returns the method which has an 2552 /// implementation. 2553 ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); 2554 2555 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 2556 /// initialization. 2557 void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 2558 SmallVectorImpl<ObjCIvarDecl*> &Ivars); 2559 2560 //===--------------------------------------------------------------------===// 2561 // Statement Parsing Callbacks: SemaStmt.cpp. 2562public: 2563 class FullExprArg { 2564 public: 2565 FullExprArg(Sema &actions) : E(0) { } 2566 2567 // FIXME: The const_cast here is ugly. RValue references would make this 2568 // much nicer (or we could duplicate a bunch of the move semantics 2569 // emulation code from Ownership.h). 2570 FullExprArg(const FullExprArg& Other) : E(Other.E) {} 2571 2572 ExprResult release() { 2573 return E; 2574 } 2575 2576 Expr *get() const { return E; } 2577 2578 Expr *operator->() { 2579 return E; 2580 } 2581 2582 private: 2583 // FIXME: No need to make the entire Sema class a friend when it's just 2584 // Sema::MakeFullExpr that needs access to the constructor below. 2585 friend class Sema; 2586 2587 explicit FullExprArg(Expr *expr) : E(expr) {} 2588 2589 Expr *E; 2590 }; 2591 2592 FullExprArg MakeFullExpr(Expr *Arg) { 2593 return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); 2594 } 2595 FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { 2596 return FullExprArg(ActOnFinishFullExpr(Arg, CC).release()); 2597 } 2598 FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { 2599 ExprResult FE = 2600 ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), 2601 /*DiscardedValue*/ true); 2602 return FullExprArg(FE.release()); 2603 } 2604 2605 StmtResult ActOnExprStmt(ExprResult Arg); 2606 2607 StmtResult ActOnNullStmt(SourceLocation SemiLoc, 2608 bool HasLeadingEmptyMacro = false); 2609 2610 void ActOnStartOfCompoundStmt(); 2611 void ActOnFinishOfCompoundStmt(); 2612 StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, 2613 MultiStmtArg Elts, 2614 bool isStmtExpr); 2615 2616 /// \brief A RAII object to enter scope of a compound statement. 2617 class CompoundScopeRAII { 2618 public: 2619 CompoundScopeRAII(Sema &S): S(S) { 2620 S.ActOnStartOfCompoundStmt(); 2621 } 2622 2623 ~CompoundScopeRAII() { 2624 S.ActOnFinishOfCompoundStmt(); 2625 } 2626 2627 private: 2628 Sema &S; 2629 }; 2630 2631 StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, 2632 SourceLocation StartLoc, 2633 SourceLocation EndLoc); 2634 void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); 2635 StmtResult ActOnForEachLValueExpr(Expr *E); 2636 StmtResult ActOnCaseStmt(SourceLocation CaseLoc, Expr *LHSVal, 2637 SourceLocation DotDotDotLoc, Expr *RHSVal, 2638 SourceLocation ColonLoc); 2639 void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); 2640 2641 StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, 2642 SourceLocation ColonLoc, 2643 Stmt *SubStmt, Scope *CurScope); 2644 StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, 2645 SourceLocation ColonLoc, Stmt *SubStmt); 2646 2647 StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, 2648 ArrayRef<const Attr*> Attrs, 2649 Stmt *SubStmt); 2650 2651 StmtResult ActOnIfStmt(SourceLocation IfLoc, 2652 FullExprArg CondVal, Decl *CondVar, 2653 Stmt *ThenVal, 2654 SourceLocation ElseLoc, Stmt *ElseVal); 2655 StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, 2656 Expr *Cond, 2657 Decl *CondVar); 2658 StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 2659 Stmt *Switch, Stmt *Body); 2660 StmtResult ActOnWhileStmt(SourceLocation WhileLoc, 2661 FullExprArg Cond, 2662 Decl *CondVar, Stmt *Body); 2663 StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, 2664 SourceLocation WhileLoc, 2665 SourceLocation CondLParen, Expr *Cond, 2666 SourceLocation CondRParen); 2667 2668 StmtResult ActOnForStmt(SourceLocation ForLoc, 2669 SourceLocation LParenLoc, 2670 Stmt *First, FullExprArg Second, 2671 Decl *SecondVar, 2672 FullExprArg Third, 2673 SourceLocation RParenLoc, 2674 Stmt *Body); 2675 ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, 2676 Expr *collection); 2677 StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, 2678 Stmt *First, Expr *collection, 2679 SourceLocation RParenLoc); 2680 StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); 2681 2682 enum BuildForRangeKind { 2683 /// Initial building of a for-range statement. 2684 BFRK_Build, 2685 /// Instantiation or recovery rebuild of a for-range statement. Don't 2686 /// attempt any typo-correction. 2687 BFRK_Rebuild, 2688 /// Determining whether a for-range statement could be built. Avoid any 2689 /// unnecessary or irreversible actions. 2690 BFRK_Check 2691 }; 2692 2693 StmtResult ActOnCXXForRangeStmt(SourceLocation ForLoc, Stmt *LoopVar, 2694 SourceLocation ColonLoc, Expr *Collection, 2695 SourceLocation RParenLoc, 2696 BuildForRangeKind Kind); 2697 StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, 2698 SourceLocation ColonLoc, 2699 Stmt *RangeDecl, Stmt *BeginEndDecl, 2700 Expr *Cond, Expr *Inc, 2701 Stmt *LoopVarDecl, 2702 SourceLocation RParenLoc, 2703 BuildForRangeKind Kind); 2704 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); 2705 2706 StmtResult ActOnGotoStmt(SourceLocation GotoLoc, 2707 SourceLocation LabelLoc, 2708 LabelDecl *TheDecl); 2709 StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, 2710 SourceLocation StarLoc, 2711 Expr *DestExp); 2712 StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); 2713 StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); 2714 2715 const VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, 2716 bool AllowFunctionParameters); 2717 2718 StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2719 StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); 2720 2721 StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, 2722 bool IsVolatile, unsigned NumOutputs, 2723 unsigned NumInputs, IdentifierInfo **Names, 2724 MultiExprArg Constraints, MultiExprArg Exprs, 2725 Expr *AsmString, MultiExprArg Clobbers, 2726 SourceLocation RParenLoc); 2727 2728 NamedDecl *LookupInlineAsmIdentifier(StringRef Name, SourceLocation Loc, 2729 unsigned &Length, unsigned &Size, 2730 unsigned &Type, bool &IsVarDecl); 2731 bool LookupInlineAsmField(StringRef Base, StringRef Member, 2732 unsigned &Offset, SourceLocation AsmLoc); 2733 StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, 2734 ArrayRef<Token> AsmToks, SourceLocation EndLoc); 2735 2736 VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, 2737 SourceLocation StartLoc, 2738 SourceLocation IdLoc, IdentifierInfo *Id, 2739 bool Invalid = false); 2740 2741 Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); 2742 2743 StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, 2744 Decl *Parm, Stmt *Body); 2745 2746 StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); 2747 2748 StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, 2749 MultiStmtArg Catch, Stmt *Finally); 2750 2751 StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); 2752 StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, 2753 Scope *CurScope); 2754 ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, 2755 Expr *operand); 2756 StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, 2757 Expr *SynchExpr, 2758 Stmt *SynchBody); 2759 2760 StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); 2761 2762 VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, 2763 SourceLocation StartLoc, 2764 SourceLocation IdLoc, 2765 IdentifierInfo *Id); 2766 2767 Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); 2768 2769 StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, 2770 Decl *ExDecl, Stmt *HandlerBlock); 2771 StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, 2772 MultiStmtArg Handlers); 2773 2774 StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? 2775 SourceLocation TryLoc, 2776 Stmt *TryBlock, 2777 Stmt *Handler); 2778 2779 StmtResult ActOnSEHExceptBlock(SourceLocation Loc, 2780 Expr *FilterExpr, 2781 Stmt *Block); 2782 2783 StmtResult ActOnSEHFinallyBlock(SourceLocation Loc, 2784 Stmt *Block); 2785 2786 void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); 2787 2788 bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; 2789 2790 /// \brief If it's a file scoped decl that must warn if not used, keep track 2791 /// of it. 2792 void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); 2793 2794 /// DiagnoseUnusedExprResult - If the statement passed in is an expression 2795 /// whose result is unused, warn. 2796 void DiagnoseUnusedExprResult(const Stmt *S); 2797 void DiagnoseUnusedDecl(const NamedDecl *ND); 2798 2799 /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null 2800 /// statement as a \p Body, and it is located on the same line. 2801 /// 2802 /// This helps prevent bugs due to typos, such as: 2803 /// if (condition); 2804 /// do_stuff(); 2805 void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 2806 const Stmt *Body, 2807 unsigned DiagID); 2808 2809 /// Warn if a for/while loop statement \p S, which is followed by 2810 /// \p PossibleBody, has a suspicious null statement as a body. 2811 void DiagnoseEmptyLoopBody(const Stmt *S, 2812 const Stmt *PossibleBody); 2813 2814 ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { 2815 return DelayedDiagnostics.push(pool); 2816 } 2817 void PopParsingDeclaration(ParsingDeclState state, Decl *decl); 2818 2819 typedef ProcessingContextState ParsingClassState; 2820 ParsingClassState PushParsingClass() { 2821 return DelayedDiagnostics.pushUndelayed(); 2822 } 2823 void PopParsingClass(ParsingClassState state) { 2824 DelayedDiagnostics.popUndelayed(state); 2825 } 2826 2827 void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); 2828 2829 void EmitDeprecationWarning(NamedDecl *D, StringRef Message, 2830 SourceLocation Loc, 2831 const ObjCInterfaceDecl *UnknownObjCClass, 2832 const ObjCPropertyDecl *ObjCProperty); 2833 2834 void HandleDelayedDeprecationCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 2835 2836 bool makeUnavailableInSystemHeader(SourceLocation loc, 2837 StringRef message); 2838 2839 //===--------------------------------------------------------------------===// 2840 // Expression Parsing Callbacks: SemaExpr.cpp. 2841 2842 bool CanUseDecl(NamedDecl *D); 2843 bool DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc, 2844 const ObjCInterfaceDecl *UnknownObjCClass=0); 2845 void NoteDeletedFunction(FunctionDecl *FD); 2846 std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); 2847 bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, 2848 ObjCMethodDecl *Getter, 2849 SourceLocation Loc); 2850 void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, 2851 Expr **Args, unsigned NumArgs); 2852 2853 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 2854 Decl *LambdaContextDecl = 0, 2855 bool IsDecltype = false); 2856 enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; 2857 void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, 2858 ReuseLambdaContextDecl_t, 2859 bool IsDecltype = false); 2860 void PopExpressionEvaluationContext(); 2861 2862 void DiscardCleanupsInEvaluationContext(); 2863 2864 ExprResult TransformToPotentiallyEvaluated(Expr *E); 2865 ExprResult HandleExprEvaluationContextForTypeof(Expr *E); 2866 2867 ExprResult ActOnConstantExpression(ExprResult Res); 2868 2869 // Functions for marking a declaration referenced. These functions also 2870 // contain the relevant logic for marking if a reference to a function or 2871 // variable is an odr-use (in the C++11 sense). There are separate variants 2872 // for expressions referring to a decl; these exist because odr-use marking 2873 // needs to be delayed for some constant variables when we build one of the 2874 // named expressions. 2875 void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse); 2876 void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func); 2877 void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); 2878 void MarkDeclRefReferenced(DeclRefExpr *E); 2879 void MarkMemberReferenced(MemberExpr *E); 2880 2881 void UpdateMarkingForLValueToRValue(Expr *E); 2882 void CleanupVarDeclMarking(); 2883 2884 enum TryCaptureKind { 2885 TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef 2886 }; 2887 2888 /// \brief Try to capture the given variable. 2889 /// 2890 /// \param Var The variable to capture. 2891 /// 2892 /// \param Loc The location at which the capture occurs. 2893 /// 2894 /// \param Kind The kind of capture, which may be implicit (for either a 2895 /// block or a lambda), or explicit by-value or by-reference (for a lambda). 2896 /// 2897 /// \param EllipsisLoc The location of the ellipsis, if one is provided in 2898 /// an explicit lambda capture. 2899 /// 2900 /// \param BuildAndDiagnose Whether we are actually supposed to add the 2901 /// captures or diagnose errors. If false, this routine merely check whether 2902 /// the capture can occur without performing the capture itself or complaining 2903 /// if the variable cannot be captured. 2904 /// 2905 /// \param CaptureType Will be set to the type of the field used to capture 2906 /// this variable in the innermost block or lambda. Only valid when the 2907 /// variable can be captured. 2908 /// 2909 /// \param DeclRefType Will be set to the type of a reference to the capture 2910 /// from within the current scope. Only valid when the variable can be 2911 /// captured. 2912 /// 2913 /// \returns true if an error occurred (i.e., the variable cannot be 2914 /// captured) and false if the capture succeeded. 2915 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, 2916 SourceLocation EllipsisLoc, bool BuildAndDiagnose, 2917 QualType &CaptureType, 2918 QualType &DeclRefType); 2919 2920 /// \brief Try to capture the given variable. 2921 bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 2922 TryCaptureKind Kind = TryCapture_Implicit, 2923 SourceLocation EllipsisLoc = SourceLocation()); 2924 2925 /// \brief Given a variable, determine the type that a reference to that 2926 /// variable will have in the given scope. 2927 QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); 2928 2929 void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); 2930 void MarkDeclarationsReferencedInExpr(Expr *E, 2931 bool SkipLocalVariables = false); 2932 2933 /// \brief Try to recover by turning the given expression into a 2934 /// call. Returns true if recovery was attempted or an error was 2935 /// emitted; this may also leave the ExprResult invalid. 2936 bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, 2937 bool ForceComplain = false, 2938 bool (*IsPlausibleResult)(QualType) = 0); 2939 2940 /// \brief Figure out if an expression could be turned into a call. 2941 bool isExprCallable(const Expr &E, QualType &ZeroArgCallReturnTy, 2942 UnresolvedSetImpl &NonTemplateOverloads); 2943 2944 /// \brief Conditionally issue a diagnostic based on the current 2945 /// evaluation context. 2946 /// 2947 /// \param Statement If Statement is non-null, delay reporting the 2948 /// diagnostic until the function body is parsed, and then do a basic 2949 /// reachability analysis to determine if the statement is reachable. 2950 /// If it is unreachable, the diagnostic will not be emitted. 2951 bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, 2952 const PartialDiagnostic &PD); 2953 2954 // Primary Expressions. 2955 SourceRange getExprRange(Expr *E) const; 2956 2957 ExprResult ActOnIdExpression(Scope *S, CXXScopeSpec &SS, 2958 SourceLocation TemplateKWLoc, 2959 UnqualifiedId &Id, 2960 bool HasTrailingLParen, bool IsAddressOfOperand, 2961 CorrectionCandidateCallback *CCC = 0); 2962 2963 void DecomposeUnqualifiedId(const UnqualifiedId &Id, 2964 TemplateArgumentListInfo &Buffer, 2965 DeclarationNameInfo &NameInfo, 2966 const TemplateArgumentListInfo *&TemplateArgs); 2967 2968 bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, 2969 CorrectionCandidateCallback &CCC, 2970 TemplateArgumentListInfo *ExplicitTemplateArgs = 0, 2971 ArrayRef<Expr *> Args = ArrayRef<Expr *>()); 2972 2973 ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, 2974 IdentifierInfo *II, 2975 bool AllowBuiltinCreation=false); 2976 2977 ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, 2978 SourceLocation TemplateKWLoc, 2979 const DeclarationNameInfo &NameInfo, 2980 bool isAddressOfOperand, 2981 const TemplateArgumentListInfo *TemplateArgs); 2982 2983 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2984 ExprValueKind VK, 2985 SourceLocation Loc, 2986 const CXXScopeSpec *SS = 0); 2987 ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, 2988 ExprValueKind VK, 2989 const DeclarationNameInfo &NameInfo, 2990 const CXXScopeSpec *SS = 0); 2991 ExprResult 2992 BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 2993 SourceLocation nameLoc, 2994 IndirectFieldDecl *indirectField, 2995 Expr *baseObjectExpr = 0, 2996 SourceLocation opLoc = SourceLocation()); 2997 ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 2998 SourceLocation TemplateKWLoc, 2999 LookupResult &R, 3000 const TemplateArgumentListInfo *TemplateArgs); 3001 ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, 3002 SourceLocation TemplateKWLoc, 3003 LookupResult &R, 3004 const TemplateArgumentListInfo *TemplateArgs, 3005 bool IsDefiniteInstance); 3006 bool UseArgumentDependentLookup(const CXXScopeSpec &SS, 3007 const LookupResult &R, 3008 bool HasTrailingLParen); 3009 3010 ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, 3011 const DeclarationNameInfo &NameInfo, 3012 bool IsAddressOfOperand); 3013 ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, 3014 SourceLocation TemplateKWLoc, 3015 const DeclarationNameInfo &NameInfo, 3016 const TemplateArgumentListInfo *TemplateArgs); 3017 3018 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3019 LookupResult &R, 3020 bool NeedsADL); 3021 ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, 3022 const DeclarationNameInfo &NameInfo, 3023 NamedDecl *D); 3024 3025 ExprResult BuildLiteralOperatorCall(LookupResult &R, 3026 DeclarationNameInfo &SuffixInfo, 3027 ArrayRef<Expr*> Args, 3028 SourceLocation LitEndLoc, 3029 TemplateArgumentListInfo *ExplicitTemplateArgs = 0); 3030 3031 ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); 3032 ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); 3033 ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = 0); 3034 ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = 0); 3035 ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); 3036 ExprResult ActOnParenListExpr(SourceLocation L, 3037 SourceLocation R, 3038 MultiExprArg Val); 3039 3040 /// ActOnStringLiteral - The specified tokens were lexed as pasted string 3041 /// fragments (e.g. "foo" "bar" L"baz"). 3042 ExprResult ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks, 3043 Scope *UDLScope = 0); 3044 3045 ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, 3046 SourceLocation DefaultLoc, 3047 SourceLocation RParenLoc, 3048 Expr *ControllingExpr, 3049 MultiTypeArg ArgTypes, 3050 MultiExprArg ArgExprs); 3051 ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, 3052 SourceLocation DefaultLoc, 3053 SourceLocation RParenLoc, 3054 Expr *ControllingExpr, 3055 TypeSourceInfo **Types, 3056 Expr **Exprs, 3057 unsigned NumAssocs); 3058 3059 // Binary/Unary Operators. 'Tok' is the token for the operator. 3060 ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 3061 Expr *InputExpr); 3062 ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, 3063 UnaryOperatorKind Opc, Expr *Input); 3064 ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, 3065 tok::TokenKind Op, Expr *Input); 3066 3067 ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, 3068 SourceLocation OpLoc, 3069 UnaryExprOrTypeTrait ExprKind, 3070 SourceRange R); 3071 ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, 3072 UnaryExprOrTypeTrait ExprKind); 3073 ExprResult 3074 ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, 3075 UnaryExprOrTypeTrait ExprKind, 3076 bool IsType, void *TyOrEx, 3077 const SourceRange &ArgRange); 3078 3079 ExprResult CheckPlaceholderExpr(Expr *E); 3080 bool CheckVecStepExpr(Expr *E); 3081 3082 bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); 3083 bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, 3084 SourceRange ExprRange, 3085 UnaryExprOrTypeTrait ExprKind); 3086 ExprResult ActOnSizeofParameterPackExpr(Scope *S, 3087 SourceLocation OpLoc, 3088 IdentifierInfo &Name, 3089 SourceLocation NameLoc, 3090 SourceLocation RParenLoc); 3091 ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, 3092 tok::TokenKind Kind, Expr *Input); 3093 3094 ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, 3095 Expr *Idx, SourceLocation RLoc); 3096 ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, 3097 Expr *Idx, SourceLocation RLoc); 3098 3099 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 3100 SourceLocation OpLoc, bool IsArrow, 3101 CXXScopeSpec &SS, 3102 SourceLocation TemplateKWLoc, 3103 NamedDecl *FirstQualifierInScope, 3104 const DeclarationNameInfo &NameInfo, 3105 const TemplateArgumentListInfo *TemplateArgs); 3106 3107 // This struct is for use by ActOnMemberAccess to allow 3108 // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after 3109 // changing the access operator from a '.' to a '->' (to see if that is the 3110 // change needed to fix an error about an unknown member, e.g. when the class 3111 // defines a custom operator->). 3112 struct ActOnMemberAccessExtraArgs { 3113 Scope *S; 3114 UnqualifiedId &Id; 3115 Decl *ObjCImpDecl; 3116 bool HasTrailingLParen; 3117 }; 3118 3119 ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 3120 SourceLocation OpLoc, bool IsArrow, 3121 const CXXScopeSpec &SS, 3122 SourceLocation TemplateKWLoc, 3123 NamedDecl *FirstQualifierInScope, 3124 LookupResult &R, 3125 const TemplateArgumentListInfo *TemplateArgs, 3126 bool SuppressQualifierCheck = false, 3127 ActOnMemberAccessExtraArgs *ExtraArgs = 0); 3128 3129 ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); 3130 ExprResult LookupMemberExpr(LookupResult &R, ExprResult &Base, 3131 bool &IsArrow, SourceLocation OpLoc, 3132 CXXScopeSpec &SS, 3133 Decl *ObjCImpDecl, 3134 bool HasTemplateArgs); 3135 3136 bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, 3137 const CXXScopeSpec &SS, 3138 const LookupResult &R); 3139 3140 ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, 3141 bool IsArrow, SourceLocation OpLoc, 3142 const CXXScopeSpec &SS, 3143 SourceLocation TemplateKWLoc, 3144 NamedDecl *FirstQualifierInScope, 3145 const DeclarationNameInfo &NameInfo, 3146 const TemplateArgumentListInfo *TemplateArgs); 3147 3148 ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, 3149 SourceLocation OpLoc, 3150 tok::TokenKind OpKind, 3151 CXXScopeSpec &SS, 3152 SourceLocation TemplateKWLoc, 3153 UnqualifiedId &Member, 3154 Decl *ObjCImpDecl, 3155 bool HasTrailingLParen); 3156 3157 void ActOnDefaultCtorInitializers(Decl *CDtorDecl); 3158 bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, 3159 FunctionDecl *FDecl, 3160 const FunctionProtoType *Proto, 3161 Expr **Args, unsigned NumArgs, 3162 SourceLocation RParenLoc, 3163 bool ExecConfig = false); 3164 void CheckStaticArrayArgument(SourceLocation CallLoc, 3165 ParmVarDecl *Param, 3166 const Expr *ArgExpr); 3167 3168 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. 3169 /// This provides the location of the left/right parens and a list of comma 3170 /// locations. 3171 ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, 3172 MultiExprArg ArgExprs, SourceLocation RParenLoc, 3173 Expr *ExecConfig = 0, bool IsExecConfig = false); 3174 ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, 3175 SourceLocation LParenLoc, 3176 Expr **Args, unsigned NumArgs, 3177 SourceLocation RParenLoc, 3178 Expr *Config = 0, 3179 bool IsExecConfig = false); 3180 3181 ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, 3182 MultiExprArg ExecConfig, 3183 SourceLocation GGGLoc); 3184 3185 ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, 3186 Declarator &D, ParsedType &Ty, 3187 SourceLocation RParenLoc, Expr *CastExpr); 3188 ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, 3189 TypeSourceInfo *Ty, 3190 SourceLocation RParenLoc, 3191 Expr *Op); 3192 CastKind PrepareScalarCast(ExprResult &src, QualType destType); 3193 3194 /// \brief Build an altivec or OpenCL literal. 3195 ExprResult BuildVectorLiteral(SourceLocation LParenLoc, 3196 SourceLocation RParenLoc, Expr *E, 3197 TypeSourceInfo *TInfo); 3198 3199 ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); 3200 3201 ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, 3202 ParsedType Ty, 3203 SourceLocation RParenLoc, 3204 Expr *InitExpr); 3205 3206 ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, 3207 TypeSourceInfo *TInfo, 3208 SourceLocation RParenLoc, 3209 Expr *LiteralExpr); 3210 3211 ExprResult ActOnInitList(SourceLocation LBraceLoc, 3212 MultiExprArg InitArgList, 3213 SourceLocation RBraceLoc); 3214 3215 ExprResult ActOnDesignatedInitializer(Designation &Desig, 3216 SourceLocation Loc, 3217 bool GNUSyntax, 3218 ExprResult Init); 3219 3220 ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, 3221 tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); 3222 ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, 3223 BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); 3224 ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, 3225 Expr *LHSExpr, Expr *RHSExpr); 3226 3227 /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null 3228 /// in the case of a the GNU conditional expr extension. 3229 ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, 3230 SourceLocation ColonLoc, 3231 Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); 3232 3233 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". 3234 ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, 3235 LabelDecl *TheDecl); 3236 3237 void ActOnStartStmtExpr(); 3238 ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, 3239 SourceLocation RPLoc); // "({..})" 3240 void ActOnStmtExprError(); 3241 3242 // __builtin_offsetof(type, identifier(.identifier|[expr])*) 3243 struct OffsetOfComponent { 3244 SourceLocation LocStart, LocEnd; 3245 bool isBrackets; // true if [expr], false if .ident 3246 union { 3247 IdentifierInfo *IdentInfo; 3248 Expr *E; 3249 } U; 3250 }; 3251 3252 /// __builtin_offsetof(type, a.b[123][456].c) 3253 ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, 3254 TypeSourceInfo *TInfo, 3255 OffsetOfComponent *CompPtr, 3256 unsigned NumComponents, 3257 SourceLocation RParenLoc); 3258 ExprResult ActOnBuiltinOffsetOf(Scope *S, 3259 SourceLocation BuiltinLoc, 3260 SourceLocation TypeLoc, 3261 ParsedType ParsedArgTy, 3262 OffsetOfComponent *CompPtr, 3263 unsigned NumComponents, 3264 SourceLocation RParenLoc); 3265 3266 // __builtin_choose_expr(constExpr, expr1, expr2) 3267 ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, 3268 Expr *CondExpr, Expr *LHSExpr, 3269 Expr *RHSExpr, SourceLocation RPLoc); 3270 3271 // __builtin_va_arg(expr, type) 3272 ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, 3273 SourceLocation RPLoc); 3274 ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, 3275 TypeSourceInfo *TInfo, SourceLocation RPLoc); 3276 3277 // __null 3278 ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); 3279 3280 bool CheckCaseExpression(Expr *E); 3281 3282 /// \brief Describes the result of an "if-exists" condition check. 3283 enum IfExistsResult { 3284 /// \brief The symbol exists. 3285 IER_Exists, 3286 3287 /// \brief The symbol does not exist. 3288 IER_DoesNotExist, 3289 3290 /// \brief The name is a dependent name, so the results will differ 3291 /// from one instantiation to the next. 3292 IER_Dependent, 3293 3294 /// \brief An error occurred. 3295 IER_Error 3296 }; 3297 3298 IfExistsResult 3299 CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, 3300 const DeclarationNameInfo &TargetNameInfo); 3301 3302 IfExistsResult 3303 CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, 3304 bool IsIfExists, CXXScopeSpec &SS, 3305 UnqualifiedId &Name); 3306 3307 StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, 3308 bool IsIfExists, 3309 NestedNameSpecifierLoc QualifierLoc, 3310 DeclarationNameInfo NameInfo, 3311 Stmt *Nested); 3312 StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, 3313 bool IsIfExists, 3314 CXXScopeSpec &SS, UnqualifiedId &Name, 3315 Stmt *Nested); 3316 3317 //===------------------------- "Block" Extension ------------------------===// 3318 3319 /// ActOnBlockStart - This callback is invoked when a block literal is 3320 /// started. 3321 void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); 3322 3323 /// ActOnBlockArguments - This callback allows processing of block arguments. 3324 /// If there are no arguments, this is still invoked. 3325 void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, 3326 Scope *CurScope); 3327 3328 /// ActOnBlockError - If there is an error parsing a block, this callback 3329 /// is invoked to pop the information about the block from the action impl. 3330 void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); 3331 3332 /// ActOnBlockStmtExpr - This is called when the body of a block statement 3333 /// literal was successfully completed. ^(int x){...} 3334 ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, 3335 Scope *CurScope); 3336 3337 //===---------------------------- OpenCL Features -----------------------===// 3338 3339 /// __builtin_astype(...) 3340 ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, 3341 SourceLocation BuiltinLoc, 3342 SourceLocation RParenLoc); 3343 3344 //===---------------------------- C++ Features --------------------------===// 3345 3346 // Act on C++ namespaces 3347 Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, 3348 SourceLocation NamespaceLoc, 3349 SourceLocation IdentLoc, 3350 IdentifierInfo *Ident, 3351 SourceLocation LBrace, 3352 AttributeList *AttrList); 3353 void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); 3354 3355 NamespaceDecl *getStdNamespace() const; 3356 NamespaceDecl *getOrCreateStdNamespace(); 3357 3358 CXXRecordDecl *getStdBadAlloc() const; 3359 3360 /// \brief Tests whether Ty is an instance of std::initializer_list and, if 3361 /// it is and Element is not NULL, assigns the element type to Element. 3362 bool isStdInitializerList(QualType Ty, QualType *Element); 3363 3364 /// \brief Looks for the std::initializer_list template and instantiates it 3365 /// with Element, or emits an error if it's not found. 3366 /// 3367 /// \returns The instantiated template, or null on error. 3368 QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); 3369 3370 /// \brief Determine whether Ctor is an initializer-list constructor, as 3371 /// defined in [dcl.init.list]p2. 3372 bool isInitListConstructor(const CXXConstructorDecl *Ctor); 3373 3374 Decl *ActOnUsingDirective(Scope *CurScope, 3375 SourceLocation UsingLoc, 3376 SourceLocation NamespcLoc, 3377 CXXScopeSpec &SS, 3378 SourceLocation IdentLoc, 3379 IdentifierInfo *NamespcName, 3380 AttributeList *AttrList); 3381 3382 void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); 3383 3384 Decl *ActOnNamespaceAliasDef(Scope *CurScope, 3385 SourceLocation NamespaceLoc, 3386 SourceLocation AliasLoc, 3387 IdentifierInfo *Alias, 3388 CXXScopeSpec &SS, 3389 SourceLocation IdentLoc, 3390 IdentifierInfo *Ident); 3391 3392 void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); 3393 bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, 3394 const LookupResult &PreviousDecls); 3395 UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, 3396 NamedDecl *Target); 3397 3398 bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, 3399 bool isTypeName, 3400 const CXXScopeSpec &SS, 3401 SourceLocation NameLoc, 3402 const LookupResult &Previous); 3403 bool CheckUsingDeclQualifier(SourceLocation UsingLoc, 3404 const CXXScopeSpec &SS, 3405 SourceLocation NameLoc); 3406 3407 NamedDecl *BuildUsingDeclaration(Scope *S, AccessSpecifier AS, 3408 SourceLocation UsingLoc, 3409 CXXScopeSpec &SS, 3410 const DeclarationNameInfo &NameInfo, 3411 AttributeList *AttrList, 3412 bool IsInstantiation, 3413 bool IsTypeName, 3414 SourceLocation TypenameLoc); 3415 3416 bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); 3417 3418 Decl *ActOnUsingDeclaration(Scope *CurScope, 3419 AccessSpecifier AS, 3420 bool HasUsingKeyword, 3421 SourceLocation UsingLoc, 3422 CXXScopeSpec &SS, 3423 UnqualifiedId &Name, 3424 AttributeList *AttrList, 3425 bool IsTypeName, 3426 SourceLocation TypenameLoc); 3427 Decl *ActOnAliasDeclaration(Scope *CurScope, 3428 AccessSpecifier AS, 3429 MultiTemplateParamsArg TemplateParams, 3430 SourceLocation UsingLoc, 3431 UnqualifiedId &Name, 3432 TypeResult Type); 3433 3434 /// BuildCXXConstructExpr - Creates a complete call to a constructor, 3435 /// including handling of its default argument expressions. 3436 /// 3437 /// \param ConstructKind - a CXXConstructExpr::ConstructionKind 3438 ExprResult 3439 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3440 CXXConstructorDecl *Constructor, MultiExprArg Exprs, 3441 bool HadMultipleCandidates, bool IsListInitialization, 3442 bool RequiresZeroInit, unsigned ConstructKind, 3443 SourceRange ParenRange); 3444 3445 // FIXME: Can re remove this and have the above BuildCXXConstructExpr check if 3446 // the constructor can be elidable? 3447 ExprResult 3448 BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, 3449 CXXConstructorDecl *Constructor, bool Elidable, 3450 MultiExprArg Exprs, bool HadMultipleCandidates, 3451 bool IsListInitialization, bool RequiresZeroInit, 3452 unsigned ConstructKind, SourceRange ParenRange); 3453 3454 /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating 3455 /// the default expr if needed. 3456 ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, 3457 FunctionDecl *FD, 3458 ParmVarDecl *Param); 3459 3460 /// FinalizeVarWithDestructor - Prepare for calling destructor on the 3461 /// constructed variable. 3462 void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); 3463 3464 /// \brief Helper class that collects exception specifications for 3465 /// implicitly-declared special member functions. 3466 class ImplicitExceptionSpecification { 3467 // Pointer to allow copying 3468 Sema *Self; 3469 // We order exception specifications thus: 3470 // noexcept is the most restrictive, but is only used in C++11. 3471 // throw() comes next. 3472 // Then a throw(collected exceptions) 3473 // Finally no specification, which is expressed as noexcept(false). 3474 // throw(...) is used instead if any called function uses it. 3475 ExceptionSpecificationType ComputedEST; 3476 llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; 3477 SmallVector<QualType, 4> Exceptions; 3478 3479 void ClearExceptions() { 3480 ExceptionsSeen.clear(); 3481 Exceptions.clear(); 3482 } 3483 3484 public: 3485 explicit ImplicitExceptionSpecification(Sema &Self) 3486 : Self(&Self), ComputedEST(EST_BasicNoexcept) { 3487 if (!Self.getLangOpts().CPlusPlus11) 3488 ComputedEST = EST_DynamicNone; 3489 } 3490 3491 /// \brief Get the computed exception specification type. 3492 ExceptionSpecificationType getExceptionSpecType() const { 3493 assert(ComputedEST != EST_ComputedNoexcept && 3494 "noexcept(expr) should not be a possible result"); 3495 return ComputedEST; 3496 } 3497 3498 /// \brief The number of exceptions in the exception specification. 3499 unsigned size() const { return Exceptions.size(); } 3500 3501 /// \brief The set of exceptions in the exception specification. 3502 const QualType *data() const { return Exceptions.data(); } 3503 3504 /// \brief Integrate another called method into the collected data. 3505 void CalledDecl(SourceLocation CallLoc, CXXMethodDecl *Method); 3506 3507 /// \brief Integrate an invoked expression into the collected data. 3508 void CalledExpr(Expr *E); 3509 3510 /// \brief Overwrite an EPI's exception specification with this 3511 /// computed exception specification. 3512 void getEPI(FunctionProtoType::ExtProtoInfo &EPI) const { 3513 EPI.ExceptionSpecType = getExceptionSpecType(); 3514 if (EPI.ExceptionSpecType == EST_Dynamic) { 3515 EPI.NumExceptions = size(); 3516 EPI.Exceptions = data(); 3517 } else if (EPI.ExceptionSpecType == EST_None) { 3518 /// C++11 [except.spec]p14: 3519 /// The exception-specification is noexcept(false) if the set of 3520 /// potential exceptions of the special member function contains "any" 3521 EPI.ExceptionSpecType = EST_ComputedNoexcept; 3522 EPI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), 3523 tok::kw_false).take(); 3524 } 3525 } 3526 FunctionProtoType::ExtProtoInfo getEPI() const { 3527 FunctionProtoType::ExtProtoInfo EPI; 3528 getEPI(EPI); 3529 return EPI; 3530 } 3531 }; 3532 3533 /// \brief Determine what sort of exception specification a defaulted 3534 /// copy constructor of a class will have. 3535 ImplicitExceptionSpecification 3536 ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, 3537 CXXMethodDecl *MD); 3538 3539 /// \brief Determine what sort of exception specification a defaulted 3540 /// default constructor of a class will have, and whether the parameter 3541 /// will be const. 3542 ImplicitExceptionSpecification 3543 ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); 3544 3545 /// \brief Determine what sort of exception specification a defautled 3546 /// copy assignment operator of a class will have, and whether the 3547 /// parameter will be const. 3548 ImplicitExceptionSpecification 3549 ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); 3550 3551 /// \brief Determine what sort of exception specification a defaulted move 3552 /// constructor of a class will have. 3553 ImplicitExceptionSpecification 3554 ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); 3555 3556 /// \brief Determine what sort of exception specification a defaulted move 3557 /// assignment operator of a class will have. 3558 ImplicitExceptionSpecification 3559 ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); 3560 3561 /// \brief Determine what sort of exception specification a defaulted 3562 /// destructor of a class will have. 3563 ImplicitExceptionSpecification 3564 ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); 3565 3566 /// \brief Evaluate the implicit exception specification for a defaulted 3567 /// special member function. 3568 void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); 3569 3570 /// \brief Check the given exception-specification and update the 3571 /// extended prototype information with the results. 3572 void checkExceptionSpecification(ExceptionSpecificationType EST, 3573 ArrayRef<ParsedType> DynamicExceptions, 3574 ArrayRef<SourceRange> DynamicExceptionRanges, 3575 Expr *NoexceptExpr, 3576 SmallVectorImpl<QualType> &Exceptions, 3577 FunctionProtoType::ExtProtoInfo &EPI); 3578 3579 /// \brief Determine if a special member function should have a deleted 3580 /// definition when it is defaulted. 3581 bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, 3582 bool Diagnose = false); 3583 3584 /// \brief Declare the implicit default constructor for the given class. 3585 /// 3586 /// \param ClassDecl The class declaration into which the implicit 3587 /// default constructor will be added. 3588 /// 3589 /// \returns The implicitly-declared default constructor. 3590 CXXConstructorDecl *DeclareImplicitDefaultConstructor( 3591 CXXRecordDecl *ClassDecl); 3592 3593 /// DefineImplicitDefaultConstructor - Checks for feasibility of 3594 /// defining this constructor as the default constructor. 3595 void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, 3596 CXXConstructorDecl *Constructor); 3597 3598 /// \brief Declare the implicit destructor for the given class. 3599 /// 3600 /// \param ClassDecl The class declaration into which the implicit 3601 /// destructor will be added. 3602 /// 3603 /// \returns The implicitly-declared destructor. 3604 CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); 3605 3606 /// DefineImplicitDestructor - Checks for feasibility of 3607 /// defining this destructor as the default destructor. 3608 void DefineImplicitDestructor(SourceLocation CurrentLocation, 3609 CXXDestructorDecl *Destructor); 3610 3611 /// \brief Build an exception spec for destructors that don't have one. 3612 /// 3613 /// C++11 says that user-defined destructors with no exception spec get one 3614 /// that looks as if the destructor was implicitly declared. 3615 void AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl, 3616 CXXDestructorDecl *Destructor); 3617 3618 /// \brief Declare all inherited constructors for the given class. 3619 /// 3620 /// \param ClassDecl The class declaration into which the inherited 3621 /// constructors will be added. 3622 void DeclareInheritedConstructors(CXXRecordDecl *ClassDecl); 3623 3624 /// \brief Declare the implicit copy constructor for the given class. 3625 /// 3626 /// \param ClassDecl The class declaration into which the implicit 3627 /// copy constructor will be added. 3628 /// 3629 /// \returns The implicitly-declared copy constructor. 3630 CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); 3631 3632 /// DefineImplicitCopyConstructor - Checks for feasibility of 3633 /// defining this constructor as the copy constructor. 3634 void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, 3635 CXXConstructorDecl *Constructor); 3636 3637 /// \brief Declare the implicit move constructor for the given class. 3638 /// 3639 /// \param ClassDecl The Class declaration into which the implicit 3640 /// move constructor will be added. 3641 /// 3642 /// \returns The implicitly-declared move constructor, or NULL if it wasn't 3643 /// declared. 3644 CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); 3645 3646 /// DefineImplicitMoveConstructor - Checks for feasibility of 3647 /// defining this constructor as the move constructor. 3648 void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, 3649 CXXConstructorDecl *Constructor); 3650 3651 /// \brief Declare the implicit copy assignment operator for the given class. 3652 /// 3653 /// \param ClassDecl The class declaration into which the implicit 3654 /// copy assignment operator will be added. 3655 /// 3656 /// \returns The implicitly-declared copy assignment operator. 3657 CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); 3658 3659 /// \brief Defines an implicitly-declared copy assignment operator. 3660 void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, 3661 CXXMethodDecl *MethodDecl); 3662 3663 /// \brief Declare the implicit move assignment operator for the given class. 3664 /// 3665 /// \param ClassDecl The Class declaration into which the implicit 3666 /// move assignment operator will be added. 3667 /// 3668 /// \returns The implicitly-declared move assignment operator, or NULL if it 3669 /// wasn't declared. 3670 CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); 3671 3672 /// \brief Defines an implicitly-declared move assignment operator. 3673 void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, 3674 CXXMethodDecl *MethodDecl); 3675 3676 /// \brief Force the declaration of any implicitly-declared members of this 3677 /// class. 3678 void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); 3679 3680 /// \brief Determine whether the given function is an implicitly-deleted 3681 /// special member function. 3682 bool isImplicitlyDeleted(FunctionDecl *FD); 3683 3684 /// \brief Check whether 'this' shows up in the type of a static member 3685 /// function after the (naturally empty) cv-qualifier-seq would be. 3686 /// 3687 /// \returns true if an error occurred. 3688 bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); 3689 3690 /// \brief Whether this' shows up in the exception specification of a static 3691 /// member function. 3692 bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); 3693 3694 /// \brief Check whether 'this' shows up in the attributes of the given 3695 /// static member function. 3696 /// 3697 /// \returns true if an error occurred. 3698 bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); 3699 3700 /// MaybeBindToTemporary - If the passed in expression has a record type with 3701 /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise 3702 /// it simply returns the passed in expression. 3703 ExprResult MaybeBindToTemporary(Expr *E); 3704 3705 bool CompleteConstructorCall(CXXConstructorDecl *Constructor, 3706 MultiExprArg ArgsPtr, 3707 SourceLocation Loc, 3708 SmallVectorImpl<Expr*> &ConvertedArgs, 3709 bool AllowExplicit = false, 3710 bool IsListInitialization = false); 3711 3712 ParsedType getDestructorName(SourceLocation TildeLoc, 3713 IdentifierInfo &II, SourceLocation NameLoc, 3714 Scope *S, CXXScopeSpec &SS, 3715 ParsedType ObjectType, 3716 bool EnteringContext); 3717 3718 ParsedType getDestructorType(const DeclSpec& DS, ParsedType ObjectType); 3719 3720 // Checks that reinterpret casts don't have undefined behavior. 3721 void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, 3722 bool IsDereference, SourceRange Range); 3723 3724 /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. 3725 ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, 3726 tok::TokenKind Kind, 3727 SourceLocation LAngleBracketLoc, 3728 Declarator &D, 3729 SourceLocation RAngleBracketLoc, 3730 SourceLocation LParenLoc, 3731 Expr *E, 3732 SourceLocation RParenLoc); 3733 3734 ExprResult BuildCXXNamedCast(SourceLocation OpLoc, 3735 tok::TokenKind Kind, 3736 TypeSourceInfo *Ty, 3737 Expr *E, 3738 SourceRange AngleBrackets, 3739 SourceRange Parens); 3740 3741 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3742 SourceLocation TypeidLoc, 3743 TypeSourceInfo *Operand, 3744 SourceLocation RParenLoc); 3745 ExprResult BuildCXXTypeId(QualType TypeInfoType, 3746 SourceLocation TypeidLoc, 3747 Expr *Operand, 3748 SourceLocation RParenLoc); 3749 3750 /// ActOnCXXTypeid - Parse typeid( something ). 3751 ExprResult ActOnCXXTypeid(SourceLocation OpLoc, 3752 SourceLocation LParenLoc, bool isType, 3753 void *TyOrExpr, 3754 SourceLocation RParenLoc); 3755 3756 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3757 SourceLocation TypeidLoc, 3758 TypeSourceInfo *Operand, 3759 SourceLocation RParenLoc); 3760 ExprResult BuildCXXUuidof(QualType TypeInfoType, 3761 SourceLocation TypeidLoc, 3762 Expr *Operand, 3763 SourceLocation RParenLoc); 3764 3765 /// ActOnCXXUuidof - Parse __uuidof( something ). 3766 ExprResult ActOnCXXUuidof(SourceLocation OpLoc, 3767 SourceLocation LParenLoc, bool isType, 3768 void *TyOrExpr, 3769 SourceLocation RParenLoc); 3770 3771 3772 //// ActOnCXXThis - Parse 'this' pointer. 3773 ExprResult ActOnCXXThis(SourceLocation loc); 3774 3775 /// \brief Try to retrieve the type of the 'this' pointer. 3776 /// 3777 /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. 3778 QualType getCurrentThisType(); 3779 3780 /// \brief When non-NULL, the C++ 'this' expression is allowed despite the 3781 /// current context not being a non-static member function. In such cases, 3782 /// this provides the type used for 'this'. 3783 QualType CXXThisTypeOverride; 3784 3785 /// \brief RAII object used to temporarily allow the C++ 'this' expression 3786 /// to be used, with the given qualifiers on the current class type. 3787 class CXXThisScopeRAII { 3788 Sema &S; 3789 QualType OldCXXThisTypeOverride; 3790 bool Enabled; 3791 3792 public: 3793 /// \brief Introduce a new scope where 'this' may be allowed (when enabled), 3794 /// using the given declaration (which is either a class template or a 3795 /// class) along with the given qualifiers. 3796 /// along with the qualifiers placed on '*this'. 3797 CXXThisScopeRAII(Sema &S, Decl *ContextDecl, unsigned CXXThisTypeQuals, 3798 bool Enabled = true); 3799 3800 ~CXXThisScopeRAII(); 3801 }; 3802 3803 /// \brief Make sure the value of 'this' is actually available in the current 3804 /// context, if it is a potentially evaluated context. 3805 /// 3806 /// \param Loc The location at which the capture of 'this' occurs. 3807 /// 3808 /// \param Explicit Whether 'this' is explicitly captured in a lambda 3809 /// capture list. 3810 void CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false); 3811 3812 /// \brief Determine whether the given type is the type of *this that is used 3813 /// outside of the body of a member function for a type that is currently 3814 /// being defined. 3815 bool isThisOutsideMemberFunctionBody(QualType BaseType); 3816 3817 /// ActOnCXXBoolLiteral - Parse {true,false} literals. 3818 ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3819 3820 3821 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. 3822 ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); 3823 3824 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. 3825 ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); 3826 3827 //// ActOnCXXThrow - Parse throw expressions. 3828 ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); 3829 ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, 3830 bool IsThrownVarInScope); 3831 ExprResult CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E, 3832 bool IsThrownVarInScope); 3833 3834 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. 3835 /// Can be interpreted either as function-style casting ("int(x)") 3836 /// or class type construction ("ClassType(x,y,z)") 3837 /// or creation of a value-initialized type ("int()"). 3838 ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, 3839 SourceLocation LParenLoc, 3840 MultiExprArg Exprs, 3841 SourceLocation RParenLoc); 3842 3843 ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, 3844 SourceLocation LParenLoc, 3845 MultiExprArg Exprs, 3846 SourceLocation RParenLoc); 3847 3848 /// ActOnCXXNew - Parsed a C++ 'new' expression. 3849 ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, 3850 SourceLocation PlacementLParen, 3851 MultiExprArg PlacementArgs, 3852 SourceLocation PlacementRParen, 3853 SourceRange TypeIdParens, Declarator &D, 3854 Expr *Initializer); 3855 ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, 3856 SourceLocation PlacementLParen, 3857 MultiExprArg PlacementArgs, 3858 SourceLocation PlacementRParen, 3859 SourceRange TypeIdParens, 3860 QualType AllocType, 3861 TypeSourceInfo *AllocTypeInfo, 3862 Expr *ArraySize, 3863 SourceRange DirectInitRange, 3864 Expr *Initializer, 3865 bool TypeMayContainAuto = true); 3866 3867 bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, 3868 SourceRange R); 3869 bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, 3870 bool UseGlobal, QualType AllocType, bool IsArray, 3871 Expr **PlaceArgs, unsigned NumPlaceArgs, 3872 FunctionDecl *&OperatorNew, 3873 FunctionDecl *&OperatorDelete); 3874 bool FindAllocationOverload(SourceLocation StartLoc, SourceRange Range, 3875 DeclarationName Name, Expr** Args, 3876 unsigned NumArgs, DeclContext *Ctx, 3877 bool AllowMissing, FunctionDecl *&Operator, 3878 bool Diagnose = true); 3879 void DeclareGlobalNewDelete(); 3880 void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, 3881 QualType Argument, 3882 bool addMallocAttr = false); 3883 3884 bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, 3885 DeclarationName Name, FunctionDecl* &Operator, 3886 bool Diagnose = true); 3887 3888 /// ActOnCXXDelete - Parsed a C++ 'delete' expression 3889 ExprResult ActOnCXXDelete(SourceLocation StartLoc, 3890 bool UseGlobal, bool ArrayForm, 3891 Expr *Operand); 3892 3893 DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); 3894 ExprResult CheckConditionVariable(VarDecl *ConditionVar, 3895 SourceLocation StmtLoc, 3896 bool ConvertToBoolean); 3897 3898 ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, 3899 Expr *Operand, SourceLocation RParen); 3900 ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, 3901 SourceLocation RParen); 3902 3903 /// ActOnUnaryTypeTrait - Parsed one of the unary type trait support 3904 /// pseudo-functions. 3905 ExprResult ActOnUnaryTypeTrait(UnaryTypeTrait OTT, 3906 SourceLocation KWLoc, 3907 ParsedType Ty, 3908 SourceLocation RParen); 3909 3910 ExprResult BuildUnaryTypeTrait(UnaryTypeTrait OTT, 3911 SourceLocation KWLoc, 3912 TypeSourceInfo *T, 3913 SourceLocation RParen); 3914 3915 /// ActOnBinaryTypeTrait - Parsed one of the bianry type trait support 3916 /// pseudo-functions. 3917 ExprResult ActOnBinaryTypeTrait(BinaryTypeTrait OTT, 3918 SourceLocation KWLoc, 3919 ParsedType LhsTy, 3920 ParsedType RhsTy, 3921 SourceLocation RParen); 3922 3923 ExprResult BuildBinaryTypeTrait(BinaryTypeTrait BTT, 3924 SourceLocation KWLoc, 3925 TypeSourceInfo *LhsT, 3926 TypeSourceInfo *RhsT, 3927 SourceLocation RParen); 3928 3929 /// \brief Parsed one of the type trait support pseudo-functions. 3930 ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3931 ArrayRef<ParsedType> Args, 3932 SourceLocation RParenLoc); 3933 ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, 3934 ArrayRef<TypeSourceInfo *> Args, 3935 SourceLocation RParenLoc); 3936 3937 /// ActOnArrayTypeTrait - Parsed one of the bianry type trait support 3938 /// pseudo-functions. 3939 ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, 3940 SourceLocation KWLoc, 3941 ParsedType LhsTy, 3942 Expr *DimExpr, 3943 SourceLocation RParen); 3944 3945 ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, 3946 SourceLocation KWLoc, 3947 TypeSourceInfo *TSInfo, 3948 Expr *DimExpr, 3949 SourceLocation RParen); 3950 3951 /// ActOnExpressionTrait - Parsed one of the unary type trait support 3952 /// pseudo-functions. 3953 ExprResult ActOnExpressionTrait(ExpressionTrait OET, 3954 SourceLocation KWLoc, 3955 Expr *Queried, 3956 SourceLocation RParen); 3957 3958 ExprResult BuildExpressionTrait(ExpressionTrait OET, 3959 SourceLocation KWLoc, 3960 Expr *Queried, 3961 SourceLocation RParen); 3962 3963 ExprResult ActOnStartCXXMemberReference(Scope *S, 3964 Expr *Base, 3965 SourceLocation OpLoc, 3966 tok::TokenKind OpKind, 3967 ParsedType &ObjectType, 3968 bool &MayBePseudoDestructor); 3969 3970 ExprResult DiagnoseDtorReference(SourceLocation NameLoc, Expr *MemExpr); 3971 3972 ExprResult BuildPseudoDestructorExpr(Expr *Base, 3973 SourceLocation OpLoc, 3974 tok::TokenKind OpKind, 3975 const CXXScopeSpec &SS, 3976 TypeSourceInfo *ScopeType, 3977 SourceLocation CCLoc, 3978 SourceLocation TildeLoc, 3979 PseudoDestructorTypeStorage DestroyedType, 3980 bool HasTrailingLParen); 3981 3982 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3983 SourceLocation OpLoc, 3984 tok::TokenKind OpKind, 3985 CXXScopeSpec &SS, 3986 UnqualifiedId &FirstTypeName, 3987 SourceLocation CCLoc, 3988 SourceLocation TildeLoc, 3989 UnqualifiedId &SecondTypeName, 3990 bool HasTrailingLParen); 3991 3992 ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, 3993 SourceLocation OpLoc, 3994 tok::TokenKind OpKind, 3995 SourceLocation TildeLoc, 3996 const DeclSpec& DS, 3997 bool HasTrailingLParen); 3998 3999 /// MaybeCreateExprWithCleanups - If the current full-expression 4000 /// requires any cleanups, surround it with a ExprWithCleanups node. 4001 /// Otherwise, just returns the passed-in expression. 4002 Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); 4003 Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); 4004 ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); 4005 4006 ExprResult ActOnFinishFullExpr(Expr *Expr) { 4007 return ActOnFinishFullExpr(Expr, Expr ? Expr->getExprLoc() 4008 : SourceLocation()); 4009 } 4010 ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, 4011 bool DiscardedValue = false, 4012 bool IsConstexpr = false); 4013 StmtResult ActOnFinishFullStmt(Stmt *Stmt); 4014 4015 // Marks SS invalid if it represents an incomplete type. 4016 bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); 4017 4018 DeclContext *computeDeclContext(QualType T); 4019 DeclContext *computeDeclContext(const CXXScopeSpec &SS, 4020 bool EnteringContext = false); 4021 bool isDependentScopeSpecifier(const CXXScopeSpec &SS); 4022 CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); 4023 bool isUnknownSpecialization(const CXXScopeSpec &SS); 4024 4025 /// \brief The parser has parsed a global nested-name-specifier '::'. 4026 /// 4027 /// \param S The scope in which this nested-name-specifier occurs. 4028 /// 4029 /// \param CCLoc The location of the '::'. 4030 /// 4031 /// \param SS The nested-name-specifier, which will be updated in-place 4032 /// to reflect the parsed nested-name-specifier. 4033 /// 4034 /// \returns true if an error occurred, false otherwise. 4035 bool ActOnCXXGlobalScopeSpecifier(Scope *S, SourceLocation CCLoc, 4036 CXXScopeSpec &SS); 4037 4038 bool isAcceptableNestedNameSpecifier(const NamedDecl *SD); 4039 NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); 4040 4041 bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, 4042 SourceLocation IdLoc, 4043 IdentifierInfo &II, 4044 ParsedType ObjectType); 4045 4046 bool BuildCXXNestedNameSpecifier(Scope *S, 4047 IdentifierInfo &Identifier, 4048 SourceLocation IdentifierLoc, 4049 SourceLocation CCLoc, 4050 QualType ObjectType, 4051 bool EnteringContext, 4052 CXXScopeSpec &SS, 4053 NamedDecl *ScopeLookupResult, 4054 bool ErrorRecoveryLookup); 4055 4056 /// \brief The parser has parsed a nested-name-specifier 'identifier::'. 4057 /// 4058 /// \param S The scope in which this nested-name-specifier occurs. 4059 /// 4060 /// \param Identifier The identifier preceding the '::'. 4061 /// 4062 /// \param IdentifierLoc The location of the identifier. 4063 /// 4064 /// \param CCLoc The location of the '::'. 4065 /// 4066 /// \param ObjectType The type of the object, if we're parsing 4067 /// nested-name-specifier in a member access expression. 4068 /// 4069 /// \param EnteringContext Whether we're entering the context nominated by 4070 /// this nested-name-specifier. 4071 /// 4072 /// \param SS The nested-name-specifier, which is both an input 4073 /// parameter (the nested-name-specifier before this type) and an 4074 /// output parameter (containing the full nested-name-specifier, 4075 /// including this new type). 4076 /// 4077 /// \returns true if an error occurred, false otherwise. 4078 bool ActOnCXXNestedNameSpecifier(Scope *S, 4079 IdentifierInfo &Identifier, 4080 SourceLocation IdentifierLoc, 4081 SourceLocation CCLoc, 4082 ParsedType ObjectType, 4083 bool EnteringContext, 4084 CXXScopeSpec &SS); 4085 4086 ExprResult ActOnDecltypeExpression(Expr *E); 4087 4088 bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, 4089 const DeclSpec &DS, 4090 SourceLocation ColonColonLoc); 4091 4092 bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, 4093 IdentifierInfo &Identifier, 4094 SourceLocation IdentifierLoc, 4095 SourceLocation ColonLoc, 4096 ParsedType ObjectType, 4097 bool EnteringContext); 4098 4099 /// \brief The parser has parsed a nested-name-specifier 4100 /// 'template[opt] template-name < template-args >::'. 4101 /// 4102 /// \param S The scope in which this nested-name-specifier occurs. 4103 /// 4104 /// \param SS The nested-name-specifier, which is both an input 4105 /// parameter (the nested-name-specifier before this type) and an 4106 /// output parameter (containing the full nested-name-specifier, 4107 /// including this new type). 4108 /// 4109 /// \param TemplateKWLoc the location of the 'template' keyword, if any. 4110 /// \param TemplateName the template name. 4111 /// \param TemplateNameLoc The location of the template name. 4112 /// \param LAngleLoc The location of the opening angle bracket ('<'). 4113 /// \param TemplateArgs The template arguments. 4114 /// \param RAngleLoc The location of the closing angle bracket ('>'). 4115 /// \param CCLoc The location of the '::'. 4116 /// 4117 /// \param EnteringContext Whether we're entering the context of the 4118 /// nested-name-specifier. 4119 /// 4120 /// 4121 /// \returns true if an error occurred, false otherwise. 4122 bool ActOnCXXNestedNameSpecifier(Scope *S, 4123 CXXScopeSpec &SS, 4124 SourceLocation TemplateKWLoc, 4125 TemplateTy TemplateName, 4126 SourceLocation TemplateNameLoc, 4127 SourceLocation LAngleLoc, 4128 ASTTemplateArgsPtr TemplateArgs, 4129 SourceLocation RAngleLoc, 4130 SourceLocation CCLoc, 4131 bool EnteringContext); 4132 4133 /// \brief Given a C++ nested-name-specifier, produce an annotation value 4134 /// that the parser can use later to reconstruct the given 4135 /// nested-name-specifier. 4136 /// 4137 /// \param SS A nested-name-specifier. 4138 /// 4139 /// \returns A pointer containing all of the information in the 4140 /// nested-name-specifier \p SS. 4141 void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); 4142 4143 /// \brief Given an annotation pointer for a nested-name-specifier, restore 4144 /// the nested-name-specifier structure. 4145 /// 4146 /// \param Annotation The annotation pointer, produced by 4147 /// \c SaveNestedNameSpecifierAnnotation(). 4148 /// 4149 /// \param AnnotationRange The source range corresponding to the annotation. 4150 /// 4151 /// \param SS The nested-name-specifier that will be updated with the contents 4152 /// of the annotation pointer. 4153 void RestoreNestedNameSpecifierAnnotation(void *Annotation, 4154 SourceRange AnnotationRange, 4155 CXXScopeSpec &SS); 4156 4157 bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4158 4159 /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global 4160 /// scope or nested-name-specifier) is parsed, part of a declarator-id. 4161 /// After this method is called, according to [C++ 3.4.3p3], names should be 4162 /// looked up in the declarator-id's scope, until the declarator is parsed and 4163 /// ActOnCXXExitDeclaratorScope is called. 4164 /// The 'SS' should be a non-empty valid CXXScopeSpec. 4165 bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); 4166 4167 /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously 4168 /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same 4169 /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. 4170 /// Used to indicate that names should revert to being looked up in the 4171 /// defining scope. 4172 void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); 4173 4174 /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an 4175 /// initializer for the declaration 'Dcl'. 4176 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a 4177 /// static data member of class X, names should be looked up in the scope of 4178 /// class X. 4179 void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); 4180 4181 /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an 4182 /// initializer for the declaration 'Dcl'. 4183 void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); 4184 4185 /// \brief Create a new lambda closure type. 4186 CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, 4187 TypeSourceInfo *Info, 4188 bool KnownDependent); 4189 4190 /// \brief Start the definition of a lambda expression. 4191 CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, 4192 SourceRange IntroducerRange, 4193 TypeSourceInfo *MethodType, 4194 SourceLocation EndLoc, 4195 ArrayRef<ParmVarDecl *> Params); 4196 4197 /// \brief Introduce the scope for a lambda expression. 4198 sema::LambdaScopeInfo *enterLambdaScope(CXXMethodDecl *CallOperator, 4199 SourceRange IntroducerRange, 4200 LambdaCaptureDefault CaptureDefault, 4201 bool ExplicitParams, 4202 bool ExplicitResultType, 4203 bool Mutable); 4204 4205 /// \brief Note that we have finished the explicit captures for the 4206 /// given lambda. 4207 void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); 4208 4209 /// \brief Introduce the lambda parameters into scope. 4210 void addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope); 4211 4212 /// \brief Deduce a block or lambda's return type based on the return 4213 /// statements present in the body. 4214 void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); 4215 4216 /// ActOnStartOfLambdaDefinition - This is called just before we start 4217 /// parsing the body of a lambda; it analyzes the explicit captures and 4218 /// arguments, and sets up various data-structures for the body of the 4219 /// lambda. 4220 void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 4221 Declarator &ParamInfo, Scope *CurScope); 4222 4223 /// ActOnLambdaError - If there is an error parsing a lambda, this callback 4224 /// is invoked to pop the information about the lambda. 4225 void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 4226 bool IsInstantiation = false); 4227 4228 /// ActOnLambdaExpr - This is called when the body of a lambda expression 4229 /// was successfully completed. 4230 ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 4231 Scope *CurScope, 4232 bool IsInstantiation = false); 4233 4234 /// \brief Define the "body" of the conversion from a lambda object to a 4235 /// function pointer. 4236 /// 4237 /// This routine doesn't actually define a sensible body; rather, it fills 4238 /// in the initialization expression needed to copy the lambda object into 4239 /// the block, and IR generation actually generates the real body of the 4240 /// block pointer conversion. 4241 void DefineImplicitLambdaToFunctionPointerConversion( 4242 SourceLocation CurrentLoc, CXXConversionDecl *Conv); 4243 4244 /// \brief Define the "body" of the conversion from a lambda object to a 4245 /// block pointer. 4246 /// 4247 /// This routine doesn't actually define a sensible body; rather, it fills 4248 /// in the initialization expression needed to copy the lambda object into 4249 /// the block, and IR generation actually generates the real body of the 4250 /// block pointer conversion. 4251 void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, 4252 CXXConversionDecl *Conv); 4253 4254 ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 4255 SourceLocation ConvLocation, 4256 CXXConversionDecl *Conv, 4257 Expr *Src); 4258 4259 // ParseObjCStringLiteral - Parse Objective-C string literals. 4260 ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, 4261 Expr **Strings, 4262 unsigned NumStrings); 4263 4264 ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); 4265 4266 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 4267 /// numeric literal expression. Type of the expression will be "NSNumber *" 4268 /// or "id" if NSNumber is unavailable. 4269 ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); 4270 ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, 4271 bool Value); 4272 ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); 4273 4274 /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the 4275 /// '@' prefixed parenthesized expression. The type of the expression will 4276 /// either be "NSNumber *" or "NSString *" depending on the type of 4277 /// ValueType, which is allowed to be a built-in numeric type or 4278 /// "char *" or "const char *". 4279 ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); 4280 4281 ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 4282 Expr *IndexExpr, 4283 ObjCMethodDecl *getterMethod, 4284 ObjCMethodDecl *setterMethod); 4285 4286 ExprResult BuildObjCDictionaryLiteral(SourceRange SR, 4287 ObjCDictionaryElement *Elements, 4288 unsigned NumElements); 4289 4290 ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, 4291 TypeSourceInfo *EncodedTypeInfo, 4292 SourceLocation RParenLoc); 4293 ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, 4294 CXXConversionDecl *Method, 4295 bool HadMultipleCandidates); 4296 4297 ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, 4298 SourceLocation EncodeLoc, 4299 SourceLocation LParenLoc, 4300 ParsedType Ty, 4301 SourceLocation RParenLoc); 4302 4303 /// ParseObjCSelectorExpression - Build selector expression for \@selector 4304 ExprResult ParseObjCSelectorExpression(Selector Sel, 4305 SourceLocation AtLoc, 4306 SourceLocation SelLoc, 4307 SourceLocation LParenLoc, 4308 SourceLocation RParenLoc); 4309 4310 /// ParseObjCProtocolExpression - Build protocol expression for \@protocol 4311 ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, 4312 SourceLocation AtLoc, 4313 SourceLocation ProtoLoc, 4314 SourceLocation LParenLoc, 4315 SourceLocation ProtoIdLoc, 4316 SourceLocation RParenLoc); 4317 4318 //===--------------------------------------------------------------------===// 4319 // C++ Declarations 4320 // 4321 Decl *ActOnStartLinkageSpecification(Scope *S, 4322 SourceLocation ExternLoc, 4323 SourceLocation LangLoc, 4324 StringRef Lang, 4325 SourceLocation LBraceLoc); 4326 Decl *ActOnFinishLinkageSpecification(Scope *S, 4327 Decl *LinkageSpec, 4328 SourceLocation RBraceLoc); 4329 4330 4331 //===--------------------------------------------------------------------===// 4332 // C++ Classes 4333 // 4334 bool isCurrentClassName(const IdentifierInfo &II, Scope *S, 4335 const CXXScopeSpec *SS = 0); 4336 4337 bool ActOnAccessSpecifier(AccessSpecifier Access, 4338 SourceLocation ASLoc, 4339 SourceLocation ColonLoc, 4340 AttributeList *Attrs = 0); 4341 4342 NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, 4343 Declarator &D, 4344 MultiTemplateParamsArg TemplateParameterLists, 4345 Expr *BitfieldWidth, const VirtSpecifiers &VS, 4346 InClassInitStyle InitStyle); 4347 void ActOnCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, 4348 Expr *Init); 4349 4350 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4351 Scope *S, 4352 CXXScopeSpec &SS, 4353 IdentifierInfo *MemberOrBase, 4354 ParsedType TemplateTypeTy, 4355 const DeclSpec &DS, 4356 SourceLocation IdLoc, 4357 SourceLocation LParenLoc, 4358 Expr **Args, unsigned NumArgs, 4359 SourceLocation RParenLoc, 4360 SourceLocation EllipsisLoc); 4361 4362 MemInitResult ActOnMemInitializer(Decl *ConstructorD, 4363 Scope *S, 4364 CXXScopeSpec &SS, 4365 IdentifierInfo *MemberOrBase, 4366 ParsedType TemplateTypeTy, 4367 const DeclSpec &DS, 4368 SourceLocation IdLoc, 4369 Expr *InitList, 4370 SourceLocation EllipsisLoc); 4371 4372 MemInitResult BuildMemInitializer(Decl *ConstructorD, 4373 Scope *S, 4374 CXXScopeSpec &SS, 4375 IdentifierInfo *MemberOrBase, 4376 ParsedType TemplateTypeTy, 4377 const DeclSpec &DS, 4378 SourceLocation IdLoc, 4379 Expr *Init, 4380 SourceLocation EllipsisLoc); 4381 4382 MemInitResult BuildMemberInitializer(ValueDecl *Member, 4383 Expr *Init, 4384 SourceLocation IdLoc); 4385 4386 MemInitResult BuildBaseInitializer(QualType BaseType, 4387 TypeSourceInfo *BaseTInfo, 4388 Expr *Init, 4389 CXXRecordDecl *ClassDecl, 4390 SourceLocation EllipsisLoc); 4391 4392 MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, 4393 Expr *Init, 4394 CXXRecordDecl *ClassDecl); 4395 4396 bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, 4397 CXXCtorInitializer *Initializer); 4398 4399 bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, 4400 ArrayRef<CXXCtorInitializer *> Initializers = 4401 ArrayRef<CXXCtorInitializer *>()); 4402 4403 void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); 4404 4405 4406 /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, 4407 /// mark all the non-trivial destructors of its members and bases as 4408 /// referenced. 4409 void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, 4410 CXXRecordDecl *Record); 4411 4412 /// \brief The list of classes whose vtables have been used within 4413 /// this translation unit, and the source locations at which the 4414 /// first use occurred. 4415 typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; 4416 4417 /// \brief The list of vtables that are required but have not yet been 4418 /// materialized. 4419 SmallVector<VTableUse, 16> VTableUses; 4420 4421 /// \brief The set of classes whose vtables have been used within 4422 /// this translation unit, and a bit that will be true if the vtable is 4423 /// required to be emitted (otherwise, it should be emitted only if needed 4424 /// by code generation). 4425 llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; 4426 4427 /// \brief Load any externally-stored vtable uses. 4428 void LoadExternalVTableUses(); 4429 4430 typedef LazyVector<CXXRecordDecl *, ExternalSemaSource, 4431 &ExternalSemaSource::ReadDynamicClasses, 2, 2> 4432 DynamicClassesType; 4433 4434 /// \brief A list of all of the dynamic classes in this translation 4435 /// unit. 4436 DynamicClassesType DynamicClasses; 4437 4438 /// \brief Note that the vtable for the given class was used at the 4439 /// given location. 4440 void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, 4441 bool DefinitionRequired = false); 4442 4443 /// \brief Mark the exception specifications of all virtual member functions 4444 /// in the given class as needed. 4445 void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, 4446 const CXXRecordDecl *RD); 4447 4448 /// MarkVirtualMembersReferenced - Will mark all members of the given 4449 /// CXXRecordDecl referenced. 4450 void MarkVirtualMembersReferenced(SourceLocation Loc, 4451 const CXXRecordDecl *RD); 4452 4453 /// \brief Define all of the vtables that have been used in this 4454 /// translation unit and reference any virtual members used by those 4455 /// vtables. 4456 /// 4457 /// \returns true if any work was done, false otherwise. 4458 bool DefineUsedVTables(); 4459 4460 void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); 4461 4462 void ActOnMemInitializers(Decl *ConstructorDecl, 4463 SourceLocation ColonLoc, 4464 ArrayRef<CXXCtorInitializer*> MemInits, 4465 bool AnyErrors); 4466 4467 void CheckCompletedCXXClass(CXXRecordDecl *Record); 4468 void ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc, 4469 Decl *TagDecl, 4470 SourceLocation LBrac, 4471 SourceLocation RBrac, 4472 AttributeList *AttrList); 4473 void ActOnFinishCXXMemberDecls(); 4474 4475 void ActOnReenterTemplateScope(Scope *S, Decl *Template); 4476 void ActOnReenterDeclaratorTemplateScope(Scope *S, DeclaratorDecl *D); 4477 void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); 4478 void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4479 void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); 4480 void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); 4481 void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); 4482 void ActOnFinishDelayedMemberInitializers(Decl *Record); 4483 void MarkAsLateParsedTemplate(FunctionDecl *FD, bool Flag = true); 4484 bool IsInsideALocalClassWithinATemplateFunction(); 4485 4486 Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4487 Expr *AssertExpr, 4488 Expr *AssertMessageExpr, 4489 SourceLocation RParenLoc); 4490 Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, 4491 Expr *AssertExpr, 4492 StringLiteral *AssertMessageExpr, 4493 SourceLocation RParenLoc, 4494 bool Failed); 4495 4496 FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, 4497 SourceLocation FriendLoc, 4498 TypeSourceInfo *TSInfo); 4499 Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, 4500 MultiTemplateParamsArg TemplateParams); 4501 NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, 4502 MultiTemplateParamsArg TemplateParams); 4503 4504 QualType CheckConstructorDeclarator(Declarator &D, QualType R, 4505 StorageClass& SC); 4506 void CheckConstructor(CXXConstructorDecl *Constructor); 4507 QualType CheckDestructorDeclarator(Declarator &D, QualType R, 4508 StorageClass& SC); 4509 bool CheckDestructor(CXXDestructorDecl *Destructor); 4510 void CheckConversionDeclarator(Declarator &D, QualType &R, 4511 StorageClass& SC); 4512 Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); 4513 4514 void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); 4515 void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, 4516 const FunctionProtoType *T); 4517 void CheckDelayedExplicitlyDefaultedMemberExceptionSpecs(); 4518 4519 //===--------------------------------------------------------------------===// 4520 // C++ Derived Classes 4521 // 4522 4523 /// ActOnBaseSpecifier - Parsed a base specifier 4524 CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, 4525 SourceRange SpecifierRange, 4526 bool Virtual, AccessSpecifier Access, 4527 TypeSourceInfo *TInfo, 4528 SourceLocation EllipsisLoc); 4529 4530 BaseResult ActOnBaseSpecifier(Decl *classdecl, 4531 SourceRange SpecifierRange, 4532 ParsedAttributes &Attrs, 4533 bool Virtual, AccessSpecifier Access, 4534 ParsedType basetype, 4535 SourceLocation BaseLoc, 4536 SourceLocation EllipsisLoc); 4537 4538 bool AttachBaseSpecifiers(CXXRecordDecl *Class, CXXBaseSpecifier **Bases, 4539 unsigned NumBases); 4540 void ActOnBaseSpecifiers(Decl *ClassDecl, CXXBaseSpecifier **Bases, 4541 unsigned NumBases); 4542 4543 bool IsDerivedFrom(QualType Derived, QualType Base); 4544 bool IsDerivedFrom(QualType Derived, QualType Base, CXXBasePaths &Paths); 4545 4546 // FIXME: I don't like this name. 4547 void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); 4548 4549 bool BasePathInvolvesVirtualBase(const CXXCastPath &BasePath); 4550 4551 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4552 SourceLocation Loc, SourceRange Range, 4553 CXXCastPath *BasePath = 0, 4554 bool IgnoreAccess = false); 4555 bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, 4556 unsigned InaccessibleBaseID, 4557 unsigned AmbigiousBaseConvID, 4558 SourceLocation Loc, SourceRange Range, 4559 DeclarationName Name, 4560 CXXCastPath *BasePath); 4561 4562 std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); 4563 4564 bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, 4565 const CXXMethodDecl *Old); 4566 4567 /// CheckOverridingFunctionReturnType - Checks whether the return types are 4568 /// covariant, according to C++ [class.virtual]p5. 4569 bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, 4570 const CXXMethodDecl *Old); 4571 4572 /// CheckOverridingFunctionExceptionSpec - Checks whether the exception 4573 /// spec is a subset of base spec. 4574 bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, 4575 const CXXMethodDecl *Old); 4576 4577 bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); 4578 4579 /// CheckOverrideControl - Check C++11 override control semantics. 4580 void CheckOverrideControl(Decl *D); 4581 4582 /// CheckForFunctionMarkedFinal - Checks whether a virtual member function 4583 /// overrides a virtual member function marked 'final', according to 4584 /// C++11 [class.virtual]p4. 4585 bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, 4586 const CXXMethodDecl *Old); 4587 4588 4589 //===--------------------------------------------------------------------===// 4590 // C++ Access Control 4591 // 4592 4593 enum AccessResult { 4594 AR_accessible, 4595 AR_inaccessible, 4596 AR_dependent, 4597 AR_delayed 4598 }; 4599 4600 bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, 4601 NamedDecl *PrevMemberDecl, 4602 AccessSpecifier LexicalAS); 4603 4604 AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, 4605 DeclAccessPair FoundDecl); 4606 AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, 4607 DeclAccessPair FoundDecl); 4608 AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, 4609 SourceRange PlacementRange, 4610 CXXRecordDecl *NamingClass, 4611 DeclAccessPair FoundDecl, 4612 bool Diagnose = true); 4613 AccessResult CheckConstructorAccess(SourceLocation Loc, 4614 CXXConstructorDecl *D, 4615 const InitializedEntity &Entity, 4616 AccessSpecifier Access, 4617 bool IsCopyBindingRefToTemp = false); 4618 AccessResult CheckConstructorAccess(SourceLocation Loc, 4619 CXXConstructorDecl *D, 4620 const InitializedEntity &Entity, 4621 AccessSpecifier Access, 4622 const PartialDiagnostic &PDiag); 4623 AccessResult CheckDestructorAccess(SourceLocation Loc, 4624 CXXDestructorDecl *Dtor, 4625 const PartialDiagnostic &PDiag, 4626 QualType objectType = QualType()); 4627 AccessResult CheckFriendAccess(NamedDecl *D); 4628 AccessResult CheckMemberOperatorAccess(SourceLocation Loc, 4629 Expr *ObjectExpr, 4630 Expr *ArgExpr, 4631 DeclAccessPair FoundDecl); 4632 AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, 4633 DeclAccessPair FoundDecl); 4634 AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, 4635 QualType Base, QualType Derived, 4636 const CXXBasePath &Path, 4637 unsigned DiagID, 4638 bool ForceCheck = false, 4639 bool ForceUnprivileged = false); 4640 void CheckLookupAccess(const LookupResult &R); 4641 bool IsSimplyAccessible(NamedDecl *decl, DeclContext *Ctx); 4642 bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, 4643 AccessSpecifier access, 4644 QualType objectType); 4645 4646 void HandleDependentAccessCheck(const DependentDiagnostic &DD, 4647 const MultiLevelTemplateArgumentList &TemplateArgs); 4648 void PerformDependentDiagnostics(const DeclContext *Pattern, 4649 const MultiLevelTemplateArgumentList &TemplateArgs); 4650 4651 void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); 4652 4653 /// \brief When true, access checking violations are treated as SFINAE 4654 /// failures rather than hard errors. 4655 bool AccessCheckingSFINAE; 4656 4657 enum AbstractDiagSelID { 4658 AbstractNone = -1, 4659 AbstractReturnType, 4660 AbstractParamType, 4661 AbstractVariableType, 4662 AbstractFieldType, 4663 AbstractIvarType, 4664 AbstractArrayType 4665 }; 4666 4667 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4668 TypeDiagnoser &Diagnoser); 4669 template<typename T1> 4670 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4671 unsigned DiagID, 4672 const T1 &Arg1) { 4673 BoundTypeDiagnoser1<T1> Diagnoser(DiagID, Arg1); 4674 return RequireNonAbstractType(Loc, T, Diagnoser); 4675 } 4676 4677 template<typename T1, typename T2> 4678 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4679 unsigned DiagID, 4680 const T1 &Arg1, const T2 &Arg2) { 4681 BoundTypeDiagnoser2<T1, T2> Diagnoser(DiagID, Arg1, Arg2); 4682 return RequireNonAbstractType(Loc, T, Diagnoser); 4683 } 4684 4685 template<typename T1, typename T2, typename T3> 4686 bool RequireNonAbstractType(SourceLocation Loc, QualType T, 4687 unsigned DiagID, 4688 const T1 &Arg1, const T2 &Arg2, const T3 &Arg3) { 4689 BoundTypeDiagnoser3<T1, T2, T3> Diagnoser(DiagID, Arg1, Arg2, Arg3); 4690 return RequireNonAbstractType(Loc, T, Diagnoser); 4691 } 4692 4693 void DiagnoseAbstractType(const CXXRecordDecl *RD); 4694 4695 bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, 4696 AbstractDiagSelID SelID = AbstractNone); 4697 4698 //===--------------------------------------------------------------------===// 4699 // C++ Overloaded Operators [C++ 13.5] 4700 // 4701 4702 bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); 4703 4704 bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); 4705 4706 //===--------------------------------------------------------------------===// 4707 // C++ Templates [C++ 14] 4708 // 4709 void FilterAcceptableTemplateNames(LookupResult &R, 4710 bool AllowFunctionTemplates = true); 4711 bool hasAnyAcceptableTemplateNames(LookupResult &R, 4712 bool AllowFunctionTemplates = true); 4713 4714 void LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, 4715 QualType ObjectType, bool EnteringContext, 4716 bool &MemberOfUnknownSpecialization); 4717 4718 TemplateNameKind isTemplateName(Scope *S, 4719 CXXScopeSpec &SS, 4720 bool hasTemplateKeyword, 4721 UnqualifiedId &Name, 4722 ParsedType ObjectType, 4723 bool EnteringContext, 4724 TemplateTy &Template, 4725 bool &MemberOfUnknownSpecialization); 4726 4727 bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, 4728 SourceLocation IILoc, 4729 Scope *S, 4730 const CXXScopeSpec *SS, 4731 TemplateTy &SuggestedTemplate, 4732 TemplateNameKind &SuggestedKind); 4733 4734 void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); 4735 TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); 4736 4737 Decl *ActOnTypeParameter(Scope *S, bool Typename, bool Ellipsis, 4738 SourceLocation EllipsisLoc, 4739 SourceLocation KeyLoc, 4740 IdentifierInfo *ParamName, 4741 SourceLocation ParamNameLoc, 4742 unsigned Depth, unsigned Position, 4743 SourceLocation EqualLoc, 4744 ParsedType DefaultArg); 4745 4746 QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); 4747 Decl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, 4748 unsigned Depth, 4749 unsigned Position, 4750 SourceLocation EqualLoc, 4751 Expr *DefaultArg); 4752 Decl *ActOnTemplateTemplateParameter(Scope *S, 4753 SourceLocation TmpLoc, 4754 TemplateParameterList *Params, 4755 SourceLocation EllipsisLoc, 4756 IdentifierInfo *ParamName, 4757 SourceLocation ParamNameLoc, 4758 unsigned Depth, 4759 unsigned Position, 4760 SourceLocation EqualLoc, 4761 ParsedTemplateArgument DefaultArg); 4762 4763 TemplateParameterList * 4764 ActOnTemplateParameterList(unsigned Depth, 4765 SourceLocation ExportLoc, 4766 SourceLocation TemplateLoc, 4767 SourceLocation LAngleLoc, 4768 Decl **Params, unsigned NumParams, 4769 SourceLocation RAngleLoc); 4770 4771 /// \brief The context in which we are checking a template parameter 4772 /// list. 4773 enum TemplateParamListContext { 4774 TPC_ClassTemplate, 4775 TPC_FunctionTemplate, 4776 TPC_ClassTemplateMember, 4777 TPC_FriendFunctionTemplate, 4778 TPC_FriendFunctionTemplateDefinition, 4779 TPC_TypeAliasTemplate 4780 }; 4781 4782 bool CheckTemplateParameterList(TemplateParameterList *NewParams, 4783 TemplateParameterList *OldParams, 4784 TemplateParamListContext TPC); 4785 TemplateParameterList * 4786 MatchTemplateParametersToScopeSpecifier(SourceLocation DeclStartLoc, 4787 SourceLocation DeclLoc, 4788 const CXXScopeSpec &SS, 4789 TemplateParameterList **ParamLists, 4790 unsigned NumParamLists, 4791 bool IsFriend, 4792 bool &IsExplicitSpecialization, 4793 bool &Invalid); 4794 4795 DeclResult CheckClassTemplate(Scope *S, unsigned TagSpec, TagUseKind TUK, 4796 SourceLocation KWLoc, CXXScopeSpec &SS, 4797 IdentifierInfo *Name, SourceLocation NameLoc, 4798 AttributeList *Attr, 4799 TemplateParameterList *TemplateParams, 4800 AccessSpecifier AS, 4801 SourceLocation ModulePrivateLoc, 4802 unsigned NumOuterTemplateParamLists, 4803 TemplateParameterList **OuterTemplateParamLists); 4804 4805 void translateTemplateArguments(const ASTTemplateArgsPtr &In, 4806 TemplateArgumentListInfo &Out); 4807 4808 void NoteAllFoundTemplates(TemplateName Name); 4809 4810 QualType CheckTemplateIdType(TemplateName Template, 4811 SourceLocation TemplateLoc, 4812 TemplateArgumentListInfo &TemplateArgs); 4813 4814 TypeResult 4815 ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 4816 TemplateTy Template, SourceLocation TemplateLoc, 4817 SourceLocation LAngleLoc, 4818 ASTTemplateArgsPtr TemplateArgs, 4819 SourceLocation RAngleLoc, 4820 bool IsCtorOrDtorName = false); 4821 4822 /// \brief Parsed an elaborated-type-specifier that refers to a template-id, 4823 /// such as \c class T::template apply<U>. 4824 TypeResult ActOnTagTemplateIdType(TagUseKind TUK, 4825 TypeSpecifierType TagSpec, 4826 SourceLocation TagLoc, 4827 CXXScopeSpec &SS, 4828 SourceLocation TemplateKWLoc, 4829 TemplateTy TemplateD, 4830 SourceLocation TemplateLoc, 4831 SourceLocation LAngleLoc, 4832 ASTTemplateArgsPtr TemplateArgsIn, 4833 SourceLocation RAngleLoc); 4834 4835 4836 ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, 4837 SourceLocation TemplateKWLoc, 4838 LookupResult &R, 4839 bool RequiresADL, 4840 const TemplateArgumentListInfo *TemplateArgs); 4841 4842 ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, 4843 SourceLocation TemplateKWLoc, 4844 const DeclarationNameInfo &NameInfo, 4845 const TemplateArgumentListInfo *TemplateArgs); 4846 4847 TemplateNameKind ActOnDependentTemplateName(Scope *S, 4848 CXXScopeSpec &SS, 4849 SourceLocation TemplateKWLoc, 4850 UnqualifiedId &Name, 4851 ParsedType ObjectType, 4852 bool EnteringContext, 4853 TemplateTy &Template); 4854 4855 DeclResult 4856 ActOnClassTemplateSpecialization(Scope *S, unsigned TagSpec, TagUseKind TUK, 4857 SourceLocation KWLoc, 4858 SourceLocation ModulePrivateLoc, 4859 CXXScopeSpec &SS, 4860 TemplateTy Template, 4861 SourceLocation TemplateNameLoc, 4862 SourceLocation LAngleLoc, 4863 ASTTemplateArgsPtr TemplateArgs, 4864 SourceLocation RAngleLoc, 4865 AttributeList *Attr, 4866 MultiTemplateParamsArg TemplateParameterLists); 4867 4868 Decl *ActOnTemplateDeclarator(Scope *S, 4869 MultiTemplateParamsArg TemplateParameterLists, 4870 Declarator &D); 4871 4872 Decl *ActOnStartOfFunctionTemplateDef(Scope *FnBodyScope, 4873 MultiTemplateParamsArg TemplateParameterLists, 4874 Declarator &D); 4875 4876 bool 4877 CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, 4878 TemplateSpecializationKind NewTSK, 4879 NamedDecl *PrevDecl, 4880 TemplateSpecializationKind PrevTSK, 4881 SourceLocation PrevPtOfInstantiation, 4882 bool &SuppressNew); 4883 4884 bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, 4885 const TemplateArgumentListInfo &ExplicitTemplateArgs, 4886 LookupResult &Previous); 4887 4888 bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, 4889 TemplateArgumentListInfo *ExplicitTemplateArgs, 4890 LookupResult &Previous); 4891 bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); 4892 4893 DeclResult 4894 ActOnExplicitInstantiation(Scope *S, 4895 SourceLocation ExternLoc, 4896 SourceLocation TemplateLoc, 4897 unsigned TagSpec, 4898 SourceLocation KWLoc, 4899 const CXXScopeSpec &SS, 4900 TemplateTy Template, 4901 SourceLocation TemplateNameLoc, 4902 SourceLocation LAngleLoc, 4903 ASTTemplateArgsPtr TemplateArgs, 4904 SourceLocation RAngleLoc, 4905 AttributeList *Attr); 4906 4907 DeclResult 4908 ActOnExplicitInstantiation(Scope *S, 4909 SourceLocation ExternLoc, 4910 SourceLocation TemplateLoc, 4911 unsigned TagSpec, 4912 SourceLocation KWLoc, 4913 CXXScopeSpec &SS, 4914 IdentifierInfo *Name, 4915 SourceLocation NameLoc, 4916 AttributeList *Attr); 4917 4918 DeclResult ActOnExplicitInstantiation(Scope *S, 4919 SourceLocation ExternLoc, 4920 SourceLocation TemplateLoc, 4921 Declarator &D); 4922 4923 TemplateArgumentLoc 4924 SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, 4925 SourceLocation TemplateLoc, 4926 SourceLocation RAngleLoc, 4927 Decl *Param, 4928 SmallVectorImpl<TemplateArgument> &Converted); 4929 4930 /// \brief Specifies the context in which a particular template 4931 /// argument is being checked. 4932 enum CheckTemplateArgumentKind { 4933 /// \brief The template argument was specified in the code or was 4934 /// instantiated with some deduced template arguments. 4935 CTAK_Specified, 4936 4937 /// \brief The template argument was deduced via template argument 4938 /// deduction. 4939 CTAK_Deduced, 4940 4941 /// \brief The template argument was deduced from an array bound 4942 /// via template argument deduction. 4943 CTAK_DeducedFromArrayBound 4944 }; 4945 4946 bool CheckTemplateArgument(NamedDecl *Param, 4947 const TemplateArgumentLoc &Arg, 4948 NamedDecl *Template, 4949 SourceLocation TemplateLoc, 4950 SourceLocation RAngleLoc, 4951 unsigned ArgumentPackIndex, 4952 SmallVectorImpl<TemplateArgument> &Converted, 4953 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4954 4955 /// \brief Check that the given template arguments can be be provided to 4956 /// the given template, converting the arguments along the way. 4957 /// 4958 /// \param Template The template to which the template arguments are being 4959 /// provided. 4960 /// 4961 /// \param TemplateLoc The location of the template name in the source. 4962 /// 4963 /// \param TemplateArgs The list of template arguments. If the template is 4964 /// a template template parameter, this function may extend the set of 4965 /// template arguments to also include substituted, defaulted template 4966 /// arguments. 4967 /// 4968 /// \param PartialTemplateArgs True if the list of template arguments is 4969 /// intentionally partial, e.g., because we're checking just the initial 4970 /// set of template arguments. 4971 /// 4972 /// \param Converted Will receive the converted, canonicalized template 4973 /// arguments. 4974 /// 4975 /// 4976 /// \param ExpansionIntoFixedList If non-NULL, will be set true to indicate 4977 /// when the template arguments contain a pack expansion that is being 4978 /// expanded into a fixed parameter list. 4979 /// 4980 /// \returns True if an error occurred, false otherwise. 4981 bool CheckTemplateArgumentList(TemplateDecl *Template, 4982 SourceLocation TemplateLoc, 4983 TemplateArgumentListInfo &TemplateArgs, 4984 bool PartialTemplateArgs, 4985 SmallVectorImpl<TemplateArgument> &Converted, 4986 bool *ExpansionIntoFixedList = 0); 4987 4988 bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, 4989 const TemplateArgumentLoc &Arg, 4990 SmallVectorImpl<TemplateArgument> &Converted); 4991 4992 bool CheckTemplateArgument(TemplateTypeParmDecl *Param, 4993 TypeSourceInfo *Arg); 4994 ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, 4995 QualType InstantiatedParamType, Expr *Arg, 4996 TemplateArgument &Converted, 4997 CheckTemplateArgumentKind CTAK = CTAK_Specified); 4998 bool CheckTemplateArgument(TemplateTemplateParmDecl *Param, 4999 const TemplateArgumentLoc &Arg, 5000 unsigned ArgumentPackIndex); 5001 5002 ExprResult 5003 BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, 5004 QualType ParamType, 5005 SourceLocation Loc); 5006 ExprResult 5007 BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, 5008 SourceLocation Loc); 5009 5010 /// \brief Enumeration describing how template parameter lists are compared 5011 /// for equality. 5012 enum TemplateParameterListEqualKind { 5013 /// \brief We are matching the template parameter lists of two templates 5014 /// that might be redeclarations. 5015 /// 5016 /// \code 5017 /// template<typename T> struct X; 5018 /// template<typename T> struct X; 5019 /// \endcode 5020 TPL_TemplateMatch, 5021 5022 /// \brief We are matching the template parameter lists of two template 5023 /// template parameters as part of matching the template parameter lists 5024 /// of two templates that might be redeclarations. 5025 /// 5026 /// \code 5027 /// template<template<int I> class TT> struct X; 5028 /// template<template<int Value> class Other> struct X; 5029 /// \endcode 5030 TPL_TemplateTemplateParmMatch, 5031 5032 /// \brief We are matching the template parameter lists of a template 5033 /// template argument against the template parameter lists of a template 5034 /// template parameter. 5035 /// 5036 /// \code 5037 /// template<template<int Value> class Metafun> struct X; 5038 /// template<int Value> struct integer_c; 5039 /// X<integer_c> xic; 5040 /// \endcode 5041 TPL_TemplateTemplateArgumentMatch 5042 }; 5043 5044 bool TemplateParameterListsAreEqual(TemplateParameterList *New, 5045 TemplateParameterList *Old, 5046 bool Complain, 5047 TemplateParameterListEqualKind Kind, 5048 SourceLocation TemplateArgLoc 5049 = SourceLocation()); 5050 5051 bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); 5052 5053 /// \brief Called when the parser has parsed a C++ typename 5054 /// specifier, e.g., "typename T::type". 5055 /// 5056 /// \param S The scope in which this typename type occurs. 5057 /// \param TypenameLoc the location of the 'typename' keyword 5058 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5059 /// \param II the identifier we're retrieving (e.g., 'type' in the example). 5060 /// \param IdLoc the location of the identifier. 5061 TypeResult 5062 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5063 const CXXScopeSpec &SS, const IdentifierInfo &II, 5064 SourceLocation IdLoc); 5065 5066 /// \brief Called when the parser has parsed a C++ typename 5067 /// specifier that ends in a template-id, e.g., 5068 /// "typename MetaFun::template apply<T1, T2>". 5069 /// 5070 /// \param S The scope in which this typename type occurs. 5071 /// \param TypenameLoc the location of the 'typename' keyword 5072 /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). 5073 /// \param TemplateLoc the location of the 'template' keyword, if any. 5074 /// \param TemplateName The template name. 5075 /// \param TemplateNameLoc The location of the template name. 5076 /// \param LAngleLoc The location of the opening angle bracket ('<'). 5077 /// \param TemplateArgs The template arguments. 5078 /// \param RAngleLoc The location of the closing angle bracket ('>'). 5079 TypeResult 5080 ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, 5081 const CXXScopeSpec &SS, 5082 SourceLocation TemplateLoc, 5083 TemplateTy TemplateName, 5084 SourceLocation TemplateNameLoc, 5085 SourceLocation LAngleLoc, 5086 ASTTemplateArgsPtr TemplateArgs, 5087 SourceLocation RAngleLoc); 5088 5089 QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, 5090 SourceLocation KeywordLoc, 5091 NestedNameSpecifierLoc QualifierLoc, 5092 const IdentifierInfo &II, 5093 SourceLocation IILoc); 5094 5095 TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, 5096 SourceLocation Loc, 5097 DeclarationName Name); 5098 bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); 5099 5100 ExprResult RebuildExprInCurrentInstantiation(Expr *E); 5101 bool RebuildTemplateParamsInCurrentInstantiation( 5102 TemplateParameterList *Params); 5103 5104 std::string 5105 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5106 const TemplateArgumentList &Args); 5107 5108 std::string 5109 getTemplateArgumentBindingsText(const TemplateParameterList *Params, 5110 const TemplateArgument *Args, 5111 unsigned NumArgs); 5112 5113 //===--------------------------------------------------------------------===// 5114 // C++ Variadic Templates (C++0x [temp.variadic]) 5115 //===--------------------------------------------------------------------===// 5116 5117 /// \brief The context in which an unexpanded parameter pack is 5118 /// being diagnosed. 5119 /// 5120 /// Note that the values of this enumeration line up with the first 5121 /// argument to the \c err_unexpanded_parameter_pack diagnostic. 5122 enum UnexpandedParameterPackContext { 5123 /// \brief An arbitrary expression. 5124 UPPC_Expression = 0, 5125 5126 /// \brief The base type of a class type. 5127 UPPC_BaseType, 5128 5129 /// \brief The type of an arbitrary declaration. 5130 UPPC_DeclarationType, 5131 5132 /// \brief The type of a data member. 5133 UPPC_DataMemberType, 5134 5135 /// \brief The size of a bit-field. 5136 UPPC_BitFieldWidth, 5137 5138 /// \brief The expression in a static assertion. 5139 UPPC_StaticAssertExpression, 5140 5141 /// \brief The fixed underlying type of an enumeration. 5142 UPPC_FixedUnderlyingType, 5143 5144 /// \brief The enumerator value. 5145 UPPC_EnumeratorValue, 5146 5147 /// \brief A using declaration. 5148 UPPC_UsingDeclaration, 5149 5150 /// \brief A friend declaration. 5151 UPPC_FriendDeclaration, 5152 5153 /// \brief A declaration qualifier. 5154 UPPC_DeclarationQualifier, 5155 5156 /// \brief An initializer. 5157 UPPC_Initializer, 5158 5159 /// \brief A default argument. 5160 UPPC_DefaultArgument, 5161 5162 /// \brief The type of a non-type template parameter. 5163 UPPC_NonTypeTemplateParameterType, 5164 5165 /// \brief The type of an exception. 5166 UPPC_ExceptionType, 5167 5168 /// \brief Partial specialization. 5169 UPPC_PartialSpecialization, 5170 5171 /// \brief Microsoft __if_exists. 5172 UPPC_IfExists, 5173 5174 /// \brief Microsoft __if_not_exists. 5175 UPPC_IfNotExists, 5176 5177 /// \brief Lambda expression. 5178 UPPC_Lambda, 5179 5180 /// \brief Block expression, 5181 UPPC_Block 5182}; 5183 5184 /// \brief Diagnose unexpanded parameter packs. 5185 /// 5186 /// \param Loc The location at which we should emit the diagnostic. 5187 /// 5188 /// \param UPPC The context in which we are diagnosing unexpanded 5189 /// parameter packs. 5190 /// 5191 /// \param Unexpanded the set of unexpanded parameter packs. 5192 /// 5193 /// \returns true if an error occurred, false otherwise. 5194 bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, 5195 UnexpandedParameterPackContext UPPC, 5196 ArrayRef<UnexpandedParameterPack> Unexpanded); 5197 5198 /// \brief If the given type contains an unexpanded parameter pack, 5199 /// diagnose the error. 5200 /// 5201 /// \param Loc The source location where a diagnostc should be emitted. 5202 /// 5203 /// \param T The type that is being checked for unexpanded parameter 5204 /// packs. 5205 /// 5206 /// \returns true if an error occurred, false otherwise. 5207 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, 5208 UnexpandedParameterPackContext UPPC); 5209 5210 /// \brief If the given expression contains an unexpanded parameter 5211 /// pack, diagnose the error. 5212 /// 5213 /// \param E The expression that is being checked for unexpanded 5214 /// parameter packs. 5215 /// 5216 /// \returns true if an error occurred, false otherwise. 5217 bool DiagnoseUnexpandedParameterPack(Expr *E, 5218 UnexpandedParameterPackContext UPPC = UPPC_Expression); 5219 5220 /// \brief If the given nested-name-specifier contains an unexpanded 5221 /// parameter pack, diagnose the error. 5222 /// 5223 /// \param SS The nested-name-specifier that is being checked for 5224 /// unexpanded parameter packs. 5225 /// 5226 /// \returns true if an error occurred, false otherwise. 5227 bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, 5228 UnexpandedParameterPackContext UPPC); 5229 5230 /// \brief If the given name contains an unexpanded parameter pack, 5231 /// diagnose the error. 5232 /// 5233 /// \param NameInfo The name (with source location information) that 5234 /// is being checked for unexpanded parameter packs. 5235 /// 5236 /// \returns true if an error occurred, false otherwise. 5237 bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, 5238 UnexpandedParameterPackContext UPPC); 5239 5240 /// \brief If the given template name contains an unexpanded parameter pack, 5241 /// diagnose the error. 5242 /// 5243 /// \param Loc The location of the template name. 5244 /// 5245 /// \param Template The template name that is being checked for unexpanded 5246 /// parameter packs. 5247 /// 5248 /// \returns true if an error occurred, false otherwise. 5249 bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, 5250 TemplateName Template, 5251 UnexpandedParameterPackContext UPPC); 5252 5253 /// \brief If the given template argument contains an unexpanded parameter 5254 /// pack, diagnose the error. 5255 /// 5256 /// \param Arg The template argument that is being checked for unexpanded 5257 /// parameter packs. 5258 /// 5259 /// \returns true if an error occurred, false otherwise. 5260 bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, 5261 UnexpandedParameterPackContext UPPC); 5262 5263 /// \brief Collect the set of unexpanded parameter packs within the given 5264 /// template argument. 5265 /// 5266 /// \param Arg The template argument that will be traversed to find 5267 /// unexpanded parameter packs. 5268 void collectUnexpandedParameterPacks(TemplateArgument Arg, 5269 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5270 5271 /// \brief Collect the set of unexpanded parameter packs within the given 5272 /// template argument. 5273 /// 5274 /// \param Arg The template argument that will be traversed to find 5275 /// unexpanded parameter packs. 5276 void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, 5277 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5278 5279 /// \brief Collect the set of unexpanded parameter packs within the given 5280 /// type. 5281 /// 5282 /// \param T The type that will be traversed to find 5283 /// unexpanded parameter packs. 5284 void collectUnexpandedParameterPacks(QualType T, 5285 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5286 5287 /// \brief Collect the set of unexpanded parameter packs within the given 5288 /// type. 5289 /// 5290 /// \param TL The type that will be traversed to find 5291 /// unexpanded parameter packs. 5292 void collectUnexpandedParameterPacks(TypeLoc TL, 5293 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5294 5295 /// \brief Collect the set of unexpanded parameter packs within the given 5296 /// nested-name-specifier. 5297 /// 5298 /// \param SS The nested-name-specifier that will be traversed to find 5299 /// unexpanded parameter packs. 5300 void collectUnexpandedParameterPacks(CXXScopeSpec &SS, 5301 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5302 5303 /// \brief Collect the set of unexpanded parameter packs within the given 5304 /// name. 5305 /// 5306 /// \param NameInfo The name that will be traversed to find 5307 /// unexpanded parameter packs. 5308 void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, 5309 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); 5310 5311 /// \brief Invoked when parsing a template argument followed by an 5312 /// ellipsis, which creates a pack expansion. 5313 /// 5314 /// \param Arg The template argument preceding the ellipsis, which 5315 /// may already be invalid. 5316 /// 5317 /// \param EllipsisLoc The location of the ellipsis. 5318 ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, 5319 SourceLocation EllipsisLoc); 5320 5321 /// \brief Invoked when parsing a type followed by an ellipsis, which 5322 /// creates a pack expansion. 5323 /// 5324 /// \param Type The type preceding the ellipsis, which will become 5325 /// the pattern of the pack expansion. 5326 /// 5327 /// \param EllipsisLoc The location of the ellipsis. 5328 TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); 5329 5330 /// \brief Construct a pack expansion type from the pattern of the pack 5331 /// expansion. 5332 TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, 5333 SourceLocation EllipsisLoc, 5334 llvm::Optional<unsigned> NumExpansions); 5335 5336 /// \brief Construct a pack expansion type from the pattern of the pack 5337 /// expansion. 5338 QualType CheckPackExpansion(QualType Pattern, 5339 SourceRange PatternRange, 5340 SourceLocation EllipsisLoc, 5341 llvm::Optional<unsigned> NumExpansions); 5342 5343 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5344 /// creates a pack expansion. 5345 /// 5346 /// \param Pattern The expression preceding the ellipsis, which will become 5347 /// the pattern of the pack expansion. 5348 /// 5349 /// \param EllipsisLoc The location of the ellipsis. 5350 ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); 5351 5352 /// \brief Invoked when parsing an expression followed by an ellipsis, which 5353 /// creates a pack expansion. 5354 /// 5355 /// \param Pattern The expression preceding the ellipsis, which will become 5356 /// the pattern of the pack expansion. 5357 /// 5358 /// \param EllipsisLoc The location of the ellipsis. 5359 ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, 5360 llvm::Optional<unsigned> NumExpansions); 5361 5362 /// \brief Determine whether we could expand a pack expansion with the 5363 /// given set of parameter packs into separate arguments by repeatedly 5364 /// transforming the pattern. 5365 /// 5366 /// \param EllipsisLoc The location of the ellipsis that identifies the 5367 /// pack expansion. 5368 /// 5369 /// \param PatternRange The source range that covers the entire pattern of 5370 /// the pack expansion. 5371 /// 5372 /// \param Unexpanded The set of unexpanded parameter packs within the 5373 /// pattern. 5374 /// 5375 /// \param ShouldExpand Will be set to \c true if the transformer should 5376 /// expand the corresponding pack expansions into separate arguments. When 5377 /// set, \c NumExpansions must also be set. 5378 /// 5379 /// \param RetainExpansion Whether the caller should add an unexpanded 5380 /// pack expansion after all of the expanded arguments. This is used 5381 /// when extending explicitly-specified template argument packs per 5382 /// C++0x [temp.arg.explicit]p9. 5383 /// 5384 /// \param NumExpansions The number of separate arguments that will be in 5385 /// the expanded form of the corresponding pack expansion. This is both an 5386 /// input and an output parameter, which can be set by the caller if the 5387 /// number of expansions is known a priori (e.g., due to a prior substitution) 5388 /// and will be set by the callee when the number of expansions is known. 5389 /// The callee must set this value when \c ShouldExpand is \c true; it may 5390 /// set this value in other cases. 5391 /// 5392 /// \returns true if an error occurred (e.g., because the parameter packs 5393 /// are to be instantiated with arguments of different lengths), false 5394 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) 5395 /// must be set. 5396 bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, 5397 SourceRange PatternRange, 5398 ArrayRef<UnexpandedParameterPack> Unexpanded, 5399 const MultiLevelTemplateArgumentList &TemplateArgs, 5400 bool &ShouldExpand, 5401 bool &RetainExpansion, 5402 llvm::Optional<unsigned> &NumExpansions); 5403 5404 /// \brief Determine the number of arguments in the given pack expansion 5405 /// type. 5406 /// 5407 /// This routine assumes that the number of arguments in the expansion is 5408 /// consistent across all of the unexpanded parameter packs in its pattern. 5409 /// 5410 /// Returns an empty Optional if the type can't be expanded. 5411 llvm::Optional<unsigned> getNumArgumentsInExpansion(QualType T, 5412 const MultiLevelTemplateArgumentList &TemplateArgs); 5413 5414 /// \brief Determine whether the given declarator contains any unexpanded 5415 /// parameter packs. 5416 /// 5417 /// This routine is used by the parser to disambiguate function declarators 5418 /// with an ellipsis prior to the ')', e.g., 5419 /// 5420 /// \code 5421 /// void f(T...); 5422 /// \endcode 5423 /// 5424 /// To determine whether we have an (unnamed) function parameter pack or 5425 /// a variadic function. 5426 /// 5427 /// \returns true if the declarator contains any unexpanded parameter packs, 5428 /// false otherwise. 5429 bool containsUnexpandedParameterPacks(Declarator &D); 5430 5431 //===--------------------------------------------------------------------===// 5432 // C++ Template Argument Deduction (C++ [temp.deduct]) 5433 //===--------------------------------------------------------------------===// 5434 5435 /// \brief Describes the result of template argument deduction. 5436 /// 5437 /// The TemplateDeductionResult enumeration describes the result of 5438 /// template argument deduction, as returned from 5439 /// DeduceTemplateArguments(). The separate TemplateDeductionInfo 5440 /// structure provides additional information about the results of 5441 /// template argument deduction, e.g., the deduced template argument 5442 /// list (if successful) or the specific template parameters or 5443 /// deduced arguments that were involved in the failure. 5444 enum TemplateDeductionResult { 5445 /// \brief Template argument deduction was successful. 5446 TDK_Success = 0, 5447 /// \brief The declaration was invalid; do nothing. 5448 TDK_Invalid, 5449 /// \brief Template argument deduction exceeded the maximum template 5450 /// instantiation depth (which has already been diagnosed). 5451 TDK_InstantiationDepth, 5452 /// \brief Template argument deduction did not deduce a value 5453 /// for every template parameter. 5454 TDK_Incomplete, 5455 /// \brief Template argument deduction produced inconsistent 5456 /// deduced values for the given template parameter. 5457 TDK_Inconsistent, 5458 /// \brief Template argument deduction failed due to inconsistent 5459 /// cv-qualifiers on a template parameter type that would 5460 /// otherwise be deduced, e.g., we tried to deduce T in "const T" 5461 /// but were given a non-const "X". 5462 TDK_Underqualified, 5463 /// \brief Substitution of the deduced template argument values 5464 /// resulted in an error. 5465 TDK_SubstitutionFailure, 5466 /// \brief A non-depnedent component of the parameter did not match the 5467 /// corresponding component of the argument. 5468 TDK_NonDeducedMismatch, 5469 /// \brief When performing template argument deduction for a function 5470 /// template, there were too many call arguments. 5471 TDK_TooManyArguments, 5472 /// \brief When performing template argument deduction for a function 5473 /// template, there were too few call arguments. 5474 TDK_TooFewArguments, 5475 /// \brief The explicitly-specified template arguments were not valid 5476 /// template arguments for the given template. 5477 TDK_InvalidExplicitArguments, 5478 /// \brief The arguments included an overloaded function name that could 5479 /// not be resolved to a suitable function. 5480 TDK_FailedOverloadResolution, 5481 /// \brief Deduction failed; that's all we know. 5482 TDK_MiscellaneousDeductionFailure 5483 }; 5484 5485 TemplateDeductionResult 5486 DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, 5487 const TemplateArgumentList &TemplateArgs, 5488 sema::TemplateDeductionInfo &Info); 5489 5490 TemplateDeductionResult 5491 SubstituteExplicitTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5492 TemplateArgumentListInfo &ExplicitTemplateArgs, 5493 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5494 SmallVectorImpl<QualType> &ParamTypes, 5495 QualType *FunctionType, 5496 sema::TemplateDeductionInfo &Info); 5497 5498 /// brief A function argument from which we performed template argument 5499 // deduction for a call. 5500 struct OriginalCallArg { 5501 OriginalCallArg(QualType OriginalParamType, 5502 unsigned ArgIdx, 5503 QualType OriginalArgType) 5504 : OriginalParamType(OriginalParamType), ArgIdx(ArgIdx), 5505 OriginalArgType(OriginalArgType) { } 5506 5507 QualType OriginalParamType; 5508 unsigned ArgIdx; 5509 QualType OriginalArgType; 5510 }; 5511 5512 TemplateDeductionResult 5513 FinishTemplateArgumentDeduction(FunctionTemplateDecl *FunctionTemplate, 5514 SmallVectorImpl<DeducedTemplateArgument> &Deduced, 5515 unsigned NumExplicitlySpecified, 5516 FunctionDecl *&Specialization, 5517 sema::TemplateDeductionInfo &Info, 5518 SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = 0); 5519 5520 TemplateDeductionResult 5521 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5522 TemplateArgumentListInfo *ExplicitTemplateArgs, 5523 ArrayRef<Expr *> Args, 5524 FunctionDecl *&Specialization, 5525 sema::TemplateDeductionInfo &Info); 5526 5527 TemplateDeductionResult 5528 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5529 TemplateArgumentListInfo *ExplicitTemplateArgs, 5530 QualType ArgFunctionType, 5531 FunctionDecl *&Specialization, 5532 sema::TemplateDeductionInfo &Info); 5533 5534 TemplateDeductionResult 5535 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5536 QualType ToType, 5537 CXXConversionDecl *&Specialization, 5538 sema::TemplateDeductionInfo &Info); 5539 5540 TemplateDeductionResult 5541 DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, 5542 TemplateArgumentListInfo *ExplicitTemplateArgs, 5543 FunctionDecl *&Specialization, 5544 sema::TemplateDeductionInfo &Info); 5545 5546 /// \brief Result type of DeduceAutoType. 5547 enum DeduceAutoResult { 5548 DAR_Succeeded, 5549 DAR_Failed, 5550 DAR_FailedAlreadyDiagnosed 5551 }; 5552 5553 DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, 5554 TypeSourceInfo *&Result); 5555 void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); 5556 5557 FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, 5558 FunctionTemplateDecl *FT2, 5559 SourceLocation Loc, 5560 TemplatePartialOrderingContext TPOC, 5561 unsigned NumCallArguments); 5562 UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, 5563 UnresolvedSetIterator SEnd, 5564 TemplatePartialOrderingContext TPOC, 5565 unsigned NumCallArguments, 5566 SourceLocation Loc, 5567 const PartialDiagnostic &NoneDiag, 5568 const PartialDiagnostic &AmbigDiag, 5569 const PartialDiagnostic &CandidateDiag, 5570 bool Complain = true, 5571 QualType TargetType = QualType()); 5572 5573 ClassTemplatePartialSpecializationDecl * 5574 getMoreSpecializedPartialSpecialization( 5575 ClassTemplatePartialSpecializationDecl *PS1, 5576 ClassTemplatePartialSpecializationDecl *PS2, 5577 SourceLocation Loc); 5578 5579 void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, 5580 bool OnlyDeduced, 5581 unsigned Depth, 5582 llvm::SmallBitVector &Used); 5583 void MarkDeducedTemplateParameters( 5584 const FunctionTemplateDecl *FunctionTemplate, 5585 llvm::SmallBitVector &Deduced) { 5586 return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); 5587 } 5588 static void MarkDeducedTemplateParameters(ASTContext &Ctx, 5589 const FunctionTemplateDecl *FunctionTemplate, 5590 llvm::SmallBitVector &Deduced); 5591 5592 //===--------------------------------------------------------------------===// 5593 // C++ Template Instantiation 5594 // 5595 5596 MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, 5597 const TemplateArgumentList *Innermost = 0, 5598 bool RelativeToPrimary = false, 5599 const FunctionDecl *Pattern = 0); 5600 5601 /// \brief A template instantiation that is currently in progress. 5602 struct ActiveTemplateInstantiation { 5603 /// \brief The kind of template instantiation we are performing 5604 enum InstantiationKind { 5605 /// We are instantiating a template declaration. The entity is 5606 /// the declaration we're instantiating (e.g., a CXXRecordDecl). 5607 TemplateInstantiation, 5608 5609 /// We are instantiating a default argument for a template 5610 /// parameter. The Entity is the template, and 5611 /// TemplateArgs/NumTemplateArguments provides the template 5612 /// arguments as specified. 5613 /// FIXME: Use a TemplateArgumentList 5614 DefaultTemplateArgumentInstantiation, 5615 5616 /// We are instantiating a default argument for a function. 5617 /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs 5618 /// provides the template arguments as specified. 5619 DefaultFunctionArgumentInstantiation, 5620 5621 /// We are substituting explicit template arguments provided for 5622 /// a function template. The entity is a FunctionTemplateDecl. 5623 ExplicitTemplateArgumentSubstitution, 5624 5625 /// We are substituting template argument determined as part of 5626 /// template argument deduction for either a class template 5627 /// partial specialization or a function template. The 5628 /// Entity is either a ClassTemplatePartialSpecializationDecl or 5629 /// a FunctionTemplateDecl. 5630 DeducedTemplateArgumentSubstitution, 5631 5632 /// We are substituting prior template arguments into a new 5633 /// template parameter. The template parameter itself is either a 5634 /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. 5635 PriorTemplateArgumentSubstitution, 5636 5637 /// We are checking the validity of a default template argument that 5638 /// has been used when naming a template-id. 5639 DefaultTemplateArgumentChecking, 5640 5641 /// We are instantiating the exception specification for a function 5642 /// template which was deferred until it was needed. 5643 ExceptionSpecInstantiation 5644 } Kind; 5645 5646 /// \brief The point of instantiation within the source code. 5647 SourceLocation PointOfInstantiation; 5648 5649 /// \brief The template (or partial specialization) in which we are 5650 /// performing the instantiation, for substitutions of prior template 5651 /// arguments. 5652 NamedDecl *Template; 5653 5654 /// \brief The entity that is being instantiated. 5655 Decl *Entity; 5656 5657 /// \brief The list of template arguments we are substituting, if they 5658 /// are not part of the entity. 5659 const TemplateArgument *TemplateArgs; 5660 5661 /// \brief The number of template arguments in TemplateArgs. 5662 unsigned NumTemplateArgs; 5663 5664 /// \brief The template deduction info object associated with the 5665 /// substitution or checking of explicit or deduced template arguments. 5666 sema::TemplateDeductionInfo *DeductionInfo; 5667 5668 /// \brief The source range that covers the construct that cause 5669 /// the instantiation, e.g., the template-id that causes a class 5670 /// template instantiation. 5671 SourceRange InstantiationRange; 5672 5673 ActiveTemplateInstantiation() 5674 : Kind(TemplateInstantiation), Template(0), Entity(0), TemplateArgs(0), 5675 NumTemplateArgs(0), DeductionInfo(0) {} 5676 5677 /// \brief Determines whether this template is an actual instantiation 5678 /// that should be counted toward the maximum instantiation depth. 5679 bool isInstantiationRecord() const; 5680 5681 friend bool operator==(const ActiveTemplateInstantiation &X, 5682 const ActiveTemplateInstantiation &Y) { 5683 if (X.Kind != Y.Kind) 5684 return false; 5685 5686 if (X.Entity != Y.Entity) 5687 return false; 5688 5689 switch (X.Kind) { 5690 case TemplateInstantiation: 5691 case ExceptionSpecInstantiation: 5692 return true; 5693 5694 case PriorTemplateArgumentSubstitution: 5695 case DefaultTemplateArgumentChecking: 5696 if (X.Template != Y.Template) 5697 return false; 5698 5699 // Fall through 5700 5701 case DefaultTemplateArgumentInstantiation: 5702 case ExplicitTemplateArgumentSubstitution: 5703 case DeducedTemplateArgumentSubstitution: 5704 case DefaultFunctionArgumentInstantiation: 5705 return X.TemplateArgs == Y.TemplateArgs; 5706 5707 } 5708 5709 llvm_unreachable("Invalid InstantiationKind!"); 5710 } 5711 5712 friend bool operator!=(const ActiveTemplateInstantiation &X, 5713 const ActiveTemplateInstantiation &Y) { 5714 return !(X == Y); 5715 } 5716 }; 5717 5718 /// \brief List of active template instantiations. 5719 /// 5720 /// This vector is treated as a stack. As one template instantiation 5721 /// requires another template instantiation, additional 5722 /// instantiations are pushed onto the stack up to a 5723 /// user-configurable limit LangOptions::InstantiationDepth. 5724 SmallVector<ActiveTemplateInstantiation, 16> 5725 ActiveTemplateInstantiations; 5726 5727 /// \brief Whether we are in a SFINAE context that is not associated with 5728 /// template instantiation. 5729 /// 5730 /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside 5731 /// of a template instantiation or template argument deduction. 5732 bool InNonInstantiationSFINAEContext; 5733 5734 /// \brief The number of ActiveTemplateInstantiation entries in 5735 /// \c ActiveTemplateInstantiations that are not actual instantiations and, 5736 /// therefore, should not be counted as part of the instantiation depth. 5737 unsigned NonInstantiationEntries; 5738 5739 /// \brief The last template from which a template instantiation 5740 /// error or warning was produced. 5741 /// 5742 /// This value is used to suppress printing of redundant template 5743 /// instantiation backtraces when there are multiple errors in the 5744 /// same instantiation. FIXME: Does this belong in Sema? It's tough 5745 /// to implement it anywhere else. 5746 ActiveTemplateInstantiation LastTemplateInstantiationErrorContext; 5747 5748 /// \brief The current index into pack expansion arguments that will be 5749 /// used for substitution of parameter packs. 5750 /// 5751 /// The pack expansion index will be -1 to indicate that parameter packs 5752 /// should be instantiated as themselves. Otherwise, the index specifies 5753 /// which argument within the parameter pack will be used for substitution. 5754 int ArgumentPackSubstitutionIndex; 5755 5756 /// \brief RAII object used to change the argument pack substitution index 5757 /// within a \c Sema object. 5758 /// 5759 /// See \c ArgumentPackSubstitutionIndex for more information. 5760 class ArgumentPackSubstitutionIndexRAII { 5761 Sema &Self; 5762 int OldSubstitutionIndex; 5763 5764 public: 5765 ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) 5766 : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { 5767 Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; 5768 } 5769 5770 ~ArgumentPackSubstitutionIndexRAII() { 5771 Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; 5772 } 5773 }; 5774 5775 friend class ArgumentPackSubstitutionRAII; 5776 5777 /// \brief The stack of calls expression undergoing template instantiation. 5778 /// 5779 /// The top of this stack is used by a fixit instantiating unresolved 5780 /// function calls to fix the AST to match the textual change it prints. 5781 SmallVector<CallExpr *, 8> CallsUndergoingInstantiation; 5782 5783 /// \brief For each declaration that involved template argument deduction, the 5784 /// set of diagnostics that were suppressed during that template argument 5785 /// deduction. 5786 /// 5787 /// FIXME: Serialize this structure to the AST file. 5788 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > 5789 SuppressedDiagnostics; 5790 5791 /// \brief A stack object to be created when performing template 5792 /// instantiation. 5793 /// 5794 /// Construction of an object of type \c InstantiatingTemplate 5795 /// pushes the current instantiation onto the stack of active 5796 /// instantiations. If the size of this stack exceeds the maximum 5797 /// number of recursive template instantiations, construction 5798 /// produces an error and evaluates true. 5799 /// 5800 /// Destruction of this object will pop the named instantiation off 5801 /// the stack. 5802 struct InstantiatingTemplate { 5803 /// \brief Note that we are instantiating a class template, 5804 /// function template, or a member thereof. 5805 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5806 Decl *Entity, 5807 SourceRange InstantiationRange = SourceRange()); 5808 5809 struct ExceptionSpecification {}; 5810 /// \brief Note that we are instantiating an exception specification 5811 /// of a function template. 5812 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5813 FunctionDecl *Entity, ExceptionSpecification, 5814 SourceRange InstantiationRange = SourceRange()); 5815 5816 /// \brief Note that we are instantiating a default argument in a 5817 /// template-id. 5818 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5819 TemplateDecl *Template, 5820 ArrayRef<TemplateArgument> TemplateArgs, 5821 SourceRange InstantiationRange = SourceRange()); 5822 5823 /// \brief Note that we are instantiating a default argument in a 5824 /// template-id. 5825 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5826 FunctionTemplateDecl *FunctionTemplate, 5827 ArrayRef<TemplateArgument> TemplateArgs, 5828 ActiveTemplateInstantiation::InstantiationKind Kind, 5829 sema::TemplateDeductionInfo &DeductionInfo, 5830 SourceRange InstantiationRange = SourceRange()); 5831 5832 /// \brief Note that we are instantiating as part of template 5833 /// argument deduction for a class template partial 5834 /// specialization. 5835 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5836 ClassTemplatePartialSpecializationDecl *PartialSpec, 5837 ArrayRef<TemplateArgument> TemplateArgs, 5838 sema::TemplateDeductionInfo &DeductionInfo, 5839 SourceRange InstantiationRange = SourceRange()); 5840 5841 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5842 ParmVarDecl *Param, 5843 ArrayRef<TemplateArgument> TemplateArgs, 5844 SourceRange InstantiationRange = SourceRange()); 5845 5846 /// \brief Note that we are substituting prior template arguments into a 5847 /// non-type or template template parameter. 5848 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5849 NamedDecl *Template, 5850 NonTypeTemplateParmDecl *Param, 5851 ArrayRef<TemplateArgument> TemplateArgs, 5852 SourceRange InstantiationRange); 5853 5854 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5855 NamedDecl *Template, 5856 TemplateTemplateParmDecl *Param, 5857 ArrayRef<TemplateArgument> TemplateArgs, 5858 SourceRange InstantiationRange); 5859 5860 /// \brief Note that we are checking the default template argument 5861 /// against the template parameter for a given template-id. 5862 InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, 5863 TemplateDecl *Template, 5864 NamedDecl *Param, 5865 ArrayRef<TemplateArgument> TemplateArgs, 5866 SourceRange InstantiationRange); 5867 5868 5869 /// \brief Note that we have finished instantiating this template. 5870 void Clear(); 5871 5872 ~InstantiatingTemplate() { Clear(); } 5873 5874 /// \brief Determines whether we have exceeded the maximum 5875 /// recursive template instantiations. 5876 operator bool() const { return Invalid; } 5877 5878 private: 5879 Sema &SemaRef; 5880 bool Invalid; 5881 bool SavedInNonInstantiationSFINAEContext; 5882 bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, 5883 SourceRange InstantiationRange); 5884 5885 InstantiatingTemplate(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 5886 5887 InstantiatingTemplate& 5888 operator=(const InstantiatingTemplate&) LLVM_DELETED_FUNCTION; 5889 }; 5890 5891 void PrintInstantiationStack(); 5892 5893 /// \brief Determines whether we are currently in a context where 5894 /// template argument substitution failures are not considered 5895 /// errors. 5896 /// 5897 /// \returns An empty \c llvm::Optional if we're not in a SFINAE context. 5898 /// Otherwise, contains a pointer that, if non-NULL, contains the nearest 5899 /// template-deduction context object, which can be used to capture 5900 /// diagnostics that will be suppressed. 5901 llvm::Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; 5902 5903 /// \brief Determines whether we are currently in a context that 5904 /// is not evaluated as per C++ [expr] p5. 5905 bool isUnevaluatedContext() const { 5906 assert(!ExprEvalContexts.empty() && 5907 "Must be in an expression evaluation context"); 5908 return ExprEvalContexts.back().Context == Sema::Unevaluated; 5909 } 5910 5911 /// \brief RAII class used to determine whether SFINAE has 5912 /// trapped any errors that occur during template argument 5913 /// deduction.` 5914 class SFINAETrap { 5915 Sema &SemaRef; 5916 unsigned PrevSFINAEErrors; 5917 bool PrevInNonInstantiationSFINAEContext; 5918 bool PrevAccessCheckingSFINAE; 5919 5920 public: 5921 explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) 5922 : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), 5923 PrevInNonInstantiationSFINAEContext( 5924 SemaRef.InNonInstantiationSFINAEContext), 5925 PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE) 5926 { 5927 if (!SemaRef.isSFINAEContext()) 5928 SemaRef.InNonInstantiationSFINAEContext = true; 5929 SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; 5930 } 5931 5932 ~SFINAETrap() { 5933 SemaRef.NumSFINAEErrors = PrevSFINAEErrors; 5934 SemaRef.InNonInstantiationSFINAEContext 5935 = PrevInNonInstantiationSFINAEContext; 5936 SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; 5937 } 5938 5939 /// \brief Determine whether any SFINAE errors have been trapped. 5940 bool hasErrorOccurred() const { 5941 return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; 5942 } 5943 }; 5944 5945 /// \brief The current instantiation scope used to store local 5946 /// variables. 5947 LocalInstantiationScope *CurrentInstantiationScope; 5948 5949 /// \brief The number of typos corrected by CorrectTypo. 5950 unsigned TyposCorrected; 5951 5952 typedef llvm::DenseMap<IdentifierInfo *, TypoCorrection> 5953 UnqualifiedTyposCorrectedMap; 5954 5955 /// \brief A cache containing the results of typo correction for unqualified 5956 /// name lookup. 5957 /// 5958 /// The string is the string that we corrected to (which may be empty, if 5959 /// there was no correction), while the boolean will be true when the 5960 /// string represents a keyword. 5961 UnqualifiedTyposCorrectedMap UnqualifiedTyposCorrected; 5962 5963 /// \brief Worker object for performing CFG-based warnings. 5964 sema::AnalysisBasedWarnings AnalysisWarnings; 5965 5966 /// \brief An entity for which implicit template instantiation is required. 5967 /// 5968 /// The source location associated with the declaration is the first place in 5969 /// the source code where the declaration was "used". It is not necessarily 5970 /// the point of instantiation (which will be either before or after the 5971 /// namespace-scope declaration that triggered this implicit instantiation), 5972 /// However, it is the location that diagnostics should generally refer to, 5973 /// because users will need to know what code triggered the instantiation. 5974 typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; 5975 5976 /// \brief The queue of implicit template instantiations that are required 5977 /// but have not yet been performed. 5978 std::deque<PendingImplicitInstantiation> PendingInstantiations; 5979 5980 /// \brief The queue of implicit template instantiations that are required 5981 /// and must be performed within the current local scope. 5982 /// 5983 /// This queue is only used for member functions of local classes in 5984 /// templates, which must be instantiated in the same scope as their 5985 /// enclosing function, so that they can reference function-local 5986 /// types, static variables, enumerators, etc. 5987 std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; 5988 5989 void PerformPendingInstantiations(bool LocalOnly = false); 5990 5991 TypeSourceInfo *SubstType(TypeSourceInfo *T, 5992 const MultiLevelTemplateArgumentList &TemplateArgs, 5993 SourceLocation Loc, DeclarationName Entity); 5994 5995 QualType SubstType(QualType T, 5996 const MultiLevelTemplateArgumentList &TemplateArgs, 5997 SourceLocation Loc, DeclarationName Entity); 5998 5999 TypeSourceInfo *SubstType(TypeLoc TL, 6000 const MultiLevelTemplateArgumentList &TemplateArgs, 6001 SourceLocation Loc, DeclarationName Entity); 6002 6003 TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, 6004 const MultiLevelTemplateArgumentList &TemplateArgs, 6005 SourceLocation Loc, 6006 DeclarationName Entity, 6007 CXXRecordDecl *ThisContext, 6008 unsigned ThisTypeQuals); 6009 ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, 6010 const MultiLevelTemplateArgumentList &TemplateArgs, 6011 int indexAdjustment, 6012 llvm::Optional<unsigned> NumExpansions, 6013 bool ExpectParameterPack); 6014 bool SubstParmTypes(SourceLocation Loc, 6015 ParmVarDecl **Params, unsigned NumParams, 6016 const MultiLevelTemplateArgumentList &TemplateArgs, 6017 SmallVectorImpl<QualType> &ParamTypes, 6018 SmallVectorImpl<ParmVarDecl *> *OutParams = 0); 6019 ExprResult SubstExpr(Expr *E, 6020 const MultiLevelTemplateArgumentList &TemplateArgs); 6021 6022 /// \brief Substitute the given template arguments into a list of 6023 /// expressions, expanding pack expansions if required. 6024 /// 6025 /// \param Exprs The list of expressions to substitute into. 6026 /// 6027 /// \param NumExprs The number of expressions in \p Exprs. 6028 /// 6029 /// \param IsCall Whether this is some form of call, in which case 6030 /// default arguments will be dropped. 6031 /// 6032 /// \param TemplateArgs The set of template arguments to substitute. 6033 /// 6034 /// \param Outputs Will receive all of the substituted arguments. 6035 /// 6036 /// \returns true if an error occurred, false otherwise. 6037 bool SubstExprs(Expr **Exprs, unsigned NumExprs, bool IsCall, 6038 const MultiLevelTemplateArgumentList &TemplateArgs, 6039 SmallVectorImpl<Expr *> &Outputs); 6040 6041 StmtResult SubstStmt(Stmt *S, 6042 const MultiLevelTemplateArgumentList &TemplateArgs); 6043 6044 Decl *SubstDecl(Decl *D, DeclContext *Owner, 6045 const MultiLevelTemplateArgumentList &TemplateArgs); 6046 6047 ExprResult SubstInitializer(Expr *E, 6048 const MultiLevelTemplateArgumentList &TemplateArgs, 6049 bool CXXDirectInit); 6050 6051 bool 6052 SubstBaseSpecifiers(CXXRecordDecl *Instantiation, 6053 CXXRecordDecl *Pattern, 6054 const MultiLevelTemplateArgumentList &TemplateArgs); 6055 6056 bool 6057 InstantiateClass(SourceLocation PointOfInstantiation, 6058 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, 6059 const MultiLevelTemplateArgumentList &TemplateArgs, 6060 TemplateSpecializationKind TSK, 6061 bool Complain = true); 6062 6063 bool InstantiateEnum(SourceLocation PointOfInstantiation, 6064 EnumDecl *Instantiation, EnumDecl *Pattern, 6065 const MultiLevelTemplateArgumentList &TemplateArgs, 6066 TemplateSpecializationKind TSK); 6067 6068 struct LateInstantiatedAttribute { 6069 const Attr *TmplAttr; 6070 LocalInstantiationScope *Scope; 6071 Decl *NewDecl; 6072 6073 LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, 6074 Decl *D) 6075 : TmplAttr(A), Scope(S), NewDecl(D) 6076 { } 6077 }; 6078 typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; 6079 6080 void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, 6081 const Decl *Pattern, Decl *Inst, 6082 LateInstantiatedAttrVec *LateAttrs = 0, 6083 LocalInstantiationScope *OuterMostScope = 0); 6084 6085 bool 6086 InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, 6087 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6088 TemplateSpecializationKind TSK, 6089 bool Complain = true); 6090 6091 void InstantiateClassMembers(SourceLocation PointOfInstantiation, 6092 CXXRecordDecl *Instantiation, 6093 const MultiLevelTemplateArgumentList &TemplateArgs, 6094 TemplateSpecializationKind TSK); 6095 6096 void InstantiateClassTemplateSpecializationMembers( 6097 SourceLocation PointOfInstantiation, 6098 ClassTemplateSpecializationDecl *ClassTemplateSpec, 6099 TemplateSpecializationKind TSK); 6100 6101 NestedNameSpecifierLoc 6102 SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, 6103 const MultiLevelTemplateArgumentList &TemplateArgs); 6104 6105 DeclarationNameInfo 6106 SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, 6107 const MultiLevelTemplateArgumentList &TemplateArgs); 6108 TemplateName 6109 SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, 6110 SourceLocation Loc, 6111 const MultiLevelTemplateArgumentList &TemplateArgs); 6112 bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, 6113 TemplateArgumentListInfo &Result, 6114 const MultiLevelTemplateArgumentList &TemplateArgs); 6115 6116 void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, 6117 FunctionDecl *Function); 6118 void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, 6119 FunctionDecl *Function, 6120 bool Recursive = false, 6121 bool DefinitionRequired = false); 6122 void InstantiateStaticDataMemberDefinition( 6123 SourceLocation PointOfInstantiation, 6124 VarDecl *Var, 6125 bool Recursive = false, 6126 bool DefinitionRequired = false); 6127 6128 void InstantiateMemInitializers(CXXConstructorDecl *New, 6129 const CXXConstructorDecl *Tmpl, 6130 const MultiLevelTemplateArgumentList &TemplateArgs); 6131 6132 NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, 6133 const MultiLevelTemplateArgumentList &TemplateArgs); 6134 DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, 6135 const MultiLevelTemplateArgumentList &TemplateArgs); 6136 6137 // Objective-C declarations. 6138 enum ObjCContainerKind { 6139 OCK_None = -1, 6140 OCK_Interface = 0, 6141 OCK_Protocol, 6142 OCK_Category, 6143 OCK_ClassExtension, 6144 OCK_Implementation, 6145 OCK_CategoryImplementation 6146 }; 6147 ObjCContainerKind getObjCContainerKind() const; 6148 6149 Decl *ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 6150 IdentifierInfo *ClassName, 6151 SourceLocation ClassLoc, 6152 IdentifierInfo *SuperName, 6153 SourceLocation SuperLoc, 6154 Decl * const *ProtoRefs, 6155 unsigned NumProtoRefs, 6156 const SourceLocation *ProtoLocs, 6157 SourceLocation EndProtoLoc, 6158 AttributeList *AttrList); 6159 6160 Decl *ActOnCompatibilityAlias( 6161 SourceLocation AtCompatibilityAliasLoc, 6162 IdentifierInfo *AliasName, SourceLocation AliasLocation, 6163 IdentifierInfo *ClassName, SourceLocation ClassLocation); 6164 6165 bool CheckForwardProtocolDeclarationForCircularDependency( 6166 IdentifierInfo *PName, 6167 SourceLocation &PLoc, SourceLocation PrevLoc, 6168 const ObjCList<ObjCProtocolDecl> &PList); 6169 6170 Decl *ActOnStartProtocolInterface( 6171 SourceLocation AtProtoInterfaceLoc, 6172 IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, 6173 Decl * const *ProtoRefNames, unsigned NumProtoRefs, 6174 const SourceLocation *ProtoLocs, 6175 SourceLocation EndProtoLoc, 6176 AttributeList *AttrList); 6177 6178 Decl *ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 6179 IdentifierInfo *ClassName, 6180 SourceLocation ClassLoc, 6181 IdentifierInfo *CategoryName, 6182 SourceLocation CategoryLoc, 6183 Decl * const *ProtoRefs, 6184 unsigned NumProtoRefs, 6185 const SourceLocation *ProtoLocs, 6186 SourceLocation EndProtoLoc); 6187 6188 Decl *ActOnStartClassImplementation( 6189 SourceLocation AtClassImplLoc, 6190 IdentifierInfo *ClassName, SourceLocation ClassLoc, 6191 IdentifierInfo *SuperClassname, 6192 SourceLocation SuperClassLoc); 6193 6194 Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, 6195 IdentifierInfo *ClassName, 6196 SourceLocation ClassLoc, 6197 IdentifierInfo *CatName, 6198 SourceLocation CatLoc); 6199 6200 DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, 6201 ArrayRef<Decl *> Decls); 6202 6203 DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, 6204 IdentifierInfo **IdentList, 6205 SourceLocation *IdentLocs, 6206 unsigned NumElts); 6207 6208 DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, 6209 const IdentifierLocPair *IdentList, 6210 unsigned NumElts, 6211 AttributeList *attrList); 6212 6213 void FindProtocolDeclaration(bool WarnOnDeclarations, 6214 const IdentifierLocPair *ProtocolId, 6215 unsigned NumProtocols, 6216 SmallVectorImpl<Decl *> &Protocols); 6217 6218 /// Ensure attributes are consistent with type. 6219 /// \param [in, out] Attributes The attributes to check; they will 6220 /// be modified to be consistent with \p PropertyTy. 6221 void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, 6222 SourceLocation Loc, 6223 unsigned &Attributes, 6224 bool propertyInPrimaryClass); 6225 6226 /// Process the specified property declaration and create decls for the 6227 /// setters and getters as needed. 6228 /// \param property The property declaration being processed 6229 /// \param CD The semantic container for the property 6230 /// \param redeclaredProperty Declaration for property if redeclared 6231 /// in class extension. 6232 /// \param lexicalDC Container for redeclaredProperty. 6233 void ProcessPropertyDecl(ObjCPropertyDecl *property, 6234 ObjCContainerDecl *CD, 6235 ObjCPropertyDecl *redeclaredProperty = 0, 6236 ObjCContainerDecl *lexicalDC = 0); 6237 6238 6239 void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 6240 ObjCPropertyDecl *SuperProperty, 6241 const IdentifierInfo *Name); 6242 6243 void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 6244 ObjCInterfaceDecl *ID); 6245 6246 void MatchOneProtocolPropertiesInClass(Decl *CDecl, 6247 ObjCProtocolDecl *PDecl); 6248 6249 Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, 6250 Decl **allMethods = 0, unsigned allNum = 0, 6251 Decl **allProperties = 0, unsigned pNum = 0, 6252 DeclGroupPtrTy *allTUVars = 0, unsigned tuvNum = 0); 6253 6254 Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, 6255 SourceLocation LParenLoc, 6256 FieldDeclarator &FD, ObjCDeclSpec &ODS, 6257 Selector GetterSel, Selector SetterSel, 6258 bool *OverridingProperty, 6259 tok::ObjCKeywordKind MethodImplKind, 6260 DeclContext *lexicalDC = 0); 6261 6262 Decl *ActOnPropertyImplDecl(Scope *S, 6263 SourceLocation AtLoc, 6264 SourceLocation PropertyLoc, 6265 bool ImplKind, 6266 IdentifierInfo *PropertyId, 6267 IdentifierInfo *PropertyIvar, 6268 SourceLocation PropertyIvarLoc); 6269 6270 enum ObjCSpecialMethodKind { 6271 OSMK_None, 6272 OSMK_Alloc, 6273 OSMK_New, 6274 OSMK_Copy, 6275 OSMK_RetainingInit, 6276 OSMK_NonRetainingInit 6277 }; 6278 6279 struct ObjCArgInfo { 6280 IdentifierInfo *Name; 6281 SourceLocation NameLoc; 6282 // The Type is null if no type was specified, and the DeclSpec is invalid 6283 // in this case. 6284 ParsedType Type; 6285 ObjCDeclSpec DeclSpec; 6286 6287 /// ArgAttrs - Attribute list for this argument. 6288 AttributeList *ArgAttrs; 6289 }; 6290 6291 Decl *ActOnMethodDeclaration( 6292 Scope *S, 6293 SourceLocation BeginLoc, // location of the + or -. 6294 SourceLocation EndLoc, // location of the ; or {. 6295 tok::TokenKind MethodType, 6296 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 6297 ArrayRef<SourceLocation> SelectorLocs, Selector Sel, 6298 // optional arguments. The number of types/arguments is obtained 6299 // from the Sel.getNumArgs(). 6300 ObjCArgInfo *ArgInfo, 6301 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 6302 AttributeList *AttrList, tok::ObjCKeywordKind MethodImplKind, 6303 bool isVariadic, bool MethodDefinition); 6304 6305 ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, 6306 const ObjCObjectPointerType *OPT, 6307 bool IsInstance); 6308 ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, 6309 bool IsInstance); 6310 6311 bool inferObjCARCLifetime(ValueDecl *decl); 6312 6313 ExprResult 6314 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 6315 Expr *BaseExpr, 6316 SourceLocation OpLoc, 6317 DeclarationName MemberName, 6318 SourceLocation MemberLoc, 6319 SourceLocation SuperLoc, QualType SuperType, 6320 bool Super); 6321 6322 ExprResult 6323 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 6324 IdentifierInfo &propertyName, 6325 SourceLocation receiverNameLoc, 6326 SourceLocation propertyNameLoc); 6327 6328 ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); 6329 6330 /// \brief Describes the kind of message expression indicated by a message 6331 /// send that starts with an identifier. 6332 enum ObjCMessageKind { 6333 /// \brief The message is sent to 'super'. 6334 ObjCSuperMessage, 6335 /// \brief The message is an instance message. 6336 ObjCInstanceMessage, 6337 /// \brief The message is a class message, and the identifier is a type 6338 /// name. 6339 ObjCClassMessage 6340 }; 6341 6342 ObjCMessageKind getObjCMessageKind(Scope *S, 6343 IdentifierInfo *Name, 6344 SourceLocation NameLoc, 6345 bool IsSuper, 6346 bool HasTrailingDot, 6347 ParsedType &ReceiverType); 6348 6349 ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, 6350 Selector Sel, 6351 SourceLocation LBracLoc, 6352 ArrayRef<SourceLocation> SelectorLocs, 6353 SourceLocation RBracLoc, 6354 MultiExprArg Args); 6355 6356 ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 6357 QualType ReceiverType, 6358 SourceLocation SuperLoc, 6359 Selector Sel, 6360 ObjCMethodDecl *Method, 6361 SourceLocation LBracLoc, 6362 ArrayRef<SourceLocation> SelectorLocs, 6363 SourceLocation RBracLoc, 6364 MultiExprArg Args, 6365 bool isImplicit = false); 6366 6367 ExprResult BuildClassMessageImplicit(QualType ReceiverType, 6368 bool isSuperReceiver, 6369 SourceLocation Loc, 6370 Selector Sel, 6371 ObjCMethodDecl *Method, 6372 MultiExprArg Args); 6373 6374 ExprResult ActOnClassMessage(Scope *S, 6375 ParsedType Receiver, 6376 Selector Sel, 6377 SourceLocation LBracLoc, 6378 ArrayRef<SourceLocation> SelectorLocs, 6379 SourceLocation RBracLoc, 6380 MultiExprArg Args); 6381 6382 ExprResult BuildInstanceMessage(Expr *Receiver, 6383 QualType ReceiverType, 6384 SourceLocation SuperLoc, 6385 Selector Sel, 6386 ObjCMethodDecl *Method, 6387 SourceLocation LBracLoc, 6388 ArrayRef<SourceLocation> SelectorLocs, 6389 SourceLocation RBracLoc, 6390 MultiExprArg Args, 6391 bool isImplicit = false); 6392 6393 ExprResult BuildInstanceMessageImplicit(Expr *Receiver, 6394 QualType ReceiverType, 6395 SourceLocation Loc, 6396 Selector Sel, 6397 ObjCMethodDecl *Method, 6398 MultiExprArg Args); 6399 6400 ExprResult ActOnInstanceMessage(Scope *S, 6401 Expr *Receiver, 6402 Selector Sel, 6403 SourceLocation LBracLoc, 6404 ArrayRef<SourceLocation> SelectorLocs, 6405 SourceLocation RBracLoc, 6406 MultiExprArg Args); 6407 6408 ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, 6409 ObjCBridgeCastKind Kind, 6410 SourceLocation BridgeKeywordLoc, 6411 TypeSourceInfo *TSInfo, 6412 Expr *SubExpr); 6413 6414 ExprResult ActOnObjCBridgedCast(Scope *S, 6415 SourceLocation LParenLoc, 6416 ObjCBridgeCastKind Kind, 6417 SourceLocation BridgeKeywordLoc, 6418 ParsedType Type, 6419 SourceLocation RParenLoc, 6420 Expr *SubExpr); 6421 6422 bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); 6423 6424 /// \brief Check whether the given new method is a valid override of the 6425 /// given overridden method, and set any properties that should be inherited. 6426 void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 6427 const ObjCMethodDecl *Overridden); 6428 6429 /// \brief Describes the compatibility of a result type with its method. 6430 enum ResultTypeCompatibilityKind { 6431 RTC_Compatible, 6432 RTC_Incompatible, 6433 RTC_Unknown 6434 }; 6435 6436 void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 6437 ObjCInterfaceDecl *CurrentClass, 6438 ResultTypeCompatibilityKind RTC); 6439 6440 enum PragmaOptionsAlignKind { 6441 POAK_Native, // #pragma options align=native 6442 POAK_Natural, // #pragma options align=natural 6443 POAK_Packed, // #pragma options align=packed 6444 POAK_Power, // #pragma options align=power 6445 POAK_Mac68k, // #pragma options align=mac68k 6446 POAK_Reset // #pragma options align=reset 6447 }; 6448 6449 /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. 6450 void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, 6451 SourceLocation PragmaLoc); 6452 6453 enum PragmaPackKind { 6454 PPK_Default, // #pragma pack([n]) 6455 PPK_Show, // #pragma pack(show), only supported by MSVC. 6456 PPK_Push, // #pragma pack(push, [identifier], [n]) 6457 PPK_Pop // #pragma pack(pop, [identifier], [n]) 6458 }; 6459 6460 enum PragmaMSStructKind { 6461 PMSST_OFF, // #pragms ms_struct off 6462 PMSST_ON // #pragms ms_struct on 6463 }; 6464 6465 /// ActOnPragmaPack - Called on well formed \#pragma pack(...). 6466 void ActOnPragmaPack(PragmaPackKind Kind, 6467 IdentifierInfo *Name, 6468 Expr *Alignment, 6469 SourceLocation PragmaLoc, 6470 SourceLocation LParenLoc, 6471 SourceLocation RParenLoc); 6472 6473 /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. 6474 void ActOnPragmaMSStruct(PragmaMSStructKind Kind); 6475 6476 /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. 6477 void ActOnPragmaUnused(const Token &Identifier, 6478 Scope *curScope, 6479 SourceLocation PragmaLoc); 6480 6481 /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . 6482 void ActOnPragmaVisibility(const IdentifierInfo* VisType, 6483 SourceLocation PragmaLoc); 6484 6485 NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6486 SourceLocation Loc); 6487 void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); 6488 6489 /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. 6490 void ActOnPragmaWeakID(IdentifierInfo* WeakName, 6491 SourceLocation PragmaLoc, 6492 SourceLocation WeakNameLoc); 6493 6494 /// ActOnPragmaRedefineExtname - Called on well formed 6495 /// \#pragma redefine_extname oldname newname. 6496 void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, 6497 IdentifierInfo* AliasName, 6498 SourceLocation PragmaLoc, 6499 SourceLocation WeakNameLoc, 6500 SourceLocation AliasNameLoc); 6501 6502 /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. 6503 void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, 6504 IdentifierInfo* AliasName, 6505 SourceLocation PragmaLoc, 6506 SourceLocation WeakNameLoc, 6507 SourceLocation AliasNameLoc); 6508 6509 /// ActOnPragmaFPContract - Called on well formed 6510 /// \#pragma {STDC,OPENCL} FP_CONTRACT 6511 void ActOnPragmaFPContract(tok::OnOffSwitch OOS); 6512 6513 /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to 6514 /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. 6515 void AddAlignmentAttributesForRecord(RecordDecl *RD); 6516 6517 /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. 6518 void AddMsStructLayoutForRecord(RecordDecl *RD); 6519 6520 /// FreePackedContext - Deallocate and null out PackContext. 6521 void FreePackedContext(); 6522 6523 /// PushNamespaceVisibilityAttr - Note that we've entered a 6524 /// namespace with a visibility attribute. 6525 void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, 6526 SourceLocation Loc); 6527 6528 /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, 6529 /// add an appropriate visibility attribute. 6530 void AddPushedVisibilityAttribute(Decl *RD); 6531 6532 /// PopPragmaVisibility - Pop the top element of the visibility stack; used 6533 /// for '\#pragma GCC visibility' and visibility attributes on namespaces. 6534 void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); 6535 6536 /// FreeVisContext - Deallocate and null out VisContext. 6537 void FreeVisContext(); 6538 6539 /// AddCFAuditedAttribute - Check whether we're currently within 6540 /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding 6541 /// the appropriate attribute. 6542 void AddCFAuditedAttribute(Decl *D); 6543 6544 /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. 6545 void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 6546 unsigned SpellingListIndex); 6547 void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, 6548 unsigned SpellingListIndex); 6549 6550 /// \brief The kind of conversion being performed. 6551 enum CheckedConversionKind { 6552 /// \brief An implicit conversion. 6553 CCK_ImplicitConversion, 6554 /// \brief A C-style cast. 6555 CCK_CStyleCast, 6556 /// \brief A functional-style cast. 6557 CCK_FunctionalCast, 6558 /// \brief A cast other than a C-style cast. 6559 CCK_OtherCast 6560 }; 6561 6562 /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit 6563 /// cast. If there is already an implicit cast, merge into the existing one. 6564 /// If isLvalue, the result of the cast is an lvalue. 6565 ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, 6566 ExprValueKind VK = VK_RValue, 6567 const CXXCastPath *BasePath = 0, 6568 CheckedConversionKind CCK 6569 = CCK_ImplicitConversion); 6570 6571 /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding 6572 /// to the conversion from scalar type ScalarTy to the Boolean type. 6573 static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); 6574 6575 /// IgnoredValueConversions - Given that an expression's result is 6576 /// syntactically ignored, perform any conversions that are 6577 /// required. 6578 ExprResult IgnoredValueConversions(Expr *E); 6579 6580 // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts 6581 // functions and arrays to their respective pointers (C99 6.3.2.1). 6582 ExprResult UsualUnaryConversions(Expr *E); 6583 6584 // DefaultFunctionArrayConversion - converts functions and arrays 6585 // to their respective pointers (C99 6.3.2.1). 6586 ExprResult DefaultFunctionArrayConversion(Expr *E); 6587 6588 // DefaultFunctionArrayLvalueConversion - converts functions and 6589 // arrays to their respective pointers and performs the 6590 // lvalue-to-rvalue conversion. 6591 ExprResult DefaultFunctionArrayLvalueConversion(Expr *E); 6592 6593 // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on 6594 // the operand. This is DefaultFunctionArrayLvalueConversion, 6595 // except that it assumes the operand isn't of function or array 6596 // type. 6597 ExprResult DefaultLvalueConversion(Expr *E); 6598 6599 // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that 6600 // do not have a prototype. Integer promotions are performed on each 6601 // argument, and arguments that have type float are promoted to double. 6602 ExprResult DefaultArgumentPromotion(Expr *E); 6603 6604 // Used for emitting the right warning by DefaultVariadicArgumentPromotion 6605 enum VariadicCallType { 6606 VariadicFunction, 6607 VariadicBlock, 6608 VariadicMethod, 6609 VariadicConstructor, 6610 VariadicDoesNotApply 6611 }; 6612 6613 VariadicCallType getVariadicCallType(FunctionDecl *FDecl, 6614 const FunctionProtoType *Proto, 6615 Expr *Fn); 6616 6617 // Used for determining in which context a type is allowed to be passed to a 6618 // vararg function. 6619 enum VarArgKind { 6620 VAK_Valid, 6621 VAK_ValidInCXX11, 6622 VAK_Invalid 6623 }; 6624 6625 // Determines which VarArgKind fits an expression. 6626 VarArgKind isValidVarArgType(const QualType &Ty); 6627 6628 /// GatherArgumentsForCall - Collector argument expressions for various 6629 /// form of call prototypes. 6630 bool GatherArgumentsForCall(SourceLocation CallLoc, 6631 FunctionDecl *FDecl, 6632 const FunctionProtoType *Proto, 6633 unsigned FirstProtoArg, 6634 Expr **Args, unsigned NumArgs, 6635 SmallVector<Expr *, 8> &AllArgs, 6636 VariadicCallType CallType = VariadicDoesNotApply, 6637 bool AllowExplicit = false, 6638 bool IsListInitialization = false); 6639 6640 // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but 6641 // will create a runtime trap if the resulting type is not a POD type. 6642 ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, 6643 FunctionDecl *FDecl); 6644 6645 /// Checks to see if the given expression is a valid argument to a variadic 6646 /// function, issuing a diagnostic and returning NULL if not. 6647 bool variadicArgumentPODCheck(const Expr *E, VariadicCallType CT); 6648 6649 // UsualArithmeticConversions - performs the UsualUnaryConversions on it's 6650 // operands and then handles various conversions that are common to binary 6651 // operators (C99 6.3.1.8). If both operands aren't arithmetic, this 6652 // routine returns the first non-arithmetic type found. The client is 6653 // responsible for emitting appropriate error diagnostics. 6654 QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, 6655 bool IsCompAssign = false); 6656 6657 /// AssignConvertType - All of the 'assignment' semantic checks return this 6658 /// enum to indicate whether the assignment was allowed. These checks are 6659 /// done for simple assignments, as well as initialization, return from 6660 /// function, argument passing, etc. The query is phrased in terms of a 6661 /// source and destination type. 6662 enum AssignConvertType { 6663 /// Compatible - the types are compatible according to the standard. 6664 Compatible, 6665 6666 /// PointerToInt - The assignment converts a pointer to an int, which we 6667 /// accept as an extension. 6668 PointerToInt, 6669 6670 /// IntToPointer - The assignment converts an int to a pointer, which we 6671 /// accept as an extension. 6672 IntToPointer, 6673 6674 /// FunctionVoidPointer - The assignment is between a function pointer and 6675 /// void*, which the standard doesn't allow, but we accept as an extension. 6676 FunctionVoidPointer, 6677 6678 /// IncompatiblePointer - The assignment is between two pointers types that 6679 /// are not compatible, but we accept them as an extension. 6680 IncompatiblePointer, 6681 6682 /// IncompatiblePointer - The assignment is between two pointers types which 6683 /// point to integers which have a different sign, but are otherwise 6684 /// identical. This is a subset of the above, but broken out because it's by 6685 /// far the most common case of incompatible pointers. 6686 IncompatiblePointerSign, 6687 6688 /// CompatiblePointerDiscardsQualifiers - The assignment discards 6689 /// c/v/r qualifiers, which we accept as an extension. 6690 CompatiblePointerDiscardsQualifiers, 6691 6692 /// IncompatiblePointerDiscardsQualifiers - The assignment 6693 /// discards qualifiers that we don't permit to be discarded, 6694 /// like address spaces. 6695 IncompatiblePointerDiscardsQualifiers, 6696 6697 /// IncompatibleNestedPointerQualifiers - The assignment is between two 6698 /// nested pointer types, and the qualifiers other than the first two 6699 /// levels differ e.g. char ** -> const char **, but we accept them as an 6700 /// extension. 6701 IncompatibleNestedPointerQualifiers, 6702 6703 /// IncompatibleVectors - The assignment is between two vector types that 6704 /// have the same size, which we accept as an extension. 6705 IncompatibleVectors, 6706 6707 /// IntToBlockPointer - The assignment converts an int to a block 6708 /// pointer. We disallow this. 6709 IntToBlockPointer, 6710 6711 /// IncompatibleBlockPointer - The assignment is between two block 6712 /// pointers types that are not compatible. 6713 IncompatibleBlockPointer, 6714 6715 /// IncompatibleObjCQualifiedId - The assignment is between a qualified 6716 /// id type and something else (that is incompatible with it). For example, 6717 /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. 6718 IncompatibleObjCQualifiedId, 6719 6720 /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an 6721 /// object with __weak qualifier. 6722 IncompatibleObjCWeakRef, 6723 6724 /// Incompatible - We reject this conversion outright, it is invalid to 6725 /// represent it in the AST. 6726 Incompatible 6727 }; 6728 6729 /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the 6730 /// assignment conversion type specified by ConvTy. This returns true if the 6731 /// conversion was invalid or false if the conversion was accepted. 6732 bool DiagnoseAssignmentResult(AssignConvertType ConvTy, 6733 SourceLocation Loc, 6734 QualType DstType, QualType SrcType, 6735 Expr *SrcExpr, AssignmentAction Action, 6736 bool *Complained = 0); 6737 6738 /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant 6739 /// integer not in the range of enum values. 6740 void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, 6741 Expr *SrcExpr); 6742 6743 /// CheckAssignmentConstraints - Perform type checking for assignment, 6744 /// argument passing, variable initialization, and function return values. 6745 /// C99 6.5.16. 6746 AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, 6747 QualType LHSType, 6748 QualType RHSType); 6749 6750 /// Check assignment constraints and prepare for a conversion of the 6751 /// RHS to the LHS type. 6752 AssignConvertType CheckAssignmentConstraints(QualType LHSType, 6753 ExprResult &RHS, 6754 CastKind &Kind); 6755 6756 // CheckSingleAssignmentConstraints - Currently used by 6757 // CheckAssignmentOperands, and ActOnReturnStmt. Prior to type checking, 6758 // this routine performs the default function/array converions. 6759 AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, 6760 ExprResult &RHS, 6761 bool Diagnose = true); 6762 6763 // \brief If the lhs type is a transparent union, check whether we 6764 // can initialize the transparent union with the given expression. 6765 AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, 6766 ExprResult &RHS); 6767 6768 bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); 6769 6770 bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); 6771 6772 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6773 AssignmentAction Action, 6774 bool AllowExplicit = false); 6775 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6776 AssignmentAction Action, 6777 bool AllowExplicit, 6778 ImplicitConversionSequence& ICS); 6779 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6780 const ImplicitConversionSequence& ICS, 6781 AssignmentAction Action, 6782 CheckedConversionKind CCK 6783 = CCK_ImplicitConversion); 6784 ExprResult PerformImplicitConversion(Expr *From, QualType ToType, 6785 const StandardConversionSequence& SCS, 6786 AssignmentAction Action, 6787 CheckedConversionKind CCK); 6788 6789 /// the following "Check" methods will return a valid/converted QualType 6790 /// or a null QualType (indicating an error diagnostic was issued). 6791 6792 /// type checking binary operators (subroutines of CreateBuiltinBinOp). 6793 QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, 6794 ExprResult &RHS); 6795 QualType CheckPointerToMemberOperands( // C++ 5.5 6796 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, 6797 SourceLocation OpLoc, bool isIndirect); 6798 QualType CheckMultiplyDivideOperands( // C99 6.5.5 6799 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, 6800 bool IsDivide); 6801 QualType CheckRemainderOperands( // C99 6.5.5 6802 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6803 bool IsCompAssign = false); 6804 QualType CheckAdditionOperands( // C99 6.5.6 6805 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6806 QualType* CompLHSTy = 0); 6807 QualType CheckSubtractionOperands( // C99 6.5.6 6808 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6809 QualType* CompLHSTy = 0); 6810 QualType CheckShiftOperands( // C99 6.5.7 6811 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc, 6812 bool IsCompAssign = false); 6813 QualType CheckCompareOperands( // C99 6.5.8/9 6814 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned OpaqueOpc, 6815 bool isRelational); 6816 QualType CheckBitwiseOperands( // C99 6.5.[10...12] 6817 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, 6818 bool IsCompAssign = false); 6819 QualType CheckLogicalOperands( // C99 6.5.[13,14] 6820 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc); 6821 // CheckAssignmentOperands is used for both simple and compound assignment. 6822 // For simple assignment, pass both expressions and a null converted type. 6823 // For compound assignment, pass both expressions and the converted type. 6824 QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] 6825 Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); 6826 6827 ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, 6828 UnaryOperatorKind Opcode, Expr *Op); 6829 ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, 6830 BinaryOperatorKind Opcode, 6831 Expr *LHS, Expr *RHS); 6832 ExprResult checkPseudoObjectRValue(Expr *E); 6833 Expr *recreateSyntacticForm(PseudoObjectExpr *E); 6834 6835 QualType CheckConditionalOperands( // C99 6.5.15 6836 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, 6837 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); 6838 QualType CXXCheckConditionalOperands( // C++ 5.16 6839 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, 6840 ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); 6841 QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, 6842 bool *NonStandardCompositeType = 0); 6843 QualType FindCompositePointerType(SourceLocation Loc, 6844 ExprResult &E1, ExprResult &E2, 6845 bool *NonStandardCompositeType = 0) { 6846 Expr *E1Tmp = E1.take(), *E2Tmp = E2.take(); 6847 QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, 6848 NonStandardCompositeType); 6849 E1 = Owned(E1Tmp); 6850 E2 = Owned(E2Tmp); 6851 return Composite; 6852 } 6853 6854 QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, 6855 SourceLocation QuestionLoc); 6856 6857 bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, 6858 SourceLocation QuestionLoc); 6859 6860 /// type checking for vector binary operators. 6861 QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, 6862 SourceLocation Loc, bool IsCompAssign); 6863 QualType GetSignedVectorType(QualType V); 6864 QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, 6865 SourceLocation Loc, bool isRelational); 6866 QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, 6867 SourceLocation Loc); 6868 6869 /// type checking declaration initializers (C99 6.7.8) 6870 bool CheckForConstantInitializer(Expr *e, QualType t); 6871 6872 // type checking C++ declaration initializers (C++ [dcl.init]). 6873 6874 /// ReferenceCompareResult - Expresses the result of comparing two 6875 /// types (cv1 T1 and cv2 T2) to determine their compatibility for the 6876 /// purposes of initialization by reference (C++ [dcl.init.ref]p4). 6877 enum ReferenceCompareResult { 6878 /// Ref_Incompatible - The two types are incompatible, so direct 6879 /// reference binding is not possible. 6880 Ref_Incompatible = 0, 6881 /// Ref_Related - The two types are reference-related, which means 6882 /// that their unqualified forms (T1 and T2) are either the same 6883 /// or T1 is a base class of T2. 6884 Ref_Related, 6885 /// Ref_Compatible_With_Added_Qualification - The two types are 6886 /// reference-compatible with added qualification, meaning that 6887 /// they are reference-compatible and the qualifiers on T1 (cv1) 6888 /// are greater than the qualifiers on T2 (cv2). 6889 Ref_Compatible_With_Added_Qualification, 6890 /// Ref_Compatible - The two types are reference-compatible and 6891 /// have equivalent qualifiers (cv1 == cv2). 6892 Ref_Compatible 6893 }; 6894 6895 ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, 6896 QualType T1, QualType T2, 6897 bool &DerivedToBase, 6898 bool &ObjCConversion, 6899 bool &ObjCLifetimeConversion); 6900 6901 ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, 6902 Expr *CastExpr, CastKind &CastKind, 6903 ExprValueKind &VK, CXXCastPath &Path); 6904 6905 /// \brief Force an expression with unknown-type to an expression of the 6906 /// given type. 6907 ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); 6908 6909 /// \brief Handle an expression that's being passed to an 6910 /// __unknown_anytype parameter. 6911 /// 6912 /// \return the effective parameter type to use, or null if the 6913 /// argument is invalid. 6914 QualType checkUnknownAnyArg(Expr *&result); 6915 6916 // CheckVectorCast - check type constraints for vectors. 6917 // Since vectors are an extension, there are no C standard reference for this. 6918 // We allow casting between vectors and integer datatypes of the same size. 6919 // returns true if the cast is invalid 6920 bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, 6921 CastKind &Kind); 6922 6923 // CheckExtVectorCast - check type constraints for extended vectors. 6924 // Since vectors are an extension, there are no C standard reference for this. 6925 // We allow casting between vectors and integer datatypes of the same size, 6926 // or vectors and the element type of that vector. 6927 // returns the cast expr 6928 ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, 6929 CastKind &Kind); 6930 6931 ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, 6932 SourceLocation LParenLoc, 6933 Expr *CastExpr, 6934 SourceLocation RParenLoc); 6935 6936 enum ARCConversionResult { ACR_okay, ACR_unbridged }; 6937 6938 /// \brief Checks for invalid conversions and casts between 6939 /// retainable pointers and other pointer kinds. 6940 ARCConversionResult CheckObjCARCConversion(SourceRange castRange, 6941 QualType castType, Expr *&op, 6942 CheckedConversionKind CCK); 6943 6944 Expr *stripARCUnbridgedCast(Expr *e); 6945 void diagnoseARCUnbridgedCast(Expr *e); 6946 6947 bool CheckObjCARCUnavailableWeakConversion(QualType castType, 6948 QualType ExprType); 6949 6950 /// checkRetainCycles - Check whether an Objective-C message send 6951 /// might create an obvious retain cycle. 6952 void checkRetainCycles(ObjCMessageExpr *msg); 6953 void checkRetainCycles(Expr *receiver, Expr *argument); 6954 void checkRetainCycles(VarDecl *Var, Expr *Init); 6955 6956 /// checkUnsafeAssigns - Check whether +1 expr is being assigned 6957 /// to weak/__unsafe_unretained type. 6958 bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); 6959 6960 /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned 6961 /// to weak/__unsafe_unretained expression. 6962 void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); 6963 6964 /// CheckMessageArgumentTypes - Check types in an Obj-C message send. 6965 /// \param Method - May be null. 6966 /// \param [out] ReturnType - The return type of the send. 6967 /// \return true iff there were any incompatible types. 6968 bool CheckMessageArgumentTypes(QualType ReceiverType, 6969 Expr **Args, unsigned NumArgs, Selector Sel, 6970 ArrayRef<SourceLocation> SelectorLocs, 6971 ObjCMethodDecl *Method, bool isClassMessage, 6972 bool isSuperMessage, 6973 SourceLocation lbrac, SourceLocation rbrac, 6974 QualType &ReturnType, ExprValueKind &VK); 6975 6976 /// \brief Determine the result of a message send expression based on 6977 /// the type of the receiver, the method expected to receive the message, 6978 /// and the form of the message send. 6979 QualType getMessageSendResultType(QualType ReceiverType, 6980 ObjCMethodDecl *Method, 6981 bool isClassMessage, bool isSuperMessage); 6982 6983 /// \brief If the given expression involves a message send to a method 6984 /// with a related result type, emit a note describing what happened. 6985 void EmitRelatedResultTypeNote(const Expr *E); 6986 6987 /// CheckBooleanCondition - Diagnose problems involving the use of 6988 /// the given expression as a boolean condition (e.g. in an if 6989 /// statement). Also performs the standard function and array 6990 /// decays, possibly changing the input variable. 6991 /// 6992 /// \param Loc - A location associated with the condition, e.g. the 6993 /// 'if' keyword. 6994 /// \return true iff there were any errors 6995 ExprResult CheckBooleanCondition(Expr *E, SourceLocation Loc); 6996 6997 ExprResult ActOnBooleanCondition(Scope *S, SourceLocation Loc, 6998 Expr *SubExpr); 6999 7000 /// DiagnoseAssignmentAsCondition - Given that an expression is 7001 /// being used as a boolean condition, warn if it's an assignment. 7002 void DiagnoseAssignmentAsCondition(Expr *E); 7003 7004 /// \brief Redundant parentheses over an equality comparison can indicate 7005 /// that the user intended an assignment used as condition. 7006 void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); 7007 7008 /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. 7009 ExprResult CheckCXXBooleanCondition(Expr *CondExpr); 7010 7011 /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have 7012 /// the specified width and sign. If an overflow occurs, detect it and emit 7013 /// the specified diagnostic. 7014 void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, 7015 unsigned NewWidth, bool NewSign, 7016 SourceLocation Loc, unsigned DiagID); 7017 7018 /// Checks that the Objective-C declaration is declared in the global scope. 7019 /// Emits an error and marks the declaration as invalid if it's not declared 7020 /// in the global scope. 7021 bool CheckObjCDeclScope(Decl *D); 7022 7023 /// \brief Abstract base class used for diagnosing integer constant 7024 /// expression violations. 7025 class VerifyICEDiagnoser { 7026 public: 7027 bool Suppress; 7028 7029 VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } 7030 7031 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; 7032 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); 7033 virtual ~VerifyICEDiagnoser() { } 7034 }; 7035 7036 /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, 7037 /// and reports the appropriate diagnostics. Returns false on success. 7038 /// Can optionally return the value of the expression. 7039 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 7040 VerifyICEDiagnoser &Diagnoser, 7041 bool AllowFold = true); 7042 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, 7043 unsigned DiagID, 7044 bool AllowFold = true); 7045 ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result=0); 7046 7047 /// VerifyBitField - verifies that a bit field expression is an ICE and has 7048 /// the correct width, and that the field type is valid. 7049 /// Returns false on success. 7050 /// Can optionally return whether the bit-field is of width 0 7051 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, 7052 QualType FieldTy, Expr *BitWidth, 7053 bool *ZeroWidth = 0); 7054 7055 enum CUDAFunctionTarget { 7056 CFT_Device, 7057 CFT_Global, 7058 CFT_Host, 7059 CFT_HostDevice 7060 }; 7061 7062 CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D); 7063 7064 bool CheckCUDATarget(CUDAFunctionTarget CallerTarget, 7065 CUDAFunctionTarget CalleeTarget); 7066 7067 bool CheckCUDATarget(const FunctionDecl *Caller, const FunctionDecl *Callee) { 7068 return CheckCUDATarget(IdentifyCUDATarget(Caller), 7069 IdentifyCUDATarget(Callee)); 7070 } 7071 7072 /// \name Code completion 7073 //@{ 7074 /// \brief Describes the context in which code completion occurs. 7075 enum ParserCompletionContext { 7076 /// \brief Code completion occurs at top-level or namespace context. 7077 PCC_Namespace, 7078 /// \brief Code completion occurs within a class, struct, or union. 7079 PCC_Class, 7080 /// \brief Code completion occurs within an Objective-C interface, protocol, 7081 /// or category. 7082 PCC_ObjCInterface, 7083 /// \brief Code completion occurs within an Objective-C implementation or 7084 /// category implementation 7085 PCC_ObjCImplementation, 7086 /// \brief Code completion occurs within the list of instance variables 7087 /// in an Objective-C interface, protocol, category, or implementation. 7088 PCC_ObjCInstanceVariableList, 7089 /// \brief Code completion occurs following one or more template 7090 /// headers. 7091 PCC_Template, 7092 /// \brief Code completion occurs following one or more template 7093 /// headers within a class. 7094 PCC_MemberTemplate, 7095 /// \brief Code completion occurs within an expression. 7096 PCC_Expression, 7097 /// \brief Code completion occurs within a statement, which may 7098 /// also be an expression or a declaration. 7099 PCC_Statement, 7100 /// \brief Code completion occurs at the beginning of the 7101 /// initialization statement (or expression) in a for loop. 7102 PCC_ForInit, 7103 /// \brief Code completion occurs within the condition of an if, 7104 /// while, switch, or for statement. 7105 PCC_Condition, 7106 /// \brief Code completion occurs within the body of a function on a 7107 /// recovery path, where we do not have a specific handle on our position 7108 /// in the grammar. 7109 PCC_RecoveryInFunction, 7110 /// \brief Code completion occurs where only a type is permitted. 7111 PCC_Type, 7112 /// \brief Code completion occurs in a parenthesized expression, which 7113 /// might also be a type cast. 7114 PCC_ParenthesizedExpression, 7115 /// \brief Code completion occurs within a sequence of declaration 7116 /// specifiers within a function, method, or block. 7117 PCC_LocalDeclarationSpecifiers 7118 }; 7119 7120 void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); 7121 void CodeCompleteOrdinaryName(Scope *S, 7122 ParserCompletionContext CompletionContext); 7123 void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, 7124 bool AllowNonIdentifiers, 7125 bool AllowNestedNameSpecifiers); 7126 7127 struct CodeCompleteExpressionData; 7128 void CodeCompleteExpression(Scope *S, 7129 const CodeCompleteExpressionData &Data); 7130 void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, 7131 SourceLocation OpLoc, 7132 bool IsArrow); 7133 void CodeCompletePostfixExpression(Scope *S, ExprResult LHS); 7134 void CodeCompleteTag(Scope *S, unsigned TagSpec); 7135 void CodeCompleteTypeQualifiers(DeclSpec &DS); 7136 void CodeCompleteCase(Scope *S); 7137 void CodeCompleteCall(Scope *S, Expr *Fn, ArrayRef<Expr *> Args); 7138 void CodeCompleteInitializer(Scope *S, Decl *D); 7139 void CodeCompleteReturn(Scope *S); 7140 void CodeCompleteAfterIf(Scope *S); 7141 void CodeCompleteAssignmentRHS(Scope *S, Expr *LHS); 7142 7143 void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, 7144 bool EnteringContext); 7145 void CodeCompleteUsing(Scope *S); 7146 void CodeCompleteUsingDirective(Scope *S); 7147 void CodeCompleteNamespaceDecl(Scope *S); 7148 void CodeCompleteNamespaceAliasDecl(Scope *S); 7149 void CodeCompleteOperatorName(Scope *S); 7150 void CodeCompleteConstructorInitializer(Decl *Constructor, 7151 CXXCtorInitializer** Initializers, 7152 unsigned NumInitializers); 7153 void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, 7154 bool AfterAmpersand); 7155 7156 void CodeCompleteObjCAtDirective(Scope *S); 7157 void CodeCompleteObjCAtVisibility(Scope *S); 7158 void CodeCompleteObjCAtStatement(Scope *S); 7159 void CodeCompleteObjCAtExpression(Scope *S); 7160 void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); 7161 void CodeCompleteObjCPropertyGetter(Scope *S); 7162 void CodeCompleteObjCPropertySetter(Scope *S); 7163 void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, 7164 bool IsParameter); 7165 void CodeCompleteObjCMessageReceiver(Scope *S); 7166 void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, 7167 IdentifierInfo **SelIdents, 7168 unsigned NumSelIdents, 7169 bool AtArgumentExpression); 7170 void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, 7171 IdentifierInfo **SelIdents, 7172 unsigned NumSelIdents, 7173 bool AtArgumentExpression, 7174 bool IsSuper = false); 7175 void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, 7176 IdentifierInfo **SelIdents, 7177 unsigned NumSelIdents, 7178 bool AtArgumentExpression, 7179 ObjCInterfaceDecl *Super = 0); 7180 void CodeCompleteObjCForCollection(Scope *S, 7181 DeclGroupPtrTy IterationVar); 7182 void CodeCompleteObjCSelector(Scope *S, 7183 IdentifierInfo **SelIdents, 7184 unsigned NumSelIdents); 7185 void CodeCompleteObjCProtocolReferences(IdentifierLocPair *Protocols, 7186 unsigned NumProtocols); 7187 void CodeCompleteObjCProtocolDecl(Scope *S); 7188 void CodeCompleteObjCInterfaceDecl(Scope *S); 7189 void CodeCompleteObjCSuperclass(Scope *S, 7190 IdentifierInfo *ClassName, 7191 SourceLocation ClassNameLoc); 7192 void CodeCompleteObjCImplementationDecl(Scope *S); 7193 void CodeCompleteObjCInterfaceCategory(Scope *S, 7194 IdentifierInfo *ClassName, 7195 SourceLocation ClassNameLoc); 7196 void CodeCompleteObjCImplementationCategory(Scope *S, 7197 IdentifierInfo *ClassName, 7198 SourceLocation ClassNameLoc); 7199 void CodeCompleteObjCPropertyDefinition(Scope *S); 7200 void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, 7201 IdentifierInfo *PropertyName); 7202 void CodeCompleteObjCMethodDecl(Scope *S, 7203 bool IsInstanceMethod, 7204 ParsedType ReturnType); 7205 void CodeCompleteObjCMethodDeclSelector(Scope *S, 7206 bool IsInstanceMethod, 7207 bool AtParameterName, 7208 ParsedType ReturnType, 7209 IdentifierInfo **SelIdents, 7210 unsigned NumSelIdents); 7211 void CodeCompletePreprocessorDirective(bool InConditional); 7212 void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); 7213 void CodeCompletePreprocessorMacroName(bool IsDefinition); 7214 void CodeCompletePreprocessorExpression(); 7215 void CodeCompletePreprocessorMacroArgument(Scope *S, 7216 IdentifierInfo *Macro, 7217 MacroInfo *MacroInfo, 7218 unsigned Argument); 7219 void CodeCompleteNaturalLanguage(); 7220 void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, 7221 CodeCompletionTUInfo &CCTUInfo, 7222 SmallVectorImpl<CodeCompletionResult> &Results); 7223 //@} 7224 7225 //===--------------------------------------------------------------------===// 7226 // Extra semantic analysis beyond the C type system 7227 7228public: 7229 SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, 7230 unsigned ByteNo) const; 7231 7232private: 7233 void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 7234 const ArraySubscriptExpr *ASE=0, 7235 bool AllowOnePastEnd=true, bool IndexNegated=false); 7236 void CheckArrayAccess(const Expr *E); 7237 // Used to grab the relevant information from a FormatAttr and a 7238 // FunctionDeclaration. 7239 struct FormatStringInfo { 7240 unsigned FormatIdx; 7241 unsigned FirstDataArg; 7242 bool HasVAListArg; 7243 }; 7244 7245 bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 7246 FormatStringInfo *FSI); 7247 bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 7248 const FunctionProtoType *Proto); 7249 bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, 7250 Expr **Args, unsigned NumArgs); 7251 bool CheckBlockCall(NamedDecl *NDecl, CallExpr *TheCall, 7252 const FunctionProtoType *Proto); 7253 void CheckConstructorCall(FunctionDecl *FDecl, 7254 ArrayRef<const Expr *> Args, 7255 const FunctionProtoType *Proto, 7256 SourceLocation Loc); 7257 7258 void checkCall(NamedDecl *FDecl, ArrayRef<const Expr *> Args, 7259 unsigned NumProtoArgs, bool IsMemberFunction, 7260 SourceLocation Loc, SourceRange Range, 7261 VariadicCallType CallType); 7262 7263 7264 bool CheckObjCString(Expr *Arg); 7265 7266 ExprResult CheckBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7267 bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7268 bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); 7269 7270 bool SemaBuiltinVAStart(CallExpr *TheCall); 7271 bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); 7272 bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); 7273 7274public: 7275 // Used by C++ template instantiation. 7276 ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); 7277 7278private: 7279 bool SemaBuiltinPrefetch(CallExpr *TheCall); 7280 bool SemaBuiltinObjectSize(CallExpr *TheCall); 7281 bool SemaBuiltinLongjmp(CallExpr *TheCall); 7282 ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); 7283 ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, 7284 AtomicExpr::AtomicOp Op); 7285 bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7286 llvm::APSInt &Result); 7287 7288 enum FormatStringType { 7289 FST_Scanf, 7290 FST_Printf, 7291 FST_NSString, 7292 FST_Strftime, 7293 FST_Strfmon, 7294 FST_Kprintf, 7295 FST_Unknown 7296 }; 7297 static FormatStringType GetFormatStringType(const FormatAttr *Format); 7298 7299 enum StringLiteralCheckType { 7300 SLCT_NotALiteral, 7301 SLCT_UncheckedLiteral, 7302 SLCT_CheckedLiteral 7303 }; 7304 7305 StringLiteralCheckType checkFormatStringExpr(const Expr *E, 7306 ArrayRef<const Expr *> Args, 7307 bool HasVAListArg, 7308 unsigned format_idx, 7309 unsigned firstDataArg, 7310 FormatStringType Type, 7311 VariadicCallType CallType, 7312 bool inFunctionCall = true); 7313 7314 void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, 7315 ArrayRef<const Expr *> Args, bool HasVAListArg, 7316 unsigned format_idx, unsigned firstDataArg, 7317 FormatStringType Type, bool inFunctionCall, 7318 VariadicCallType CallType); 7319 7320 bool CheckFormatArguments(const FormatAttr *Format, 7321 ArrayRef<const Expr *> Args, 7322 bool IsCXXMember, 7323 VariadicCallType CallType, 7324 SourceLocation Loc, SourceRange Range); 7325 bool CheckFormatArguments(ArrayRef<const Expr *> Args, 7326 bool HasVAListArg, unsigned format_idx, 7327 unsigned firstDataArg, FormatStringType Type, 7328 VariadicCallType CallType, 7329 SourceLocation Loc, SourceRange range); 7330 7331 void CheckNonNullArguments(const NonNullAttr *NonNull, 7332 const Expr * const *ExprArgs, 7333 SourceLocation CallSiteLoc); 7334 7335 void CheckMemaccessArguments(const CallExpr *Call, 7336 unsigned BId, 7337 IdentifierInfo *FnName); 7338 7339 void CheckStrlcpycatArguments(const CallExpr *Call, 7340 IdentifierInfo *FnName); 7341 7342 void CheckStrncatArguments(const CallExpr *Call, 7343 IdentifierInfo *FnName); 7344 7345 void CheckReturnStackAddr(Expr *RetValExp, QualType lhsType, 7346 SourceLocation ReturnLoc); 7347 void CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr* RHS); 7348 void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); 7349 void CheckForIntOverflow(Expr *E); 7350 void CheckUnsequencedOperations(Expr *E); 7351 7352 /// \brief Perform semantic checks on a completed expression. This will either 7353 /// be a full-expression or a default argument expression. 7354 void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), 7355 bool IsConstexpr = false); 7356 7357 void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, 7358 Expr *Init); 7359 7360public: 7361 /// \brief Register a magic integral constant to be used as a type tag. 7362 void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 7363 uint64_t MagicValue, QualType Type, 7364 bool LayoutCompatible, bool MustBeNull); 7365 7366 struct TypeTagData { 7367 TypeTagData() {} 7368 7369 TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : 7370 Type(Type), LayoutCompatible(LayoutCompatible), 7371 MustBeNull(MustBeNull) 7372 {} 7373 7374 QualType Type; 7375 7376 /// If true, \c Type should be compared with other expression's types for 7377 /// layout-compatibility. 7378 unsigned LayoutCompatible : 1; 7379 unsigned MustBeNull : 1; 7380 }; 7381 7382 /// A pair of ArgumentKind identifier and magic value. This uniquely 7383 /// identifies the magic value. 7384 typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; 7385 7386private: 7387 /// \brief A map from magic value to type information. 7388 OwningPtr<llvm::DenseMap<TypeTagMagicValue, TypeTagData> > 7389 TypeTagForDatatypeMagicValues; 7390 7391 /// \brief Peform checks on a call of a function with argument_with_type_tag 7392 /// or pointer_with_type_tag attributes. 7393 void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 7394 const Expr * const *ExprArgs); 7395 7396 /// \brief The parser's current scope. 7397 /// 7398 /// The parser maintains this state here. 7399 Scope *CurScope; 7400 7401protected: 7402 friend class Parser; 7403 friend class InitializationSequence; 7404 friend class ASTReader; 7405 friend class ASTWriter; 7406 7407public: 7408 /// \brief Retrieve the parser's current scope. 7409 /// 7410 /// This routine must only be used when it is certain that semantic analysis 7411 /// and the parser are in precisely the same context, which is not the case 7412 /// when, e.g., we are performing any kind of template instantiation. 7413 /// Therefore, the only safe places to use this scope are in the parser 7414 /// itself and in routines directly invoked from the parser and *never* from 7415 /// template substitution or instantiation. 7416 Scope *getCurScope() const { return CurScope; } 7417 7418 Decl *getObjCDeclContext() const; 7419 7420 DeclContext *getCurLexicalContext() const { 7421 return OriginalLexicalContext ? OriginalLexicalContext : CurContext; 7422 } 7423 7424 AvailabilityResult getCurContextAvailability() const; 7425 7426 const DeclContext *getCurObjCLexicalContext() const { 7427 const DeclContext *DC = getCurLexicalContext(); 7428 // A category implicitly has the attribute of the interface. 7429 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) 7430 DC = CatD->getClassInterface(); 7431 return DC; 7432 } 7433}; 7434 7435/// \brief RAII object that enters a new expression evaluation context. 7436class EnterExpressionEvaluationContext { 7437 Sema &Actions; 7438 7439public: 7440 EnterExpressionEvaluationContext(Sema &Actions, 7441 Sema::ExpressionEvaluationContext NewContext, 7442 Decl *LambdaContextDecl = 0, 7443 bool IsDecltype = false) 7444 : Actions(Actions) { 7445 Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, 7446 IsDecltype); 7447 } 7448 EnterExpressionEvaluationContext(Sema &Actions, 7449 Sema::ExpressionEvaluationContext NewContext, 7450 Sema::ReuseLambdaContextDecl_t, 7451 bool IsDecltype = false) 7452 : Actions(Actions) { 7453 Actions.PushExpressionEvaluationContext(NewContext, 7454 Sema::ReuseLambdaContextDecl, 7455 IsDecltype); 7456 } 7457 7458 ~EnterExpressionEvaluationContext() { 7459 Actions.PopExpressionEvaluationContext(); 7460 } 7461}; 7462 7463} // end namespace clang 7464 7465#endif 7466