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