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