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