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