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