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