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