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