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