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