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