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