DeclBase.cpp revision e664977aca2a05a77abab5a06dc0fb69e870cfb9
1//===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===// 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 implements the Decl and DeclContext classes. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/DeclBase.h" 15#include "clang/AST/Decl.h" 16#include "clang/AST/DeclContextInternals.h" 17#include "clang/AST/DeclCXX.h" 18#include "clang/AST/DeclFriend.h" 19#include "clang/AST/DeclObjC.h" 20#include "clang/AST/DeclTemplate.h" 21#include "clang/AST/DependentDiagnostic.h" 22#include "clang/AST/ExternalASTSource.h" 23#include "clang/AST/ASTContext.h" 24#include "clang/AST/Type.h" 25#include "clang/AST/Stmt.h" 26#include "clang/AST/StmtCXX.h" 27#include "clang/AST/ASTMutationListener.h" 28#include "clang/Basic/TargetInfo.h" 29#include "llvm/ADT/DenseMap.h" 30#include "llvm/Support/raw_ostream.h" 31#include <algorithm> 32using namespace clang; 33 34//===----------------------------------------------------------------------===// 35// Statistics 36//===----------------------------------------------------------------------===// 37 38#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0; 39#define ABSTRACT_DECL(DECL) 40#include "clang/AST/DeclNodes.inc" 41 42static bool StatSwitch = false; 43 44const char *Decl::getDeclKindName() const { 45 switch (DeclKind) { 46 default: llvm_unreachable("Declaration not in DeclNodes.inc!"); 47#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED; 48#define ABSTRACT_DECL(DECL) 49#include "clang/AST/DeclNodes.inc" 50 } 51} 52 53void Decl::setInvalidDecl(bool Invalid) { 54 InvalidDecl = Invalid; 55 if (Invalid) { 56 // Defensive maneuver for ill-formed code: we're likely not to make it to 57 // a point where we set the access specifier, so default it to "public" 58 // to avoid triggering asserts elsewhere in the front end. 59 setAccess(AS_public); 60 } 61} 62 63const char *DeclContext::getDeclKindName() const { 64 switch (DeclKind) { 65 default: llvm_unreachable("Declaration context not in DeclNodes.inc!"); 66#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED; 67#define ABSTRACT_DECL(DECL) 68#include "clang/AST/DeclNodes.inc" 69 } 70} 71 72bool Decl::CollectingStats(bool Enable) { 73 if (Enable) StatSwitch = true; 74 return StatSwitch; 75} 76 77void Decl::PrintStats() { 78 llvm::errs() << "\n*** Decl Stats:\n"; 79 80 int totalDecls = 0; 81#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s; 82#define ABSTRACT_DECL(DECL) 83#include "clang/AST/DeclNodes.inc" 84 llvm::errs() << " " << totalDecls << " decls total.\n"; 85 86 int totalBytes = 0; 87#define DECL(DERIVED, BASE) \ 88 if (n##DERIVED##s > 0) { \ 89 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \ 90 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \ 91 << sizeof(DERIVED##Decl) << " each (" \ 92 << n##DERIVED##s * sizeof(DERIVED##Decl) \ 93 << " bytes)\n"; \ 94 } 95#define ABSTRACT_DECL(DECL) 96#include "clang/AST/DeclNodes.inc" 97 98 llvm::errs() << "Total bytes = " << totalBytes << "\n"; 99} 100 101void Decl::add(Kind k) { 102 switch (k) { 103 default: llvm_unreachable("Declaration not in DeclNodes.inc!"); 104#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break; 105#define ABSTRACT_DECL(DECL) 106#include "clang/AST/DeclNodes.inc" 107 } 108} 109 110bool Decl::isTemplateParameterPack() const { 111 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this)) 112 return TTP->isParameterPack(); 113 if (const NonTypeTemplateParmDecl *NTTP 114 = dyn_cast<NonTypeTemplateParmDecl>(this)) 115 return NTTP->isParameterPack(); 116 if (const TemplateTemplateParmDecl *TTP 117 = dyn_cast<TemplateTemplateParmDecl>(this)) 118 return TTP->isParameterPack(); 119 return false; 120} 121 122bool Decl::isParameterPack() const { 123 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this)) 124 return Parm->isParameterPack(); 125 126 return isTemplateParameterPack(); 127} 128 129bool Decl::isFunctionOrFunctionTemplate() const { 130 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this)) 131 return UD->getTargetDecl()->isFunctionOrFunctionTemplate(); 132 133 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this); 134} 135 136bool Decl::isTemplateDecl() const { 137 return isa<TemplateDecl>(this); 138} 139 140const DeclContext *Decl::getParentFunctionOrMethod() const { 141 for (const DeclContext *DC = getDeclContext(); 142 DC && !DC->isTranslationUnit() && !DC->isNamespace(); 143 DC = DC->getParent()) 144 if (DC->isFunctionOrMethod()) 145 return DC; 146 147 return 0; 148} 149 150 151//===----------------------------------------------------------------------===// 152// PrettyStackTraceDecl Implementation 153//===----------------------------------------------------------------------===// 154 155void PrettyStackTraceDecl::print(raw_ostream &OS) const { 156 SourceLocation TheLoc = Loc; 157 if (TheLoc.isInvalid() && TheDecl) 158 TheLoc = TheDecl->getLocation(); 159 160 if (TheLoc.isValid()) { 161 TheLoc.print(OS, SM); 162 OS << ": "; 163 } 164 165 OS << Message; 166 167 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) 168 OS << " '" << DN->getQualifiedNameAsString() << '\''; 169 OS << '\n'; 170} 171 172//===----------------------------------------------------------------------===// 173// Decl Implementation 174//===----------------------------------------------------------------------===// 175 176// Out-of-line virtual method providing a home for Decl. 177Decl::~Decl() { } 178 179void Decl::setDeclContext(DeclContext *DC) { 180 DeclCtx = DC; 181} 182 183void Decl::setLexicalDeclContext(DeclContext *DC) { 184 if (DC == getLexicalDeclContext()) 185 return; 186 187 if (isInSemaDC()) { 188 MultipleDC *MDC = new (getASTContext()) MultipleDC(); 189 MDC->SemanticDC = getDeclContext(); 190 MDC->LexicalDC = DC; 191 DeclCtx = MDC; 192 } else { 193 getMultipleDC()->LexicalDC = DC; 194 } 195} 196 197bool Decl::isInAnonymousNamespace() const { 198 const DeclContext *DC = getDeclContext(); 199 do { 200 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC)) 201 if (ND->isAnonymousNamespace()) 202 return true; 203 } while ((DC = DC->getParent())); 204 205 return false; 206} 207 208TranslationUnitDecl *Decl::getTranslationUnitDecl() { 209 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this)) 210 return TUD; 211 212 DeclContext *DC = getDeclContext(); 213 assert(DC && "This decl is not contained in a translation unit!"); 214 215 while (!DC->isTranslationUnit()) { 216 DC = DC->getParent(); 217 assert(DC && "This decl is not contained in a translation unit!"); 218 } 219 220 return cast<TranslationUnitDecl>(DC); 221} 222 223ASTContext &Decl::getASTContext() const { 224 return getTranslationUnitDecl()->getASTContext(); 225} 226 227ASTMutationListener *Decl::getASTMutationListener() const { 228 return getASTContext().getASTMutationListener(); 229} 230 231bool Decl::isUsed(bool CheckUsedAttr) const { 232 if (Used) 233 return true; 234 235 // Check for used attribute. 236 if (CheckUsedAttr && hasAttr<UsedAttr>()) 237 return true; 238 239 // Check redeclarations for used attribute. 240 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 241 if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used) 242 return true; 243 } 244 245 return false; 246} 247 248bool Decl::isReferenced() const { 249 if (Referenced) 250 return true; 251 252 // Check redeclarations. 253 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 254 if (I->Referenced) 255 return true; 256 257 return false; 258} 259 260/// \brief Determine the availability of the given declaration based on 261/// the target platform. 262/// 263/// When it returns an availability result other than \c AR_Available, 264/// if the \p Message parameter is non-NULL, it will be set to a 265/// string describing why the entity is unavailable. 266/// 267/// FIXME: Make these strings localizable, since they end up in 268/// diagnostics. 269static AvailabilityResult CheckAvailability(ASTContext &Context, 270 const AvailabilityAttr *A, 271 std::string *Message) { 272 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 273 StringRef PrettyPlatformName 274 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform); 275 if (PrettyPlatformName.empty()) 276 PrettyPlatformName = TargetPlatform; 277 278 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion(); 279 if (TargetMinVersion.empty()) 280 return AR_Available; 281 282 // Match the platform name. 283 if (A->getPlatform()->getName() != TargetPlatform) 284 return AR_Available; 285 286 // Make sure that this declaration has not been marked 'unavailable'. 287 if (A->getUnavailable()) { 288 if (Message) { 289 Message->clear(); 290 llvm::raw_string_ostream Out(*Message); 291 Out << "not available on " << PrettyPlatformName; 292 } 293 294 return AR_Unavailable; 295 } 296 297 // Make sure that this declaration has already been introduced. 298 if (!A->getIntroduced().empty() && 299 TargetMinVersion < A->getIntroduced()) { 300 if (Message) { 301 Message->clear(); 302 llvm::raw_string_ostream Out(*Message); 303 Out << "introduced in " << PrettyPlatformName << ' ' 304 << A->getIntroduced(); 305 } 306 307 return AR_NotYetIntroduced; 308 } 309 310 // Make sure that this declaration hasn't been obsoleted. 311 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) { 312 if (Message) { 313 Message->clear(); 314 llvm::raw_string_ostream Out(*Message); 315 Out << "obsoleted in " << PrettyPlatformName << ' ' 316 << A->getObsoleted(); 317 } 318 319 return AR_Unavailable; 320 } 321 322 // Make sure that this declaration hasn't been deprecated. 323 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) { 324 if (Message) { 325 Message->clear(); 326 llvm::raw_string_ostream Out(*Message); 327 Out << "first deprecated in " << PrettyPlatformName << ' ' 328 << A->getDeprecated(); 329 } 330 331 return AR_Deprecated; 332 } 333 334 return AR_Available; 335} 336 337AvailabilityResult Decl::getAvailability(std::string *Message) const { 338 AvailabilityResult Result = AR_Available; 339 std::string ResultMessage; 340 341 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) { 342 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) { 343 if (Result >= AR_Deprecated) 344 continue; 345 346 if (Message) 347 ResultMessage = Deprecated->getMessage(); 348 349 Result = AR_Deprecated; 350 continue; 351 } 352 353 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) { 354 if (Message) 355 *Message = Unavailable->getMessage(); 356 return AR_Unavailable; 357 } 358 359 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) { 360 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability, 361 Message); 362 363 if (AR == AR_Unavailable) 364 return AR_Unavailable; 365 366 if (AR > Result) { 367 Result = AR; 368 if (Message) 369 ResultMessage.swap(*Message); 370 } 371 continue; 372 } 373 } 374 375 if (Message) 376 Message->swap(ResultMessage); 377 return Result; 378} 379 380bool Decl::canBeWeakImported(bool &IsDefinition) const { 381 IsDefinition = false; 382 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) { 383 if (!Var->hasExternalStorage() || Var->getInit()) { 384 IsDefinition = true; 385 return false; 386 } 387 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 388 if (FD->hasBody()) { 389 IsDefinition = true; 390 return false; 391 } 392 } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this)) 393 return false; 394 else if (!(getASTContext().getLangOptions().ObjCNonFragileABI && 395 isa<ObjCInterfaceDecl>(this))) 396 return false; 397 398 return true; 399} 400 401bool Decl::isWeakImported() const { 402 bool IsDefinition; 403 if (!canBeWeakImported(IsDefinition)) 404 return false; 405 406 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) { 407 if (isa<WeakImportAttr>(*A)) 408 return true; 409 410 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) { 411 if (CheckAvailability(getASTContext(), Availability, 0) 412 == AR_NotYetIntroduced) 413 return true; 414 } 415 } 416 417 return false; 418} 419 420unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { 421 switch (DeclKind) { 422 case Function: 423 case CXXMethod: 424 case CXXConstructor: 425 case CXXDestructor: 426 case CXXConversion: 427 case EnumConstant: 428 case Var: 429 case ImplicitParam: 430 case ParmVar: 431 case NonTypeTemplateParm: 432 case ObjCMethod: 433 case ObjCProperty: 434 return IDNS_Ordinary; 435 case Label: 436 return IDNS_Label; 437 case IndirectField: 438 return IDNS_Ordinary | IDNS_Member; 439 440 case ObjCCompatibleAlias: 441 case ObjCInterface: 442 return IDNS_Ordinary | IDNS_Type; 443 444 case Typedef: 445 case TypeAlias: 446 case TypeAliasTemplate: 447 case UnresolvedUsingTypename: 448 case TemplateTypeParm: 449 return IDNS_Ordinary | IDNS_Type; 450 451 case UsingShadow: 452 return 0; // we'll actually overwrite this later 453 454 case UnresolvedUsingValue: 455 return IDNS_Ordinary | IDNS_Using; 456 457 case Using: 458 return IDNS_Using; 459 460 case ObjCProtocol: 461 return IDNS_ObjCProtocol; 462 463 case Field: 464 case ObjCAtDefsField: 465 case ObjCIvar: 466 return IDNS_Member; 467 468 case Record: 469 case CXXRecord: 470 case Enum: 471 return IDNS_Tag | IDNS_Type; 472 473 case Namespace: 474 case NamespaceAlias: 475 return IDNS_Namespace; 476 477 case FunctionTemplate: 478 return IDNS_Ordinary; 479 480 case ClassTemplate: 481 case TemplateTemplateParm: 482 return IDNS_Ordinary | IDNS_Tag | IDNS_Type; 483 484 // Never have names. 485 case Friend: 486 case FriendTemplate: 487 case AccessSpec: 488 case LinkageSpec: 489 case FileScopeAsm: 490 case StaticAssert: 491 case ObjCClass: 492 case ObjCPropertyImpl: 493 case ObjCForwardProtocol: 494 case Block: 495 case TranslationUnit: 496 497 case UsingDirective: 498 case ClassTemplateSpecialization: 499 case ClassTemplatePartialSpecialization: 500 case ClassScopeFunctionSpecialization: 501 case ObjCImplementation: 502 case ObjCCategory: 503 case ObjCCategoryImpl: 504 case Import: 505 // Never looked up by name. 506 return 0; 507 } 508 509 return 0; 510} 511 512void Decl::setAttrs(const AttrVec &attrs) { 513 assert(!HasAttrs && "Decl already contains attrs."); 514 515 AttrVec &AttrBlank = getASTContext().getDeclAttrs(this); 516 assert(AttrBlank.empty() && "HasAttrs was wrong?"); 517 518 AttrBlank = attrs; 519 HasAttrs = true; 520} 521 522void Decl::dropAttrs() { 523 if (!HasAttrs) return; 524 525 HasAttrs = false; 526 getASTContext().eraseDeclAttrs(this); 527} 528 529const AttrVec &Decl::getAttrs() const { 530 assert(HasAttrs && "No attrs to get!"); 531 return getASTContext().getDeclAttrs(this); 532} 533 534void Decl::swapAttrs(Decl *RHS) { 535 bool HasLHSAttr = this->HasAttrs; 536 bool HasRHSAttr = RHS->HasAttrs; 537 538 // Usually, neither decl has attrs, nothing to do. 539 if (!HasLHSAttr && !HasRHSAttr) return; 540 541 // If 'this' has no attrs, swap the other way. 542 if (!HasLHSAttr) 543 return RHS->swapAttrs(this); 544 545 ASTContext &Context = getASTContext(); 546 547 // Handle the case when both decls have attrs. 548 if (HasRHSAttr) { 549 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS)); 550 return; 551 } 552 553 // Otherwise, LHS has an attr and RHS doesn't. 554 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this); 555 Context.eraseDeclAttrs(this); 556 this->HasAttrs = false; 557 RHS->HasAttrs = true; 558} 559 560Decl *Decl::castFromDeclContext (const DeclContext *D) { 561 Decl::Kind DK = D->getDeclKind(); 562 switch(DK) { 563#define DECL(NAME, BASE) 564#define DECL_CONTEXT(NAME) \ 565 case Decl::NAME: \ 566 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 567#define DECL_CONTEXT_BASE(NAME) 568#include "clang/AST/DeclNodes.inc" 569 default: 570#define DECL(NAME, BASE) 571#define DECL_CONTEXT_BASE(NAME) \ 572 if (DK >= first##NAME && DK <= last##NAME) \ 573 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 574#include "clang/AST/DeclNodes.inc" 575 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 576 } 577} 578 579DeclContext *Decl::castToDeclContext(const Decl *D) { 580 Decl::Kind DK = D->getKind(); 581 switch(DK) { 582#define DECL(NAME, BASE) 583#define DECL_CONTEXT(NAME) \ 584 case Decl::NAME: \ 585 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 586#define DECL_CONTEXT_BASE(NAME) 587#include "clang/AST/DeclNodes.inc" 588 default: 589#define DECL(NAME, BASE) 590#define DECL_CONTEXT_BASE(NAME) \ 591 if (DK >= first##NAME && DK <= last##NAME) \ 592 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 593#include "clang/AST/DeclNodes.inc" 594 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 595 } 596} 597 598SourceLocation Decl::getBodyRBrace() const { 599 // Special handling of FunctionDecl to avoid de-serializing the body from PCH. 600 // FunctionDecl stores EndRangeLoc for this purpose. 601 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 602 const FunctionDecl *Definition; 603 if (FD->hasBody(Definition)) 604 return Definition->getSourceRange().getEnd(); 605 return SourceLocation(); 606 } 607 608 if (Stmt *Body = getBody()) 609 return Body->getSourceRange().getEnd(); 610 611 return SourceLocation(); 612} 613 614void Decl::CheckAccessDeclContext() const { 615#ifndef NDEBUG 616 // Suppress this check if any of the following hold: 617 // 1. this is the translation unit (and thus has no parent) 618 // 2. this is a template parameter (and thus doesn't belong to its context) 619 // 3. this is a non-type template parameter 620 // 4. the context is not a record 621 // 5. it's invalid 622 // 6. it's a C++0x static_assert. 623 if (isa<TranslationUnitDecl>(this) || 624 isa<TemplateTypeParmDecl>(this) || 625 isa<NonTypeTemplateParmDecl>(this) || 626 !isa<CXXRecordDecl>(getDeclContext()) || 627 isInvalidDecl() || 628 isa<StaticAssertDecl>(this) || 629 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 630 // as DeclContext (?). 631 isa<ParmVarDecl>(this) || 632 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 633 // AS_none as access specifier. 634 isa<CXXRecordDecl>(this) || 635 isa<ClassScopeFunctionSpecializationDecl>(this)) 636 return; 637 638 assert(Access != AS_none && 639 "Access specifier is AS_none inside a record decl"); 640#endif 641} 642 643DeclContext *Decl::getNonClosureContext() { 644 return getDeclContext()->getNonClosureAncestor(); 645} 646 647DeclContext *DeclContext::getNonClosureAncestor() { 648 DeclContext *DC = this; 649 650 // This is basically "while (DC->isClosure()) DC = DC->getParent();" 651 // except that it's significantly more efficient to cast to a known 652 // decl type and call getDeclContext() than to call getParent(). 653 while (isa<BlockDecl>(DC)) 654 DC = cast<BlockDecl>(DC)->getDeclContext(); 655 656 assert(!DC->isClosure()); 657 return DC; 658} 659 660//===----------------------------------------------------------------------===// 661// DeclContext Implementation 662//===----------------------------------------------------------------------===// 663 664bool DeclContext::classof(const Decl *D) { 665 switch (D->getKind()) { 666#define DECL(NAME, BASE) 667#define DECL_CONTEXT(NAME) case Decl::NAME: 668#define DECL_CONTEXT_BASE(NAME) 669#include "clang/AST/DeclNodes.inc" 670 return true; 671 default: 672#define DECL(NAME, BASE) 673#define DECL_CONTEXT_BASE(NAME) \ 674 if (D->getKind() >= Decl::first##NAME && \ 675 D->getKind() <= Decl::last##NAME) \ 676 return true; 677#include "clang/AST/DeclNodes.inc" 678 return false; 679 } 680} 681 682DeclContext::~DeclContext() { } 683 684/// \brief Find the parent context of this context that will be 685/// used for unqualified name lookup. 686/// 687/// Generally, the parent lookup context is the semantic context. However, for 688/// a friend function the parent lookup context is the lexical context, which 689/// is the class in which the friend is declared. 690DeclContext *DeclContext::getLookupParent() { 691 // FIXME: Find a better way to identify friends 692 if (isa<FunctionDecl>(this)) 693 if (getParent()->getRedeclContext()->isFileContext() && 694 getLexicalParent()->getRedeclContext()->isRecord()) 695 return getLexicalParent(); 696 697 return getParent(); 698} 699 700bool DeclContext::isInlineNamespace() const { 701 return isNamespace() && 702 cast<NamespaceDecl>(this)->isInline(); 703} 704 705bool DeclContext::isDependentContext() const { 706 if (isFileContext()) 707 return false; 708 709 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 710 return true; 711 712 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 713 if (Record->getDescribedClassTemplate()) 714 return true; 715 716 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 717 if (Function->getDescribedFunctionTemplate()) 718 return true; 719 720 // Friend function declarations are dependent if their *lexical* 721 // context is dependent. 722 if (cast<Decl>(this)->getFriendObjectKind()) 723 return getLexicalParent()->isDependentContext(); 724 } 725 726 return getParent() && getParent()->isDependentContext(); 727} 728 729bool DeclContext::isTransparentContext() const { 730 if (DeclKind == Decl::Enum) 731 return !cast<EnumDecl>(this)->isScoped(); 732 else if (DeclKind == Decl::LinkageSpec) 733 return true; 734 735 return false; 736} 737 738bool DeclContext::isExternCContext() const { 739 const DeclContext *DC = this; 740 while (DC->DeclKind != Decl::TranslationUnit) { 741 if (DC->DeclKind == Decl::LinkageSpec) 742 return cast<LinkageSpecDecl>(DC)->getLanguage() 743 == LinkageSpecDecl::lang_c; 744 DC = DC->getParent(); 745 } 746 return false; 747} 748 749bool DeclContext::Encloses(const DeclContext *DC) const { 750 if (getPrimaryContext() != this) 751 return getPrimaryContext()->Encloses(DC); 752 753 for (; DC; DC = DC->getParent()) 754 if (DC->getPrimaryContext() == this) 755 return true; 756 return false; 757} 758 759DeclContext *DeclContext::getPrimaryContext() { 760 switch (DeclKind) { 761 case Decl::TranslationUnit: 762 case Decl::LinkageSpec: 763 case Decl::Block: 764 // There is only one DeclContext for these entities. 765 return this; 766 767 case Decl::Namespace: 768 // The original namespace is our primary context. 769 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 770 771 case Decl::ObjCMethod: 772 return this; 773 774 case Decl::ObjCInterface: 775 case Decl::ObjCProtocol: 776 case Decl::ObjCCategory: 777 // FIXME: Can Objective-C interfaces be forward-declared? 778 return this; 779 780 case Decl::ObjCImplementation: 781 case Decl::ObjCCategoryImpl: 782 return this; 783 784 default: 785 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 786 // If this is a tag type that has a definition or is currently 787 // being defined, that definition is our primary context. 788 TagDecl *Tag = cast<TagDecl>(this); 789 assert(isa<TagType>(Tag->TypeForDecl) || 790 isa<InjectedClassNameType>(Tag->TypeForDecl)); 791 792 if (TagDecl *Def = Tag->getDefinition()) 793 return Def; 794 795 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) { 796 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl); 797 if (TagTy->isBeingDefined()) 798 // FIXME: is it necessarily being defined in the decl 799 // that owns the type? 800 return TagTy->getDecl(); 801 } 802 803 return Tag; 804 } 805 806 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 807 "Unknown DeclContext kind"); 808 return this; 809 } 810} 811 812DeclContext *DeclContext::getNextContext() { 813 switch (DeclKind) { 814 case Decl::Namespace: 815 // Return the next namespace 816 return static_cast<NamespaceDecl*>(this)->getNextNamespace(); 817 818 default: 819 return 0; 820 } 821} 822 823std::pair<Decl *, Decl *> 824DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls, 825 bool FieldsAlreadyLoaded) { 826 // Build up a chain of declarations via the Decl::NextDeclInContext field. 827 Decl *FirstNewDecl = 0; 828 Decl *PrevDecl = 0; 829 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 830 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I])) 831 continue; 832 833 Decl *D = Decls[I]; 834 if (PrevDecl) 835 PrevDecl->NextDeclInContext = D; 836 else 837 FirstNewDecl = D; 838 839 PrevDecl = D; 840 } 841 842 return std::make_pair(FirstNewDecl, PrevDecl); 843} 844 845/// \brief Load the declarations within this lexical storage from an 846/// external source. 847void 848DeclContext::LoadLexicalDeclsFromExternalStorage() const { 849 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 850 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 851 852 // Notify that we have a DeclContext that is initializing. 853 ExternalASTSource::Deserializing ADeclContext(Source); 854 855 // Load the external declarations, if any. 856 SmallVector<Decl*, 64> Decls; 857 ExternalLexicalStorage = false; 858 switch (Source->FindExternalLexicalDecls(this, Decls)) { 859 case ELR_Success: 860 break; 861 862 case ELR_Failure: 863 case ELR_AlreadyLoaded: 864 return; 865 } 866 867 if (Decls.empty()) 868 return; 869 870 // We may have already loaded just the fields of this record, in which case 871 // we need to ignore them. 872 bool FieldsAlreadyLoaded = false; 873 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) 874 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage; 875 876 // Splice the newly-read declarations into the beginning of the list 877 // of declarations. 878 Decl *ExternalFirst, *ExternalLast; 879 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls, 880 FieldsAlreadyLoaded); 881 ExternalLast->NextDeclInContext = FirstDecl; 882 FirstDecl = ExternalFirst; 883 if (!LastDecl) 884 LastDecl = ExternalLast; 885} 886 887DeclContext::lookup_result 888ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 889 DeclarationName Name) { 890 ASTContext &Context = DC->getParentASTContext(); 891 StoredDeclsMap *Map; 892 if (!(Map = DC->LookupPtr)) 893 Map = DC->CreateStoredDeclsMap(Context); 894 895 StoredDeclsList &List = (*Map)[Name]; 896 assert(List.isNull()); 897 (void) List; 898 899 return DeclContext::lookup_result(); 900} 901 902DeclContext::lookup_result 903ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 904 DeclarationName Name, 905 ArrayRef<NamedDecl*> Decls) { 906 ASTContext &Context = DC->getParentASTContext();; 907 908 StoredDeclsMap *Map; 909 if (!(Map = DC->LookupPtr)) 910 Map = DC->CreateStoredDeclsMap(Context); 911 912 StoredDeclsList &List = (*Map)[Name]; 913 for (ArrayRef<NamedDecl*>::iterator 914 I = Decls.begin(), E = Decls.end(); I != E; ++I) { 915 if (List.isNull()) 916 List.setOnlyValue(*I); 917 else 918 List.AddSubsequentDecl(*I); 919 } 920 921 return List.getLookupResult(); 922} 923 924DeclContext::decl_iterator DeclContext::noload_decls_begin() const { 925 return decl_iterator(FirstDecl); 926} 927 928DeclContext::decl_iterator DeclContext::noload_decls_end() const { 929 return decl_iterator(); 930} 931 932DeclContext::decl_iterator DeclContext::decls_begin() const { 933 if (hasExternalLexicalStorage()) 934 LoadLexicalDeclsFromExternalStorage(); 935 936 return decl_iterator(FirstDecl); 937} 938 939DeclContext::decl_iterator DeclContext::decls_end() const { 940 if (hasExternalLexicalStorage()) 941 LoadLexicalDeclsFromExternalStorage(); 942 943 return decl_iterator(); 944} 945 946bool DeclContext::decls_empty() const { 947 if (hasExternalLexicalStorage()) 948 LoadLexicalDeclsFromExternalStorage(); 949 950 return !FirstDecl; 951} 952 953void DeclContext::removeDecl(Decl *D) { 954 assert(D->getLexicalDeclContext() == this && 955 "decl being removed from non-lexical context"); 956 assert((D->NextDeclInContext || D == LastDecl) && 957 "decl is not in decls list"); 958 959 // Remove D from the decl chain. This is O(n) but hopefully rare. 960 if (D == FirstDecl) { 961 if (D == LastDecl) 962 FirstDecl = LastDecl = 0; 963 else 964 FirstDecl = D->NextDeclInContext; 965 } else { 966 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) { 967 assert(I && "decl not found in linked list"); 968 if (I->NextDeclInContext == D) { 969 I->NextDeclInContext = D->NextDeclInContext; 970 if (D == LastDecl) LastDecl = I; 971 break; 972 } 973 } 974 } 975 976 // Mark that D is no longer in the decl chain. 977 D->NextDeclInContext = 0; 978 979 // Remove D from the lookup table if necessary. 980 if (isa<NamedDecl>(D)) { 981 NamedDecl *ND = cast<NamedDecl>(D); 982 983 // Remove only decls that have a name 984 if (!ND->getDeclName()) return; 985 986 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr; 987 if (!Map) return; 988 989 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 990 assert(Pos != Map->end() && "no lookup entry for decl"); 991 if (Pos->second.getAsVector() || Pos->second.getAsDecl() == ND) 992 Pos->second.remove(ND); 993 } 994} 995 996void DeclContext::addHiddenDecl(Decl *D) { 997 assert(D->getLexicalDeclContext() == this && 998 "Decl inserted into wrong lexical context"); 999 assert(!D->getNextDeclInContext() && D != LastDecl && 1000 "Decl already inserted into a DeclContext"); 1001 1002 if (FirstDecl) { 1003 LastDecl->NextDeclInContext = D; 1004 LastDecl = D; 1005 } else { 1006 FirstDecl = LastDecl = D; 1007 } 1008 1009 // Notify a C++ record declaration that we've added a member, so it can 1010 // update it's class-specific state. 1011 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 1012 Record->addedMember(D); 1013 1014 // If this is a newly-created (not de-serialized) import declaration, wire 1015 // it in to the list of local import declarations. 1016 if (!D->isFromASTFile()) { 1017 if (ImportDecl *Import = dyn_cast<ImportDecl>(D)) 1018 D->getASTContext().addedLocalImportDecl(Import); 1019 } 1020} 1021 1022void DeclContext::addDecl(Decl *D) { 1023 addHiddenDecl(D); 1024 1025 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1026 ND->getDeclContext()->makeDeclVisibleInContext(ND); 1027} 1028 1029void DeclContext::addDeclInternal(Decl *D) { 1030 addHiddenDecl(D); 1031 1032 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1033 ND->getDeclContext()->makeDeclVisibleInContextInternal(ND); 1034} 1035 1036/// buildLookup - Build the lookup data structure with all of the 1037/// declarations in DCtx (and any other contexts linked to it or 1038/// transparent contexts nested within it). 1039void DeclContext::buildLookup(DeclContext *DCtx) { 1040 for (; DCtx; DCtx = DCtx->getNextContext()) { 1041 for (decl_iterator D = DCtx->decls_begin(), 1042 DEnd = DCtx->decls_end(); 1043 D != DEnd; ++D) { 1044 // Insert this declaration into the lookup structure, but only 1045 // if it's semantically in its decl context. During non-lazy 1046 // lookup building, this is implicitly enforced by addDecl. 1047 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 1048 if (D->getDeclContext() == DCtx) 1049 makeDeclVisibleInContextImpl(ND, false); 1050 1051 // Insert any forward-declared Objective-C interface into the lookup 1052 // data structure. 1053 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) 1054 makeDeclVisibleInContextImpl(Class->getForwardInterfaceDecl(), false); 1055 1056 // If this declaration is itself a transparent declaration context or 1057 // inline namespace, add its members (recursively). 1058 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) 1059 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1060 buildLookup(InnerCtx->getPrimaryContext()); 1061 } 1062 } 1063} 1064 1065DeclContext::lookup_result 1066DeclContext::lookup(DeclarationName Name) { 1067 DeclContext *PrimaryContext = getPrimaryContext(); 1068 if (PrimaryContext != this) 1069 return PrimaryContext->lookup(Name); 1070 1071 if (hasExternalVisibleStorage()) { 1072 // Check to see if we've already cached the lookup results. 1073 if (LookupPtr) { 1074 StoredDeclsMap::iterator I = LookupPtr->find(Name); 1075 if (I != LookupPtr->end()) 1076 return I->second.getLookupResult(); 1077 } 1078 1079 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1080 return Source->FindExternalVisibleDeclsByName(this, Name); 1081 } 1082 1083 /// If there is no lookup data structure, build one now by walking 1084 /// all of the linked DeclContexts (in declaration order!) and 1085 /// inserting their values. 1086 if (!LookupPtr) { 1087 buildLookup(this); 1088 1089 if (!LookupPtr) 1090 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1091 } 1092 1093 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 1094 if (Pos == LookupPtr->end()) 1095 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1096 return Pos->second.getLookupResult(); 1097} 1098 1099DeclContext::lookup_const_result 1100DeclContext::lookup(DeclarationName Name) const { 1101 return const_cast<DeclContext*>(this)->lookup(Name); 1102} 1103 1104void DeclContext::localUncachedLookup(DeclarationName Name, 1105 llvm::SmallVectorImpl<NamedDecl *> &Results) { 1106 Results.clear(); 1107 1108 // If there's no external storage, just perform a normal lookup and copy 1109 // the results. 1110 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage()) { 1111 lookup_result LookupResults = lookup(Name); 1112 Results.insert(Results.end(), LookupResults.first, LookupResults.second); 1113 return; 1114 } 1115 1116 // If we have a lookup table, check there first. Maybe we'll get lucky. 1117 if (LookupPtr) { 1118 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 1119 if (Pos != LookupPtr->end()) { 1120 Results.insert(Results.end(), 1121 Pos->second.getLookupResult().first, 1122 Pos->second.getLookupResult().second); 1123 return; 1124 } 1125 } 1126 1127 // Slow case: grovel through the declarations in our chain looking for 1128 // matches. 1129 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) { 1130 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1131 if (ND->getDeclName() == Name) 1132 Results.push_back(ND); 1133 } 1134} 1135 1136DeclContext *DeclContext::getRedeclContext() { 1137 DeclContext *Ctx = this; 1138 // Skip through transparent contexts. 1139 while (Ctx->isTransparentContext()) 1140 Ctx = Ctx->getParent(); 1141 return Ctx; 1142} 1143 1144DeclContext *DeclContext::getEnclosingNamespaceContext() { 1145 DeclContext *Ctx = this; 1146 // Skip through non-namespace, non-translation-unit contexts. 1147 while (!Ctx->isFileContext()) 1148 Ctx = Ctx->getParent(); 1149 return Ctx->getPrimaryContext(); 1150} 1151 1152bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1153 // For non-file contexts, this is equivalent to Equals. 1154 if (!isFileContext()) 1155 return O->Equals(this); 1156 1157 do { 1158 if (O->Equals(this)) 1159 return true; 1160 1161 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O); 1162 if (!NS || !NS->isInline()) 1163 break; 1164 O = NS->getParent(); 1165 } while (O); 1166 1167 return false; 1168} 1169 1170void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) 1171{ 1172 makeDeclVisibleInContextWithFlags(D, false, Recoverable); 1173} 1174 1175void DeclContext::makeDeclVisibleInContextInternal(NamedDecl *D, bool Recoverable) 1176{ 1177 makeDeclVisibleInContextWithFlags(D, true, Recoverable); 1178} 1179 1180void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, bool Recoverable) { 1181 // FIXME: This feels like a hack. Should DeclarationName support 1182 // template-ids, or is there a better way to keep specializations 1183 // from being visible? 1184 if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter()) 1185 return; 1186 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1187 if (FD->isFunctionTemplateSpecialization()) 1188 return; 1189 1190 DeclContext *PrimaryContext = getPrimaryContext(); 1191 if (PrimaryContext != this) { 1192 PrimaryContext->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 1193 return; 1194 } 1195 1196 // If we already have a lookup data structure, perform the insertion 1197 // into it. If we haven't deserialized externally stored decls, deserialize 1198 // them so we can add the decl. Otherwise, be lazy and don't build that 1199 // structure until someone asks for it. 1200 if (LookupPtr || !Recoverable || hasExternalVisibleStorage()) 1201 makeDeclVisibleInContextImpl(D, Internal); 1202 1203 // If we are a transparent context or inline namespace, insert into our 1204 // parent context, too. This operation is recursive. 1205 if (isTransparentContext() || isInlineNamespace()) 1206 getParent()->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 1207 1208 Decl *DCAsDecl = cast<Decl>(this); 1209 // Notify that a decl was made visible unless it's a Tag being defined. 1210 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1211 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1212 L->AddedVisibleDecl(this, D); 1213} 1214 1215void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) { 1216 // Skip unnamed declarations. 1217 if (!D->getDeclName()) 1218 return; 1219 1220 // Skip entities that can't be found by name lookup into a particular 1221 // context. 1222 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1223 D->isTemplateParameter()) 1224 return; 1225 1226 ASTContext *C = 0; 1227 if (!LookupPtr) { 1228 C = &getParentASTContext(); 1229 CreateStoredDeclsMap(*C); 1230 } 1231 1232 // If there is an external AST source, load any declarations it knows about 1233 // with this declaration's name. 1234 // If the lookup table contains an entry about this name it means that we 1235 // have already checked the external source. 1236 if (!Internal) 1237 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1238 if (hasExternalVisibleStorage() && 1239 LookupPtr->find(D->getDeclName()) == LookupPtr->end()) 1240 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1241 1242 // Insert this declaration into the map. 1243 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()]; 1244 if (DeclNameEntries.isNull()) { 1245 DeclNameEntries.setOnlyValue(D); 1246 return; 1247 } 1248 1249 // If it is possible that this is a redeclaration, check to see if there is 1250 // already a decl for which declarationReplaces returns true. If there is 1251 // one, just replace it and return. 1252 if (DeclNameEntries.HandleRedeclaration(D)) 1253 return; 1254 1255 // Put this declaration into the appropriate slot. 1256 DeclNameEntries.AddSubsequentDecl(D); 1257} 1258 1259/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1260/// this context. 1261DeclContext::udir_iterator_range 1262DeclContext::getUsingDirectives() const { 1263 lookup_const_result Result = lookup(UsingDirectiveDecl::getName()); 1264 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first), 1265 reinterpret_cast<udir_iterator>(Result.second)); 1266} 1267 1268//===----------------------------------------------------------------------===// 1269// Creation and Destruction of StoredDeclsMaps. // 1270//===----------------------------------------------------------------------===// 1271 1272StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1273 assert(!LookupPtr && "context already has a decls map"); 1274 assert(getPrimaryContext() == this && 1275 "creating decls map on non-primary context"); 1276 1277 StoredDeclsMap *M; 1278 bool Dependent = isDependentContext(); 1279 if (Dependent) 1280 M = new DependentStoredDeclsMap(); 1281 else 1282 M = new StoredDeclsMap(); 1283 M->Previous = C.LastSDM; 1284 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1285 LookupPtr = M; 1286 return M; 1287} 1288 1289void ASTContext::ReleaseDeclContextMaps() { 1290 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1291 // pointer because the subclass doesn't add anything that needs to 1292 // be deleted. 1293 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1294} 1295 1296void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1297 while (Map) { 1298 // Advance the iteration before we invalidate memory. 1299 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1300 1301 if (Dependent) 1302 delete static_cast<DependentStoredDeclsMap*>(Map); 1303 else 1304 delete Map; 1305 1306 Map = Next.getPointer(); 1307 Dependent = Next.getInt(); 1308 } 1309} 1310 1311DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1312 DeclContext *Parent, 1313 const PartialDiagnostic &PDiag) { 1314 assert(Parent->isDependentContext() 1315 && "cannot iterate dependent diagnostics of non-dependent context"); 1316 Parent = Parent->getPrimaryContext(); 1317 if (!Parent->LookupPtr) 1318 Parent->CreateStoredDeclsMap(C); 1319 1320 DependentStoredDeclsMap *Map 1321 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr); 1322 1323 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1324 // BumpPtrAllocator, rather than the ASTContext itself. 1325 PartialDiagnostic::Storage *DiagStorage = 0; 1326 if (PDiag.hasStorage()) 1327 DiagStorage = new (C) PartialDiagnostic::Storage; 1328 1329 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1330 1331 // TODO: Maybe we shouldn't reverse the order during insertion. 1332 DD->NextDiagnostic = Map->FirstDiagnostic; 1333 Map->FirstDiagnostic = DD; 1334 1335 return DD; 1336} 1337