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