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