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