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