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