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