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