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