DeclBase.cpp revision 5586b019c18024b2967d027a17d5a05584a8b181
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 "llvm/ADT/DenseMap.h" 28#include "llvm/Support/raw_ostream.h" 29#include <algorithm> 30#include <cstdio> 31#include <vector> 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: assert(0 && "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: assert(0 && "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 fprintf(stderr, "*** 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 fprintf(stderr, " %d decls total.\n", totalDecls); 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 fprintf(stderr, " %d " #DERIVED " decls, %d each (%d bytes)\n", \ 91 n##DERIVED##s, (int)sizeof(DERIVED##Decl), \ 92 (int)(n##DERIVED##s * sizeof(DERIVED##Decl))); \ 93 } 94#define ABSTRACT_DECL(DECL) 95#include "clang/AST/DeclNodes.inc" 96 97 fprintf(stderr, "Total bytes = %d\n", totalBytes); 98} 99 100void Decl::add(Kind k) { 101 switch (k) { 102 default: assert(0 && "Declaration not in DeclNodes.inc!"); 103#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break; 104#define ABSTRACT_DECL(DECL) 105#include "clang/AST/DeclNodes.inc" 106 } 107} 108 109bool Decl::isTemplateParameterPack() const { 110 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this)) 111 return TTP->isParameterPack(); 112 113 return false; 114} 115 116bool Decl::isFunctionOrFunctionTemplate() const { 117 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this)) 118 return UD->getTargetDecl()->isFunctionOrFunctionTemplate(); 119 120 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this); 121} 122 123bool Decl::isDefinedOutsideFunctionOrMethod() const { 124 for (const DeclContext *DC = getDeclContext(); 125 DC && !DC->isTranslationUnit(); 126 DC = DC->getParent()) 127 if (DC->isFunctionOrMethod()) 128 return false; 129 130 return true; 131} 132 133 134//===----------------------------------------------------------------------===// 135// PrettyStackTraceDecl Implementation 136//===----------------------------------------------------------------------===// 137 138void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const { 139 SourceLocation TheLoc = Loc; 140 if (TheLoc.isInvalid() && TheDecl) 141 TheLoc = TheDecl->getLocation(); 142 143 if (TheLoc.isValid()) { 144 TheLoc.print(OS, SM); 145 OS << ": "; 146 } 147 148 OS << Message; 149 150 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) 151 OS << " '" << DN->getQualifiedNameAsString() << '\''; 152 OS << '\n'; 153} 154 155//===----------------------------------------------------------------------===// 156// Decl Implementation 157//===----------------------------------------------------------------------===// 158 159// Out-of-line virtual method providing a home for Decl. 160Decl::~Decl() { 161 assert(!HasAttrs && "attributes should have been freed by Destroy"); 162} 163 164void Decl::setDeclContext(DeclContext *DC) { 165 if (isOutOfSemaDC()) 166 delete getMultipleDC(); 167 168 DeclCtx = DC; 169} 170 171void Decl::setLexicalDeclContext(DeclContext *DC) { 172 if (DC == getLexicalDeclContext()) 173 return; 174 175 if (isInSemaDC()) { 176 MultipleDC *MDC = new (getASTContext()) MultipleDC(); 177 MDC->SemanticDC = getDeclContext(); 178 MDC->LexicalDC = DC; 179 DeclCtx = MDC; 180 } else { 181 getMultipleDC()->LexicalDC = DC; 182 } 183} 184 185bool Decl::isInAnonymousNamespace() const { 186 const DeclContext *DC = getDeclContext(); 187 do { 188 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC)) 189 if (ND->isAnonymousNamespace()) 190 return true; 191 } while ((DC = DC->getParent())); 192 193 return false; 194} 195 196TranslationUnitDecl *Decl::getTranslationUnitDecl() { 197 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this)) 198 return TUD; 199 200 DeclContext *DC = getDeclContext(); 201 assert(DC && "This decl is not contained in a translation unit!"); 202 203 while (!DC->isTranslationUnit()) { 204 DC = DC->getParent(); 205 assert(DC && "This decl is not contained in a translation unit!"); 206 } 207 208 return cast<TranslationUnitDecl>(DC); 209} 210 211ASTContext &Decl::getASTContext() const { 212 return getTranslationUnitDecl()->getASTContext(); 213} 214 215bool Decl::isUsed(bool CheckUsedAttr) const { 216 if (Used) 217 return true; 218 219 // Check for used attribute. 220 if (CheckUsedAttr && hasAttr<UsedAttr>()) 221 return true; 222 223 // Check redeclarations for used attribute. 224 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 225 if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used) 226 return true; 227 } 228 229 return false; 230} 231 232 233unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { 234 switch (DeclKind) { 235 case Function: 236 case CXXMethod: 237 case CXXConstructor: 238 case CXXDestructor: 239 case CXXConversion: 240 case EnumConstant: 241 case Var: 242 case ImplicitParam: 243 case ParmVar: 244 case NonTypeTemplateParm: 245 case ObjCMethod: 246 case ObjCProperty: 247 return IDNS_Ordinary; 248 249 case ObjCCompatibleAlias: 250 case ObjCInterface: 251 return IDNS_Ordinary | IDNS_Type; 252 253 case Typedef: 254 case UnresolvedUsingTypename: 255 case TemplateTypeParm: 256 return IDNS_Ordinary | IDNS_Type; 257 258 case UsingShadow: 259 return 0; // we'll actually overwrite this later 260 261 case UnresolvedUsingValue: 262 return IDNS_Ordinary | IDNS_Using; 263 264 case Using: 265 return IDNS_Using; 266 267 case ObjCProtocol: 268 return IDNS_ObjCProtocol; 269 270 case Field: 271 case ObjCAtDefsField: 272 case ObjCIvar: 273 return IDNS_Member; 274 275 case Record: 276 case CXXRecord: 277 case Enum: 278 return IDNS_Tag | IDNS_Type; 279 280 case Namespace: 281 case NamespaceAlias: 282 return IDNS_Namespace; 283 284 case FunctionTemplate: 285 return IDNS_Ordinary; 286 287 case ClassTemplate: 288 case TemplateTemplateParm: 289 return IDNS_Ordinary | IDNS_Tag | IDNS_Type; 290 291 // Never have names. 292 case Friend: 293 case FriendTemplate: 294 case AccessSpec: 295 case LinkageSpec: 296 case FileScopeAsm: 297 case StaticAssert: 298 case ObjCClass: 299 case ObjCPropertyImpl: 300 case ObjCForwardProtocol: 301 case Block: 302 case TranslationUnit: 303 304 case UsingDirective: 305 case ClassTemplateSpecialization: 306 case ClassTemplatePartialSpecialization: 307 case ObjCImplementation: 308 case ObjCCategory: 309 case ObjCCategoryImpl: 310 // Never looked up by name. 311 return 0; 312 } 313 314 return 0; 315} 316 317void Decl::initAttrs(Attr *attrs) { 318 assert(!HasAttrs && "Decl already contains attrs."); 319 320 Attr *&AttrBlank = getASTContext().getDeclAttrs(this); 321 assert(AttrBlank == 0 && "HasAttrs was wrong?"); 322 323 AttrBlank = attrs; 324 HasAttrs = true; 325} 326 327void Decl::addAttr(Attr *NewAttr) { 328 Attr *&ExistingAttr = getASTContext().getDeclAttrs(this); 329 330 assert(NewAttr->getNext() == 0 && "Chain of attributes will be truncated!"); 331 NewAttr->setNext(ExistingAttr); 332 ExistingAttr = NewAttr; 333 334 HasAttrs = true; 335} 336 337void Decl::invalidateAttrs() { 338 if (!HasAttrs) return; 339 340 HasAttrs = false; 341 getASTContext().eraseDeclAttrs(this); 342} 343 344const Attr *Decl::getAttrsImpl() const { 345 assert(HasAttrs && "getAttrs() should verify this!"); 346 return getASTContext().getDeclAttrs(this); 347} 348 349void Decl::swapAttrs(Decl *RHS) { 350 bool HasLHSAttr = this->HasAttrs; 351 bool HasRHSAttr = RHS->HasAttrs; 352 353 // Usually, neither decl has attrs, nothing to do. 354 if (!HasLHSAttr && !HasRHSAttr) return; 355 356 // If 'this' has no attrs, swap the other way. 357 if (!HasLHSAttr) 358 return RHS->swapAttrs(this); 359 360 ASTContext &Context = getASTContext(); 361 362 // Handle the case when both decls have attrs. 363 if (HasRHSAttr) { 364 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS)); 365 return; 366 } 367 368 // Otherwise, LHS has an attr and RHS doesn't. 369 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this); 370 Context.eraseDeclAttrs(this); 371 this->HasAttrs = false; 372 RHS->HasAttrs = true; 373} 374 375 376void Decl::Destroy(ASTContext &C) { 377 // Free attributes for this decl. 378 if (HasAttrs) { 379 C.getDeclAttrs(this)->Destroy(C); 380 invalidateAttrs(); 381 HasAttrs = false; 382 } 383 384#if 0 385 // FIXME: Once ownership is fully understood, we can enable this code 386 if (DeclContext *DC = dyn_cast<DeclContext>(this)) 387 DC->decls_begin()->Destroy(C); 388 389 // Observe the unrolled recursion. By setting N->NextDeclInContext = 0x0 390 // within the loop, only the Destroy method for the first Decl 391 // will deallocate all of the Decls in a chain. 392 393 Decl* N = getNextDeclInContext(); 394 395 while (N) { 396 Decl* Tmp = N->getNextDeclInContext(); 397 N->NextDeclInContext = 0; 398 N->Destroy(C); 399 N = Tmp; 400 } 401 402 if (isOutOfSemaDC()) 403 delete (C) getMultipleDC(); 404 405 this->~Decl(); 406 C.Deallocate((void *)this); 407#endif 408} 409 410Decl *Decl::castFromDeclContext (const DeclContext *D) { 411 Decl::Kind DK = D->getDeclKind(); 412 switch(DK) { 413#define DECL(NAME, BASE) 414#define DECL_CONTEXT(NAME) \ 415 case Decl::NAME: \ 416 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 417#define DECL_CONTEXT_BASE(NAME) 418#include "clang/AST/DeclNodes.inc" 419 default: 420#define DECL(NAME, BASE) 421#define DECL_CONTEXT_BASE(NAME) \ 422 if (DK >= first##NAME && DK <= last##NAME) \ 423 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 424#include "clang/AST/DeclNodes.inc" 425 assert(false && "a decl that inherits DeclContext isn't handled"); 426 return 0; 427 } 428} 429 430DeclContext *Decl::castToDeclContext(const Decl *D) { 431 Decl::Kind DK = D->getKind(); 432 switch(DK) { 433#define DECL(NAME, BASE) 434#define DECL_CONTEXT(NAME) \ 435 case Decl::NAME: \ 436 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 437#define DECL_CONTEXT_BASE(NAME) 438#include "clang/AST/DeclNodes.inc" 439 default: 440#define DECL(NAME, BASE) 441#define DECL_CONTEXT_BASE(NAME) \ 442 if (DK >= first##NAME && DK <= last##NAME) \ 443 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 444#include "clang/AST/DeclNodes.inc" 445 assert(false && "a decl that inherits DeclContext isn't handled"); 446 return 0; 447 } 448} 449 450CompoundStmt* Decl::getCompoundBody() const { 451 return dyn_cast_or_null<CompoundStmt>(getBody()); 452} 453 454SourceLocation Decl::getBodyRBrace() const { 455 Stmt *Body = getBody(); 456 if (!Body) 457 return SourceLocation(); 458 if (CompoundStmt *CS = dyn_cast<CompoundStmt>(Body)) 459 return CS->getRBracLoc(); 460 assert(isa<CXXTryStmt>(Body) && 461 "Body can only be CompoundStmt or CXXTryStmt"); 462 return cast<CXXTryStmt>(Body)->getSourceRange().getEnd(); 463} 464 465#ifndef NDEBUG 466void Decl::CheckAccessDeclContext() const { 467 // FIXME: Disable this until rdar://8146294 "access specifier for inner class 468 // templates is not set or checked" is fixed. 469 return; 470 // Suppress this check if any of the following hold: 471 // 1. this is the translation unit (and thus has no parent) 472 // 2. this is a template parameter (and thus doesn't belong to its context) 473 // 3. the context is not a record 474 // 4. it's invalid 475 if (isa<TranslationUnitDecl>(this) || 476 isa<TemplateTypeParmDecl>(this) || 477 !isa<CXXRecordDecl>(getDeclContext()) || 478 isInvalidDecl()) 479 return; 480 481 assert(Access != AS_none && 482 "Access specifier is AS_none inside a record decl"); 483} 484 485#endif 486 487//===----------------------------------------------------------------------===// 488// DeclContext Implementation 489//===----------------------------------------------------------------------===// 490 491bool DeclContext::classof(const Decl *D) { 492 switch (D->getKind()) { 493#define DECL(NAME, BASE) 494#define DECL_CONTEXT(NAME) case Decl::NAME: 495#define DECL_CONTEXT_BASE(NAME) 496#include "clang/AST/DeclNodes.inc" 497 return true; 498 default: 499#define DECL(NAME, BASE) 500#define DECL_CONTEXT_BASE(NAME) \ 501 if (D->getKind() >= Decl::first##NAME && \ 502 D->getKind() <= Decl::last##NAME) \ 503 return true; 504#include "clang/AST/DeclNodes.inc" 505 return false; 506 } 507} 508 509DeclContext::~DeclContext() { 510 // FIXME: Currently ~ASTContext will delete the StoredDeclsMaps because 511 // ~DeclContext() is not guaranteed to be called when ASTContext uses 512 // a BumpPtrAllocator. 513 // delete LookupPtr; 514} 515 516void DeclContext::DestroyDecls(ASTContext &C) { 517 for (decl_iterator D = decls_begin(); D != decls_end(); ) 518 (*D++)->Destroy(C); 519} 520 521/// \brief Find the parent context of this context that will be 522/// used for unqualified name lookup. 523/// 524/// Generally, the parent lookup context is the semantic context. However, for 525/// a friend function the parent lookup context is the lexical context, which 526/// is the class in which the friend is declared. 527DeclContext *DeclContext::getLookupParent() { 528 // FIXME: Find a better way to identify friends 529 if (isa<FunctionDecl>(this)) 530 if (getParent()->getLookupContext()->isFileContext() && 531 getLexicalParent()->getLookupContext()->isRecord()) 532 return getLexicalParent(); 533 534 return getParent(); 535} 536 537bool DeclContext::isDependentContext() const { 538 if (isFileContext()) 539 return false; 540 541 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 542 return true; 543 544 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 545 if (Record->getDescribedClassTemplate()) 546 return true; 547 548 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 549 if (Function->getDescribedFunctionTemplate()) 550 return true; 551 552 // Friend function declarations are dependent if their *lexical* 553 // context is dependent. 554 if (cast<Decl>(this)->getFriendObjectKind()) 555 return getLexicalParent()->isDependentContext(); 556 } 557 558 return getParent() && getParent()->isDependentContext(); 559} 560 561bool DeclContext::isTransparentContext() const { 562 if (DeclKind == Decl::Enum) 563 return true; // FIXME: Check for C++0x scoped enums 564 else if (DeclKind == Decl::LinkageSpec) 565 return true; 566 else if (DeclKind >= Decl::firstRecord && DeclKind <= Decl::lastRecord) 567 return cast<RecordDecl>(this)->isAnonymousStructOrUnion(); 568 else if (DeclKind == Decl::Namespace) 569 return false; // FIXME: Check for C++0x inline namespaces 570 571 return false; 572} 573 574bool DeclContext::Encloses(DeclContext *DC) { 575 if (getPrimaryContext() != this) 576 return getPrimaryContext()->Encloses(DC); 577 578 for (; DC; DC = DC->getParent()) 579 if (DC->getPrimaryContext() == this) 580 return true; 581 return false; 582} 583 584DeclContext *DeclContext::getPrimaryContext() { 585 switch (DeclKind) { 586 case Decl::TranslationUnit: 587 case Decl::LinkageSpec: 588 case Decl::Block: 589 // There is only one DeclContext for these entities. 590 return this; 591 592 case Decl::Namespace: 593 // The original namespace is our primary context. 594 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 595 596 case Decl::ObjCMethod: 597 return this; 598 599 case Decl::ObjCInterface: 600 case Decl::ObjCProtocol: 601 case Decl::ObjCCategory: 602 // FIXME: Can Objective-C interfaces be forward-declared? 603 return this; 604 605 case Decl::ObjCImplementation: 606 case Decl::ObjCCategoryImpl: 607 return this; 608 609 default: 610 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 611 // If this is a tag type that has a definition or is currently 612 // being defined, that definition is our primary context. 613 TagDecl *Tag = cast<TagDecl>(this); 614 assert(isa<TagType>(Tag->TypeForDecl) || 615 isa<InjectedClassNameType>(Tag->TypeForDecl)); 616 617 if (TagDecl *Def = Tag->getDefinition()) 618 return Def; 619 620 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) { 621 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl); 622 if (TagTy->isBeingDefined()) 623 // FIXME: is it necessarily being defined in the decl 624 // that owns the type? 625 return TagTy->getDecl(); 626 } 627 628 return Tag; 629 } 630 631 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 632 "Unknown DeclContext kind"); 633 return this; 634 } 635} 636 637DeclContext *DeclContext::getNextContext() { 638 switch (DeclKind) { 639 case Decl::Namespace: 640 // Return the next namespace 641 return static_cast<NamespaceDecl*>(this)->getNextNamespace(); 642 643 default: 644 return 0; 645 } 646} 647 648/// \brief Load the declarations within this lexical storage from an 649/// external source. 650void 651DeclContext::LoadLexicalDeclsFromExternalStorage() const { 652 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 653 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 654 655 llvm::SmallVector<Decl*, 64> Decls; 656 if (Source->FindExternalLexicalDecls(this, Decls)) 657 return; 658 659 // There is no longer any lexical storage in this context 660 ExternalLexicalStorage = false; 661 662 if (Decls.empty()) 663 return; 664 665 // Resolve all of the declaration IDs into declarations, building up 666 // a chain of declarations via the Decl::NextDeclInContext field. 667 Decl *FirstNewDecl = 0; 668 Decl *PrevDecl = 0; 669 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 670 Decl *D = Decls[I]; 671 if (PrevDecl) 672 PrevDecl->NextDeclInContext = D; 673 else 674 FirstNewDecl = D; 675 676 PrevDecl = D; 677 } 678 679 // Splice the newly-read declarations into the beginning of the list 680 // of declarations. 681 PrevDecl->NextDeclInContext = FirstDecl; 682 FirstDecl = FirstNewDecl; 683 if (!LastDecl) 684 LastDecl = PrevDecl; 685} 686 687DeclContext::lookup_result 688ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 689 DeclarationName Name) { 690 ASTContext &Context = DC->getParentASTContext(); 691 StoredDeclsMap *Map; 692 if (!(Map = DC->LookupPtr)) 693 Map = DC->CreateStoredDeclsMap(Context); 694 695 StoredDeclsList &List = (*Map)[Name]; 696 assert(List.isNull()); 697 (void) List; 698 699 return DeclContext::lookup_result(); 700} 701 702DeclContext::lookup_result 703ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 704 const VisibleDeclaration &VD) { 705 ASTContext &Context = DC->getParentASTContext(); 706 StoredDeclsMap *Map; 707 if (!(Map = DC->LookupPtr)) 708 Map = DC->CreateStoredDeclsMap(Context); 709 710 StoredDeclsList &List = (*Map)[VD.Name]; 711 List.setFromDeclIDs(VD.Declarations); 712 return List.getLookupResult(Context); 713} 714 715DeclContext::lookup_result 716ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 717 DeclarationName Name, 718 llvm::SmallVectorImpl<NamedDecl*> &Decls) { 719 ASTContext &Context = DC->getParentASTContext();; 720 721 StoredDeclsMap *Map; 722 if (!(Map = DC->LookupPtr)) 723 Map = DC->CreateStoredDeclsMap(Context); 724 725 StoredDeclsList &List = (*Map)[Name]; 726 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 727 if (List.isNull()) 728 List.setOnlyValue(Decls[I]); 729 else 730 List.AddSubsequentDecl(Decls[I]); 731 } 732 733 return List.getLookupResult(Context); 734} 735 736void ExternalASTSource::SetExternalVisibleDecls(const DeclContext *DC, 737 const llvm::SmallVectorImpl<VisibleDeclaration> &Decls) { 738 // There is no longer any visible storage in this context. 739 DC->ExternalVisibleStorage = false; 740 741 assert(!DC->LookupPtr && "Have a lookup map before de-serialization?"); 742 StoredDeclsMap *Map = DC->CreateStoredDeclsMap(DC->getParentASTContext()); 743 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 744 (*Map)[Decls[I].Name].setFromDeclIDs(Decls[I].Declarations); 745 } 746} 747 748void ExternalASTSource::SetExternalVisibleDecls(const DeclContext *DC, 749 const llvm::SmallVectorImpl<NamedDecl*> &Decls) { 750 // There is no longer any visible storage in this context. 751 DC->ExternalVisibleStorage = false; 752 753 assert(!DC->LookupPtr && "Have a lookup map before de-serialization?"); 754 StoredDeclsMap &Map = *DC->CreateStoredDeclsMap(DC->getParentASTContext()); 755 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 756 StoredDeclsList &List = Map[Decls[I]->getDeclName()]; 757 if (List.isNull()) 758 List.setOnlyValue(Decls[I]); 759 else 760 List.AddSubsequentDecl(Decls[I]); 761 } 762} 763 764DeclContext::decl_iterator DeclContext::decls_begin() const { 765 if (hasExternalLexicalStorage()) 766 LoadLexicalDeclsFromExternalStorage(); 767 768 // FIXME: Check whether we need to load some declarations from 769 // external storage. 770 return decl_iterator(FirstDecl); 771} 772 773DeclContext::decl_iterator DeclContext::decls_end() const { 774 if (hasExternalLexicalStorage()) 775 LoadLexicalDeclsFromExternalStorage(); 776 777 return decl_iterator(); 778} 779 780bool DeclContext::decls_empty() const { 781 if (hasExternalLexicalStorage()) 782 LoadLexicalDeclsFromExternalStorage(); 783 784 return !FirstDecl; 785} 786 787void DeclContext::removeDecl(Decl *D) { 788 assert(D->getLexicalDeclContext() == this && 789 "decl being removed from non-lexical context"); 790 assert((D->NextDeclInContext || D == LastDecl) && 791 "decl is not in decls list"); 792 793 // Remove D from the decl chain. This is O(n) but hopefully rare. 794 if (D == FirstDecl) { 795 if (D == LastDecl) 796 FirstDecl = LastDecl = 0; 797 else 798 FirstDecl = D->NextDeclInContext; 799 } else { 800 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) { 801 assert(I && "decl not found in linked list"); 802 if (I->NextDeclInContext == D) { 803 I->NextDeclInContext = D->NextDeclInContext; 804 if (D == LastDecl) LastDecl = I; 805 break; 806 } 807 } 808 } 809 810 // Mark that D is no longer in the decl chain. 811 D->NextDeclInContext = 0; 812 813 // Remove D from the lookup table if necessary. 814 if (isa<NamedDecl>(D)) { 815 NamedDecl *ND = cast<NamedDecl>(D); 816 817 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr; 818 if (!Map) return; 819 820 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 821 assert(Pos != Map->end() && "no lookup entry for decl"); 822 Pos->second.remove(ND); 823 } 824} 825 826void DeclContext::addHiddenDecl(Decl *D) { 827 assert(D->getLexicalDeclContext() == this && 828 "Decl inserted into wrong lexical context"); 829 assert(!D->getNextDeclInContext() && D != LastDecl && 830 "Decl already inserted into a DeclContext"); 831 832 if (FirstDecl) { 833 LastDecl->NextDeclInContext = D; 834 LastDecl = D; 835 } else { 836 FirstDecl = LastDecl = D; 837 } 838} 839 840void DeclContext::addDecl(Decl *D) { 841 addHiddenDecl(D); 842 843 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 844 ND->getDeclContext()->makeDeclVisibleInContext(ND); 845} 846 847/// buildLookup - Build the lookup data structure with all of the 848/// declarations in DCtx (and any other contexts linked to it or 849/// transparent contexts nested within it). 850void DeclContext::buildLookup(DeclContext *DCtx) { 851 for (; DCtx; DCtx = DCtx->getNextContext()) { 852 for (decl_iterator D = DCtx->decls_begin(), 853 DEnd = DCtx->decls_end(); 854 D != DEnd; ++D) { 855 // Insert this declaration into the lookup structure, but only 856 // if it's semantically in its decl context. During non-lazy 857 // lookup building, this is implicitly enforced by addDecl. 858 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 859 if (D->getDeclContext() == DCtx) 860 makeDeclVisibleInContextImpl(ND); 861 862 // Insert any forward-declared Objective-C interfaces into the lookup 863 // data structure. 864 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) 865 for (ObjCClassDecl::iterator I = Class->begin(), IEnd = Class->end(); 866 I != IEnd; ++I) 867 makeDeclVisibleInContextImpl(I->getInterface()); 868 869 // If this declaration is itself a transparent declaration context, 870 // add its members (recursively). 871 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) 872 if (InnerCtx->isTransparentContext()) 873 buildLookup(InnerCtx->getPrimaryContext()); 874 } 875 } 876} 877 878DeclContext::lookup_result 879DeclContext::lookup(DeclarationName Name) { 880 DeclContext *PrimaryContext = getPrimaryContext(); 881 if (PrimaryContext != this) 882 return PrimaryContext->lookup(Name); 883 884 if (hasExternalVisibleStorage()) { 885 // Check to see if we've already cached the lookup results. 886 if (LookupPtr) { 887 StoredDeclsMap::iterator I = LookupPtr->find(Name); 888 if (I != LookupPtr->end()) 889 return I->second.getLookupResult(getParentASTContext()); 890 } 891 892 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 893 return Source->FindExternalVisibleDeclsByName(this, Name); 894 } 895 896 /// If there is no lookup data structure, build one now by walking 897 /// all of the linked DeclContexts (in declaration order!) and 898 /// inserting their values. 899 if (!LookupPtr) { 900 buildLookup(this); 901 902 if (!LookupPtr) 903 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 904 } 905 906 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 907 if (Pos == LookupPtr->end()) 908 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 909 return Pos->second.getLookupResult(getParentASTContext()); 910} 911 912DeclContext::lookup_const_result 913DeclContext::lookup(DeclarationName Name) const { 914 return const_cast<DeclContext*>(this)->lookup(Name); 915} 916 917DeclContext *DeclContext::getLookupContext() { 918 DeclContext *Ctx = this; 919 // Skip through transparent contexts. 920 while (Ctx->isTransparentContext()) 921 Ctx = Ctx->getParent(); 922 return Ctx; 923} 924 925DeclContext *DeclContext::getEnclosingNamespaceContext() { 926 DeclContext *Ctx = this; 927 // Skip through non-namespace, non-translation-unit contexts. 928 while (!Ctx->isFileContext() || Ctx->isTransparentContext()) 929 Ctx = Ctx->getParent(); 930 return Ctx->getPrimaryContext(); 931} 932 933void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) { 934 // FIXME: This feels like a hack. Should DeclarationName support 935 // template-ids, or is there a better way to keep specializations 936 // from being visible? 937 if (isa<ClassTemplateSpecializationDecl>(D)) 938 return; 939 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 940 if (FD->isFunctionTemplateSpecialization()) 941 return; 942 943 DeclContext *PrimaryContext = getPrimaryContext(); 944 if (PrimaryContext != this) { 945 PrimaryContext->makeDeclVisibleInContext(D, Recoverable); 946 return; 947 } 948 949 // If we already have a lookup data structure, perform the insertion 950 // into it. If we haven't deserialized externally stored decls, deserialize 951 // them so we can add the decl. Otherwise, be lazy and don't build that 952 // structure until someone asks for it. 953 if (LookupPtr || !Recoverable || hasExternalVisibleStorage()) 954 makeDeclVisibleInContextImpl(D); 955 956 // If we are a transparent context, insert into our parent context, 957 // too. This operation is recursive. 958 if (isTransparentContext()) 959 getParent()->makeDeclVisibleInContext(D, Recoverable); 960} 961 962void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) { 963 // Skip unnamed declarations. 964 if (!D->getDeclName()) 965 return; 966 967 // FIXME: This feels like a hack. Should DeclarationName support 968 // template-ids, or is there a better way to keep specializations 969 // from being visible? 970 if (isa<ClassTemplateSpecializationDecl>(D)) 971 return; 972 973 // If there is an external AST source, load any declarations it knows about 974 // with this declaration's name. 975 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 976 if (hasExternalVisibleStorage()) 977 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 978 979 ASTContext *C = 0; 980 if (!LookupPtr) { 981 C = &getParentASTContext(); 982 CreateStoredDeclsMap(*C); 983 } 984 985 // Insert this declaration into the map. 986 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()]; 987 if (DeclNameEntries.isNull()) { 988 DeclNameEntries.setOnlyValue(D); 989 return; 990 } 991 992 // If it is possible that this is a redeclaration, check to see if there is 993 // already a decl for which declarationReplaces returns true. If there is 994 // one, just replace it and return. 995 if (!C) 996 C = &getParentASTContext(); 997 998 if (DeclNameEntries.HandleRedeclaration(*C, D)) 999 return; 1000 1001 // Put this declaration into the appropriate slot. 1002 DeclNameEntries.AddSubsequentDecl(D); 1003} 1004 1005/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1006/// this context. 1007DeclContext::udir_iterator_range 1008DeclContext::getUsingDirectives() const { 1009 lookup_const_result Result = lookup(UsingDirectiveDecl::getName()); 1010 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first), 1011 reinterpret_cast<udir_iterator>(Result.second)); 1012} 1013 1014void StoredDeclsList::materializeDecls(ASTContext &Context) { 1015 if (isNull()) 1016 return; 1017 1018 switch ((DataKind)(Data & 0x03)) { 1019 case DK_Decl: 1020 case DK_Decl_Vector: 1021 break; 1022 1023 case DK_DeclID: { 1024 // Resolve this declaration ID to an actual declaration by 1025 // querying the external AST source. 1026 unsigned DeclID = Data >> 2; 1027 1028 ExternalASTSource *Source = Context.getExternalSource(); 1029 assert(Source && "No external AST source available!"); 1030 1031 Data = reinterpret_cast<uintptr_t>(Source->GetExternalDecl(DeclID)); 1032 break; 1033 } 1034 1035 case DK_ID_Vector: { 1036 // We have a vector of declaration IDs. Resolve all of them to 1037 // actual declarations. 1038 VectorTy &Vector = *getAsVector(); 1039 ExternalASTSource *Source = Context.getExternalSource(); 1040 assert(Source && "No external AST source available!"); 1041 1042 for (unsigned I = 0, N = Vector.size(); I != N; ++I) 1043 Vector[I] = reinterpret_cast<uintptr_t>(Source->GetExternalDecl(Vector[I])); 1044 1045 Data = (Data & ~0x03) | DK_Decl_Vector; 1046 break; 1047 } 1048 } 1049} 1050 1051//===----------------------------------------------------------------------===// 1052// Creation and Destruction of StoredDeclsMaps. // 1053//===----------------------------------------------------------------------===// 1054 1055StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1056 assert(!LookupPtr && "context already has a decls map"); 1057 assert(getPrimaryContext() == this && 1058 "creating decls map on non-primary context"); 1059 1060 StoredDeclsMap *M; 1061 bool Dependent = isDependentContext(); 1062 if (Dependent) 1063 M = new DependentStoredDeclsMap(); 1064 else 1065 M = new StoredDeclsMap(); 1066 M->Previous = C.LastSDM; 1067 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1068 LookupPtr = M; 1069 return M; 1070} 1071 1072void ASTContext::ReleaseDeclContextMaps() { 1073 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1074 // pointer because the subclass doesn't add anything that needs to 1075 // be deleted. 1076 1077 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1078} 1079 1080void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1081 while (Map) { 1082 // Advance the iteration before we invalidate memory. 1083 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1084 1085 if (Dependent) 1086 delete static_cast<DependentStoredDeclsMap*>(Map); 1087 else 1088 delete Map; 1089 1090 Map = Next.getPointer(); 1091 Dependent = Next.getInt(); 1092 } 1093} 1094 1095DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1096 DeclContext *Parent, 1097 const PartialDiagnostic &PDiag) { 1098 assert(Parent->isDependentContext() 1099 && "cannot iterate dependent diagnostics of non-dependent context"); 1100 Parent = Parent->getPrimaryContext(); 1101 if (!Parent->LookupPtr) 1102 Parent->CreateStoredDeclsMap(C); 1103 1104 DependentStoredDeclsMap *Map 1105 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr); 1106 1107 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1108 // BumpPtrAllocator, rather than the ASTContext itself. 1109 PartialDiagnostic::Storage *DiagStorage = 0; 1110 if (PDiag.hasStorage()) 1111 DiagStorage = new (C) PartialDiagnostic::Storage; 1112 1113 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1114 1115 // TODO: Maybe we shouldn't reverse the order during insertion. 1116 DD->NextDiagnostic = Map->FirstDiagnostic; 1117 Map->FirstDiagnostic = DD; 1118 1119 return DD; 1120} 1121