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