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