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