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