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