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