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