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