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