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