Decl.h revision d8ffd0b7b61566f15a67192883a607f7703bcece
1//===--- Decl.h - Classes for representing declarations ---------*- 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 Decl subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_AST_DECL_H 15#define LLVM_CLANG_AST_DECL_H 16 17#include "clang/AST/APValue.h" 18#include "clang/AST/DeclBase.h" 19#include "clang/AST/DeclarationName.h" 20#include "clang/AST/ExternalASTSource.h" 21#include "clang/AST/Redeclarable.h" 22#include "clang/AST/Type.h" 23#include "clang/Basic/Linkage.h" 24#include "llvm/ADT/ArrayRef.h" 25#include "llvm/ADT/Optional.h" 26#include "llvm/Support/Compiler.h" 27 28namespace clang { 29struct ASTTemplateArgumentListInfo; 30class CXXTemporary; 31class CompoundStmt; 32class DependentFunctionTemplateSpecializationInfo; 33class Expr; 34class FunctionTemplateDecl; 35class FunctionTemplateSpecializationInfo; 36class LabelStmt; 37class MemberSpecializationInfo; 38class Module; 39class NestedNameSpecifier; 40class Stmt; 41class StringLiteral; 42class TemplateArgumentList; 43class TemplateParameterList; 44class TypeLoc; 45class UnresolvedSetImpl; 46 47/// \brief A container of type source information. 48/// 49/// A client can read the relevant info using TypeLoc wrappers, e.g: 50/// @code 51/// TypeLoc TL = TypeSourceInfo->getTypeLoc(); 52/// if (PointerLoc *PL = dyn_cast<PointerLoc>(&TL)) 53/// PL->getStarLoc().print(OS, SrcMgr); 54/// @endcode 55/// 56class TypeSourceInfo { 57 QualType Ty; 58 // Contains a memory block after the class, used for type source information, 59 // allocated by ASTContext. 60 friend class ASTContext; 61 TypeSourceInfo(QualType ty) : Ty(ty) { } 62public: 63 /// \brief Return the type wrapped by this type source info. 64 QualType getType() const { return Ty; } 65 66 /// \brief Return the TypeLoc wrapper for the type source info. 67 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h 68}; 69 70/// TranslationUnitDecl - The top declaration context. 71class TranslationUnitDecl : public Decl, public DeclContext { 72 virtual void anchor(); 73 ASTContext &Ctx; 74 75 /// The (most recently entered) anonymous namespace for this 76 /// translation unit, if one has been created. 77 NamespaceDecl *AnonymousNamespace; 78 79 explicit TranslationUnitDecl(ASTContext &ctx) 80 : Decl(TranslationUnit, 0, SourceLocation()), 81 DeclContext(TranslationUnit), 82 Ctx(ctx), AnonymousNamespace(0) {} 83public: 84 ASTContext &getASTContext() const { return Ctx; } 85 86 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; } 87 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; } 88 89 static TranslationUnitDecl *Create(ASTContext &C); 90 // Implement isa/cast/dyncast/etc. 91 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 92 static bool classofKind(Kind K) { return K == TranslationUnit; } 93 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) { 94 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D)); 95 } 96 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) { 97 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC)); 98 } 99}; 100 101/// NamedDecl - This represents a decl with a name. Many decls have names such 102/// as ObjCMethodDecl, but not \@class, etc. 103class NamedDecl : public Decl { 104 virtual void anchor(); 105 /// Name - The name of this declaration, which is typically a normal 106 /// identifier but may also be a special kind of name (C++ 107 /// constructor, Objective-C selector, etc.) 108 DeclarationName Name; 109 110private: 111 NamedDecl *getUnderlyingDeclImpl(); 112 void verifyLinkage() const; 113 114protected: 115 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N) 116 : Decl(DK, DC, L), Name(N) { } 117 118public: 119 /// getIdentifier - Get the identifier that names this declaration, 120 /// if there is one. This will return NULL if this declaration has 121 /// no name (e.g., for an unnamed class) or if the name is a special 122 /// name (C++ constructor, Objective-C selector, etc.). 123 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); } 124 125 /// getName - Get the name of identifier for this declaration as a StringRef. 126 /// This requires that the declaration have a name and that it be a simple 127 /// identifier. 128 StringRef getName() const { 129 assert(Name.isIdentifier() && "Name is not a simple identifier"); 130 return getIdentifier() ? getIdentifier()->getName() : ""; 131 } 132 133 /// getNameAsString - Get a human-readable name for the declaration, even if 134 /// it is one of the special kinds of names (C++ constructor, Objective-C 135 /// selector, etc). Creating this name requires expensive string 136 /// manipulation, so it should be called only when performance doesn't matter. 137 /// For simple declarations, getNameAsCString() should suffice. 138 // 139 // FIXME: This function should be renamed to indicate that it is not just an 140 // alternate form of getName(), and clients should move as appropriate. 141 // 142 // FIXME: Deprecated, move clients to getName(). 143 std::string getNameAsString() const { return Name.getAsString(); } 144 145 void printName(raw_ostream &os) const { return Name.printName(os); } 146 147 /// getDeclName - Get the actual, stored name of the declaration, 148 /// which may be a special name. 149 DeclarationName getDeclName() const { return Name; } 150 151 /// \brief Set the name of this declaration. 152 void setDeclName(DeclarationName N) { Name = N; } 153 154 /// printQualifiedName - Returns human-readable qualified name for 155 /// declaration, like A::B::i, for i being member of namespace A::B. 156 /// If declaration is not member of context which can be named (record, 157 /// namespace), it will return same result as printName(). 158 /// Creating this name is expensive, so it should be called only when 159 /// performance doesn't matter. 160 void printQualifiedName(raw_ostream &OS) const; 161 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const; 162 163 // FIXME: Remove string versions. 164 std::string getQualifiedNameAsString() const; 165 std::string getQualifiedNameAsString(const PrintingPolicy &Policy) const; 166 167 /// getNameForDiagnostic - Appends a human-readable name for this 168 /// declaration into the given stream. 169 /// 170 /// This is the method invoked by Sema when displaying a NamedDecl 171 /// in a diagnostic. It does not necessarily produce the same 172 /// result as printName(); for example, class template 173 /// specializations are printed with their template arguments. 174 virtual void getNameForDiagnostic(raw_ostream &OS, 175 const PrintingPolicy &Policy, 176 bool Qualified) const; 177 178 /// declarationReplaces - Determine whether this declaration, if 179 /// known to be well-formed within its context, will replace the 180 /// declaration OldD if introduced into scope. A declaration will 181 /// replace another declaration if, for example, it is a 182 /// redeclaration of the same variable or function, but not if it is 183 /// a declaration of a different kind (function vs. class) or an 184 /// overloaded function. 185 bool declarationReplaces(NamedDecl *OldD) const; 186 187 /// \brief Determine whether this declaration has linkage. 188 bool hasLinkage() const; 189 190 using Decl::isModulePrivate; 191 using Decl::setModulePrivate; 192 193 /// \brief Determine whether this declaration is hidden from name lookup. 194 bool isHidden() const { return Hidden; } 195 196 /// \brief Determine whether this declaration is a C++ class member. 197 bool isCXXClassMember() const { 198 const DeclContext *DC = getDeclContext(); 199 200 // C++0x [class.mem]p1: 201 // The enumerators of an unscoped enumeration defined in 202 // the class are members of the class. 203 // FIXME: support C++0x scoped enumerations. 204 if (isa<EnumDecl>(DC)) 205 DC = DC->getParent(); 206 207 return DC->isRecord(); 208 } 209 210 /// \brief Determine whether the given declaration is an instance member of 211 /// a C++ class. 212 bool isCXXInstanceMember() const; 213 214 /// \brief Determine what kind of linkage this entity has. 215 Linkage getLinkage() const; 216 217 /// \brief True if this decl has external linkage. 218 bool hasExternalLinkage() const { 219 return getLinkage() == ExternalLinkage; 220 } 221 222 /// \brief Determines the visibility of this entity. 223 Visibility getVisibility() const { 224 return getLinkageAndVisibility().getVisibility(); 225 } 226 227 /// \brief Determines the linkage and visibility of this entity. 228 LinkageInfo getLinkageAndVisibility() const; 229 230 /// Kinds of explicit visibility. 231 enum ExplicitVisibilityKind { 232 VisibilityForType, 233 VisibilityForValue 234 }; 235 236 /// \brief If visibility was explicitly specified for this 237 /// declaration, return that visibility. 238 Optional<Visibility> 239 getExplicitVisibility(ExplicitVisibilityKind kind) const; 240 241 /// \brief True if the computed linkage is valid. Used for consistency 242 /// checking. Should always return true. 243 bool isLinkageValid() const; 244 245 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for 246 /// the underlying named decl. 247 NamedDecl *getUnderlyingDecl() { 248 // Fast-path the common case. 249 if (this->getKind() != UsingShadow && 250 this->getKind() != ObjCCompatibleAlias) 251 return this; 252 253 return getUnderlyingDeclImpl(); 254 } 255 const NamedDecl *getUnderlyingDecl() const { 256 return const_cast<NamedDecl*>(this)->getUnderlyingDecl(); 257 } 258 259 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 260 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; } 261}; 262 263inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) { 264 ND.printName(OS); 265 return OS; 266} 267 268/// LabelDecl - Represents the declaration of a label. Labels also have a 269/// corresponding LabelStmt, which indicates the position that the label was 270/// defined at. For normal labels, the location of the decl is the same as the 271/// location of the statement. For GNU local labels (__label__), the decl 272/// location is where the __label__ is. 273class LabelDecl : public NamedDecl { 274 virtual void anchor(); 275 LabelStmt *TheStmt; 276 /// LocStart - For normal labels, this is the same as the main declaration 277 /// label, i.e., the location of the identifier; for GNU local labels, 278 /// this is the location of the __label__ keyword. 279 SourceLocation LocStart; 280 281 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II, 282 LabelStmt *S, SourceLocation StartL) 283 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {} 284 285public: 286 static LabelDecl *Create(ASTContext &C, DeclContext *DC, 287 SourceLocation IdentL, IdentifierInfo *II); 288 static LabelDecl *Create(ASTContext &C, DeclContext *DC, 289 SourceLocation IdentL, IdentifierInfo *II, 290 SourceLocation GnuLabelL); 291 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID); 292 293 LabelStmt *getStmt() const { return TheStmt; } 294 void setStmt(LabelStmt *T) { TheStmt = T; } 295 296 bool isGnuLocal() const { return LocStart != getLocation(); } 297 void setLocStart(SourceLocation L) { LocStart = L; } 298 299 SourceRange getSourceRange() const LLVM_READONLY { 300 return SourceRange(LocStart, getLocation()); 301 } 302 303 // Implement isa/cast/dyncast/etc. 304 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 305 static bool classofKind(Kind K) { return K == Label; } 306}; 307 308/// NamespaceDecl - Represent a C++ namespace. 309class NamespaceDecl : public NamedDecl, public DeclContext, 310 public Redeclarable<NamespaceDecl> 311{ 312 virtual void anchor(); 313 314 /// LocStart - The starting location of the source range, pointing 315 /// to either the namespace or the inline keyword. 316 SourceLocation LocStart; 317 /// RBraceLoc - The ending location of the source range. 318 SourceLocation RBraceLoc; 319 320 /// \brief A pointer to either the anonymous namespace that lives just inside 321 /// this namespace or to the first namespace in the chain (the latter case 322 /// only when this is not the first in the chain), along with a 323 /// boolean value indicating whether this is an inline namespace. 324 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline; 325 326 NamespaceDecl(DeclContext *DC, bool Inline, SourceLocation StartLoc, 327 SourceLocation IdLoc, IdentifierInfo *Id, 328 NamespaceDecl *PrevDecl); 329 330 typedef Redeclarable<NamespaceDecl> redeclarable_base; 331 virtual NamespaceDecl *getNextRedeclaration() { 332 return RedeclLink.getNext(); 333 } 334 virtual NamespaceDecl *getPreviousDeclImpl() { 335 return getPreviousDecl(); 336 } 337 virtual NamespaceDecl *getMostRecentDeclImpl() { 338 return getMostRecentDecl(); 339 } 340 341public: 342 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC, 343 bool Inline, SourceLocation StartLoc, 344 SourceLocation IdLoc, IdentifierInfo *Id, 345 NamespaceDecl *PrevDecl); 346 347 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID); 348 349 typedef redeclarable_base::redecl_iterator redecl_iterator; 350 using redeclarable_base::redecls_begin; 351 using redeclarable_base::redecls_end; 352 using redeclarable_base::getPreviousDecl; 353 using redeclarable_base::getMostRecentDecl; 354 355 /// \brief Returns true if this is an anonymous namespace declaration. 356 /// 357 /// For example: 358 /// \code 359 /// namespace { 360 /// ... 361 /// }; 362 /// \endcode 363 /// q.v. C++ [namespace.unnamed] 364 bool isAnonymousNamespace() const { 365 return !getIdentifier(); 366 } 367 368 /// \brief Returns true if this is an inline namespace declaration. 369 bool isInline() const { 370 return AnonOrFirstNamespaceAndInline.getInt(); 371 } 372 373 /// \brief Set whether this is an inline namespace declaration. 374 void setInline(bool Inline) { 375 AnonOrFirstNamespaceAndInline.setInt(Inline); 376 } 377 378 /// \brief Get the original (first) namespace declaration. 379 NamespaceDecl *getOriginalNamespace() { 380 if (isFirstDeclaration()) 381 return this; 382 383 return AnonOrFirstNamespaceAndInline.getPointer(); 384 } 385 386 /// \brief Get the original (first) namespace declaration. 387 const NamespaceDecl *getOriginalNamespace() const { 388 if (isFirstDeclaration()) 389 return this; 390 391 return AnonOrFirstNamespaceAndInline.getPointer(); 392 } 393 394 /// \brief Return true if this declaration is an original (first) declaration 395 /// of the namespace. This is false for non-original (subsequent) namespace 396 /// declarations and anonymous namespaces. 397 bool isOriginalNamespace() const { 398 return isFirstDeclaration(); 399 } 400 401 /// \brief Retrieve the anonymous namespace nested inside this namespace, 402 /// if any. 403 NamespaceDecl *getAnonymousNamespace() const { 404 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer(); 405 } 406 407 void setAnonymousNamespace(NamespaceDecl *D) { 408 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D); 409 } 410 411 /// Retrieves the canonical declaration of this namespace. 412 NamespaceDecl *getCanonicalDecl() { 413 return getOriginalNamespace(); 414 } 415 const NamespaceDecl *getCanonicalDecl() const { 416 return getOriginalNamespace(); 417 } 418 419 virtual SourceRange getSourceRange() const LLVM_READONLY { 420 return SourceRange(LocStart, RBraceLoc); 421 } 422 423 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; } 424 SourceLocation getRBraceLoc() const { return RBraceLoc; } 425 void setLocStart(SourceLocation L) { LocStart = L; } 426 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } 427 428 // Implement isa/cast/dyncast/etc. 429 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 430 static bool classofKind(Kind K) { return K == Namespace; } 431 static DeclContext *castToDeclContext(const NamespaceDecl *D) { 432 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D)); 433 } 434 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) { 435 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC)); 436 } 437 438 friend class ASTDeclReader; 439 friend class ASTDeclWriter; 440}; 441 442/// ValueDecl - Represent the declaration of a variable (in which case it is 443/// an lvalue) a function (in which case it is a function designator) or 444/// an enum constant. 445class ValueDecl : public NamedDecl { 446 virtual void anchor(); 447 QualType DeclType; 448 449protected: 450 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L, 451 DeclarationName N, QualType T) 452 : NamedDecl(DK, DC, L, N), DeclType(T) {} 453public: 454 QualType getType() const { return DeclType; } 455 void setType(QualType newType) { DeclType = newType; } 456 457 /// \brief Determine whether this symbol is weakly-imported, 458 /// or declared with the weak or weak-ref attr. 459 bool isWeak() const; 460 461 // Implement isa/cast/dyncast/etc. 462 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 463 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; } 464}; 465 466/// QualifierInfo - A struct with extended info about a syntactic 467/// name qualifier, to be used for the case of out-of-line declarations. 468struct QualifierInfo { 469 NestedNameSpecifierLoc QualifierLoc; 470 471 /// NumTemplParamLists - The number of "outer" template parameter lists. 472 /// The count includes all of the template parameter lists that were matched 473 /// against the template-ids occurring into the NNS and possibly (in the 474 /// case of an explicit specialization) a final "template <>". 475 unsigned NumTemplParamLists; 476 477 /// TemplParamLists - A new-allocated array of size NumTemplParamLists, 478 /// containing pointers to the "outer" template parameter lists. 479 /// It includes all of the template parameter lists that were matched 480 /// against the template-ids occurring into the NNS and possibly (in the 481 /// case of an explicit specialization) a final "template <>". 482 TemplateParameterList** TemplParamLists; 483 484 /// Default constructor. 485 QualifierInfo() : QualifierLoc(), NumTemplParamLists(0), TemplParamLists(0) {} 486 487 /// setTemplateParameterListsInfo - Sets info about "outer" template 488 /// parameter lists. 489 void setTemplateParameterListsInfo(ASTContext &Context, 490 unsigned NumTPLists, 491 TemplateParameterList **TPLists); 492 493private: 494 // Copy constructor and copy assignment are disabled. 495 QualifierInfo(const QualifierInfo&) LLVM_DELETED_FUNCTION; 496 QualifierInfo& operator=(const QualifierInfo&) LLVM_DELETED_FUNCTION; 497}; 498 499/// \brief Represents a ValueDecl that came out of a declarator. 500/// Contains type source information through TypeSourceInfo. 501class DeclaratorDecl : public ValueDecl { 502 // A struct representing both a TInfo and a syntactic qualifier, 503 // to be used for the (uncommon) case of out-of-line declarations. 504 struct ExtInfo : public QualifierInfo { 505 TypeSourceInfo *TInfo; 506 }; 507 508 llvm::PointerUnion<TypeSourceInfo*, ExtInfo*> DeclInfo; 509 510 /// InnerLocStart - The start of the source range for this declaration, 511 /// ignoring outer template declarations. 512 SourceLocation InnerLocStart; 513 514 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); } 515 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); } 516 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); } 517 518protected: 519 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L, 520 DeclarationName N, QualType T, TypeSourceInfo *TInfo, 521 SourceLocation StartL) 522 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) { 523 } 524 525public: 526 TypeSourceInfo *getTypeSourceInfo() const { 527 return hasExtInfo() 528 ? getExtInfo()->TInfo 529 : DeclInfo.get<TypeSourceInfo*>(); 530 } 531 void setTypeSourceInfo(TypeSourceInfo *TI) { 532 if (hasExtInfo()) 533 getExtInfo()->TInfo = TI; 534 else 535 DeclInfo = TI; 536 } 537 538 /// getInnerLocStart - Return SourceLocation representing start of source 539 /// range ignoring outer template declarations. 540 SourceLocation getInnerLocStart() const { return InnerLocStart; } 541 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; } 542 543 /// getOuterLocStart - Return SourceLocation representing start of source 544 /// range taking into account any outer template declarations. 545 SourceLocation getOuterLocStart() const; 546 547 virtual SourceRange getSourceRange() const LLVM_READONLY; 548 SourceLocation getLocStart() const LLVM_READONLY { 549 return getOuterLocStart(); 550 } 551 552 /// \brief Retrieve the nested-name-specifier that qualifies the name of this 553 /// declaration, if it was present in the source. 554 NestedNameSpecifier *getQualifier() const { 555 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() 556 : 0; 557 } 558 559 /// \brief Retrieve the nested-name-specifier (with source-location 560 /// information) that qualifies the name of this declaration, if it was 561 /// present in the source. 562 NestedNameSpecifierLoc getQualifierLoc() const { 563 return hasExtInfo() ? getExtInfo()->QualifierLoc 564 : NestedNameSpecifierLoc(); 565 } 566 567 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); 568 569 unsigned getNumTemplateParameterLists() const { 570 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; 571 } 572 TemplateParameterList *getTemplateParameterList(unsigned index) const { 573 assert(index < getNumTemplateParameterLists()); 574 return getExtInfo()->TemplParamLists[index]; 575 } 576 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, 577 TemplateParameterList **TPLists); 578 579 SourceLocation getTypeSpecStartLoc() const; 580 581 // Implement isa/cast/dyncast/etc. 582 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 583 static bool classofKind(Kind K) { 584 return K >= firstDeclarator && K <= lastDeclarator; 585 } 586 587 friend class ASTDeclReader; 588 friend class ASTDeclWriter; 589}; 590 591/// \brief Structure used to store a statement, the constant value to 592/// which it was evaluated (if any), and whether or not the statement 593/// is an integral constant expression (if known). 594struct EvaluatedStmt { 595 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false), 596 CheckingICE(false), IsICE(false) { } 597 598 /// \brief Whether this statement was already evaluated. 599 bool WasEvaluated : 1; 600 601 /// \brief Whether this statement is being evaluated. 602 bool IsEvaluating : 1; 603 604 /// \brief Whether we already checked whether this statement was an 605 /// integral constant expression. 606 bool CheckedICE : 1; 607 608 /// \brief Whether we are checking whether this statement is an 609 /// integral constant expression. 610 bool CheckingICE : 1; 611 612 /// \brief Whether this statement is an integral constant expression, 613 /// or in C++11, whether the statement is a constant expression. Only 614 /// valid if CheckedICE is true. 615 bool IsICE : 1; 616 617 Stmt *Value; 618 APValue Evaluated; 619}; 620 621/// VarDecl - An instance of this class is created to represent a variable 622/// declaration or definition. 623class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> { 624public: 625 typedef clang::StorageClass StorageClass; 626 627 /// getStorageClassSpecifierString - Return the string used to 628 /// specify the storage class \p SC. 629 /// 630 /// It is illegal to call this function with SC == None. 631 static const char *getStorageClassSpecifierString(StorageClass SC); 632 633 /// \brief Initialization styles. 634 enum InitializationStyle { 635 CInit, ///< C-style initialization with assignment 636 CallInit, ///< Call-style initialization (C++98) 637 ListInit ///< Direct list-initialization (C++11) 638 }; 639 640 /// \brief Kinds of thread-local storage. 641 enum TLSKind { 642 TLS_None, ///< Not a TLS variable. 643 TLS_Static, ///< TLS with a known-constant initializer. 644 TLS_Dynamic ///< TLS with a dynamic initializer. 645 }; 646 647protected: 648 /// \brief Placeholder type used in Init to denote an unparsed C++ default 649 /// argument. 650 struct UnparsedDefaultArgument; 651 652 /// \brief Placeholder type used in Init to denote an uninstantiated C++ 653 /// default argument. 654 struct UninstantiatedDefaultArgument; 655 656 typedef llvm::PointerUnion4<Stmt *, EvaluatedStmt *, 657 UnparsedDefaultArgument *, 658 UninstantiatedDefaultArgument *> InitType; 659 660 /// \brief The initializer for this variable or, for a ParmVarDecl, the 661 /// C++ default argument. 662 mutable InitType Init; 663 664private: 665 class VarDeclBitfields { 666 friend class VarDecl; 667 friend class ASTDeclReader; 668 669 unsigned SClass : 3; 670 unsigned TSCSpec : 2; 671 unsigned InitStyle : 2; 672 673 /// \brief Whether this variable is the exception variable in a C++ catch 674 /// or an Objective-C @catch statement. 675 unsigned ExceptionVar : 1; 676 677 /// \brief Whether this local variable could be allocated in the return 678 /// slot of its function, enabling the named return value optimization 679 /// (NRVO). 680 unsigned NRVOVariable : 1; 681 682 /// \brief Whether this variable is the for-range-declaration in a C++0x 683 /// for-range statement. 684 unsigned CXXForRangeDecl : 1; 685 686 /// \brief Whether this variable is an ARC pseudo-__strong 687 /// variable; see isARCPseudoStrong() for details. 688 unsigned ARCPseudoStrong : 1; 689 690 /// \brief Whether this variable is (C++0x) constexpr. 691 unsigned IsConstexpr : 1; 692 }; 693 enum { NumVarDeclBits = 12 }; 694 695 friend class ASTDeclReader; 696 friend class StmtIteratorBase; 697 698protected: 699 enum { NumParameterIndexBits = 8 }; 700 701 class ParmVarDeclBitfields { 702 friend class ParmVarDecl; 703 friend class ASTDeclReader; 704 705 unsigned : NumVarDeclBits; 706 707 /// Whether this parameter inherits a default argument from a 708 /// prior declaration. 709 unsigned HasInheritedDefaultArg : 1; 710 711 /// Whether this parameter undergoes K&R argument promotion. 712 unsigned IsKNRPromoted : 1; 713 714 /// Whether this parameter is an ObjC method parameter or not. 715 unsigned IsObjCMethodParam : 1; 716 717 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier. 718 /// Otherwise, the number of function parameter scopes enclosing 719 /// the function parameter scope in which this parameter was 720 /// declared. 721 unsigned ScopeDepthOrObjCQuals : 7; 722 723 /// The number of parameters preceding this parameter in the 724 /// function parameter scope in which it was declared. 725 unsigned ParameterIndex : NumParameterIndexBits; 726 }; 727 728 union { 729 unsigned AllBits; 730 VarDeclBitfields VarDeclBits; 731 ParmVarDeclBitfields ParmVarDeclBits; 732 }; 733 734 VarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 735 SourceLocation IdLoc, IdentifierInfo *Id, 736 QualType T, TypeSourceInfo *TInfo, StorageClass SC) 737 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), Init() { 738 assert(sizeof(VarDeclBitfields) <= sizeof(unsigned)); 739 assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned)); 740 AllBits = 0; 741 VarDeclBits.SClass = SC; 742 // Everything else is implicitly initialized to false. 743 } 744 745 typedef Redeclarable<VarDecl> redeclarable_base; 746 virtual VarDecl *getNextRedeclaration() { return RedeclLink.getNext(); } 747 virtual VarDecl *getPreviousDeclImpl() { 748 return getPreviousDecl(); 749 } 750 virtual VarDecl *getMostRecentDeclImpl() { 751 return getMostRecentDecl(); 752 } 753 754public: 755 typedef redeclarable_base::redecl_iterator redecl_iterator; 756 using redeclarable_base::redecls_begin; 757 using redeclarable_base::redecls_end; 758 using redeclarable_base::getPreviousDecl; 759 using redeclarable_base::getMostRecentDecl; 760 761 static VarDecl *Create(ASTContext &C, DeclContext *DC, 762 SourceLocation StartLoc, SourceLocation IdLoc, 763 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 764 StorageClass S); 765 766 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID); 767 768 virtual SourceRange getSourceRange() const LLVM_READONLY; 769 770 /// \brief Returns the storage class as written in the source. For the 771 /// computed linkage of symbol, see getLinkage. 772 StorageClass getStorageClass() const { 773 return (StorageClass) VarDeclBits.SClass; 774 } 775 void setStorageClass(StorageClass SC); 776 777 void setTSCSpec(ThreadStorageClassSpecifier TSC) { 778 VarDeclBits.TSCSpec = TSC; 779 } 780 ThreadStorageClassSpecifier getTSCSpec() const { 781 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec); 782 } 783 TLSKind getTLSKind() const { 784 switch (VarDeclBits.TSCSpec) { 785 case TSCS_unspecified: 786 return TLS_None; 787 case TSCS___thread: // Fall through. 788 case TSCS__Thread_local: 789 return TLS_Static; 790 case TSCS_thread_local: 791 return TLS_Dynamic; 792 } 793 llvm_unreachable("Unknown thread storage class specifier!"); 794 } 795 796 /// hasLocalStorage - Returns true if a variable with function scope 797 /// is a non-static local variable. 798 bool hasLocalStorage() const { 799 if (getStorageClass() == SC_None) 800 return !isFileVarDecl(); 801 802 // Return true for: Auto, Register. 803 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal. 804 805 return getStorageClass() >= SC_Auto; 806 } 807 808 /// isStaticLocal - Returns true if a variable with function scope is a 809 /// static local variable. 810 bool isStaticLocal() const { 811 return getStorageClass() == SC_Static && !isFileVarDecl(); 812 } 813 814 /// \brief Returns true if a variable has extern or __private_extern__ 815 /// storage. 816 bool hasExternalStorage() const { 817 return getStorageClass() == SC_Extern || 818 getStorageClass() == SC_PrivateExtern; 819 } 820 821 /// hasGlobalStorage - Returns true for all variables that do not 822 /// have local storage. This includs all global variables as well 823 /// as static variables declared within a function. 824 bool hasGlobalStorage() const { return !hasLocalStorage(); } 825 826 /// Compute the language linkage. 827 LanguageLinkage getLanguageLinkage() const; 828 829 /// \brief Determines whether this variable is a variable with 830 /// external, C linkage. 831 bool isExternC() const; 832 833 /// \brief Determines whether this variable's context is, or is nested within, 834 /// a C++ extern "C" linkage spec. 835 bool isInExternCContext() const; 836 837 /// \brief Determines whether this variable's context is, or is nested within, 838 /// a C++ extern "C++" linkage spec. 839 bool isInExternCXXContext() const; 840 841 /// isLocalVarDecl - Returns true for local variable declarations 842 /// other than parameters. Note that this includes static variables 843 /// inside of functions. It also includes variables inside blocks. 844 /// 845 /// void foo() { int x; static int y; extern int z; } 846 /// 847 bool isLocalVarDecl() const { 848 if (getKind() != Decl::Var) 849 return false; 850 if (const DeclContext *DC = getDeclContext()) 851 return DC->getRedeclContext()->isFunctionOrMethod(); 852 return false; 853 } 854 855 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but 856 /// excludes variables declared in blocks. 857 bool isFunctionOrMethodVarDecl() const { 858 if (getKind() != Decl::Var) 859 return false; 860 const DeclContext *DC = getDeclContext()->getRedeclContext(); 861 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block; 862 } 863 864 /// \brief Determines whether this is a static data member. 865 /// 866 /// This will only be true in C++, and applies to, e.g., the 867 /// variable 'x' in: 868 /// \code 869 /// struct S { 870 /// static int x; 871 /// }; 872 /// \endcode 873 bool isStaticDataMember() const { 874 // If it wasn't static, it would be a FieldDecl. 875 return getKind() != Decl::ParmVar && getDeclContext()->isRecord(); 876 } 877 878 virtual VarDecl *getCanonicalDecl(); 879 const VarDecl *getCanonicalDecl() const { 880 return const_cast<VarDecl*>(this)->getCanonicalDecl(); 881 } 882 883 enum DefinitionKind { 884 DeclarationOnly, ///< This declaration is only a declaration. 885 TentativeDefinition, ///< This declaration is a tentative definition. 886 Definition ///< This declaration is definitely a definition. 887 }; 888 889 /// \brief Check whether this declaration is a definition. If this could be 890 /// a tentative definition (in C), don't check whether there's an overriding 891 /// definition. 892 DefinitionKind isThisDeclarationADefinition(ASTContext &) const; 893 DefinitionKind isThisDeclarationADefinition() const { 894 return isThisDeclarationADefinition(getASTContext()); 895 } 896 897 /// \brief Check whether this variable is defined in this 898 /// translation unit. 899 DefinitionKind hasDefinition(ASTContext &) const; 900 DefinitionKind hasDefinition() const { 901 return hasDefinition(getASTContext()); 902 } 903 904 /// \brief Get the tentative definition that acts as the real definition in 905 /// a TU. Returns null if there is a proper definition available. 906 VarDecl *getActingDefinition(); 907 const VarDecl *getActingDefinition() const { 908 return const_cast<VarDecl*>(this)->getActingDefinition(); 909 } 910 911 /// \brief Determine whether this is a tentative definition of a 912 /// variable in C. 913 bool isTentativeDefinitionNow() const; 914 915 /// \brief Get the real (not just tentative) definition for this declaration. 916 VarDecl *getDefinition(ASTContext &); 917 const VarDecl *getDefinition(ASTContext &C) const { 918 return const_cast<VarDecl*>(this)->getDefinition(C); 919 } 920 VarDecl *getDefinition() { 921 return getDefinition(getASTContext()); 922 } 923 const VarDecl *getDefinition() const { 924 return const_cast<VarDecl*>(this)->getDefinition(); 925 } 926 927 /// \brief Determine whether this is or was instantiated from an out-of-line 928 /// definition of a static data member. 929 virtual bool isOutOfLine() const; 930 931 /// \brief If this is a static data member, find its out-of-line definition. 932 VarDecl *getOutOfLineDefinition(); 933 934 /// isFileVarDecl - Returns true for file scoped variable declaration. 935 bool isFileVarDecl() const { 936 if (getKind() != Decl::Var) 937 return false; 938 939 if (getDeclContext()->getRedeclContext()->isFileContext()) 940 return true; 941 942 if (isStaticDataMember()) 943 return true; 944 945 return false; 946 } 947 948 /// getAnyInitializer - Get the initializer for this variable, no matter which 949 /// declaration it is attached to. 950 const Expr *getAnyInitializer() const { 951 const VarDecl *D; 952 return getAnyInitializer(D); 953 } 954 955 /// getAnyInitializer - Get the initializer for this variable, no matter which 956 /// declaration it is attached to. Also get that declaration. 957 const Expr *getAnyInitializer(const VarDecl *&D) const; 958 959 bool hasInit() const { 960 return !Init.isNull() && (Init.is<Stmt *>() || Init.is<EvaluatedStmt *>()); 961 } 962 const Expr *getInit() const { 963 if (Init.isNull()) 964 return 0; 965 966 const Stmt *S = Init.dyn_cast<Stmt *>(); 967 if (!S) { 968 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>()) 969 S = ES->Value; 970 } 971 return (const Expr*) S; 972 } 973 Expr *getInit() { 974 if (Init.isNull()) 975 return 0; 976 977 Stmt *S = Init.dyn_cast<Stmt *>(); 978 if (!S) { 979 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>()) 980 S = ES->Value; 981 } 982 983 return (Expr*) S; 984 } 985 986 /// \brief Retrieve the address of the initializer expression. 987 Stmt **getInitAddress() { 988 if (EvaluatedStmt *ES = Init.dyn_cast<EvaluatedStmt*>()) 989 return &ES->Value; 990 991 // This union hack tip-toes around strict-aliasing rules. 992 union { 993 InitType *InitPtr; 994 Stmt **StmtPtr; 995 }; 996 997 InitPtr = &Init; 998 return StmtPtr; 999 } 1000 1001 void setInit(Expr *I); 1002 1003 /// \brief Determine whether this variable is a reference that 1004 /// extends the lifetime of its temporary initializer. 1005 /// 1006 /// A reference extends the lifetime of its temporary initializer if 1007 /// it's initializer is an rvalue that would normally go out of scope 1008 /// at the end of the initializer (a full expression). In such cases, 1009 /// the reference itself takes ownership of the temporary, which will 1010 /// be destroyed when the reference goes out of scope. For example: 1011 /// 1012 /// \code 1013 /// const int &r = 1.0; // creates a temporary of type 'int' 1014 /// \endcode 1015 bool extendsLifetimeOfTemporary() const; 1016 1017 /// \brief Determine whether this variable's value can be used in a 1018 /// constant expression, according to the relevant language standard. 1019 /// This only checks properties of the declaration, and does not check 1020 /// whether the initializer is in fact a constant expression. 1021 bool isUsableInConstantExpressions(ASTContext &C) const; 1022 1023 EvaluatedStmt *ensureEvaluatedStmt() const; 1024 1025 /// \brief Attempt to evaluate the value of the initializer attached to this 1026 /// declaration, and produce notes explaining why it cannot be evaluated or is 1027 /// not a constant expression. Returns a pointer to the value if evaluation 1028 /// succeeded, 0 otherwise. 1029 APValue *evaluateValue() const; 1030 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const; 1031 1032 /// \brief Return the already-evaluated value of this variable's 1033 /// initializer, or NULL if the value is not yet known. Returns pointer 1034 /// to untyped APValue if the value could not be evaluated. 1035 APValue *getEvaluatedValue() const { 1036 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 1037 if (Eval->WasEvaluated) 1038 return &Eval->Evaluated; 1039 1040 return 0; 1041 } 1042 1043 /// \brief Determines whether it is already known whether the 1044 /// initializer is an integral constant expression or not. 1045 bool isInitKnownICE() const { 1046 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) 1047 return Eval->CheckedICE; 1048 1049 return false; 1050 } 1051 1052 /// \brief Determines whether the initializer is an integral constant 1053 /// expression, or in C++11, whether the initializer is a constant 1054 /// expression. 1055 /// 1056 /// \pre isInitKnownICE() 1057 bool isInitICE() const { 1058 assert(isInitKnownICE() && 1059 "Check whether we already know that the initializer is an ICE"); 1060 return Init.get<EvaluatedStmt *>()->IsICE; 1061 } 1062 1063 /// \brief Determine whether the value of the initializer attached to this 1064 /// declaration is an integral constant expression. 1065 bool checkInitIsICE() const; 1066 1067 void setInitStyle(InitializationStyle Style) { 1068 VarDeclBits.InitStyle = Style; 1069 } 1070 1071 /// \brief The style of initialization for this declaration. 1072 /// 1073 /// C-style initialization is "int x = 1;". Call-style initialization is 1074 /// a C++98 direct-initializer, e.g. "int x(1);". The Init expression will be 1075 /// the expression inside the parens or a "ClassType(a,b,c)" class constructor 1076 /// expression for class types. List-style initialization is C++11 syntax, 1077 /// e.g. "int x{1};". Clients can distinguish between different forms of 1078 /// initialization by checking this value. In particular, "int x = {1};" is 1079 /// C-style, "int x({1})" is call-style, and "int x{1};" is list-style; the 1080 /// Init expression in all three cases is an InitListExpr. 1081 InitializationStyle getInitStyle() const { 1082 return static_cast<InitializationStyle>(VarDeclBits.InitStyle); 1083 } 1084 1085 /// \brief Whether the initializer is a direct-initializer (list or call). 1086 bool isDirectInit() const { 1087 return getInitStyle() != CInit; 1088 } 1089 1090 /// \brief Determine whether this variable is the exception variable in a 1091 /// C++ catch statememt or an Objective-C \@catch statement. 1092 bool isExceptionVariable() const { 1093 return VarDeclBits.ExceptionVar; 1094 } 1095 void setExceptionVariable(bool EV) { VarDeclBits.ExceptionVar = EV; } 1096 1097 /// \brief Determine whether this local variable can be used with the named 1098 /// return value optimization (NRVO). 1099 /// 1100 /// The named return value optimization (NRVO) works by marking certain 1101 /// non-volatile local variables of class type as NRVO objects. These 1102 /// locals can be allocated within the return slot of their containing 1103 /// function, in which case there is no need to copy the object to the 1104 /// return slot when returning from the function. Within the function body, 1105 /// each return that returns the NRVO object will have this variable as its 1106 /// NRVO candidate. 1107 bool isNRVOVariable() const { return VarDeclBits.NRVOVariable; } 1108 void setNRVOVariable(bool NRVO) { VarDeclBits.NRVOVariable = NRVO; } 1109 1110 /// \brief Determine whether this variable is the for-range-declaration in 1111 /// a C++0x for-range statement. 1112 bool isCXXForRangeDecl() const { return VarDeclBits.CXXForRangeDecl; } 1113 void setCXXForRangeDecl(bool FRD) { VarDeclBits.CXXForRangeDecl = FRD; } 1114 1115 /// \brief Determine whether this variable is an ARC pseudo-__strong 1116 /// variable. A pseudo-__strong variable has a __strong-qualified 1117 /// type but does not actually retain the object written into it. 1118 /// Generally such variables are also 'const' for safety. 1119 bool isARCPseudoStrong() const { return VarDeclBits.ARCPseudoStrong; } 1120 void setARCPseudoStrong(bool ps) { VarDeclBits.ARCPseudoStrong = ps; } 1121 1122 /// Whether this variable is (C++11) constexpr. 1123 bool isConstexpr() const { return VarDeclBits.IsConstexpr; } 1124 void setConstexpr(bool IC) { VarDeclBits.IsConstexpr = IC; } 1125 1126 /// \brief If this variable is an instantiated static data member of a 1127 /// class template specialization, returns the templated static data member 1128 /// from which it was instantiated. 1129 VarDecl *getInstantiatedFromStaticDataMember() const; 1130 1131 /// \brief If this variable is a static data member, determine what kind of 1132 /// template specialization or instantiation this is. 1133 TemplateSpecializationKind getTemplateSpecializationKind() const; 1134 1135 /// \brief If this variable is an instantiation of a static data member of a 1136 /// class template specialization, retrieves the member specialization 1137 /// information. 1138 MemberSpecializationInfo *getMemberSpecializationInfo() const; 1139 1140 /// \brief For a static data member that was instantiated from a static 1141 /// data member of a class template, set the template specialiation kind. 1142 void setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1143 SourceLocation PointOfInstantiation = SourceLocation()); 1144 1145 // Implement isa/cast/dyncast/etc. 1146 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1147 static bool classofKind(Kind K) { return K >= firstVar && K <= lastVar; } 1148}; 1149 1150class ImplicitParamDecl : public VarDecl { 1151 virtual void anchor(); 1152public: 1153 static ImplicitParamDecl *Create(ASTContext &C, DeclContext *DC, 1154 SourceLocation IdLoc, IdentifierInfo *Id, 1155 QualType T); 1156 1157 static ImplicitParamDecl *CreateDeserialized(ASTContext &C, unsigned ID); 1158 1159 ImplicitParamDecl(DeclContext *DC, SourceLocation IdLoc, 1160 IdentifierInfo *Id, QualType Type) 1161 : VarDecl(ImplicitParam, DC, IdLoc, IdLoc, Id, Type, 1162 /*tinfo*/ 0, SC_None) { 1163 setImplicit(); 1164 } 1165 1166 // Implement isa/cast/dyncast/etc. 1167 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1168 static bool classofKind(Kind K) { return K == ImplicitParam; } 1169}; 1170 1171/// ParmVarDecl - Represents a parameter to a function. 1172class ParmVarDecl : public VarDecl { 1173public: 1174 enum { MaxFunctionScopeDepth = 255 }; 1175 enum { MaxFunctionScopeIndex = 255 }; 1176 1177protected: 1178 ParmVarDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 1179 SourceLocation IdLoc, IdentifierInfo *Id, 1180 QualType T, TypeSourceInfo *TInfo, 1181 StorageClass S, Expr *DefArg) 1182 : VarDecl(DK, DC, StartLoc, IdLoc, Id, T, TInfo, S) { 1183 assert(ParmVarDeclBits.HasInheritedDefaultArg == false); 1184 assert(ParmVarDeclBits.IsKNRPromoted == false); 1185 assert(ParmVarDeclBits.IsObjCMethodParam == false); 1186 setDefaultArg(DefArg); 1187 } 1188 1189public: 1190 static ParmVarDecl *Create(ASTContext &C, DeclContext *DC, 1191 SourceLocation StartLoc, 1192 SourceLocation IdLoc, IdentifierInfo *Id, 1193 QualType T, TypeSourceInfo *TInfo, 1194 StorageClass S, Expr *DefArg); 1195 1196 static ParmVarDecl *CreateDeserialized(ASTContext &C, unsigned ID); 1197 1198 virtual SourceRange getSourceRange() const LLVM_READONLY; 1199 1200 void setObjCMethodScopeInfo(unsigned parameterIndex) { 1201 ParmVarDeclBits.IsObjCMethodParam = true; 1202 setParameterIndex(parameterIndex); 1203 } 1204 1205 void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex) { 1206 assert(!ParmVarDeclBits.IsObjCMethodParam); 1207 1208 ParmVarDeclBits.ScopeDepthOrObjCQuals = scopeDepth; 1209 assert(ParmVarDeclBits.ScopeDepthOrObjCQuals == scopeDepth 1210 && "truncation!"); 1211 1212 setParameterIndex(parameterIndex); 1213 } 1214 1215 bool isObjCMethodParameter() const { 1216 return ParmVarDeclBits.IsObjCMethodParam; 1217 } 1218 1219 unsigned getFunctionScopeDepth() const { 1220 if (ParmVarDeclBits.IsObjCMethodParam) return 0; 1221 return ParmVarDeclBits.ScopeDepthOrObjCQuals; 1222 } 1223 1224 /// Returns the index of this parameter in its prototype or method scope. 1225 unsigned getFunctionScopeIndex() const { 1226 return getParameterIndex(); 1227 } 1228 1229 ObjCDeclQualifier getObjCDeclQualifier() const { 1230 if (!ParmVarDeclBits.IsObjCMethodParam) return OBJC_TQ_None; 1231 return ObjCDeclQualifier(ParmVarDeclBits.ScopeDepthOrObjCQuals); 1232 } 1233 void setObjCDeclQualifier(ObjCDeclQualifier QTVal) { 1234 assert(ParmVarDeclBits.IsObjCMethodParam); 1235 ParmVarDeclBits.ScopeDepthOrObjCQuals = QTVal; 1236 } 1237 1238 /// True if the value passed to this parameter must undergo 1239 /// K&R-style default argument promotion: 1240 /// 1241 /// C99 6.5.2.2. 1242 /// If the expression that denotes the called function has a type 1243 /// that does not include a prototype, the integer promotions are 1244 /// performed on each argument, and arguments that have type float 1245 /// are promoted to double. 1246 bool isKNRPromoted() const { 1247 return ParmVarDeclBits.IsKNRPromoted; 1248 } 1249 void setKNRPromoted(bool promoted) { 1250 ParmVarDeclBits.IsKNRPromoted = promoted; 1251 } 1252 1253 Expr *getDefaultArg(); 1254 const Expr *getDefaultArg() const { 1255 return const_cast<ParmVarDecl *>(this)->getDefaultArg(); 1256 } 1257 1258 void setDefaultArg(Expr *defarg) { 1259 Init = reinterpret_cast<Stmt *>(defarg); 1260 } 1261 1262 /// \brief Retrieve the source range that covers the entire default 1263 /// argument. 1264 SourceRange getDefaultArgRange() const; 1265 void setUninstantiatedDefaultArg(Expr *arg) { 1266 Init = reinterpret_cast<UninstantiatedDefaultArgument *>(arg); 1267 } 1268 Expr *getUninstantiatedDefaultArg() { 1269 return (Expr *)Init.get<UninstantiatedDefaultArgument *>(); 1270 } 1271 const Expr *getUninstantiatedDefaultArg() const { 1272 return (const Expr *)Init.get<UninstantiatedDefaultArgument *>(); 1273 } 1274 1275 /// hasDefaultArg - Determines whether this parameter has a default argument, 1276 /// either parsed or not. 1277 bool hasDefaultArg() const { 1278 return getInit() || hasUnparsedDefaultArg() || 1279 hasUninstantiatedDefaultArg(); 1280 } 1281 1282 /// hasUnparsedDefaultArg - Determines whether this parameter has a 1283 /// default argument that has not yet been parsed. This will occur 1284 /// during the processing of a C++ class whose member functions have 1285 /// default arguments, e.g., 1286 /// @code 1287 /// class X { 1288 /// public: 1289 /// void f(int x = 17); // x has an unparsed default argument now 1290 /// }; // x has a regular default argument now 1291 /// @endcode 1292 bool hasUnparsedDefaultArg() const { 1293 return Init.is<UnparsedDefaultArgument*>(); 1294 } 1295 1296 bool hasUninstantiatedDefaultArg() const { 1297 return Init.is<UninstantiatedDefaultArgument*>(); 1298 } 1299 1300 /// setUnparsedDefaultArg - Specify that this parameter has an 1301 /// unparsed default argument. The argument will be replaced with a 1302 /// real default argument via setDefaultArg when the class 1303 /// definition enclosing the function declaration that owns this 1304 /// default argument is completed. 1305 void setUnparsedDefaultArg() { 1306 Init = (UnparsedDefaultArgument *)0; 1307 } 1308 1309 bool hasInheritedDefaultArg() const { 1310 return ParmVarDeclBits.HasInheritedDefaultArg; 1311 } 1312 1313 void setHasInheritedDefaultArg(bool I = true) { 1314 ParmVarDeclBits.HasInheritedDefaultArg = I; 1315 } 1316 1317 QualType getOriginalType() const { 1318 if (getTypeSourceInfo()) 1319 return getTypeSourceInfo()->getType(); 1320 return getType(); 1321 } 1322 1323 /// \brief Determine whether this parameter is actually a function 1324 /// parameter pack. 1325 bool isParameterPack() const; 1326 1327 /// setOwningFunction - Sets the function declaration that owns this 1328 /// ParmVarDecl. Since ParmVarDecls are often created before the 1329 /// FunctionDecls that own them, this routine is required to update 1330 /// the DeclContext appropriately. 1331 void setOwningFunction(DeclContext *FD) { setDeclContext(FD); } 1332 1333 // Implement isa/cast/dyncast/etc. 1334 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 1335 static bool classofKind(Kind K) { return K == ParmVar; } 1336 1337private: 1338 enum { ParameterIndexSentinel = (1 << NumParameterIndexBits) - 1 }; 1339 1340 void setParameterIndex(unsigned parameterIndex) { 1341 if (parameterIndex >= ParameterIndexSentinel) { 1342 setParameterIndexLarge(parameterIndex); 1343 return; 1344 } 1345 1346 ParmVarDeclBits.ParameterIndex = parameterIndex; 1347 assert(ParmVarDeclBits.ParameterIndex == parameterIndex && "truncation!"); 1348 } 1349 unsigned getParameterIndex() const { 1350 unsigned d = ParmVarDeclBits.ParameterIndex; 1351 return d == ParameterIndexSentinel ? getParameterIndexLarge() : d; 1352 } 1353 1354 void setParameterIndexLarge(unsigned parameterIndex); 1355 unsigned getParameterIndexLarge() const; 1356}; 1357 1358/// FunctionDecl - An instance of this class is created to represent a 1359/// function declaration or definition. 1360/// 1361/// Since a given function can be declared several times in a program, 1362/// there may be several FunctionDecls that correspond to that 1363/// function. Only one of those FunctionDecls will be found when 1364/// traversing the list of declarations in the context of the 1365/// FunctionDecl (e.g., the translation unit); this FunctionDecl 1366/// contains all of the information known about the function. Other, 1367/// previous declarations of the function are available via the 1368/// getPreviousDecl() chain. 1369class FunctionDecl : public DeclaratorDecl, public DeclContext, 1370 public Redeclarable<FunctionDecl> { 1371public: 1372 typedef clang::StorageClass StorageClass; 1373 1374 /// \brief The kind of templated function a FunctionDecl can be. 1375 enum TemplatedKind { 1376 TK_NonTemplate, 1377 TK_FunctionTemplate, 1378 TK_MemberSpecialization, 1379 TK_FunctionTemplateSpecialization, 1380 TK_DependentFunctionTemplateSpecialization 1381 }; 1382 1383private: 1384 /// ParamInfo - new[]'d array of pointers to VarDecls for the formal 1385 /// parameters of this function. This is null if a prototype or if there are 1386 /// no formals. 1387 ParmVarDecl **ParamInfo; 1388 1389 /// DeclsInPrototypeScope - Array of pointers to NamedDecls for 1390 /// decls defined in the function prototype that are not parameters. E.g. 1391 /// 'enum Y' in 'void f(enum Y {AA} x) {}'. 1392 ArrayRef<NamedDecl *> DeclsInPrototypeScope; 1393 1394 LazyDeclStmtPtr Body; 1395 1396 // FIXME: This can be packed into the bitfields in Decl. 1397 // NOTE: VC++ treats enums as signed, avoid using the StorageClass enum 1398 unsigned SClass : 2; 1399 bool IsInline : 1; 1400 bool IsInlineSpecified : 1; 1401 bool IsVirtualAsWritten : 1; 1402 bool IsPure : 1; 1403 bool HasInheritedPrototype : 1; 1404 bool HasWrittenPrototype : 1; 1405 bool IsDeleted : 1; 1406 bool IsTrivial : 1; // sunk from CXXMethodDecl 1407 bool IsDefaulted : 1; // sunk from CXXMethoDecl 1408 bool IsExplicitlyDefaulted : 1; //sunk from CXXMethodDecl 1409 bool HasImplicitReturnZero : 1; 1410 bool IsLateTemplateParsed : 1; 1411 bool IsConstexpr : 1; 1412 1413 /// \brief Indicates if the function was a definition but its body was 1414 /// skipped. 1415 unsigned HasSkippedBody : 1; 1416 1417 /// \brief End part of this FunctionDecl's source range. 1418 /// 1419 /// We could compute the full range in getSourceRange(). However, when we're 1420 /// dealing with a function definition deserialized from a PCH/AST file, 1421 /// we can only compute the full range once the function body has been 1422 /// de-serialized, so it's far better to have the (sometimes-redundant) 1423 /// EndRangeLoc. 1424 SourceLocation EndRangeLoc; 1425 1426 /// \brief The template or declaration that this declaration 1427 /// describes or was instantiated from, respectively. 1428 /// 1429 /// For non-templates, this value will be NULL. For function 1430 /// declarations that describe a function template, this will be a 1431 /// pointer to a FunctionTemplateDecl. For member functions 1432 /// of class template specializations, this will be a MemberSpecializationInfo 1433 /// pointer containing information about the specialization. 1434 /// For function template specializations, this will be a 1435 /// FunctionTemplateSpecializationInfo, which contains information about 1436 /// the template being specialized and the template arguments involved in 1437 /// that specialization. 1438 llvm::PointerUnion4<FunctionTemplateDecl *, 1439 MemberSpecializationInfo *, 1440 FunctionTemplateSpecializationInfo *, 1441 DependentFunctionTemplateSpecializationInfo *> 1442 TemplateOrSpecialization; 1443 1444 /// DNLoc - Provides source/type location info for the 1445 /// declaration name embedded in the DeclaratorDecl base class. 1446 DeclarationNameLoc DNLoc; 1447 1448 /// \brief Specify that this function declaration is actually a function 1449 /// template specialization. 1450 /// 1451 /// \param C the ASTContext. 1452 /// 1453 /// \param Template the function template that this function template 1454 /// specialization specializes. 1455 /// 1456 /// \param TemplateArgs the template arguments that produced this 1457 /// function template specialization from the template. 1458 /// 1459 /// \param InsertPos If non-NULL, the position in the function template 1460 /// specialization set where the function template specialization data will 1461 /// be inserted. 1462 /// 1463 /// \param TSK the kind of template specialization this is. 1464 /// 1465 /// \param TemplateArgsAsWritten location info of template arguments. 1466 /// 1467 /// \param PointOfInstantiation point at which the function template 1468 /// specialization was first instantiated. 1469 void setFunctionTemplateSpecialization(ASTContext &C, 1470 FunctionTemplateDecl *Template, 1471 const TemplateArgumentList *TemplateArgs, 1472 void *InsertPos, 1473 TemplateSpecializationKind TSK, 1474 const TemplateArgumentListInfo *TemplateArgsAsWritten, 1475 SourceLocation PointOfInstantiation); 1476 1477 /// \brief Specify that this record is an instantiation of the 1478 /// member function FD. 1479 void setInstantiationOfMemberFunction(ASTContext &C, FunctionDecl *FD, 1480 TemplateSpecializationKind TSK); 1481 1482 void setParams(ASTContext &C, ArrayRef<ParmVarDecl *> NewParamInfo); 1483 1484protected: 1485 FunctionDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 1486 const DeclarationNameInfo &NameInfo, 1487 QualType T, TypeSourceInfo *TInfo, 1488 StorageClass S, bool isInlineSpecified, 1489 bool isConstexprSpecified) 1490 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo, 1491 StartLoc), 1492 DeclContext(DK), 1493 ParamInfo(0), Body(), 1494 SClass(S), 1495 IsInline(isInlineSpecified), IsInlineSpecified(isInlineSpecified), 1496 IsVirtualAsWritten(false), IsPure(false), HasInheritedPrototype(false), 1497 HasWrittenPrototype(true), IsDeleted(false), IsTrivial(false), 1498 IsDefaulted(false), IsExplicitlyDefaulted(false), 1499 HasImplicitReturnZero(false), IsLateTemplateParsed(false), 1500 IsConstexpr(isConstexprSpecified), HasSkippedBody(false), 1501 EndRangeLoc(NameInfo.getEndLoc()), 1502 TemplateOrSpecialization(), 1503 DNLoc(NameInfo.getInfo()) {} 1504 1505 typedef Redeclarable<FunctionDecl> redeclarable_base; 1506 virtual FunctionDecl *getNextRedeclaration() { return RedeclLink.getNext(); } 1507 virtual FunctionDecl *getPreviousDeclImpl() { 1508 return getPreviousDecl(); 1509 } 1510 virtual FunctionDecl *getMostRecentDeclImpl() { 1511 return getMostRecentDecl(); 1512 } 1513 1514public: 1515 typedef redeclarable_base::redecl_iterator redecl_iterator; 1516 using redeclarable_base::redecls_begin; 1517 using redeclarable_base::redecls_end; 1518 using redeclarable_base::getPreviousDecl; 1519 using redeclarable_base::getMostRecentDecl; 1520 1521 static FunctionDecl *Create(ASTContext &C, DeclContext *DC, 1522 SourceLocation StartLoc, SourceLocation NLoc, 1523 DeclarationName N, QualType T, 1524 TypeSourceInfo *TInfo, 1525 StorageClass SC, 1526 bool isInlineSpecified = false, 1527 bool hasWrittenPrototype = true, 1528 bool isConstexprSpecified = false) { 1529 DeclarationNameInfo NameInfo(N, NLoc); 1530 return FunctionDecl::Create(C, DC, StartLoc, NameInfo, T, TInfo, 1531 SC, 1532 isInlineSpecified, hasWrittenPrototype, 1533 isConstexprSpecified); 1534 } 1535 1536 static FunctionDecl *Create(ASTContext &C, DeclContext *DC, 1537 SourceLocation StartLoc, 1538 const DeclarationNameInfo &NameInfo, 1539 QualType T, TypeSourceInfo *TInfo, 1540 StorageClass SC, 1541 bool isInlineSpecified, 1542 bool hasWrittenPrototype, 1543 bool isConstexprSpecified = false); 1544 1545 static FunctionDecl *CreateDeserialized(ASTContext &C, unsigned ID); 1546 1547 DeclarationNameInfo getNameInfo() const { 1548 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc); 1549 } 1550 1551 virtual void getNameForDiagnostic(raw_ostream &OS, 1552 const PrintingPolicy &Policy, 1553 bool Qualified) const; 1554 1555 void setRangeEnd(SourceLocation E) { EndRangeLoc = E; } 1556 1557 virtual SourceRange getSourceRange() const LLVM_READONLY; 1558 1559 /// \brief Returns true if the function has a body (definition). The 1560 /// function body might be in any of the (re-)declarations of this 1561 /// function. The variant that accepts a FunctionDecl pointer will 1562 /// set that function declaration to the actual declaration 1563 /// containing the body (if there is one). 1564 bool hasBody(const FunctionDecl *&Definition) const; 1565 1566 virtual bool hasBody() const { 1567 const FunctionDecl* Definition; 1568 return hasBody(Definition); 1569 } 1570 1571 /// hasTrivialBody - Returns whether the function has a trivial body that does 1572 /// not require any specific codegen. 1573 bool hasTrivialBody() const; 1574 1575 /// isDefined - Returns true if the function is defined at all, including 1576 /// a deleted definition. Except for the behavior when the function is 1577 /// deleted, behaves like hasBody. 1578 bool isDefined(const FunctionDecl *&Definition) const; 1579 1580 virtual bool isDefined() const { 1581 const FunctionDecl* Definition; 1582 return isDefined(Definition); 1583 } 1584 1585 /// getBody - Retrieve the body (definition) of the function. The 1586 /// function body might be in any of the (re-)declarations of this 1587 /// function. The variant that accepts a FunctionDecl pointer will 1588 /// set that function declaration to the actual declaration 1589 /// containing the body (if there is one). 1590 /// NOTE: For checking if there is a body, use hasBody() instead, to avoid 1591 /// unnecessary AST de-serialization of the body. 1592 Stmt *getBody(const FunctionDecl *&Definition) const; 1593 1594 virtual Stmt *getBody() const { 1595 const FunctionDecl* Definition; 1596 return getBody(Definition); 1597 } 1598 1599 /// isThisDeclarationADefinition - Returns whether this specific 1600 /// declaration of the function is also a definition. This does not 1601 /// determine whether the function has been defined (e.g., in a 1602 /// previous definition); for that information, use isDefined. Note 1603 /// that this returns false for a defaulted function unless that function 1604 /// has been implicitly defined (possibly as deleted). 1605 bool isThisDeclarationADefinition() const { 1606 return IsDeleted || Body || IsLateTemplateParsed; 1607 } 1608 1609 /// doesThisDeclarationHaveABody - Returns whether this specific 1610 /// declaration of the function has a body - that is, if it is a non- 1611 /// deleted definition. 1612 bool doesThisDeclarationHaveABody() const { 1613 return Body || IsLateTemplateParsed; 1614 } 1615 1616 void setBody(Stmt *B); 1617 void setLazyBody(uint64_t Offset) { Body = Offset; } 1618 1619 /// Whether this function is variadic. 1620 bool isVariadic() const; 1621 1622 /// Whether this function is marked as virtual explicitly. 1623 bool isVirtualAsWritten() const { return IsVirtualAsWritten; } 1624 void setVirtualAsWritten(bool V) { IsVirtualAsWritten = V; } 1625 1626 /// Whether this virtual function is pure, i.e. makes the containing class 1627 /// abstract. 1628 bool isPure() const { return IsPure; } 1629 void setPure(bool P = true); 1630 1631 /// Whether this templated function will be late parsed. 1632 bool isLateTemplateParsed() const { return IsLateTemplateParsed; } 1633 void setLateTemplateParsed(bool ILT = true) { IsLateTemplateParsed = ILT; } 1634 1635 /// Whether this function is "trivial" in some specialized C++ senses. 1636 /// Can only be true for default constructors, copy constructors, 1637 /// copy assignment operators, and destructors. Not meaningful until 1638 /// the class has been fully built by Sema. 1639 bool isTrivial() const { return IsTrivial; } 1640 void setTrivial(bool IT) { IsTrivial = IT; } 1641 1642 /// Whether this function is defaulted per C++0x. Only valid for 1643 /// special member functions. 1644 bool isDefaulted() const { return IsDefaulted; } 1645 void setDefaulted(bool D = true) { IsDefaulted = D; } 1646 1647 /// Whether this function is explicitly defaulted per C++0x. Only valid 1648 /// for special member functions. 1649 bool isExplicitlyDefaulted() const { return IsExplicitlyDefaulted; } 1650 void setExplicitlyDefaulted(bool ED = true) { IsExplicitlyDefaulted = ED; } 1651 1652 /// Whether falling off this function implicitly returns null/zero. 1653 /// If a more specific implicit return value is required, front-ends 1654 /// should synthesize the appropriate return statements. 1655 bool hasImplicitReturnZero() const { return HasImplicitReturnZero; } 1656 void setHasImplicitReturnZero(bool IRZ) { HasImplicitReturnZero = IRZ; } 1657 1658 /// \brief Whether this function has a prototype, either because one 1659 /// was explicitly written or because it was "inherited" by merging 1660 /// a declaration without a prototype with a declaration that has a 1661 /// prototype. 1662 bool hasPrototype() const { 1663 return HasWrittenPrototype || HasInheritedPrototype; 1664 } 1665 1666 bool hasWrittenPrototype() const { return HasWrittenPrototype; } 1667 1668 /// \brief Whether this function inherited its prototype from a 1669 /// previous declaration. 1670 bool hasInheritedPrototype() const { return HasInheritedPrototype; } 1671 void setHasInheritedPrototype(bool P = true) { HasInheritedPrototype = P; } 1672 1673 /// Whether this is a (C++11) constexpr function or constexpr constructor. 1674 bool isConstexpr() const { return IsConstexpr; } 1675 void setConstexpr(bool IC) { IsConstexpr = IC; } 1676 1677 /// \brief Whether this function has been deleted. 1678 /// 1679 /// A function that is "deleted" (via the C++0x "= delete" syntax) 1680 /// acts like a normal function, except that it cannot actually be 1681 /// called or have its address taken. Deleted functions are 1682 /// typically used in C++ overload resolution to attract arguments 1683 /// whose type or lvalue/rvalue-ness would permit the use of a 1684 /// different overload that would behave incorrectly. For example, 1685 /// one might use deleted functions to ban implicit conversion from 1686 /// a floating-point number to an Integer type: 1687 /// 1688 /// @code 1689 /// struct Integer { 1690 /// Integer(long); // construct from a long 1691 /// Integer(double) = delete; // no construction from float or double 1692 /// Integer(long double) = delete; // no construction from long double 1693 /// }; 1694 /// @endcode 1695 // If a function is deleted, its first declaration must be. 1696 bool isDeleted() const { return getCanonicalDecl()->IsDeleted; } 1697 bool isDeletedAsWritten() const { return IsDeleted && !IsDefaulted; } 1698 void setDeletedAsWritten(bool D = true) { IsDeleted = D; } 1699 1700 /// \brief Determines whether this function is "main", which is the 1701 /// entry point into an executable program. 1702 bool isMain() const; 1703 1704 /// \brief Determines whether this operator new or delete is one 1705 /// of the reserved global placement operators: 1706 /// void *operator new(size_t, void *); 1707 /// void *operator new[](size_t, void *); 1708 /// void operator delete(void *, void *); 1709 /// void operator delete[](void *, void *); 1710 /// These functions have special behavior under [new.delete.placement]: 1711 /// These functions are reserved, a C++ program may not define 1712 /// functions that displace the versions in the Standard C++ library. 1713 /// The provisions of [basic.stc.dynamic] do not apply to these 1714 /// reserved placement forms of operator new and operator delete. 1715 /// 1716 /// This function must be an allocation or deallocation function. 1717 bool isReservedGlobalPlacementOperator() const; 1718 1719 /// Compute the language linkage. 1720 LanguageLinkage getLanguageLinkage() const; 1721 1722 /// \brief Determines whether this function is a function with 1723 /// external, C linkage. 1724 bool isExternC() const; 1725 1726 /// \brief Determines whether this function's context is, or is nested within, 1727 /// a C++ extern "C" linkage spec. 1728 bool isInExternCContext() const; 1729 1730 /// \brief Determines whether this function's context is, or is nested within, 1731 /// a C++ extern "C++" linkage spec. 1732 bool isInExternCXXContext() const; 1733 1734 /// \brief Determines whether this is a global function. 1735 bool isGlobal() const; 1736 1737 /// \brief Determines whether this function is known to be 'noreturn', through 1738 /// an attribute on its declaration or its type. 1739 bool isNoReturn() const; 1740 1741 /// \brief True if the function was a definition but its body was skipped. 1742 bool hasSkippedBody() const { return HasSkippedBody; } 1743 void setHasSkippedBody(bool Skipped = true) { HasSkippedBody = Skipped; } 1744 1745 void setPreviousDeclaration(FunctionDecl * PrevDecl); 1746 1747 virtual const FunctionDecl *getCanonicalDecl() const; 1748 virtual FunctionDecl *getCanonicalDecl(); 1749 1750 unsigned getBuiltinID() const; 1751 1752 // Iterator access to formal parameters. 1753 unsigned param_size() const { return getNumParams(); } 1754 typedef ParmVarDecl **param_iterator; 1755 typedef ParmVarDecl * const *param_const_iterator; 1756 1757 param_iterator param_begin() { return ParamInfo; } 1758 param_iterator param_end() { return ParamInfo+param_size(); } 1759 1760 param_const_iterator param_begin() const { return ParamInfo; } 1761 param_const_iterator param_end() const { return ParamInfo+param_size(); } 1762 1763 /// getNumParams - Return the number of parameters this function must have 1764 /// based on its FunctionType. This is the length of the ParamInfo array 1765 /// after it has been created. 1766 unsigned getNumParams() const; 1767 1768 const ParmVarDecl *getParamDecl(unsigned i) const { 1769 assert(i < getNumParams() && "Illegal param #"); 1770 return ParamInfo[i]; 1771 } 1772 ParmVarDecl *getParamDecl(unsigned i) { 1773 assert(i < getNumParams() && "Illegal param #"); 1774 return ParamInfo[i]; 1775 } 1776 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 1777 setParams(getASTContext(), NewParamInfo); 1778 } 1779 1780 const ArrayRef<NamedDecl *> &getDeclsInPrototypeScope() const { 1781 return DeclsInPrototypeScope; 1782 } 1783 void setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls); 1784 1785 /// getMinRequiredArguments - Returns the minimum number of arguments 1786 /// needed to call this function. This may be fewer than the number of 1787 /// function parameters, if some of the parameters have default 1788 /// arguments (in C++). 1789 unsigned getMinRequiredArguments() const; 1790 1791 QualType getResultType() const { 1792 return getType()->getAs<FunctionType>()->getResultType(); 1793 } 1794 1795 /// \brief Determine the type of an expression that calls this function. 1796 QualType getCallResultType() const { 1797 return getType()->getAs<FunctionType>()->getCallResultType(getASTContext()); 1798 } 1799 1800 /// \brief Returns the storage class as written in the source. For the 1801 /// computed linkage of symbol, see getLinkage. 1802 StorageClass getStorageClass() const { return StorageClass(SClass); } 1803 1804 /// \brief Determine whether the "inline" keyword was specified for this 1805 /// function. 1806 bool isInlineSpecified() const { return IsInlineSpecified; } 1807 1808 /// Set whether the "inline" keyword was specified for this function. 1809 void setInlineSpecified(bool I) { 1810 IsInlineSpecified = I; 1811 IsInline = I; 1812 } 1813 1814 /// Flag that this function is implicitly inline. 1815 void setImplicitlyInline() { 1816 IsInline = true; 1817 } 1818 1819 /// \brief Determine whether this function should be inlined, because it is 1820 /// either marked "inline" or "constexpr" or is a member function of a class 1821 /// that was defined in the class body. 1822 bool isInlined() const { return IsInline; } 1823 1824 bool isInlineDefinitionExternallyVisible() const; 1825 1826 bool doesDeclarationForceExternallyVisibleDefinition() const; 1827 1828 /// isOverloadedOperator - Whether this function declaration 1829 /// represents an C++ overloaded operator, e.g., "operator+". 1830 bool isOverloadedOperator() const { 1831 return getOverloadedOperator() != OO_None; 1832 } 1833 1834 OverloadedOperatorKind getOverloadedOperator() const; 1835 1836 const IdentifierInfo *getLiteralIdentifier() const; 1837 1838 /// \brief If this function is an instantiation of a member function 1839 /// of a class template specialization, retrieves the function from 1840 /// which it was instantiated. 1841 /// 1842 /// This routine will return non-NULL for (non-templated) member 1843 /// functions of class templates and for instantiations of function 1844 /// templates. For example, given: 1845 /// 1846 /// \code 1847 /// template<typename T> 1848 /// struct X { 1849 /// void f(T); 1850 /// }; 1851 /// \endcode 1852 /// 1853 /// The declaration for X<int>::f is a (non-templated) FunctionDecl 1854 /// whose parent is the class template specialization X<int>. For 1855 /// this declaration, getInstantiatedFromFunction() will return 1856 /// the FunctionDecl X<T>::A. When a complete definition of 1857 /// X<int>::A is required, it will be instantiated from the 1858 /// declaration returned by getInstantiatedFromMemberFunction(). 1859 FunctionDecl *getInstantiatedFromMemberFunction() const; 1860 1861 /// \brief What kind of templated function this is. 1862 TemplatedKind getTemplatedKind() const; 1863 1864 /// \brief If this function is an instantiation of a member function of a 1865 /// class template specialization, retrieves the member specialization 1866 /// information. 1867 MemberSpecializationInfo *getMemberSpecializationInfo() const { 1868 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1869 } 1870 1871 /// \brief Specify that this record is an instantiation of the 1872 /// member function FD. 1873 void setInstantiationOfMemberFunction(FunctionDecl *FD, 1874 TemplateSpecializationKind TSK) { 1875 setInstantiationOfMemberFunction(getASTContext(), FD, TSK); 1876 } 1877 1878 /// \brief Retrieves the function template that is described by this 1879 /// function declaration. 1880 /// 1881 /// Every function template is represented as a FunctionTemplateDecl 1882 /// and a FunctionDecl (or something derived from FunctionDecl). The 1883 /// former contains template properties (such as the template 1884 /// parameter lists) while the latter contains the actual 1885 /// description of the template's 1886 /// contents. FunctionTemplateDecl::getTemplatedDecl() retrieves the 1887 /// FunctionDecl that describes the function template, 1888 /// getDescribedFunctionTemplate() retrieves the 1889 /// FunctionTemplateDecl from a FunctionDecl. 1890 FunctionTemplateDecl *getDescribedFunctionTemplate() const { 1891 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl*>(); 1892 } 1893 1894 void setDescribedFunctionTemplate(FunctionTemplateDecl *Template) { 1895 TemplateOrSpecialization = Template; 1896 } 1897 1898 /// \brief Determine whether this function is a function template 1899 /// specialization. 1900 bool isFunctionTemplateSpecialization() const { 1901 return getPrimaryTemplate() != 0; 1902 } 1903 1904 /// \brief Retrieve the class scope template pattern that this function 1905 /// template specialization is instantiated from. 1906 FunctionDecl *getClassScopeSpecializationPattern() const; 1907 1908 /// \brief If this function is actually a function template specialization, 1909 /// retrieve information about this function template specialization. 1910 /// Otherwise, returns NULL. 1911 FunctionTemplateSpecializationInfo *getTemplateSpecializationInfo() const { 1912 return TemplateOrSpecialization. 1913 dyn_cast<FunctionTemplateSpecializationInfo*>(); 1914 } 1915 1916 /// \brief Determines whether this function is a function template 1917 /// specialization or a member of a class template specialization that can 1918 /// be implicitly instantiated. 1919 bool isImplicitlyInstantiable() const; 1920 1921 /// \brief Determines if the given function was instantiated from a 1922 /// function template. 1923 bool isTemplateInstantiation() const; 1924 1925 /// \brief Retrieve the function declaration from which this function could 1926 /// be instantiated, if it is an instantiation (rather than a non-template 1927 /// or a specialization, for example). 1928 FunctionDecl *getTemplateInstantiationPattern() const; 1929 1930 /// \brief Retrieve the primary template that this function template 1931 /// specialization either specializes or was instantiated from. 1932 /// 1933 /// If this function declaration is not a function template specialization, 1934 /// returns NULL. 1935 FunctionTemplateDecl *getPrimaryTemplate() const; 1936 1937 /// \brief Retrieve the template arguments used to produce this function 1938 /// template specialization from the primary template. 1939 /// 1940 /// If this function declaration is not a function template specialization, 1941 /// returns NULL. 1942 const TemplateArgumentList *getTemplateSpecializationArgs() const; 1943 1944 /// \brief Retrieve the template argument list as written in the sources, 1945 /// if any. 1946 /// 1947 /// If this function declaration is not a function template specialization 1948 /// or if it had no explicit template argument list, returns NULL. 1949 /// Note that it an explicit template argument list may be written empty, 1950 /// e.g., template<> void foo<>(char* s); 1951 const ASTTemplateArgumentListInfo* 1952 getTemplateSpecializationArgsAsWritten() const; 1953 1954 /// \brief Specify that this function declaration is actually a function 1955 /// template specialization. 1956 /// 1957 /// \param Template the function template that this function template 1958 /// specialization specializes. 1959 /// 1960 /// \param TemplateArgs the template arguments that produced this 1961 /// function template specialization from the template. 1962 /// 1963 /// \param InsertPos If non-NULL, the position in the function template 1964 /// specialization set where the function template specialization data will 1965 /// be inserted. 1966 /// 1967 /// \param TSK the kind of template specialization this is. 1968 /// 1969 /// \param TemplateArgsAsWritten location info of template arguments. 1970 /// 1971 /// \param PointOfInstantiation point at which the function template 1972 /// specialization was first instantiated. 1973 void setFunctionTemplateSpecialization(FunctionTemplateDecl *Template, 1974 const TemplateArgumentList *TemplateArgs, 1975 void *InsertPos, 1976 TemplateSpecializationKind TSK = TSK_ImplicitInstantiation, 1977 const TemplateArgumentListInfo *TemplateArgsAsWritten = 0, 1978 SourceLocation PointOfInstantiation = SourceLocation()) { 1979 setFunctionTemplateSpecialization(getASTContext(), Template, TemplateArgs, 1980 InsertPos, TSK, TemplateArgsAsWritten, 1981 PointOfInstantiation); 1982 } 1983 1984 /// \brief Specifies that this function declaration is actually a 1985 /// dependent function template specialization. 1986 void setDependentTemplateSpecialization(ASTContext &Context, 1987 const UnresolvedSetImpl &Templates, 1988 const TemplateArgumentListInfo &TemplateArgs); 1989 1990 DependentFunctionTemplateSpecializationInfo * 1991 getDependentSpecializationInfo() const { 1992 return TemplateOrSpecialization. 1993 dyn_cast<DependentFunctionTemplateSpecializationInfo*>(); 1994 } 1995 1996 /// \brief Determine what kind of template instantiation this function 1997 /// represents. 1998 TemplateSpecializationKind getTemplateSpecializationKind() const; 1999 2000 /// \brief Determine what kind of template instantiation this function 2001 /// represents. 2002 void setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2003 SourceLocation PointOfInstantiation = SourceLocation()); 2004 2005 /// \brief Retrieve the (first) point of instantiation of a function template 2006 /// specialization or a member of a class template specialization. 2007 /// 2008 /// \returns the first point of instantiation, if this function was 2009 /// instantiated from a template; otherwise, returns an invalid source 2010 /// location. 2011 SourceLocation getPointOfInstantiation() const; 2012 2013 /// \brief Determine whether this is or was instantiated from an out-of-line 2014 /// definition of a member function. 2015 virtual bool isOutOfLine() const; 2016 2017 /// \brief Identify a memory copying or setting function. 2018 /// If the given function is a memory copy or setting function, returns 2019 /// the corresponding Builtin ID. If the function is not a memory function, 2020 /// returns 0. 2021 unsigned getMemoryFunctionKind() const; 2022 2023 // Implement isa/cast/dyncast/etc. 2024 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2025 static bool classofKind(Kind K) { 2026 return K >= firstFunction && K <= lastFunction; 2027 } 2028 static DeclContext *castToDeclContext(const FunctionDecl *D) { 2029 return static_cast<DeclContext *>(const_cast<FunctionDecl*>(D)); 2030 } 2031 static FunctionDecl *castFromDeclContext(const DeclContext *DC) { 2032 return static_cast<FunctionDecl *>(const_cast<DeclContext*>(DC)); 2033 } 2034 2035 friend class ASTDeclReader; 2036 friend class ASTDeclWriter; 2037}; 2038 2039 2040/// FieldDecl - An instance of this class is created by Sema::ActOnField to 2041/// represent a member of a struct/union/class. 2042class FieldDecl : public DeclaratorDecl { 2043 // FIXME: This can be packed into the bitfields in Decl. 2044 bool Mutable : 1; 2045 mutable unsigned CachedFieldIndex : 31; 2046 2047 /// \brief An InClassInitStyle value, and either a bit width expression (if 2048 /// the InClassInitStyle value is ICIS_NoInit), or a pointer to the in-class 2049 /// initializer for this field (otherwise). 2050 /// 2051 /// We can safely combine these two because in-class initializers are not 2052 /// permitted for bit-fields. 2053 /// 2054 /// If the InClassInitStyle is not ICIS_NoInit and the initializer is null, 2055 /// then this field has an in-class initializer which has not yet been parsed 2056 /// and attached. 2057 llvm::PointerIntPair<Expr *, 2, unsigned> InitializerOrBitWidth; 2058protected: 2059 FieldDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 2060 SourceLocation IdLoc, IdentifierInfo *Id, 2061 QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 2062 InClassInitStyle InitStyle) 2063 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc), 2064 Mutable(Mutable), CachedFieldIndex(0), 2065 InitializerOrBitWidth(BW, InitStyle) { 2066 assert((!BW || InitStyle == ICIS_NoInit) && "got initializer for bitfield"); 2067 } 2068 2069public: 2070 static FieldDecl *Create(const ASTContext &C, DeclContext *DC, 2071 SourceLocation StartLoc, SourceLocation IdLoc, 2072 IdentifierInfo *Id, QualType T, 2073 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 2074 InClassInitStyle InitStyle); 2075 2076 static FieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); 2077 2078 /// getFieldIndex - Returns the index of this field within its record, 2079 /// as appropriate for passing to ASTRecordLayout::getFieldOffset. 2080 unsigned getFieldIndex() const; 2081 2082 /// isMutable - Determines whether this field is mutable (C++ only). 2083 bool isMutable() const { return Mutable; } 2084 2085 /// isBitfield - Determines whether this field is a bitfield. 2086 bool isBitField() const { 2087 return getInClassInitStyle() == ICIS_NoInit && 2088 InitializerOrBitWidth.getPointer(); 2089 } 2090 2091 /// @brief Determines whether this is an unnamed bitfield. 2092 bool isUnnamedBitfield() const { return isBitField() && !getDeclName(); } 2093 2094 /// isAnonymousStructOrUnion - Determines whether this field is a 2095 /// representative for an anonymous struct or union. Such fields are 2096 /// unnamed and are implicitly generated by the implementation to 2097 /// store the data for the anonymous union or struct. 2098 bool isAnonymousStructOrUnion() const; 2099 2100 Expr *getBitWidth() const { 2101 return isBitField() ? InitializerOrBitWidth.getPointer() : 0; 2102 } 2103 unsigned getBitWidthValue(const ASTContext &Ctx) const; 2104 2105 /// setBitWidth - Set the bit-field width for this member. 2106 // Note: used by some clients (i.e., do not remove it). 2107 void setBitWidth(Expr *Width); 2108 /// removeBitWidth - Remove the bit-field width from this member. 2109 // Note: used by some clients (i.e., do not remove it). 2110 void removeBitWidth() { 2111 assert(isBitField() && "no bitfield width to remove"); 2112 InitializerOrBitWidth.setPointer(0); 2113 } 2114 2115 /// getInClassInitStyle - Get the kind of (C++11) in-class initializer which 2116 /// this field has. 2117 InClassInitStyle getInClassInitStyle() const { 2118 return static_cast<InClassInitStyle>(InitializerOrBitWidth.getInt()); 2119 } 2120 2121 /// hasInClassInitializer - Determine whether this member has a C++11 in-class 2122 /// initializer. 2123 bool hasInClassInitializer() const { 2124 return getInClassInitStyle() != ICIS_NoInit; 2125 } 2126 /// getInClassInitializer - Get the C++11 in-class initializer for this 2127 /// member, or null if one has not been set. If a valid declaration has an 2128 /// in-class initializer, but this returns null, then we have not parsed and 2129 /// attached it yet. 2130 Expr *getInClassInitializer() const { 2131 return hasInClassInitializer() ? InitializerOrBitWidth.getPointer() : 0; 2132 } 2133 /// setInClassInitializer - Set the C++11 in-class initializer for this 2134 /// member. 2135 void setInClassInitializer(Expr *Init); 2136 /// removeInClassInitializer - Remove the C++11 in-class initializer from this 2137 /// member. 2138 void removeInClassInitializer() { 2139 assert(hasInClassInitializer() && "no initializer to remove"); 2140 InitializerOrBitWidth.setPointer(0); 2141 InitializerOrBitWidth.setInt(ICIS_NoInit); 2142 } 2143 2144 /// getParent - Returns the parent of this field declaration, which 2145 /// is the struct in which this method is defined. 2146 const RecordDecl *getParent() const { 2147 return cast<RecordDecl>(getDeclContext()); 2148 } 2149 2150 RecordDecl *getParent() { 2151 return cast<RecordDecl>(getDeclContext()); 2152 } 2153 2154 SourceRange getSourceRange() const LLVM_READONLY; 2155 2156 // Implement isa/cast/dyncast/etc. 2157 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2158 static bool classofKind(Kind K) { return K >= firstField && K <= lastField; } 2159 2160 friend class ASTDeclReader; 2161 friend class ASTDeclWriter; 2162}; 2163 2164/// EnumConstantDecl - An instance of this object exists for each enum constant 2165/// that is defined. For example, in "enum X {a,b}", each of a/b are 2166/// EnumConstantDecl's, X is an instance of EnumDecl, and the type of a/b is a 2167/// TagType for the X EnumDecl. 2168class EnumConstantDecl : public ValueDecl { 2169 Stmt *Init; // an integer constant expression 2170 llvm::APSInt Val; // The value. 2171protected: 2172 EnumConstantDecl(DeclContext *DC, SourceLocation L, 2173 IdentifierInfo *Id, QualType T, Expr *E, 2174 const llvm::APSInt &V) 2175 : ValueDecl(EnumConstant, DC, L, Id, T), Init((Stmt*)E), Val(V) {} 2176 2177public: 2178 2179 static EnumConstantDecl *Create(ASTContext &C, EnumDecl *DC, 2180 SourceLocation L, IdentifierInfo *Id, 2181 QualType T, Expr *E, 2182 const llvm::APSInt &V); 2183 static EnumConstantDecl *CreateDeserialized(ASTContext &C, unsigned ID); 2184 2185 const Expr *getInitExpr() const { return (const Expr*) Init; } 2186 Expr *getInitExpr() { return (Expr*) Init; } 2187 const llvm::APSInt &getInitVal() const { return Val; } 2188 2189 void setInitExpr(Expr *E) { Init = (Stmt*) E; } 2190 void setInitVal(const llvm::APSInt &V) { Val = V; } 2191 2192 SourceRange getSourceRange() const LLVM_READONLY; 2193 2194 // Implement isa/cast/dyncast/etc. 2195 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2196 static bool classofKind(Kind K) { return K == EnumConstant; } 2197 2198 friend class StmtIteratorBase; 2199}; 2200 2201/// IndirectFieldDecl - An instance of this class is created to represent a 2202/// field injected from an anonymous union/struct into the parent scope. 2203/// IndirectFieldDecl are always implicit. 2204class IndirectFieldDecl : public ValueDecl { 2205 virtual void anchor(); 2206 NamedDecl **Chaining; 2207 unsigned ChainingSize; 2208 2209 IndirectFieldDecl(DeclContext *DC, SourceLocation L, 2210 DeclarationName N, QualType T, 2211 NamedDecl **CH, unsigned CHS) 2212 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH), ChainingSize(CHS) {} 2213 2214public: 2215 static IndirectFieldDecl *Create(ASTContext &C, DeclContext *DC, 2216 SourceLocation L, IdentifierInfo *Id, 2217 QualType T, NamedDecl **CH, unsigned CHS); 2218 2219 static IndirectFieldDecl *CreateDeserialized(ASTContext &C, unsigned ID); 2220 2221 typedef NamedDecl * const *chain_iterator; 2222 chain_iterator chain_begin() const { return Chaining; } 2223 chain_iterator chain_end() const { return Chaining+ChainingSize; } 2224 2225 unsigned getChainingSize() const { return ChainingSize; } 2226 2227 FieldDecl *getAnonField() const { 2228 assert(ChainingSize >= 2); 2229 return cast<FieldDecl>(Chaining[ChainingSize - 1]); 2230 } 2231 2232 VarDecl *getVarDecl() const { 2233 assert(ChainingSize >= 2); 2234 return dyn_cast<VarDecl>(*chain_begin()); 2235 } 2236 2237 // Implement isa/cast/dyncast/etc. 2238 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2239 static bool classofKind(Kind K) { return K == IndirectField; } 2240 friend class ASTDeclReader; 2241}; 2242 2243/// TypeDecl - Represents a declaration of a type. 2244/// 2245class TypeDecl : public NamedDecl { 2246 virtual void anchor(); 2247 /// TypeForDecl - This indicates the Type object that represents 2248 /// this TypeDecl. It is a cache maintained by 2249 /// ASTContext::getTypedefType, ASTContext::getTagDeclType, and 2250 /// ASTContext::getTemplateTypeParmType, and TemplateTypeParmDecl. 2251 mutable const Type *TypeForDecl; 2252 /// LocStart - The start of the source range for this declaration. 2253 SourceLocation LocStart; 2254 friend class ASTContext; 2255 friend class DeclContext; 2256 friend class TagDecl; 2257 friend class TemplateTypeParmDecl; 2258 friend class TagType; 2259 friend class ASTReader; 2260 2261protected: 2262 TypeDecl(Kind DK, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, 2263 SourceLocation StartL = SourceLocation()) 2264 : NamedDecl(DK, DC, L, Id), TypeForDecl(0), LocStart(StartL) {} 2265 2266public: 2267 // Low-level accessor. If you just want the type defined by this node, 2268 // check out ASTContext::getTypeDeclType or one of 2269 // ASTContext::getTypedefType, ASTContext::getRecordType, etc. if you 2270 // already know the specific kind of node this is. 2271 const Type *getTypeForDecl() const { return TypeForDecl; } 2272 void setTypeForDecl(const Type *TD) { TypeForDecl = TD; } 2273 2274 SourceLocation getLocStart() const LLVM_READONLY { return LocStart; } 2275 void setLocStart(SourceLocation L) { LocStart = L; } 2276 virtual SourceRange getSourceRange() const LLVM_READONLY { 2277 if (LocStart.isValid()) 2278 return SourceRange(LocStart, getLocation()); 2279 else 2280 return SourceRange(getLocation()); 2281 } 2282 2283 // Implement isa/cast/dyncast/etc. 2284 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2285 static bool classofKind(Kind K) { return K >= firstType && K <= lastType; } 2286}; 2287 2288 2289/// Base class for declarations which introduce a typedef-name. 2290class TypedefNameDecl : public TypeDecl, public Redeclarable<TypedefNameDecl> { 2291 virtual void anchor(); 2292 /// UnderlyingType - This is the type the typedef is set to. 2293 TypeSourceInfo *TInfo; 2294 2295protected: 2296 TypedefNameDecl(Kind DK, DeclContext *DC, SourceLocation StartLoc, 2297 SourceLocation IdLoc, IdentifierInfo *Id, 2298 TypeSourceInfo *TInfo) 2299 : TypeDecl(DK, DC, IdLoc, Id, StartLoc), TInfo(TInfo) {} 2300 2301 typedef Redeclarable<TypedefNameDecl> redeclarable_base; 2302 virtual TypedefNameDecl *getNextRedeclaration() { 2303 return RedeclLink.getNext(); 2304 } 2305 virtual TypedefNameDecl *getPreviousDeclImpl() { 2306 return getPreviousDecl(); 2307 } 2308 virtual TypedefNameDecl *getMostRecentDeclImpl() { 2309 return getMostRecentDecl(); 2310 } 2311 2312public: 2313 typedef redeclarable_base::redecl_iterator redecl_iterator; 2314 using redeclarable_base::redecls_begin; 2315 using redeclarable_base::redecls_end; 2316 using redeclarable_base::getPreviousDecl; 2317 using redeclarable_base::getMostRecentDecl; 2318 2319 TypeSourceInfo *getTypeSourceInfo() const { 2320 return TInfo; 2321 } 2322 2323 /// Retrieves the canonical declaration of this typedef-name. 2324 TypedefNameDecl *getCanonicalDecl() { 2325 return getFirstDeclaration(); 2326 } 2327 const TypedefNameDecl *getCanonicalDecl() const { 2328 return getFirstDeclaration(); 2329 } 2330 2331 QualType getUnderlyingType() const { 2332 return TInfo->getType(); 2333 } 2334 void setTypeSourceInfo(TypeSourceInfo *newType) { 2335 TInfo = newType; 2336 } 2337 2338 // Implement isa/cast/dyncast/etc. 2339 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2340 static bool classofKind(Kind K) { 2341 return K >= firstTypedefName && K <= lastTypedefName; 2342 } 2343}; 2344 2345/// TypedefDecl - Represents the declaration of a typedef-name via the 'typedef' 2346/// type specifier. 2347class TypedefDecl : public TypedefNameDecl { 2348 TypedefDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, 2349 IdentifierInfo *Id, TypeSourceInfo *TInfo) 2350 : TypedefNameDecl(Typedef, DC, StartLoc, IdLoc, Id, TInfo) {} 2351 2352public: 2353 static TypedefDecl *Create(ASTContext &C, DeclContext *DC, 2354 SourceLocation StartLoc, SourceLocation IdLoc, 2355 IdentifierInfo *Id, TypeSourceInfo *TInfo); 2356 static TypedefDecl *CreateDeserialized(ASTContext &C, unsigned ID); 2357 2358 SourceRange getSourceRange() const LLVM_READONLY; 2359 2360 // Implement isa/cast/dyncast/etc. 2361 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2362 static bool classofKind(Kind K) { return K == Typedef; } 2363}; 2364 2365/// TypeAliasDecl - Represents the declaration of a typedef-name via a C++0x 2366/// alias-declaration. 2367class TypeAliasDecl : public TypedefNameDecl { 2368 TypeAliasDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, 2369 IdentifierInfo *Id, TypeSourceInfo *TInfo) 2370 : TypedefNameDecl(TypeAlias, DC, StartLoc, IdLoc, Id, TInfo) {} 2371 2372public: 2373 static TypeAliasDecl *Create(ASTContext &C, DeclContext *DC, 2374 SourceLocation StartLoc, SourceLocation IdLoc, 2375 IdentifierInfo *Id, TypeSourceInfo *TInfo); 2376 static TypeAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID); 2377 2378 SourceRange getSourceRange() const LLVM_READONLY; 2379 2380 // Implement isa/cast/dyncast/etc. 2381 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2382 static bool classofKind(Kind K) { return K == TypeAlias; } 2383}; 2384 2385/// TagDecl - Represents the declaration of a struct/union/class/enum. 2386class TagDecl 2387 : public TypeDecl, public DeclContext, public Redeclarable<TagDecl> { 2388public: 2389 // This is really ugly. 2390 typedef TagTypeKind TagKind; 2391 2392private: 2393 // FIXME: This can be packed into the bitfields in Decl. 2394 /// TagDeclKind - The TagKind enum. 2395 unsigned TagDeclKind : 3; 2396 2397 /// IsCompleteDefinition - True if this is a definition ("struct foo 2398 /// {};"), false if it is a declaration ("struct foo;"). It is not 2399 /// a definition until the definition has been fully processed. 2400 bool IsCompleteDefinition : 1; 2401 2402protected: 2403 /// IsBeingDefined - True if this is currently being defined. 2404 bool IsBeingDefined : 1; 2405 2406private: 2407 /// IsEmbeddedInDeclarator - True if this tag declaration is 2408 /// "embedded" (i.e., defined or declared for the very first time) 2409 /// in the syntax of a declarator. 2410 bool IsEmbeddedInDeclarator : 1; 2411 2412 /// \brief True if this tag is free standing, e.g. "struct foo;". 2413 bool IsFreeStanding : 1; 2414 2415protected: 2416 // These are used by (and only defined for) EnumDecl. 2417 unsigned NumPositiveBits : 8; 2418 unsigned NumNegativeBits : 8; 2419 2420 /// IsScoped - True if this tag declaration is a scoped enumeration. Only 2421 /// possible in C++11 mode. 2422 bool IsScoped : 1; 2423 /// IsScopedUsingClassTag - If this tag declaration is a scoped enum, 2424 /// then this is true if the scoped enum was declared using the class 2425 /// tag, false if it was declared with the struct tag. No meaning is 2426 /// associated if this tag declaration is not a scoped enum. 2427 bool IsScopedUsingClassTag : 1; 2428 2429 /// IsFixed - True if this is an enumeration with fixed underlying type. Only 2430 /// possible in C++11, Microsoft extensions, or Objective C mode. 2431 bool IsFixed : 1; 2432 2433 /// \brief Indicates whether it is possible for declarations of this kind 2434 /// to have an out-of-date definition. 2435 /// 2436 /// This option is only enabled when modules are enabled. 2437 bool MayHaveOutOfDateDef : 1; 2438 2439private: 2440 SourceLocation RBraceLoc; 2441 2442 // A struct representing syntactic qualifier info, 2443 // to be used for the (uncommon) case of out-of-line declarations. 2444 typedef QualifierInfo ExtInfo; 2445 2446 /// TypedefNameDeclOrQualifier - If the (out-of-line) tag declaration name 2447 /// is qualified, it points to the qualifier info (nns and range); 2448 /// otherwise, if the tag declaration is anonymous and it is part of 2449 /// a typedef or alias, it points to the TypedefNameDecl (used for mangling); 2450 /// otherwise, it is a null (TypedefNameDecl) pointer. 2451 llvm::PointerUnion<TypedefNameDecl*, ExtInfo*> TypedefNameDeclOrQualifier; 2452 2453 bool hasExtInfo() const { return TypedefNameDeclOrQualifier.is<ExtInfo*>(); } 2454 ExtInfo *getExtInfo() { return TypedefNameDeclOrQualifier.get<ExtInfo*>(); } 2455 const ExtInfo *getExtInfo() const { 2456 return TypedefNameDeclOrQualifier.get<ExtInfo*>(); 2457 } 2458 2459protected: 2460 TagDecl(Kind DK, TagKind TK, DeclContext *DC, 2461 SourceLocation L, IdentifierInfo *Id, 2462 TagDecl *PrevDecl, SourceLocation StartL) 2463 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), 2464 TypedefNameDeclOrQualifier((TypedefNameDecl*) 0) { 2465 assert((DK != Enum || TK == TTK_Enum) && 2466 "EnumDecl not matched with TTK_Enum"); 2467 TagDeclKind = TK; 2468 IsCompleteDefinition = false; 2469 IsBeingDefined = false; 2470 IsEmbeddedInDeclarator = false; 2471 IsFreeStanding = false; 2472 setPreviousDeclaration(PrevDecl); 2473 } 2474 2475 typedef Redeclarable<TagDecl> redeclarable_base; 2476 virtual TagDecl *getNextRedeclaration() { return RedeclLink.getNext(); } 2477 virtual TagDecl *getPreviousDeclImpl() { 2478 return getPreviousDecl(); 2479 } 2480 virtual TagDecl *getMostRecentDeclImpl() { 2481 return getMostRecentDecl(); 2482 } 2483 2484 /// @brief Completes the definition of this tag declaration. 2485 /// 2486 /// This is a helper function for derived classes. 2487 void completeDefinition(); 2488 2489public: 2490 typedef redeclarable_base::redecl_iterator redecl_iterator; 2491 using redeclarable_base::redecls_begin; 2492 using redeclarable_base::redecls_end; 2493 using redeclarable_base::getPreviousDecl; 2494 using redeclarable_base::getMostRecentDecl; 2495 2496 SourceLocation getRBraceLoc() const { return RBraceLoc; } 2497 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; } 2498 2499 /// getInnerLocStart - Return SourceLocation representing start of source 2500 /// range ignoring outer template declarations. 2501 SourceLocation getInnerLocStart() const { return getLocStart(); } 2502 2503 /// getOuterLocStart - Return SourceLocation representing start of source 2504 /// range taking into account any outer template declarations. 2505 SourceLocation getOuterLocStart() const; 2506 virtual SourceRange getSourceRange() const LLVM_READONLY; 2507 2508 virtual TagDecl* getCanonicalDecl(); 2509 const TagDecl* getCanonicalDecl() const { 2510 return const_cast<TagDecl*>(this)->getCanonicalDecl(); 2511 } 2512 2513 /// isThisDeclarationADefinition() - Return true if this declaration 2514 /// is a completion definintion of the type. Provided for consistency. 2515 bool isThisDeclarationADefinition() const { 2516 return isCompleteDefinition(); 2517 } 2518 2519 /// isCompleteDefinition - Return true if this decl has its body 2520 /// fully specified. 2521 bool isCompleteDefinition() const { 2522 return IsCompleteDefinition; 2523 } 2524 2525 /// isBeingDefined - Return true if this decl is currently being defined. 2526 bool isBeingDefined() const { 2527 return IsBeingDefined; 2528 } 2529 2530 bool isEmbeddedInDeclarator() const { 2531 return IsEmbeddedInDeclarator; 2532 } 2533 void setEmbeddedInDeclarator(bool isInDeclarator) { 2534 IsEmbeddedInDeclarator = isInDeclarator; 2535 } 2536 2537 bool isFreeStanding() const { return IsFreeStanding; } 2538 void setFreeStanding(bool isFreeStanding = true) { 2539 IsFreeStanding = isFreeStanding; 2540 } 2541 2542 /// \brief Whether this declaration declares a type that is 2543 /// dependent, i.e., a type that somehow depends on template 2544 /// parameters. 2545 bool isDependentType() const { return isDependentContext(); } 2546 2547 /// @brief Starts the definition of this tag declaration. 2548 /// 2549 /// This method should be invoked at the beginning of the definition 2550 /// of this tag declaration. It will set the tag type into a state 2551 /// where it is in the process of being defined. 2552 void startDefinition(); 2553 2554 /// getDefinition - Returns the TagDecl that actually defines this 2555 /// struct/union/class/enum. When determining whether or not a 2556 /// struct/union/class/enum has a definition, one should use this 2557 /// method as opposed to 'isDefinition'. 'isDefinition' indicates 2558 /// whether or not a specific TagDecl is defining declaration, not 2559 /// whether or not the struct/union/class/enum type is defined. 2560 /// This method returns NULL if there is no TagDecl that defines 2561 /// the struct/union/class/enum. 2562 TagDecl *getDefinition() const; 2563 2564 void setCompleteDefinition(bool V) { IsCompleteDefinition = V; } 2565 2566 // FIXME: Return StringRef; 2567 const char *getKindName() const { 2568 return TypeWithKeyword::getTagTypeKindName(getTagKind()); 2569 } 2570 2571 TagKind getTagKind() const { 2572 return TagKind(TagDeclKind); 2573 } 2574 2575 void setTagKind(TagKind TK) { TagDeclKind = TK; } 2576 2577 bool isStruct() const { return getTagKind() == TTK_Struct; } 2578 bool isInterface() const { return getTagKind() == TTK_Interface; } 2579 bool isClass() const { return getTagKind() == TTK_Class; } 2580 bool isUnion() const { return getTagKind() == TTK_Union; } 2581 bool isEnum() const { return getTagKind() == TTK_Enum; } 2582 2583 /// Is this tag type named, either directly or via being defined in 2584 /// a typedef of this type? 2585 /// 2586 /// C++11 [basic.link]p8: 2587 /// A type is said to have linkage if and only if: 2588 /// - it is a class or enumeration type that is named (or has a 2589 /// name for linkage purposes) and the name has linkage; ... 2590 /// C++11 [dcl.typedef]p9: 2591 /// If the typedef declaration defines an unnamed class (or enum), 2592 /// the first typedef-name declared by the declaration to be that 2593 /// class type (or enum type) is used to denote the class type (or 2594 /// enum type) for linkage purposes only. 2595 /// 2596 /// C does not have an analogous rule, but the same concept is 2597 /// nonetheless useful in some places. 2598 bool hasNameForLinkage() const { 2599 return (getDeclName() || getTypedefNameForAnonDecl()); 2600 } 2601 2602 TypedefNameDecl *getTypedefNameForAnonDecl() const { 2603 return hasExtInfo() ? 0 : 2604 TypedefNameDeclOrQualifier.get<TypedefNameDecl*>(); 2605 } 2606 2607 void setTypedefNameForAnonDecl(TypedefNameDecl *TDD); 2608 2609 /// \brief Retrieve the nested-name-specifier that qualifies the name of this 2610 /// declaration, if it was present in the source. 2611 NestedNameSpecifier *getQualifier() const { 2612 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier() 2613 : 0; 2614 } 2615 2616 /// \brief Retrieve the nested-name-specifier (with source-location 2617 /// information) that qualifies the name of this declaration, if it was 2618 /// present in the source. 2619 NestedNameSpecifierLoc getQualifierLoc() const { 2620 return hasExtInfo() ? getExtInfo()->QualifierLoc 2621 : NestedNameSpecifierLoc(); 2622 } 2623 2624 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc); 2625 2626 unsigned getNumTemplateParameterLists() const { 2627 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0; 2628 } 2629 TemplateParameterList *getTemplateParameterList(unsigned i) const { 2630 assert(i < getNumTemplateParameterLists()); 2631 return getExtInfo()->TemplParamLists[i]; 2632 } 2633 void setTemplateParameterListsInfo(ASTContext &Context, unsigned NumTPLists, 2634 TemplateParameterList **TPLists); 2635 2636 // Implement isa/cast/dyncast/etc. 2637 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2638 static bool classofKind(Kind K) { return K >= firstTag && K <= lastTag; } 2639 2640 static DeclContext *castToDeclContext(const TagDecl *D) { 2641 return static_cast<DeclContext *>(const_cast<TagDecl*>(D)); 2642 } 2643 static TagDecl *castFromDeclContext(const DeclContext *DC) { 2644 return static_cast<TagDecl *>(const_cast<DeclContext*>(DC)); 2645 } 2646 2647 friend class ASTDeclReader; 2648 friend class ASTDeclWriter; 2649}; 2650 2651/// EnumDecl - Represents an enum. In C++11, enums can be forward-declared 2652/// with a fixed underlying type, and in C we allow them to be forward-declared 2653/// with no underlying type as an extension. 2654class EnumDecl : public TagDecl { 2655 virtual void anchor(); 2656 /// IntegerType - This represent the integer type that the enum corresponds 2657 /// to for code generation purposes. Note that the enumerator constants may 2658 /// have a different type than this does. 2659 /// 2660 /// If the underlying integer type was explicitly stated in the source 2661 /// code, this is a TypeSourceInfo* for that type. Otherwise this type 2662 /// was automatically deduced somehow, and this is a Type*. 2663 /// 2664 /// Normally if IsFixed(), this would contain a TypeSourceInfo*, but in 2665 /// some cases it won't. 2666 /// 2667 /// The underlying type of an enumeration never has any qualifiers, so 2668 /// we can get away with just storing a raw Type*, and thus save an 2669 /// extra pointer when TypeSourceInfo is needed. 2670 2671 llvm::PointerUnion<const Type*, TypeSourceInfo*> IntegerType; 2672 2673 /// PromotionType - The integer type that values of this type should 2674 /// promote to. In C, enumerators are generally of an integer type 2675 /// directly, but gcc-style large enumerators (and all enumerators 2676 /// in C++) are of the enum type instead. 2677 QualType PromotionType; 2678 2679 /// \brief If this enumeration is an instantiation of a member enumeration 2680 /// of a class template specialization, this is the member specialization 2681 /// information. 2682 MemberSpecializationInfo *SpecializationInfo; 2683 2684 EnumDecl(DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, 2685 IdentifierInfo *Id, EnumDecl *PrevDecl, 2686 bool Scoped, bool ScopedUsingClassTag, bool Fixed) 2687 : TagDecl(Enum, TTK_Enum, DC, IdLoc, Id, PrevDecl, StartLoc), 2688 SpecializationInfo(0) { 2689 assert(Scoped || !ScopedUsingClassTag); 2690 IntegerType = (const Type*)0; 2691 NumNegativeBits = 0; 2692 NumPositiveBits = 0; 2693 IsScoped = Scoped; 2694 IsScopedUsingClassTag = ScopedUsingClassTag; 2695 IsFixed = Fixed; 2696 } 2697 2698 void setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 2699 TemplateSpecializationKind TSK); 2700public: 2701 EnumDecl *getCanonicalDecl() { 2702 return cast<EnumDecl>(TagDecl::getCanonicalDecl()); 2703 } 2704 const EnumDecl *getCanonicalDecl() const { 2705 return cast<EnumDecl>(TagDecl::getCanonicalDecl()); 2706 } 2707 2708 const EnumDecl *getPreviousDecl() const { 2709 return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl()); 2710 } 2711 EnumDecl *getPreviousDecl() { 2712 return cast_or_null<EnumDecl>(TagDecl::getPreviousDecl()); 2713 } 2714 2715 const EnumDecl *getMostRecentDecl() const { 2716 return cast<EnumDecl>(TagDecl::getMostRecentDecl()); 2717 } 2718 EnumDecl *getMostRecentDecl() { 2719 return cast<EnumDecl>(TagDecl::getMostRecentDecl()); 2720 } 2721 2722 EnumDecl *getDefinition() const { 2723 return cast_or_null<EnumDecl>(TagDecl::getDefinition()); 2724 } 2725 2726 static EnumDecl *Create(ASTContext &C, DeclContext *DC, 2727 SourceLocation StartLoc, SourceLocation IdLoc, 2728 IdentifierInfo *Id, EnumDecl *PrevDecl, 2729 bool IsScoped, bool IsScopedUsingClassTag, 2730 bool IsFixed); 2731 static EnumDecl *CreateDeserialized(ASTContext &C, unsigned ID); 2732 2733 /// completeDefinition - When created, the EnumDecl corresponds to a 2734 /// forward-declared enum. This method is used to mark the 2735 /// declaration as being defined; it's enumerators have already been 2736 /// added (via DeclContext::addDecl). NewType is the new underlying 2737 /// type of the enumeration type. 2738 void completeDefinition(QualType NewType, 2739 QualType PromotionType, 2740 unsigned NumPositiveBits, 2741 unsigned NumNegativeBits); 2742 2743 // enumerator_iterator - Iterates through the enumerators of this 2744 // enumeration. 2745 typedef specific_decl_iterator<EnumConstantDecl> enumerator_iterator; 2746 2747 enumerator_iterator enumerator_begin() const { 2748 const EnumDecl *E = getDefinition(); 2749 if (!E) 2750 E = this; 2751 return enumerator_iterator(E->decls_begin()); 2752 } 2753 2754 enumerator_iterator enumerator_end() const { 2755 const EnumDecl *E = getDefinition(); 2756 if (!E) 2757 E = this; 2758 return enumerator_iterator(E->decls_end()); 2759 } 2760 2761 /// getPromotionType - Return the integer type that enumerators 2762 /// should promote to. 2763 QualType getPromotionType() const { return PromotionType; } 2764 2765 /// \brief Set the promotion type. 2766 void setPromotionType(QualType T) { PromotionType = T; } 2767 2768 /// getIntegerType - Return the integer type this enum decl corresponds to. 2769 /// This returns a null qualtype for an enum forward definition. 2770 QualType getIntegerType() const { 2771 if (!IntegerType) 2772 return QualType(); 2773 if (const Type* T = IntegerType.dyn_cast<const Type*>()) 2774 return QualType(T, 0); 2775 return IntegerType.get<TypeSourceInfo*>()->getType(); 2776 } 2777 2778 /// \brief Set the underlying integer type. 2779 void setIntegerType(QualType T) { IntegerType = T.getTypePtrOrNull(); } 2780 2781 /// \brief Set the underlying integer type source info. 2782 void setIntegerTypeSourceInfo(TypeSourceInfo* TInfo) { IntegerType = TInfo; } 2783 2784 /// \brief Return the type source info for the underlying integer type, 2785 /// if no type source info exists, return 0. 2786 TypeSourceInfo* getIntegerTypeSourceInfo() const { 2787 return IntegerType.dyn_cast<TypeSourceInfo*>(); 2788 } 2789 2790 /// \brief Returns the width in bits required to store all the 2791 /// non-negative enumerators of this enum. 2792 unsigned getNumPositiveBits() const { 2793 return NumPositiveBits; 2794 } 2795 void setNumPositiveBits(unsigned Num) { 2796 NumPositiveBits = Num; 2797 assert(NumPositiveBits == Num && "can't store this bitcount"); 2798 } 2799 2800 /// \brief Returns the width in bits required to store all the 2801 /// negative enumerators of this enum. These widths include 2802 /// the rightmost leading 1; that is: 2803 /// 2804 /// MOST NEGATIVE ENUMERATOR PATTERN NUM NEGATIVE BITS 2805 /// ------------------------ ------- ----------------- 2806 /// -1 1111111 1 2807 /// -10 1110110 5 2808 /// -101 1001011 8 2809 unsigned getNumNegativeBits() const { 2810 return NumNegativeBits; 2811 } 2812 void setNumNegativeBits(unsigned Num) { 2813 NumNegativeBits = Num; 2814 } 2815 2816 /// \brief Returns true if this is a C++11 scoped enumeration. 2817 bool isScoped() const { 2818 return IsScoped; 2819 } 2820 2821 /// \brief Returns true if this is a C++11 scoped enumeration. 2822 bool isScopedUsingClassTag() const { 2823 return IsScopedUsingClassTag; 2824 } 2825 2826 /// \brief Returns true if this is an Objective-C, C++11, or 2827 /// Microsoft-style enumeration with a fixed underlying type. 2828 bool isFixed() const { 2829 return IsFixed; 2830 } 2831 2832 /// \brief Returns true if this can be considered a complete type. 2833 bool isComplete() const { 2834 return isCompleteDefinition() || isFixed(); 2835 } 2836 2837 /// \brief Returns the enumeration (declared within the template) 2838 /// from which this enumeration type was instantiated, or NULL if 2839 /// this enumeration was not instantiated from any template. 2840 EnumDecl *getInstantiatedFromMemberEnum() const; 2841 2842 /// \brief If this enumeration is a member of a specialization of a 2843 /// templated class, determine what kind of template specialization 2844 /// or instantiation this is. 2845 TemplateSpecializationKind getTemplateSpecializationKind() const; 2846 2847 /// \brief For an enumeration member that was instantiated from a member 2848 /// enumeration of a templated class, set the template specialiation kind. 2849 void setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2850 SourceLocation PointOfInstantiation = SourceLocation()); 2851 2852 /// \brief If this enumeration is an instantiation of a member enumeration of 2853 /// a class template specialization, retrieves the member specialization 2854 /// information. 2855 MemberSpecializationInfo *getMemberSpecializationInfo() const { 2856 return SpecializationInfo; 2857 } 2858 2859 /// \brief Specify that this enumeration is an instantiation of the 2860 /// member enumeration ED. 2861 void setInstantiationOfMemberEnum(EnumDecl *ED, 2862 TemplateSpecializationKind TSK) { 2863 setInstantiationOfMemberEnum(getASTContext(), ED, TSK); 2864 } 2865 2866 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 2867 static bool classofKind(Kind K) { return K == Enum; } 2868 2869 friend class ASTDeclReader; 2870}; 2871 2872 2873/// RecordDecl - Represents a struct/union/class. For example: 2874/// struct X; // Forward declaration, no "body". 2875/// union Y { int A, B; }; // Has body with members A and B (FieldDecls). 2876/// This decl will be marked invalid if *any* members are invalid. 2877/// 2878class RecordDecl : public TagDecl { 2879 // FIXME: This can be packed into the bitfields in Decl. 2880 /// HasFlexibleArrayMember - This is true if this struct ends with a flexible 2881 /// array member (e.g. int X[]) or if this union contains a struct that does. 2882 /// If so, this cannot be contained in arrays or other structs as a member. 2883 bool HasFlexibleArrayMember : 1; 2884 2885 /// AnonymousStructOrUnion - Whether this is the type of an anonymous struct 2886 /// or union. 2887 bool AnonymousStructOrUnion : 1; 2888 2889 /// HasObjectMember - This is true if this struct has at least one member 2890 /// containing an Objective-C object pointer type. 2891 bool HasObjectMember : 1; 2892 2893 /// HasVolatileMember - This is true if struct has at least one member of 2894 /// 'volatile' type. 2895 bool HasVolatileMember : 1; 2896 2897 /// \brief Whether the field declarations of this record have been loaded 2898 /// from external storage. To avoid unnecessary deserialization of 2899 /// methods/nested types we allow deserialization of just the fields 2900 /// when needed. 2901 mutable bool LoadedFieldsFromExternalStorage : 1; 2902 friend class DeclContext; 2903 2904protected: 2905 RecordDecl(Kind DK, TagKind TK, DeclContext *DC, 2906 SourceLocation StartLoc, SourceLocation IdLoc, 2907 IdentifierInfo *Id, RecordDecl *PrevDecl); 2908 2909public: 2910 static RecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC, 2911 SourceLocation StartLoc, SourceLocation IdLoc, 2912 IdentifierInfo *Id, RecordDecl* PrevDecl = 0); 2913 static RecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID); 2914 2915 const RecordDecl *getPreviousDecl() const { 2916 return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl()); 2917 } 2918 RecordDecl *getPreviousDecl() { 2919 return cast_or_null<RecordDecl>(TagDecl::getPreviousDecl()); 2920 } 2921 2922 const RecordDecl *getMostRecentDecl() const { 2923 return cast<RecordDecl>(TagDecl::getMostRecentDecl()); 2924 } 2925 RecordDecl *getMostRecentDecl() { 2926 return cast<RecordDecl>(TagDecl::getMostRecentDecl()); 2927 } 2928 2929 bool hasFlexibleArrayMember() const { return HasFlexibleArrayMember; } 2930 void setHasFlexibleArrayMember(bool V) { HasFlexibleArrayMember = V; } 2931 2932 /// isAnonymousStructOrUnion - Whether this is an anonymous struct 2933 /// or union. To be an anonymous struct or union, it must have been 2934 /// declared without a name and there must be no objects of this 2935 /// type declared, e.g., 2936 /// @code 2937 /// union { int i; float f; }; 2938 /// @endcode 2939 /// is an anonymous union but neither of the following are: 2940 /// @code 2941 /// union X { int i; float f; }; 2942 /// union { int i; float f; } obj; 2943 /// @endcode 2944 bool isAnonymousStructOrUnion() const { return AnonymousStructOrUnion; } 2945 void setAnonymousStructOrUnion(bool Anon) { 2946 AnonymousStructOrUnion = Anon; 2947 } 2948 2949 bool hasObjectMember() const { return HasObjectMember; } 2950 void setHasObjectMember (bool val) { HasObjectMember = val; } 2951 2952 bool hasVolatileMember() const { return HasVolatileMember; } 2953 void setHasVolatileMember (bool val) { HasVolatileMember = val; } 2954 2955 /// \brief Determines whether this declaration represents the 2956 /// injected class name. 2957 /// 2958 /// The injected class name in C++ is the name of the class that 2959 /// appears inside the class itself. For example: 2960 /// 2961 /// \code 2962 /// struct C { 2963 /// // C is implicitly declared here as a synonym for the class name. 2964 /// }; 2965 /// 2966 /// C::C c; // same as "C c;" 2967 /// \endcode 2968 bool isInjectedClassName() const; 2969 2970 /// getDefinition - Returns the RecordDecl that actually defines 2971 /// this struct/union/class. When determining whether or not a 2972 /// struct/union/class is completely defined, one should use this 2973 /// method as opposed to 'isCompleteDefinition'. 2974 /// 'isCompleteDefinition' indicates whether or not a specific 2975 /// RecordDecl is a completed definition, not whether or not the 2976 /// record type is defined. This method returns NULL if there is 2977 /// no RecordDecl that defines the struct/union/tag. 2978 RecordDecl *getDefinition() const { 2979 return cast_or_null<RecordDecl>(TagDecl::getDefinition()); 2980 } 2981 2982 // Iterator access to field members. The field iterator only visits 2983 // the non-static data members of this class, ignoring any static 2984 // data members, functions, constructors, destructors, etc. 2985 typedef specific_decl_iterator<FieldDecl> field_iterator; 2986 2987 field_iterator field_begin() const; 2988 2989 field_iterator field_end() const { 2990 return field_iterator(decl_iterator()); 2991 } 2992 2993 // field_empty - Whether there are any fields (non-static data 2994 // members) in this record. 2995 bool field_empty() const { 2996 return field_begin() == field_end(); 2997 } 2998 2999 /// completeDefinition - Notes that the definition of this type is 3000 /// now complete. 3001 virtual void completeDefinition(); 3002 3003 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 3004 static bool classofKind(Kind K) { 3005 return K >= firstRecord && K <= lastRecord; 3006 } 3007 3008 /// isMsStrust - Get whether or not this is an ms_struct which can 3009 /// be turned on with an attribute, pragma, or -mms-bitfields 3010 /// commandline option. 3011 bool isMsStruct(const ASTContext &C) const; 3012 3013private: 3014 /// \brief Deserialize just the fields. 3015 void LoadFieldsFromExternalStorage() const; 3016}; 3017 3018class FileScopeAsmDecl : public Decl { 3019 virtual void anchor(); 3020 StringLiteral *AsmString; 3021 SourceLocation RParenLoc; 3022 FileScopeAsmDecl(DeclContext *DC, StringLiteral *asmstring, 3023 SourceLocation StartL, SourceLocation EndL) 3024 : Decl(FileScopeAsm, DC, StartL), AsmString(asmstring), RParenLoc(EndL) {} 3025public: 3026 static FileScopeAsmDecl *Create(ASTContext &C, DeclContext *DC, 3027 StringLiteral *Str, SourceLocation AsmLoc, 3028 SourceLocation RParenLoc); 3029 3030 static FileScopeAsmDecl *CreateDeserialized(ASTContext &C, unsigned ID); 3031 3032 SourceLocation getAsmLoc() const { return getLocation(); } 3033 SourceLocation getRParenLoc() const { return RParenLoc; } 3034 void setRParenLoc(SourceLocation L) { RParenLoc = L; } 3035 SourceRange getSourceRange() const LLVM_READONLY { 3036 return SourceRange(getAsmLoc(), getRParenLoc()); 3037 } 3038 3039 const StringLiteral *getAsmString() const { return AsmString; } 3040 StringLiteral *getAsmString() { return AsmString; } 3041 void setAsmString(StringLiteral *Asm) { AsmString = Asm; } 3042 3043 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 3044 static bool classofKind(Kind K) { return K == FileScopeAsm; } 3045}; 3046 3047/// BlockDecl - This represents a block literal declaration, which is like an 3048/// unnamed FunctionDecl. For example: 3049/// ^{ statement-body } or ^(int arg1, float arg2){ statement-body } 3050/// 3051class BlockDecl : public Decl, public DeclContext { 3052public: 3053 /// A class which contains all the information about a particular 3054 /// captured value. 3055 class Capture { 3056 enum { 3057 flag_isByRef = 0x1, 3058 flag_isNested = 0x2 3059 }; 3060 3061 /// The variable being captured. 3062 llvm::PointerIntPair<VarDecl*, 2> VariableAndFlags; 3063 3064 /// The copy expression, expressed in terms of a DeclRef (or 3065 /// BlockDeclRef) to the captured variable. Only required if the 3066 /// variable has a C++ class type. 3067 Expr *CopyExpr; 3068 3069 public: 3070 Capture(VarDecl *variable, bool byRef, bool nested, Expr *copy) 3071 : VariableAndFlags(variable, 3072 (byRef ? flag_isByRef : 0) | (nested ? flag_isNested : 0)), 3073 CopyExpr(copy) {} 3074 3075 /// The variable being captured. 3076 VarDecl *getVariable() const { return VariableAndFlags.getPointer(); } 3077 3078 /// Whether this is a "by ref" capture, i.e. a capture of a __block 3079 /// variable. 3080 bool isByRef() const { return VariableAndFlags.getInt() & flag_isByRef; } 3081 3082 /// Whether this is a nested capture, i.e. the variable captured 3083 /// is not from outside the immediately enclosing function/block. 3084 bool isNested() const { return VariableAndFlags.getInt() & flag_isNested; } 3085 3086 bool hasCopyExpr() const { return CopyExpr != 0; } 3087 Expr *getCopyExpr() const { return CopyExpr; } 3088 void setCopyExpr(Expr *e) { CopyExpr = e; } 3089 }; 3090 3091private: 3092 // FIXME: This can be packed into the bitfields in Decl. 3093 bool IsVariadic : 1; 3094 bool CapturesCXXThis : 1; 3095 bool BlockMissingReturnType : 1; 3096 bool IsConversionFromLambda : 1; 3097 /// ParamInfo - new[]'d array of pointers to ParmVarDecls for the formal 3098 /// parameters of this function. This is null if a prototype or if there are 3099 /// no formals. 3100 ParmVarDecl **ParamInfo; 3101 unsigned NumParams; 3102 3103 Stmt *Body; 3104 TypeSourceInfo *SignatureAsWritten; 3105 3106 Capture *Captures; 3107 unsigned NumCaptures; 3108 3109protected: 3110 BlockDecl(DeclContext *DC, SourceLocation CaretLoc) 3111 : Decl(Block, DC, CaretLoc), DeclContext(Block), 3112 IsVariadic(false), CapturesCXXThis(false), 3113 BlockMissingReturnType(true), IsConversionFromLambda(false), 3114 ParamInfo(0), NumParams(0), Body(0), 3115 SignatureAsWritten(0), Captures(0), NumCaptures(0) {} 3116 3117public: 3118 static BlockDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L); 3119 static BlockDecl *CreateDeserialized(ASTContext &C, unsigned ID); 3120 3121 SourceLocation getCaretLocation() const { return getLocation(); } 3122 3123 bool isVariadic() const { return IsVariadic; } 3124 void setIsVariadic(bool value) { IsVariadic = value; } 3125 3126 CompoundStmt *getCompoundBody() const { return (CompoundStmt*) Body; } 3127 Stmt *getBody() const { return (Stmt*) Body; } 3128 void setBody(CompoundStmt *B) { Body = (Stmt*) B; } 3129 3130 void setSignatureAsWritten(TypeSourceInfo *Sig) { SignatureAsWritten = Sig; } 3131 TypeSourceInfo *getSignatureAsWritten() const { return SignatureAsWritten; } 3132 3133 // Iterator access to formal parameters. 3134 unsigned param_size() const { return getNumParams(); } 3135 typedef ParmVarDecl **param_iterator; 3136 typedef ParmVarDecl * const *param_const_iterator; 3137 3138 bool param_empty() const { return NumParams == 0; } 3139 param_iterator param_begin() { return ParamInfo; } 3140 param_iterator param_end() { return ParamInfo+param_size(); } 3141 3142 param_const_iterator param_begin() const { return ParamInfo; } 3143 param_const_iterator param_end() const { return ParamInfo+param_size(); } 3144 3145 unsigned getNumParams() const { return NumParams; } 3146 const ParmVarDecl *getParamDecl(unsigned i) const { 3147 assert(i < getNumParams() && "Illegal param #"); 3148 return ParamInfo[i]; 3149 } 3150 ParmVarDecl *getParamDecl(unsigned i) { 3151 assert(i < getNumParams() && "Illegal param #"); 3152 return ParamInfo[i]; 3153 } 3154 void setParams(ArrayRef<ParmVarDecl *> NewParamInfo); 3155 3156 /// hasCaptures - True if this block (or its nested blocks) captures 3157 /// anything of local storage from its enclosing scopes. 3158 bool hasCaptures() const { return NumCaptures != 0 || CapturesCXXThis; } 3159 3160 /// getNumCaptures - Returns the number of captured variables. 3161 /// Does not include an entry for 'this'. 3162 unsigned getNumCaptures() const { return NumCaptures; } 3163 3164 typedef const Capture *capture_iterator; 3165 typedef const Capture *capture_const_iterator; 3166 capture_iterator capture_begin() { return Captures; } 3167 capture_iterator capture_end() { return Captures + NumCaptures; } 3168 capture_const_iterator capture_begin() const { return Captures; } 3169 capture_const_iterator capture_end() const { return Captures + NumCaptures; } 3170 3171 bool capturesCXXThis() const { return CapturesCXXThis; } 3172 bool blockMissingReturnType() const { return BlockMissingReturnType; } 3173 void setBlockMissingReturnType(bool val) { BlockMissingReturnType = val; } 3174 3175 bool isConversionFromLambda() const { return IsConversionFromLambda; } 3176 void setIsConversionFromLambda(bool val) { IsConversionFromLambda = val; } 3177 3178 bool capturesVariable(const VarDecl *var) const; 3179 3180 void setCaptures(ASTContext &Context, 3181 const Capture *begin, 3182 const Capture *end, 3183 bool capturesCXXThis); 3184 3185 virtual SourceRange getSourceRange() const LLVM_READONLY; 3186 3187 // Implement isa/cast/dyncast/etc. 3188 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 3189 static bool classofKind(Kind K) { return K == Block; } 3190 static DeclContext *castToDeclContext(const BlockDecl *D) { 3191 return static_cast<DeclContext *>(const_cast<BlockDecl*>(D)); 3192 } 3193 static BlockDecl *castFromDeclContext(const DeclContext *DC) { 3194 return static_cast<BlockDecl *>(const_cast<DeclContext*>(DC)); 3195 } 3196}; 3197 3198/// \brief This represents the body of a CapturedStmt, and serves as its 3199/// DeclContext. 3200class CapturedDecl : public Decl, public DeclContext { 3201private: 3202 /// \brief The number of parameters to the outlined function. 3203 unsigned NumParams; 3204 /// \brief The body of the outlined function. 3205 Stmt *Body; 3206 3207 explicit CapturedDecl(DeclContext *DC, unsigned NumParams) 3208 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured), 3209 NumParams(NumParams), Body(0) { } 3210 3211 ImplicitParamDecl **getParams() const { 3212 return reinterpret_cast<ImplicitParamDecl **>( 3213 const_cast<CapturedDecl *>(this) + 1); 3214 } 3215 3216public: 3217 static CapturedDecl *Create(ASTContext &C, DeclContext *DC, unsigned NumParams); 3218 static CapturedDecl *CreateDeserialized(ASTContext &C, unsigned ID, 3219 unsigned NumParams); 3220 3221 Stmt *getBody() const { return Body; } 3222 void setBody(Stmt *B) { Body = B; } 3223 3224 unsigned getNumParams() const { return NumParams; } 3225 3226 ImplicitParamDecl *getParam(unsigned i) const { 3227 assert(i < NumParams); 3228 return getParams()[i]; 3229 } 3230 void setParam(unsigned i, ImplicitParamDecl *P) { 3231 assert(i < NumParams); 3232 getParams()[i] = P; 3233 } 3234 3235 /// \brief Retrieve the parameter containing captured variables. 3236 ImplicitParamDecl *getContextParam() const { return getParam(0); } 3237 void setContextParam(ImplicitParamDecl *P) { setParam(0, P); } 3238 3239 typedef ImplicitParamDecl **param_iterator; 3240 /// \brief Retrieve an iterator pointing to the first parameter decl. 3241 param_iterator param_begin() const { return getParams(); } 3242 /// \brief Retrieve an iterator one past the last parameter decl. 3243 param_iterator param_end() const { return getParams() + NumParams; } 3244 3245 // Implement isa/cast/dyncast/etc. 3246 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 3247 static bool classofKind(Kind K) { return K == Captured; } 3248 static DeclContext *castToDeclContext(const CapturedDecl *D) { 3249 return static_cast<DeclContext *>(const_cast<CapturedDecl *>(D)); 3250 } 3251 static CapturedDecl *castFromDeclContext(const DeclContext *DC) { 3252 return static_cast<CapturedDecl *>(const_cast<DeclContext *>(DC)); 3253 } 3254 3255 friend class ASTDeclReader; 3256 friend class ASTDeclWriter; 3257}; 3258 3259/// \brief Describes a module import declaration, which makes the contents 3260/// of the named module visible in the current translation unit. 3261/// 3262/// An import declaration imports the named module (or submodule). For example: 3263/// \code 3264/// @import std.vector; 3265/// \endcode 3266/// 3267/// Import declarations can also be implicitly generated from 3268/// \#include/\#import directives. 3269class ImportDecl : public Decl { 3270 /// \brief The imported module, along with a bit that indicates whether 3271 /// we have source-location information for each identifier in the module 3272 /// name. 3273 /// 3274 /// When the bit is false, we only have a single source location for the 3275 /// end of the import declaration. 3276 llvm::PointerIntPair<Module *, 1, bool> ImportedAndComplete; 3277 3278 /// \brief The next import in the list of imports local to the translation 3279 /// unit being parsed (not loaded from an AST file). 3280 ImportDecl *NextLocalImport; 3281 3282 friend class ASTReader; 3283 friend class ASTDeclReader; 3284 friend class ASTContext; 3285 3286 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, 3287 ArrayRef<SourceLocation> IdentifierLocs); 3288 3289 ImportDecl(DeclContext *DC, SourceLocation StartLoc, Module *Imported, 3290 SourceLocation EndLoc); 3291 3292 ImportDecl(EmptyShell Empty) : Decl(Import, Empty), NextLocalImport() { } 3293 3294public: 3295 /// \brief Create a new module import declaration. 3296 static ImportDecl *Create(ASTContext &C, DeclContext *DC, 3297 SourceLocation StartLoc, Module *Imported, 3298 ArrayRef<SourceLocation> IdentifierLocs); 3299 3300 /// \brief Create a new module import declaration for an implicitly-generated 3301 /// import. 3302 static ImportDecl *CreateImplicit(ASTContext &C, DeclContext *DC, 3303 SourceLocation StartLoc, Module *Imported, 3304 SourceLocation EndLoc); 3305 3306 /// \brief Create a new, deserialized module import declaration. 3307 static ImportDecl *CreateDeserialized(ASTContext &C, unsigned ID, 3308 unsigned NumLocations); 3309 3310 /// \brief Retrieve the module that was imported by the import declaration. 3311 Module *getImportedModule() const { return ImportedAndComplete.getPointer(); } 3312 3313 /// \brief Retrieves the locations of each of the identifiers that make up 3314 /// the complete module name in the import declaration. 3315 /// 3316 /// This will return an empty array if the locations of the individual 3317 /// identifiers aren't available. 3318 ArrayRef<SourceLocation> getIdentifierLocs() const; 3319 3320 virtual SourceRange getSourceRange() const LLVM_READONLY; 3321 3322 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 3323 static bool classofKind(Kind K) { return K == Import; } 3324}; 3325 3326/// \brief Represents an empty-declaration. 3327class EmptyDecl : public Decl { 3328 virtual void anchor(); 3329 EmptyDecl(DeclContext *DC, SourceLocation L) 3330 : Decl(Empty, DC, L) { } 3331 3332public: 3333 static EmptyDecl *Create(ASTContext &C, DeclContext *DC, 3334 SourceLocation L); 3335 static EmptyDecl *CreateDeserialized(ASTContext &C, unsigned ID); 3336 3337 static bool classof(const Decl *D) { return classofKind(D->getKind()); } 3338 static bool classofKind(Kind K) { return K == Empty; } 3339}; 3340 3341/// Insertion operator for diagnostics. This allows sending NamedDecl's 3342/// into a diagnostic with <<. 3343inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 3344 const NamedDecl* ND) { 3345 DB.AddTaggedVal(reinterpret_cast<intptr_t>(ND), 3346 DiagnosticsEngine::ak_nameddecl); 3347 return DB; 3348} 3349inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD, 3350 const NamedDecl* ND) { 3351 PD.AddTaggedVal(reinterpret_cast<intptr_t>(ND), 3352 DiagnosticsEngine::ak_nameddecl); 3353 return PD; 3354} 3355 3356template<typename decl_type> 3357void Redeclarable<decl_type>::setPreviousDeclaration(decl_type *PrevDecl) { 3358 // Note: This routine is implemented here because we need both NamedDecl 3359 // and Redeclarable to be defined. 3360 3361 decl_type *First; 3362 3363 if (PrevDecl) { 3364 // Point to previous. Make sure that this is actually the most recent 3365 // redeclaration, or we can build invalid chains. If the most recent 3366 // redeclaration is invalid, it won't be PrevDecl, but we want it anyway. 3367 First = PrevDecl->getFirstDeclaration(); 3368 assert(First->RedeclLink.NextIsLatest() && "Expected first"); 3369 decl_type *MostRecent = First->RedeclLink.getNext(); 3370 RedeclLink = PreviousDeclLink(cast<decl_type>(MostRecent)); 3371 } else { 3372 // Make this first. 3373 First = static_cast<decl_type*>(this); 3374 } 3375 3376 // First one will point to this one as latest. 3377 First->RedeclLink = LatestDeclLink(static_cast<decl_type*>(this)); 3378 assert(!isa<NamedDecl>(static_cast<decl_type*>(this)) || 3379 cast<NamedDecl>(static_cast<decl_type*>(this))->isLinkageValid()); 3380} 3381 3382// Inline function definitions. 3383 3384/// \brief Check if the given decl is complete. 3385/// 3386/// We use this function to break a cycle between the inline definitions in 3387/// Type.h and Decl.h. 3388inline bool IsEnumDeclComplete(EnumDecl *ED) { 3389 return ED->isComplete(); 3390} 3391 3392/// \brief Check if the given decl is scoped. 3393/// 3394/// We use this function to break a cycle between the inline definitions in 3395/// Type.h and Decl.h. 3396inline bool IsEnumDeclScoped(EnumDecl *ED) { 3397 return ED->isScoped(); 3398} 3399 3400} // end namespace clang 3401 3402#endif 3403