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