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