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