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