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