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