1 //===- DeclBase.cpp - Declaration AST Node Implementation -----------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Decl and DeclContext classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/DeclBase.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTLambda.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/AttrIterator.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclContextInternals.h" 22 #include "clang/AST/DeclFriend.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/DeclOpenMP.h" 25 #include "clang/AST/DeclTemplate.h" 26 #include "clang/AST/DependentDiagnostic.h" 27 #include "clang/AST/ExternalASTSource.h" 28 #include "clang/AST/Stmt.h" 29 #include "clang/AST/Type.h" 30 #include "clang/Basic/IdentifierTable.h" 31 #include "clang/Basic/LLVM.h" 32 #include "clang/Basic/LangOptions.h" 33 #include "clang/Basic/ObjCRuntime.h" 34 #include "clang/Basic/PartialDiagnostic.h" 35 #include "clang/Basic/SourceLocation.h" 36 #include "clang/Basic/TargetInfo.h" 37 #include "llvm/ADT/ArrayRef.h" 38 #include "llvm/ADT/PointerIntPair.h" 39 #include "llvm/ADT/SmallVector.h" 40 #include "llvm/ADT/StringRef.h" 41 #include "llvm/Support/Casting.h" 42 #include "llvm/Support/ErrorHandling.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/VersionTuple.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include <algorithm> 47 #include <cassert> 48 #include <cstddef> 49 #include <string> 50 #include <tuple> 51 #include <utility> 52 53 using namespace clang; 54 55 //===----------------------------------------------------------------------===// 56 // Statistics 57 //===----------------------------------------------------------------------===// 58 59 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0; 60 #define ABSTRACT_DECL(DECL) 61 #include "clang/AST/DeclNodes.inc" 62 63 void Decl::updateOutOfDate(IdentifierInfo &II) const { 64 getASTContext().getExternalSource()->updateOutOfDateIdentifier(II); 65 } 66 67 #define DECL(DERIVED, BASE) \ 68 static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \ 69 "Alignment sufficient after objects prepended to " #DERIVED); 70 #define ABSTRACT_DECL(DECL) 71 #include "clang/AST/DeclNodes.inc" 72 73 void *Decl::operator new(std::size_t Size, const ASTContext &Context, 74 unsigned ID, std::size_t Extra) { 75 // Allocate an extra 8 bytes worth of storage, which ensures that the 76 // resulting pointer will still be 8-byte aligned. 77 static_assert(sizeof(unsigned) * 2 >= alignof(Decl), 78 "Decl won't be misaligned"); 79 void *Start = Context.Allocate(Size + Extra + 8); 80 void *Result = (char*)Start + 8; 81 82 unsigned *PrefixPtr = (unsigned *)Result - 2; 83 84 // Zero out the first 4 bytes; this is used to store the owning module ID. 85 PrefixPtr[0] = 0; 86 87 // Store the global declaration ID in the second 4 bytes. 88 PrefixPtr[1] = ID; 89 90 return Result; 91 } 92 93 void *Decl::operator new(std::size_t Size, const ASTContext &Ctx, 94 DeclContext *Parent, std::size_t Extra) { 95 assert(!Parent || &Parent->getParentASTContext() == &Ctx); 96 // With local visibility enabled, we track the owning module even for local 97 // declarations. We create the TU decl early and may not yet know what the 98 // LangOpts are, so conservatively allocate the storage. 99 if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) { 100 // Ensure required alignment of the resulting object by adding extra 101 // padding at the start if required. 102 size_t ExtraAlign = 103 llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl))); 104 auto *Buffer = reinterpret_cast<char *>( 105 ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx)); 106 Buffer += ExtraAlign; 107 auto *ParentModule = 108 Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr; 109 return new (Buffer) Module*(ParentModule) + 1; 110 } 111 return ::operator new(Size + Extra, Ctx); 112 } 113 114 Module *Decl::getOwningModuleSlow() const { 115 assert(isFromASTFile() && "Not from AST file?"); 116 return getASTContext().getExternalSource()->getModule(getOwningModuleID()); 117 } 118 119 bool Decl::hasLocalOwningModuleStorage() const { 120 return getASTContext().getLangOpts().trackLocalOwningModule(); 121 } 122 123 const char *Decl::getDeclKindName() const { 124 switch (DeclKind) { 125 default: llvm_unreachable("Declaration not in DeclNodes.inc!"); 126 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED; 127 #define ABSTRACT_DECL(DECL) 128 #include "clang/AST/DeclNodes.inc" 129 } 130 } 131 132 void Decl::setInvalidDecl(bool Invalid) { 133 InvalidDecl = Invalid; 134 assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition()); 135 if (!Invalid) { 136 return; 137 } 138 139 if (!isa<ParmVarDecl>(this)) { 140 // Defensive maneuver for ill-formed code: we're likely not to make it to 141 // a point where we set the access specifier, so default it to "public" 142 // to avoid triggering asserts elsewhere in the front end. 143 setAccess(AS_public); 144 } 145 146 // Marking a DecompositionDecl as invalid implies all the child BindingDecl's 147 // are invalid too. 148 if (auto *DD = dyn_cast<DecompositionDecl>(this)) { 149 for (auto *Binding : DD->bindings()) { 150 Binding->setInvalidDecl(); 151 } 152 } 153 } 154 155 bool DeclContext::hasValidDeclKind() const { 156 switch (getDeclKind()) { 157 #define DECL(DERIVED, BASE) case Decl::DERIVED: return true; 158 #define ABSTRACT_DECL(DECL) 159 #include "clang/AST/DeclNodes.inc" 160 } 161 return false; 162 } 163 164 const char *DeclContext::getDeclKindName() const { 165 switch (getDeclKind()) { 166 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED; 167 #define ABSTRACT_DECL(DECL) 168 #include "clang/AST/DeclNodes.inc" 169 } 170 llvm_unreachable("Declaration context not in DeclNodes.inc!"); 171 } 172 173 bool Decl::StatisticsEnabled = false; 174 void Decl::EnableStatistics() { 175 StatisticsEnabled = true; 176 } 177 178 void Decl::PrintStats() { 179 llvm::errs() << "\n*** Decl Stats:\n"; 180 181 int totalDecls = 0; 182 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s; 183 #define ABSTRACT_DECL(DECL) 184 #include "clang/AST/DeclNodes.inc" 185 llvm::errs() << " " << totalDecls << " decls total.\n"; 186 187 int totalBytes = 0; 188 #define DECL(DERIVED, BASE) \ 189 if (n##DERIVED##s > 0) { \ 190 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \ 191 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \ 192 << sizeof(DERIVED##Decl) << " each (" \ 193 << n##DERIVED##s * sizeof(DERIVED##Decl) \ 194 << " bytes)\n"; \ 195 } 196 #define ABSTRACT_DECL(DECL) 197 #include "clang/AST/DeclNodes.inc" 198 199 llvm::errs() << "Total bytes = " << totalBytes << "\n"; 200 } 201 202 void Decl::add(Kind k) { 203 switch (k) { 204 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break; 205 #define ABSTRACT_DECL(DECL) 206 #include "clang/AST/DeclNodes.inc" 207 } 208 } 209 210 bool Decl::isTemplateParameterPack() const { 211 if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this)) 212 return TTP->isParameterPack(); 213 if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this)) 214 return NTTP->isParameterPack(); 215 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this)) 216 return TTP->isParameterPack(); 217 return false; 218 } 219 220 bool Decl::isParameterPack() const { 221 if (const auto *Var = dyn_cast<VarDecl>(this)) 222 return Var->isParameterPack(); 223 224 return isTemplateParameterPack(); 225 } 226 227 FunctionDecl *Decl::getAsFunction() { 228 if (auto *FD = dyn_cast<FunctionDecl>(this)) 229 return FD; 230 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this)) 231 return FTD->getTemplatedDecl(); 232 return nullptr; 233 } 234 235 bool Decl::isTemplateDecl() const { 236 return isa<TemplateDecl>(this); 237 } 238 239 TemplateDecl *Decl::getDescribedTemplate() const { 240 if (auto *FD = dyn_cast<FunctionDecl>(this)) 241 return FD->getDescribedFunctionTemplate(); 242 if (auto *RD = dyn_cast<CXXRecordDecl>(this)) 243 return RD->getDescribedClassTemplate(); 244 if (auto *VD = dyn_cast<VarDecl>(this)) 245 return VD->getDescribedVarTemplate(); 246 if (auto *AD = dyn_cast<TypeAliasDecl>(this)) 247 return AD->getDescribedAliasTemplate(); 248 249 return nullptr; 250 } 251 252 const TemplateParameterList *Decl::getDescribedTemplateParams() const { 253 if (auto *TD = getDescribedTemplate()) 254 return TD->getTemplateParameters(); 255 if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this)) 256 return CTPSD->getTemplateParameters(); 257 if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this)) 258 return VTPSD->getTemplateParameters(); 259 return nullptr; 260 } 261 262 bool Decl::isTemplated() const { 263 // A declaration is templated if it is a template or a template pattern, or 264 // is within (lexcially for a friend or local function declaration, 265 // semantically otherwise) a dependent context. 266 if (auto *AsDC = dyn_cast<DeclContext>(this)) 267 return AsDC->isDependentContext(); 268 auto *DC = getFriendObjectKind() || isLocalExternDecl() 269 ? getLexicalDeclContext() : getDeclContext(); 270 return DC->isDependentContext() || isTemplateDecl() || 271 getDescribedTemplateParams(); 272 } 273 274 unsigned Decl::getTemplateDepth() const { 275 if (auto *DC = dyn_cast<DeclContext>(this)) 276 if (DC->isFileContext()) 277 return 0; 278 279 if (auto *TPL = getDescribedTemplateParams()) 280 return TPL->getDepth() + 1; 281 282 // If this is a dependent lambda, there might be an enclosing variable 283 // template. In this case, the next step is not the parent DeclContext (or 284 // even a DeclContext at all). 285 auto *RD = dyn_cast<CXXRecordDecl>(this); 286 if (RD && RD->isDependentLambda()) 287 if (Decl *Context = RD->getLambdaContextDecl()) 288 return Context->getTemplateDepth(); 289 290 const DeclContext *DC = 291 getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext(); 292 return cast<Decl>(DC)->getTemplateDepth(); 293 } 294 295 const DeclContext *Decl::getParentFunctionOrMethod(bool LexicalParent) const { 296 for (const DeclContext *DC = LexicalParent ? getLexicalDeclContext() 297 : getDeclContext(); 298 DC && !DC->isFileContext(); DC = DC->getParent()) 299 if (DC->isFunctionOrMethod()) 300 return DC; 301 302 return nullptr; 303 } 304 305 //===----------------------------------------------------------------------===// 306 // PrettyStackTraceDecl Implementation 307 //===----------------------------------------------------------------------===// 308 309 void PrettyStackTraceDecl::print(raw_ostream &OS) const { 310 SourceLocation TheLoc = Loc; 311 if (TheLoc.isInvalid() && TheDecl) 312 TheLoc = TheDecl->getLocation(); 313 314 if (TheLoc.isValid()) { 315 TheLoc.print(OS, SM); 316 OS << ": "; 317 } 318 319 OS << Message; 320 321 if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) { 322 OS << " '"; 323 DN->printQualifiedName(OS); 324 OS << '\''; 325 } 326 OS << '\n'; 327 } 328 329 //===----------------------------------------------------------------------===// 330 // Decl Implementation 331 //===----------------------------------------------------------------------===// 332 333 // Out-of-line virtual method providing a home for Decl. 334 Decl::~Decl() = default; 335 336 void Decl::setDeclContext(DeclContext *DC) { 337 DeclCtx = DC; 338 } 339 340 void Decl::setLexicalDeclContext(DeclContext *DC) { 341 if (DC == getLexicalDeclContext()) 342 return; 343 344 if (isInSemaDC()) { 345 setDeclContextsImpl(getDeclContext(), DC, getASTContext()); 346 } else { 347 getMultipleDC()->LexicalDC = DC; 348 } 349 350 // FIXME: We shouldn't be changing the lexical context of declarations 351 // imported from AST files. 352 if (!isFromASTFile()) { 353 setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC)); 354 if (hasOwningModule()) 355 setLocalOwningModule(cast<Decl>(DC)->getOwningModule()); 356 } 357 358 assert( 359 (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported || 360 getOwningModule()) && 361 "hidden declaration has no owning module"); 362 } 363 364 void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC, 365 ASTContext &Ctx) { 366 if (SemaDC == LexicalDC) { 367 DeclCtx = SemaDC; 368 } else { 369 auto *MDC = new (Ctx) Decl::MultipleDC(); 370 MDC->SemanticDC = SemaDC; 371 MDC->LexicalDC = LexicalDC; 372 DeclCtx = MDC; 373 } 374 } 375 376 bool Decl::isInLocalScopeForInstantiation() const { 377 const DeclContext *LDC = getLexicalDeclContext(); 378 if (!LDC->isDependentContext()) 379 return false; 380 while (true) { 381 if (LDC->isFunctionOrMethod()) 382 return true; 383 if (!isa<TagDecl>(LDC)) 384 return false; 385 if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC)) 386 if (CRD->isLambda()) 387 return true; 388 LDC = LDC->getLexicalParent(); 389 } 390 return false; 391 } 392 393 bool Decl::isInAnonymousNamespace() const { 394 for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) { 395 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) 396 if (ND->isAnonymousNamespace()) 397 return true; 398 } 399 400 return false; 401 } 402 403 bool Decl::isInStdNamespace() const { 404 const DeclContext *DC = getDeclContext(); 405 return DC && DC->isStdNamespace(); 406 } 407 408 bool Decl::isFileContextDecl() const { 409 const auto *DC = dyn_cast<DeclContext>(this); 410 return DC && DC->isFileContext(); 411 } 412 413 TranslationUnitDecl *Decl::getTranslationUnitDecl() { 414 if (auto *TUD = dyn_cast<TranslationUnitDecl>(this)) 415 return TUD; 416 417 DeclContext *DC = getDeclContext(); 418 assert(DC && "This decl is not contained in a translation unit!"); 419 420 while (!DC->isTranslationUnit()) { 421 DC = DC->getParent(); 422 assert(DC && "This decl is not contained in a translation unit!"); 423 } 424 425 return cast<TranslationUnitDecl>(DC); 426 } 427 428 ASTContext &Decl::getASTContext() const { 429 return getTranslationUnitDecl()->getASTContext(); 430 } 431 432 /// Helper to get the language options from the ASTContext. 433 /// Defined out of line to avoid depending on ASTContext.h. 434 const LangOptions &Decl::getLangOpts() const { 435 return getASTContext().getLangOpts(); 436 } 437 438 ASTMutationListener *Decl::getASTMutationListener() const { 439 return getASTContext().getASTMutationListener(); 440 } 441 442 unsigned Decl::getMaxAlignment() const { 443 if (!hasAttrs()) 444 return 0; 445 446 unsigned Align = 0; 447 const AttrVec &V = getAttrs(); 448 ASTContext &Ctx = getASTContext(); 449 specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end()); 450 for (; I != E; ++I) { 451 if (!I->isAlignmentErrorDependent()) 452 Align = std::max(Align, I->getAlignment(Ctx)); 453 } 454 return Align; 455 } 456 457 bool Decl::isUsed(bool CheckUsedAttr) const { 458 const Decl *CanonD = getCanonicalDecl(); 459 if (CanonD->Used) 460 return true; 461 462 // Check for used attribute. 463 // Ask the most recent decl, since attributes accumulate in the redecl chain. 464 if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>()) 465 return true; 466 467 // The information may have not been deserialized yet. Force deserialization 468 // to complete the needed information. 469 return getMostRecentDecl()->getCanonicalDecl()->Used; 470 } 471 472 void Decl::markUsed(ASTContext &C) { 473 if (isUsed(false)) 474 return; 475 476 if (C.getASTMutationListener()) 477 C.getASTMutationListener()->DeclarationMarkedUsed(this); 478 479 setIsUsed(); 480 } 481 482 bool Decl::isReferenced() const { 483 if (Referenced) 484 return true; 485 486 // Check redeclarations. 487 for (const auto *I : redecls()) 488 if (I->Referenced) 489 return true; 490 491 return false; 492 } 493 494 ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const { 495 const Decl *Definition = nullptr; 496 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) { 497 Definition = ID->getDefinition(); 498 } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) { 499 Definition = PD->getDefinition(); 500 } else if (auto *TD = dyn_cast<TagDecl>(this)) { 501 Definition = TD->getDefinition(); 502 } 503 if (!Definition) 504 Definition = this; 505 506 if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>()) 507 return attr; 508 if (auto *dcd = dyn_cast<Decl>(getDeclContext())) { 509 return dcd->getAttr<ExternalSourceSymbolAttr>(); 510 } 511 512 return nullptr; 513 } 514 515 bool Decl::hasDefiningAttr() const { 516 return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>() || 517 hasAttr<LoaderUninitializedAttr>(); 518 } 519 520 const Attr *Decl::getDefiningAttr() const { 521 if (auto *AA = getAttr<AliasAttr>()) 522 return AA; 523 if (auto *IFA = getAttr<IFuncAttr>()) 524 return IFA; 525 if (auto *NZA = getAttr<LoaderUninitializedAttr>()) 526 return NZA; 527 return nullptr; 528 } 529 530 static StringRef getRealizedPlatform(const AvailabilityAttr *A, 531 const ASTContext &Context) { 532 // Check if this is an App Extension "platform", and if so chop off 533 // the suffix for matching with the actual platform. 534 StringRef RealizedPlatform = A->getPlatform()->getName(); 535 if (!Context.getLangOpts().AppExt) 536 return RealizedPlatform; 537 size_t suffix = RealizedPlatform.rfind("_app_extension"); 538 if (suffix != StringRef::npos) 539 return RealizedPlatform.slice(0, suffix); 540 return RealizedPlatform; 541 } 542 543 /// Determine the availability of the given declaration based on 544 /// the target platform. 545 /// 546 /// When it returns an availability result other than \c AR_Available, 547 /// if the \p Message parameter is non-NULL, it will be set to a 548 /// string describing why the entity is unavailable. 549 /// 550 /// FIXME: Make these strings localizable, since they end up in 551 /// diagnostics. 552 static AvailabilityResult CheckAvailability(ASTContext &Context, 553 const AvailabilityAttr *A, 554 std::string *Message, 555 VersionTuple EnclosingVersion) { 556 if (EnclosingVersion.empty()) 557 EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion(); 558 559 if (EnclosingVersion.empty()) 560 return AR_Available; 561 562 StringRef ActualPlatform = A->getPlatform()->getName(); 563 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 564 565 // Match the platform name. 566 if (getRealizedPlatform(A, Context) != TargetPlatform) 567 return AR_Available; 568 569 StringRef PrettyPlatformName 570 = AvailabilityAttr::getPrettyPlatformName(ActualPlatform); 571 572 if (PrettyPlatformName.empty()) 573 PrettyPlatformName = ActualPlatform; 574 575 std::string HintMessage; 576 if (!A->getMessage().empty()) { 577 HintMessage = " - "; 578 HintMessage += A->getMessage(); 579 } 580 581 // Make sure that this declaration has not been marked 'unavailable'. 582 if (A->getUnavailable()) { 583 if (Message) { 584 Message->clear(); 585 llvm::raw_string_ostream Out(*Message); 586 Out << "not available on " << PrettyPlatformName 587 << HintMessage; 588 } 589 590 return AR_Unavailable; 591 } 592 593 // Make sure that this declaration has already been introduced. 594 if (!A->getIntroduced().empty() && 595 EnclosingVersion < A->getIntroduced()) { 596 if (Message) { 597 Message->clear(); 598 llvm::raw_string_ostream Out(*Message); 599 VersionTuple VTI(A->getIntroduced()); 600 Out << "introduced in " << PrettyPlatformName << ' ' 601 << VTI << HintMessage; 602 } 603 604 return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced; 605 } 606 607 // Make sure that this declaration hasn't been obsoleted. 608 if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) { 609 if (Message) { 610 Message->clear(); 611 llvm::raw_string_ostream Out(*Message); 612 VersionTuple VTO(A->getObsoleted()); 613 Out << "obsoleted in " << PrettyPlatformName << ' ' 614 << VTO << HintMessage; 615 } 616 617 return AR_Unavailable; 618 } 619 620 // Make sure that this declaration hasn't been deprecated. 621 if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) { 622 if (Message) { 623 Message->clear(); 624 llvm::raw_string_ostream Out(*Message); 625 VersionTuple VTD(A->getDeprecated()); 626 Out << "first deprecated in " << PrettyPlatformName << ' ' 627 << VTD << HintMessage; 628 } 629 630 return AR_Deprecated; 631 } 632 633 return AR_Available; 634 } 635 636 AvailabilityResult Decl::getAvailability(std::string *Message, 637 VersionTuple EnclosingVersion, 638 StringRef *RealizedPlatform) const { 639 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this)) 640 return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion, 641 RealizedPlatform); 642 643 AvailabilityResult Result = AR_Available; 644 std::string ResultMessage; 645 646 for (const auto *A : attrs()) { 647 if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) { 648 if (Result >= AR_Deprecated) 649 continue; 650 651 if (Message) 652 ResultMessage = std::string(Deprecated->getMessage()); 653 654 Result = AR_Deprecated; 655 continue; 656 } 657 658 if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) { 659 if (Message) 660 *Message = std::string(Unavailable->getMessage()); 661 return AR_Unavailable; 662 } 663 664 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 665 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability, 666 Message, EnclosingVersion); 667 668 if (AR == AR_Unavailable) { 669 if (RealizedPlatform) 670 *RealizedPlatform = Availability->getPlatform()->getName(); 671 return AR_Unavailable; 672 } 673 674 if (AR > Result) { 675 Result = AR; 676 if (Message) 677 ResultMessage.swap(*Message); 678 } 679 continue; 680 } 681 } 682 683 if (Message) 684 Message->swap(ResultMessage); 685 return Result; 686 } 687 688 VersionTuple Decl::getVersionIntroduced() const { 689 const ASTContext &Context = getASTContext(); 690 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 691 for (const auto *A : attrs()) { 692 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 693 if (getRealizedPlatform(Availability, Context) != TargetPlatform) 694 continue; 695 if (!Availability->getIntroduced().empty()) 696 return Availability->getIntroduced(); 697 } 698 } 699 return {}; 700 } 701 702 bool Decl::canBeWeakImported(bool &IsDefinition) const { 703 IsDefinition = false; 704 705 // Variables, if they aren't definitions. 706 if (const auto *Var = dyn_cast<VarDecl>(this)) { 707 if (Var->isThisDeclarationADefinition()) { 708 IsDefinition = true; 709 return false; 710 } 711 return true; 712 } 713 // Functions, if they aren't definitions. 714 if (const auto *FD = dyn_cast<FunctionDecl>(this)) { 715 if (FD->hasBody()) { 716 IsDefinition = true; 717 return false; 718 } 719 return true; 720 721 } 722 // Objective-C classes, if this is the non-fragile runtime. 723 if (isa<ObjCInterfaceDecl>(this) && 724 getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) { 725 return true; 726 } 727 // Nothing else. 728 return false; 729 } 730 731 bool Decl::isWeakImported() const { 732 bool IsDefinition; 733 if (!canBeWeakImported(IsDefinition)) 734 return false; 735 736 for (const auto *A : getMostRecentDecl()->attrs()) { 737 if (isa<WeakImportAttr>(A)) 738 return true; 739 740 if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) { 741 if (CheckAvailability(getASTContext(), Availability, nullptr, 742 VersionTuple()) == AR_NotYetIntroduced) 743 return true; 744 } 745 } 746 747 return false; 748 } 749 750 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { 751 switch (DeclKind) { 752 case Function: 753 case CXXDeductionGuide: 754 case CXXMethod: 755 case CXXConstructor: 756 case ConstructorUsingShadow: 757 case CXXDestructor: 758 case CXXConversion: 759 case EnumConstant: 760 case Var: 761 case ImplicitParam: 762 case ParmVar: 763 case ObjCMethod: 764 case ObjCProperty: 765 case MSProperty: 766 case HLSLBuffer: 767 return IDNS_Ordinary; 768 case Label: 769 return IDNS_Label; 770 case IndirectField: 771 return IDNS_Ordinary | IDNS_Member; 772 773 case Binding: 774 case NonTypeTemplateParm: 775 case VarTemplate: 776 case Concept: 777 // These (C++-only) declarations are found by redeclaration lookup for 778 // tag types, so we include them in the tag namespace. 779 return IDNS_Ordinary | IDNS_Tag; 780 781 case ObjCCompatibleAlias: 782 case ObjCInterface: 783 return IDNS_Ordinary | IDNS_Type; 784 785 case Typedef: 786 case TypeAlias: 787 case TemplateTypeParm: 788 case ObjCTypeParam: 789 return IDNS_Ordinary | IDNS_Type; 790 791 case UnresolvedUsingTypename: 792 return IDNS_Ordinary | IDNS_Type | IDNS_Using; 793 794 case UsingShadow: 795 return 0; // we'll actually overwrite this later 796 797 case UnresolvedUsingValue: 798 return IDNS_Ordinary | IDNS_Using; 799 800 case Using: 801 case UsingPack: 802 case UsingEnum: 803 return IDNS_Using; 804 805 case ObjCProtocol: 806 return IDNS_ObjCProtocol; 807 808 case Field: 809 case ObjCAtDefsField: 810 case ObjCIvar: 811 return IDNS_Member; 812 813 case Record: 814 case CXXRecord: 815 case Enum: 816 return IDNS_Tag | IDNS_Type; 817 818 case Namespace: 819 case NamespaceAlias: 820 return IDNS_Namespace; 821 822 case FunctionTemplate: 823 return IDNS_Ordinary; 824 825 case ClassTemplate: 826 case TemplateTemplateParm: 827 case TypeAliasTemplate: 828 return IDNS_Ordinary | IDNS_Tag | IDNS_Type; 829 830 case UnresolvedUsingIfExists: 831 return IDNS_Type | IDNS_Ordinary; 832 833 case OMPDeclareReduction: 834 return IDNS_OMPReduction; 835 836 case OMPDeclareMapper: 837 return IDNS_OMPMapper; 838 839 // Never have names. 840 case Friend: 841 case FriendTemplate: 842 case AccessSpec: 843 case LinkageSpec: 844 case Export: 845 case FileScopeAsm: 846 case TopLevelStmt: 847 case StaticAssert: 848 case ObjCPropertyImpl: 849 case PragmaComment: 850 case PragmaDetectMismatch: 851 case Block: 852 case Captured: 853 case TranslationUnit: 854 case ExternCContext: 855 case Decomposition: 856 case MSGuid: 857 case UnnamedGlobalConstant: 858 case TemplateParamObject: 859 860 case UsingDirective: 861 case BuiltinTemplate: 862 case ClassTemplateSpecialization: 863 case ClassTemplatePartialSpecialization: 864 case ClassScopeFunctionSpecialization: 865 case VarTemplateSpecialization: 866 case VarTemplatePartialSpecialization: 867 case ObjCImplementation: 868 case ObjCCategory: 869 case ObjCCategoryImpl: 870 case Import: 871 case OMPThreadPrivate: 872 case OMPAllocate: 873 case OMPRequires: 874 case OMPCapturedExpr: 875 case Empty: 876 case LifetimeExtendedTemporary: 877 case RequiresExprBody: 878 case ImplicitConceptSpecialization: 879 // Never looked up by name. 880 return 0; 881 } 882 883 llvm_unreachable("Invalid DeclKind!"); 884 } 885 886 void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) { 887 assert(!HasAttrs && "Decl already contains attrs."); 888 889 AttrVec &AttrBlank = Ctx.getDeclAttrs(this); 890 assert(AttrBlank.empty() && "HasAttrs was wrong?"); 891 892 AttrBlank = attrs; 893 HasAttrs = true; 894 } 895 896 void Decl::dropAttrs() { 897 if (!HasAttrs) return; 898 899 HasAttrs = false; 900 getASTContext().eraseDeclAttrs(this); 901 } 902 903 void Decl::addAttr(Attr *A) { 904 if (!hasAttrs()) { 905 setAttrs(AttrVec(1, A)); 906 return; 907 } 908 909 AttrVec &Attrs = getAttrs(); 910 if (!A->isInherited()) { 911 Attrs.push_back(A); 912 return; 913 } 914 915 // Attribute inheritance is processed after attribute parsing. To keep the 916 // order as in the source code, add inherited attributes before non-inherited 917 // ones. 918 auto I = Attrs.begin(), E = Attrs.end(); 919 for (; I != E; ++I) { 920 if (!(*I)->isInherited()) 921 break; 922 } 923 Attrs.insert(I, A); 924 } 925 926 const AttrVec &Decl::getAttrs() const { 927 assert(HasAttrs && "No attrs to get!"); 928 return getASTContext().getDeclAttrs(this); 929 } 930 931 Decl *Decl::castFromDeclContext (const DeclContext *D) { 932 Decl::Kind DK = D->getDeclKind(); 933 switch(DK) { 934 #define DECL(NAME, BASE) 935 #define DECL_CONTEXT(NAME) \ 936 case Decl::NAME: \ 937 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D)); 938 #define DECL_CONTEXT_BASE(NAME) 939 #include "clang/AST/DeclNodes.inc" 940 default: 941 #define DECL(NAME, BASE) 942 #define DECL_CONTEXT_BASE(NAME) \ 943 if (DK >= first##NAME && DK <= last##NAME) \ 944 return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D)); 945 #include "clang/AST/DeclNodes.inc" 946 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 947 } 948 } 949 950 DeclContext *Decl::castToDeclContext(const Decl *D) { 951 Decl::Kind DK = D->getKind(); 952 switch(DK) { 953 #define DECL(NAME, BASE) 954 #define DECL_CONTEXT(NAME) \ 955 case Decl::NAME: \ 956 return static_cast<NAME##Decl *>(const_cast<Decl *>(D)); 957 #define DECL_CONTEXT_BASE(NAME) 958 #include "clang/AST/DeclNodes.inc" 959 default: 960 #define DECL(NAME, BASE) 961 #define DECL_CONTEXT_BASE(NAME) \ 962 if (DK >= first##NAME && DK <= last##NAME) \ 963 return static_cast<NAME##Decl *>(const_cast<Decl *>(D)); 964 #include "clang/AST/DeclNodes.inc" 965 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 966 } 967 } 968 969 SourceLocation Decl::getBodyRBrace() const { 970 // Special handling of FunctionDecl to avoid de-serializing the body from PCH. 971 // FunctionDecl stores EndRangeLoc for this purpose. 972 if (const auto *FD = dyn_cast<FunctionDecl>(this)) { 973 const FunctionDecl *Definition; 974 if (FD->hasBody(Definition)) 975 return Definition->getSourceRange().getEnd(); 976 return {}; 977 } 978 979 if (Stmt *Body = getBody()) 980 return Body->getSourceRange().getEnd(); 981 982 return {}; 983 } 984 985 bool Decl::AccessDeclContextCheck() const { 986 #ifndef NDEBUG 987 // Suppress this check if any of the following hold: 988 // 1. this is the translation unit (and thus has no parent) 989 // 2. this is a template parameter (and thus doesn't belong to its context) 990 // 3. this is a non-type template parameter 991 // 4. the context is not a record 992 // 5. it's invalid 993 // 6. it's a C++0x static_assert. 994 // 7. it's a block literal declaration 995 // 8. it's a temporary with lifetime extended due to being default value. 996 if (isa<TranslationUnitDecl>(this) || isa<TemplateTypeParmDecl>(this) || 997 isa<NonTypeTemplateParmDecl>(this) || !getDeclContext() || 998 !isa<CXXRecordDecl>(getDeclContext()) || isInvalidDecl() || 999 isa<StaticAssertDecl>(this) || isa<BlockDecl>(this) || 1000 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 1001 // as DeclContext (?). 1002 isa<ParmVarDecl>(this) || 1003 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 1004 // AS_none as access specifier. 1005 isa<CXXRecordDecl>(this) || 1006 isa<ClassScopeFunctionSpecializationDecl>(this) || 1007 isa<LifetimeExtendedTemporaryDecl>(this)) 1008 return true; 1009 1010 assert(Access != AS_none && 1011 "Access specifier is AS_none inside a record decl"); 1012 #endif 1013 return true; 1014 } 1015 1016 bool Decl::isInExportDeclContext() const { 1017 const DeclContext *DC = getLexicalDeclContext(); 1018 1019 while (DC && !isa<ExportDecl>(DC)) 1020 DC = DC->getLexicalParent(); 1021 1022 return DC && isa<ExportDecl>(DC); 1023 } 1024 1025 static Decl::Kind getKind(const Decl *D) { return D->getKind(); } 1026 static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); } 1027 1028 int64_t Decl::getID() const { 1029 return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this); 1030 } 1031 1032 const FunctionType *Decl::getFunctionType(bool BlocksToo) const { 1033 QualType Ty; 1034 if (const auto *D = dyn_cast<ValueDecl>(this)) 1035 Ty = D->getType(); 1036 else if (const auto *D = dyn_cast<TypedefNameDecl>(this)) 1037 Ty = D->getUnderlyingType(); 1038 else 1039 return nullptr; 1040 1041 if (Ty->isFunctionPointerType()) 1042 Ty = Ty->castAs<PointerType>()->getPointeeType(); 1043 else if (Ty->isFunctionReferenceType()) 1044 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1045 else if (BlocksToo && Ty->isBlockPointerType()) 1046 Ty = Ty->castAs<BlockPointerType>()->getPointeeType(); 1047 1048 return Ty->getAs<FunctionType>(); 1049 } 1050 1051 DeclContext *Decl::getNonTransparentDeclContext() { 1052 assert(getDeclContext()); 1053 return getDeclContext()->getNonTransparentContext(); 1054 } 1055 1056 /// Starting at a given context (a Decl or DeclContext), look for a 1057 /// code context that is not a closure (a lambda, block, etc.). 1058 template <class T> static Decl *getNonClosureContext(T *D) { 1059 if (getKind(D) == Decl::CXXMethod) { 1060 auto *MD = cast<CXXMethodDecl>(D); 1061 if (MD->getOverloadedOperator() == OO_Call && 1062 MD->getParent()->isLambda()) 1063 return getNonClosureContext(MD->getParent()->getParent()); 1064 return MD; 1065 } 1066 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1067 return FD; 1068 if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) 1069 return MD; 1070 if (auto *BD = dyn_cast<BlockDecl>(D)) 1071 return getNonClosureContext(BD->getParent()); 1072 if (auto *CD = dyn_cast<CapturedDecl>(D)) 1073 return getNonClosureContext(CD->getParent()); 1074 return nullptr; 1075 } 1076 1077 Decl *Decl::getNonClosureContext() { 1078 return ::getNonClosureContext(this); 1079 } 1080 1081 Decl *DeclContext::getNonClosureAncestor() { 1082 return ::getNonClosureContext(this); 1083 } 1084 1085 //===----------------------------------------------------------------------===// 1086 // DeclContext Implementation 1087 //===----------------------------------------------------------------------===// 1088 1089 DeclContext::DeclContext(Decl::Kind K) { 1090 DeclContextBits.DeclKind = K; 1091 setHasExternalLexicalStorage(false); 1092 setHasExternalVisibleStorage(false); 1093 setNeedToReconcileExternalVisibleStorage(false); 1094 setHasLazyLocalLexicalLookups(false); 1095 setHasLazyExternalLexicalLookups(false); 1096 setUseQualifiedLookup(false); 1097 } 1098 1099 bool DeclContext::classof(const Decl *D) { 1100 switch (D->getKind()) { 1101 #define DECL(NAME, BASE) 1102 #define DECL_CONTEXT(NAME) case Decl::NAME: 1103 #define DECL_CONTEXT_BASE(NAME) 1104 #include "clang/AST/DeclNodes.inc" 1105 return true; 1106 default: 1107 #define DECL(NAME, BASE) 1108 #define DECL_CONTEXT_BASE(NAME) \ 1109 if (D->getKind() >= Decl::first##NAME && \ 1110 D->getKind() <= Decl::last##NAME) \ 1111 return true; 1112 #include "clang/AST/DeclNodes.inc" 1113 return false; 1114 } 1115 } 1116 1117 DeclContext::~DeclContext() = default; 1118 1119 /// Find the parent context of this context that will be 1120 /// used for unqualified name lookup. 1121 /// 1122 /// Generally, the parent lookup context is the semantic context. However, for 1123 /// a friend function the parent lookup context is the lexical context, which 1124 /// is the class in which the friend is declared. 1125 DeclContext *DeclContext::getLookupParent() { 1126 // FIXME: Find a better way to identify friends. 1127 if (isa<FunctionDecl>(this)) 1128 if (getParent()->getRedeclContext()->isFileContext() && 1129 getLexicalParent()->getRedeclContext()->isRecord()) 1130 return getLexicalParent(); 1131 1132 // A lookup within the call operator of a lambda never looks in the lambda 1133 // class; instead, skip to the context in which that closure type is 1134 // declared. 1135 if (isLambdaCallOperator(this)) 1136 return getParent()->getParent(); 1137 1138 return getParent(); 1139 } 1140 1141 const BlockDecl *DeclContext::getInnermostBlockDecl() const { 1142 const DeclContext *Ctx = this; 1143 1144 do { 1145 if (Ctx->isClosure()) 1146 return cast<BlockDecl>(Ctx); 1147 Ctx = Ctx->getParent(); 1148 } while (Ctx); 1149 1150 return nullptr; 1151 } 1152 1153 bool DeclContext::isInlineNamespace() const { 1154 return isNamespace() && 1155 cast<NamespaceDecl>(this)->isInline(); 1156 } 1157 1158 bool DeclContext::isStdNamespace() const { 1159 if (!isNamespace()) 1160 return false; 1161 1162 const auto *ND = cast<NamespaceDecl>(this); 1163 if (ND->isInline()) { 1164 return ND->getParent()->isStdNamespace(); 1165 } 1166 1167 if (!getParent()->getRedeclContext()->isTranslationUnit()) 1168 return false; 1169 1170 const IdentifierInfo *II = ND->getIdentifier(); 1171 return II && II->isStr("std"); 1172 } 1173 1174 bool DeclContext::isDependentContext() const { 1175 if (isFileContext()) 1176 return false; 1177 1178 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 1179 return true; 1180 1181 if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) { 1182 if (Record->getDescribedClassTemplate()) 1183 return true; 1184 1185 if (Record->isDependentLambda()) 1186 return true; 1187 if (Record->isNeverDependentLambda()) 1188 return false; 1189 } 1190 1191 if (const auto *Function = dyn_cast<FunctionDecl>(this)) { 1192 if (Function->getDescribedFunctionTemplate()) 1193 return true; 1194 1195 // Friend function declarations are dependent if their *lexical* 1196 // context is dependent. 1197 if (cast<Decl>(this)->getFriendObjectKind()) 1198 return getLexicalParent()->isDependentContext(); 1199 } 1200 1201 // FIXME: A variable template is a dependent context, but is not a 1202 // DeclContext. A context within it (such as a lambda-expression) 1203 // should be considered dependent. 1204 1205 return getParent() && getParent()->isDependentContext(); 1206 } 1207 1208 bool DeclContext::isTransparentContext() const { 1209 if (getDeclKind() == Decl::Enum) 1210 return !cast<EnumDecl>(this)->isScoped(); 1211 1212 return isa<LinkageSpecDecl, ExportDecl, HLSLBufferDecl>(this); 1213 } 1214 1215 static bool isLinkageSpecContext(const DeclContext *DC, 1216 LinkageSpecDecl::LanguageIDs ID) { 1217 while (DC->getDeclKind() != Decl::TranslationUnit) { 1218 if (DC->getDeclKind() == Decl::LinkageSpec) 1219 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID; 1220 DC = DC->getLexicalParent(); 1221 } 1222 return false; 1223 } 1224 1225 bool DeclContext::isExternCContext() const { 1226 return isLinkageSpecContext(this, LinkageSpecDecl::lang_c); 1227 } 1228 1229 const LinkageSpecDecl *DeclContext::getExternCContext() const { 1230 const DeclContext *DC = this; 1231 while (DC->getDeclKind() != Decl::TranslationUnit) { 1232 if (DC->getDeclKind() == Decl::LinkageSpec && 1233 cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c) 1234 return cast<LinkageSpecDecl>(DC); 1235 DC = DC->getLexicalParent(); 1236 } 1237 return nullptr; 1238 } 1239 1240 bool DeclContext::isExternCXXContext() const { 1241 return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx); 1242 } 1243 1244 bool DeclContext::Encloses(const DeclContext *DC) const { 1245 if (getPrimaryContext() != this) 1246 return getPrimaryContext()->Encloses(DC); 1247 1248 for (; DC; DC = DC->getParent()) 1249 if (!isa<LinkageSpecDecl>(DC) && !isa<ExportDecl>(DC) && 1250 DC->getPrimaryContext() == this) 1251 return true; 1252 return false; 1253 } 1254 1255 DeclContext *DeclContext::getNonTransparentContext() { 1256 DeclContext *DC = this; 1257 while (DC->isTransparentContext()) { 1258 DC = DC->getParent(); 1259 assert(DC && "All transparent contexts should have a parent!"); 1260 } 1261 return DC; 1262 } 1263 1264 DeclContext *DeclContext::getPrimaryContext() { 1265 switch (getDeclKind()) { 1266 case Decl::ExternCContext: 1267 case Decl::LinkageSpec: 1268 case Decl::Export: 1269 case Decl::Block: 1270 case Decl::Captured: 1271 case Decl::OMPDeclareReduction: 1272 case Decl::OMPDeclareMapper: 1273 case Decl::RequiresExprBody: 1274 // There is only one DeclContext for these entities. 1275 return this; 1276 1277 case Decl::HLSLBuffer: 1278 // Each buffer, even with the same name, is a distinct construct. 1279 // Multiple buffers with the same name are allowed for backward 1280 // compatibility. 1281 // As long as buffers have unique resource bindings the names don't matter. 1282 // The names get exposed via the CPU-side reflection API which 1283 // supports querying bindings, so we cannot remove them. 1284 return this; 1285 1286 case Decl::TranslationUnit: 1287 return static_cast<TranslationUnitDecl *>(this)->getFirstDecl(); 1288 case Decl::Namespace: 1289 // The original namespace is our primary context. 1290 return static_cast<NamespaceDecl *>(this)->getOriginalNamespace(); 1291 1292 case Decl::ObjCMethod: 1293 return this; 1294 1295 case Decl::ObjCInterface: 1296 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this)) 1297 if (auto *Def = OID->getDefinition()) 1298 return Def; 1299 return this; 1300 1301 case Decl::ObjCProtocol: 1302 if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this)) 1303 if (auto *Def = OPD->getDefinition()) 1304 return Def; 1305 return this; 1306 1307 case Decl::ObjCCategory: 1308 return this; 1309 1310 case Decl::ObjCImplementation: 1311 case Decl::ObjCCategoryImpl: 1312 return this; 1313 1314 default: 1315 if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) { 1316 // If this is a tag type that has a definition or is currently 1317 // being defined, that definition is our primary context. 1318 auto *Tag = cast<TagDecl>(this); 1319 1320 if (TagDecl *Def = Tag->getDefinition()) 1321 return Def; 1322 1323 if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) { 1324 // Note, TagType::getDecl returns the (partial) definition one exists. 1325 TagDecl *PossiblePartialDef = TagTy->getDecl(); 1326 if (PossiblePartialDef->isBeingDefined()) 1327 return PossiblePartialDef; 1328 } else { 1329 assert(isa<InjectedClassNameType>(Tag->getTypeForDecl())); 1330 } 1331 1332 return Tag; 1333 } 1334 1335 assert(getDeclKind() >= Decl::firstFunction && 1336 getDeclKind() <= Decl::lastFunction && 1337 "Unknown DeclContext kind"); 1338 return this; 1339 } 1340 } 1341 1342 template <typename T> 1343 void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) { 1344 for (T *D = Self->getMostRecentDecl(); D; D = D->getPreviousDecl()) 1345 Contexts.push_back(D); 1346 1347 std::reverse(Contexts.begin(), Contexts.end()); 1348 } 1349 1350 void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts) { 1351 Contexts.clear(); 1352 1353 Decl::Kind Kind = getDeclKind(); 1354 1355 if (Kind == Decl::TranslationUnit) 1356 collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts); 1357 else if (Kind == Decl::Namespace) 1358 collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts); 1359 else 1360 Contexts.push_back(this); 1361 } 1362 1363 std::pair<Decl *, Decl *> 1364 DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls, 1365 bool FieldsAlreadyLoaded) { 1366 // Build up a chain of declarations via the Decl::NextInContextAndBits field. 1367 Decl *FirstNewDecl = nullptr; 1368 Decl *PrevDecl = nullptr; 1369 for (auto *D : Decls) { 1370 if (FieldsAlreadyLoaded && isa<FieldDecl>(D)) 1371 continue; 1372 1373 if (PrevDecl) 1374 PrevDecl->NextInContextAndBits.setPointer(D); 1375 else 1376 FirstNewDecl = D; 1377 1378 PrevDecl = D; 1379 } 1380 1381 return std::make_pair(FirstNewDecl, PrevDecl); 1382 } 1383 1384 /// We have just acquired external visible storage, and we already have 1385 /// built a lookup map. For every name in the map, pull in the new names from 1386 /// the external storage. 1387 void DeclContext::reconcileExternalVisibleStorage() const { 1388 assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr); 1389 setNeedToReconcileExternalVisibleStorage(false); 1390 1391 for (auto &Lookup : *LookupPtr) 1392 Lookup.second.setHasExternalDecls(); 1393 } 1394 1395 /// Load the declarations within this lexical storage from an 1396 /// external source. 1397 /// \return \c true if any declarations were added. 1398 bool 1399 DeclContext::LoadLexicalDeclsFromExternalStorage() const { 1400 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1401 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 1402 1403 // Notify that we have a DeclContext that is initializing. 1404 ExternalASTSource::Deserializing ADeclContext(Source); 1405 1406 // Load the external declarations, if any. 1407 SmallVector<Decl*, 64> Decls; 1408 setHasExternalLexicalStorage(false); 1409 Source->FindExternalLexicalDecls(this, Decls); 1410 1411 if (Decls.empty()) 1412 return false; 1413 1414 // We may have already loaded just the fields of this record, in which case 1415 // we need to ignore them. 1416 bool FieldsAlreadyLoaded = false; 1417 if (const auto *RD = dyn_cast<RecordDecl>(this)) 1418 FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage(); 1419 1420 // Splice the newly-read declarations into the beginning of the list 1421 // of declarations. 1422 Decl *ExternalFirst, *ExternalLast; 1423 std::tie(ExternalFirst, ExternalLast) = 1424 BuildDeclChain(Decls, FieldsAlreadyLoaded); 1425 ExternalLast->NextInContextAndBits.setPointer(FirstDecl); 1426 FirstDecl = ExternalFirst; 1427 if (!LastDecl) 1428 LastDecl = ExternalLast; 1429 return true; 1430 } 1431 1432 DeclContext::lookup_result 1433 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 1434 DeclarationName Name) { 1435 ASTContext &Context = DC->getParentASTContext(); 1436 StoredDeclsMap *Map; 1437 if (!(Map = DC->LookupPtr)) 1438 Map = DC->CreateStoredDeclsMap(Context); 1439 if (DC->hasNeedToReconcileExternalVisibleStorage()) 1440 DC->reconcileExternalVisibleStorage(); 1441 1442 (*Map)[Name].removeExternalDecls(); 1443 1444 return DeclContext::lookup_result(); 1445 } 1446 1447 DeclContext::lookup_result 1448 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 1449 DeclarationName Name, 1450 ArrayRef<NamedDecl*> Decls) { 1451 ASTContext &Context = DC->getParentASTContext(); 1452 StoredDeclsMap *Map; 1453 if (!(Map = DC->LookupPtr)) 1454 Map = DC->CreateStoredDeclsMap(Context); 1455 if (DC->hasNeedToReconcileExternalVisibleStorage()) 1456 DC->reconcileExternalVisibleStorage(); 1457 1458 StoredDeclsList &List = (*Map)[Name]; 1459 List.replaceExternalDecls(Decls); 1460 return List.getLookupResult(); 1461 } 1462 1463 DeclContext::decl_iterator DeclContext::decls_begin() const { 1464 if (hasExternalLexicalStorage()) 1465 LoadLexicalDeclsFromExternalStorage(); 1466 return decl_iterator(FirstDecl); 1467 } 1468 1469 bool DeclContext::decls_empty() const { 1470 if (hasExternalLexicalStorage()) 1471 LoadLexicalDeclsFromExternalStorage(); 1472 1473 return !FirstDecl; 1474 } 1475 1476 bool DeclContext::containsDecl(Decl *D) const { 1477 return (D->getLexicalDeclContext() == this && 1478 (D->NextInContextAndBits.getPointer() || D == LastDecl)); 1479 } 1480 1481 bool DeclContext::containsDeclAndLoad(Decl *D) const { 1482 if (hasExternalLexicalStorage()) 1483 LoadLexicalDeclsFromExternalStorage(); 1484 return containsDecl(D); 1485 } 1486 1487 /// shouldBeHidden - Determine whether a declaration which was declared 1488 /// within its semantic context should be invisible to qualified name lookup. 1489 static bool shouldBeHidden(NamedDecl *D) { 1490 // Skip unnamed declarations. 1491 if (!D->getDeclName()) 1492 return true; 1493 1494 // Skip entities that can't be found by name lookup into a particular 1495 // context. 1496 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1497 D->isTemplateParameter()) 1498 return true; 1499 1500 // Skip friends and local extern declarations unless they're the first 1501 // declaration of the entity. 1502 if ((D->isLocalExternDecl() || D->getFriendObjectKind()) && 1503 D != D->getCanonicalDecl()) 1504 return true; 1505 1506 // Skip template specializations. 1507 // FIXME: This feels like a hack. Should DeclarationName support 1508 // template-ids, or is there a better way to keep specializations 1509 // from being visible? 1510 if (isa<ClassTemplateSpecializationDecl>(D)) 1511 return true; 1512 if (auto *FD = dyn_cast<FunctionDecl>(D)) 1513 if (FD->isFunctionTemplateSpecialization()) 1514 return true; 1515 1516 // Hide destructors that are invalid. There should always be one destructor, 1517 // but if it is an invalid decl, another one is created. We need to hide the 1518 // invalid one from places that expect exactly one destructor, like the 1519 // serialization code. 1520 if (isa<CXXDestructorDecl>(D) && D->isInvalidDecl()) 1521 return true; 1522 1523 return false; 1524 } 1525 1526 void DeclContext::removeDecl(Decl *D) { 1527 assert(D->getLexicalDeclContext() == this && 1528 "decl being removed from non-lexical context"); 1529 assert((D->NextInContextAndBits.getPointer() || D == LastDecl) && 1530 "decl is not in decls list"); 1531 1532 // Remove D from the decl chain. This is O(n) but hopefully rare. 1533 if (D == FirstDecl) { 1534 if (D == LastDecl) 1535 FirstDecl = LastDecl = nullptr; 1536 else 1537 FirstDecl = D->NextInContextAndBits.getPointer(); 1538 } else { 1539 for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) { 1540 assert(I && "decl not found in linked list"); 1541 if (I->NextInContextAndBits.getPointer() == D) { 1542 I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer()); 1543 if (D == LastDecl) LastDecl = I; 1544 break; 1545 } 1546 } 1547 } 1548 1549 // Mark that D is no longer in the decl chain. 1550 D->NextInContextAndBits.setPointer(nullptr); 1551 1552 // Remove D from the lookup table if necessary. 1553 if (isa<NamedDecl>(D)) { 1554 auto *ND = cast<NamedDecl>(D); 1555 1556 // Do not try to remove the declaration if that is invisible to qualified 1557 // lookup. E.g. template specializations are skipped. 1558 if (shouldBeHidden(ND)) 1559 return; 1560 1561 // Remove only decls that have a name 1562 if (!ND->getDeclName()) 1563 return; 1564 1565 auto *DC = D->getDeclContext(); 1566 do { 1567 StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr; 1568 if (Map) { 1569 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 1570 assert(Pos != Map->end() && "no lookup entry for decl"); 1571 StoredDeclsList &List = Pos->second; 1572 List.remove(ND); 1573 // Clean up the entry if there are no more decls. 1574 if (List.isNull()) 1575 Map->erase(Pos); 1576 } 1577 } while (DC->isTransparentContext() && (DC = DC->getParent())); 1578 } 1579 } 1580 1581 void DeclContext::addHiddenDecl(Decl *D) { 1582 assert(D->getLexicalDeclContext() == this && 1583 "Decl inserted into wrong lexical context"); 1584 assert(!D->getNextDeclInContext() && D != LastDecl && 1585 "Decl already inserted into a DeclContext"); 1586 1587 if (FirstDecl) { 1588 LastDecl->NextInContextAndBits.setPointer(D); 1589 LastDecl = D; 1590 } else { 1591 FirstDecl = LastDecl = D; 1592 } 1593 1594 // Notify a C++ record declaration that we've added a member, so it can 1595 // update its class-specific state. 1596 if (auto *Record = dyn_cast<CXXRecordDecl>(this)) 1597 Record->addedMember(D); 1598 1599 // If this is a newly-created (not de-serialized) import declaration, wire 1600 // it in to the list of local import declarations. 1601 if (!D->isFromASTFile()) { 1602 if (auto *Import = dyn_cast<ImportDecl>(D)) 1603 D->getASTContext().addedLocalImportDecl(Import); 1604 } 1605 } 1606 1607 void DeclContext::addDecl(Decl *D) { 1608 addHiddenDecl(D); 1609 1610 if (auto *ND = dyn_cast<NamedDecl>(D)) 1611 ND->getDeclContext()->getPrimaryContext()-> 1612 makeDeclVisibleInContextWithFlags(ND, false, true); 1613 } 1614 1615 void DeclContext::addDeclInternal(Decl *D) { 1616 addHiddenDecl(D); 1617 1618 if (auto *ND = dyn_cast<NamedDecl>(D)) 1619 ND->getDeclContext()->getPrimaryContext()-> 1620 makeDeclVisibleInContextWithFlags(ND, true, true); 1621 } 1622 1623 /// buildLookup - Build the lookup data structure with all of the 1624 /// declarations in this DeclContext (and any other contexts linked 1625 /// to it or transparent contexts nested within it) and return it. 1626 /// 1627 /// Note that the produced map may miss out declarations from an 1628 /// external source. If it does, those entries will be marked with 1629 /// the 'hasExternalDecls' flag. 1630 StoredDeclsMap *DeclContext::buildLookup() { 1631 assert(this == getPrimaryContext() && "buildLookup called on non-primary DC"); 1632 1633 if (!hasLazyLocalLexicalLookups() && 1634 !hasLazyExternalLexicalLookups()) 1635 return LookupPtr; 1636 1637 SmallVector<DeclContext *, 2> Contexts; 1638 collectAllContexts(Contexts); 1639 1640 if (hasLazyExternalLexicalLookups()) { 1641 setHasLazyExternalLexicalLookups(false); 1642 for (auto *DC : Contexts) { 1643 if (DC->hasExternalLexicalStorage()) { 1644 bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage(); 1645 setHasLazyLocalLexicalLookups( 1646 hasLazyLocalLexicalLookups() | LoadedDecls ); 1647 } 1648 } 1649 1650 if (!hasLazyLocalLexicalLookups()) 1651 return LookupPtr; 1652 } 1653 1654 for (auto *DC : Contexts) 1655 buildLookupImpl(DC, hasExternalVisibleStorage()); 1656 1657 // We no longer have any lazy decls. 1658 setHasLazyLocalLexicalLookups(false); 1659 return LookupPtr; 1660 } 1661 1662 /// buildLookupImpl - Build part of the lookup data structure for the 1663 /// declarations contained within DCtx, which will either be this 1664 /// DeclContext, a DeclContext linked to it, or a transparent context 1665 /// nested within it. 1666 void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) { 1667 for (auto *D : DCtx->noload_decls()) { 1668 // Insert this declaration into the lookup structure, but only if 1669 // it's semantically within its decl context. Any other decls which 1670 // should be found in this context are added eagerly. 1671 // 1672 // If it's from an AST file, don't add it now. It'll get handled by 1673 // FindExternalVisibleDeclsByName if needed. Exception: if we're not 1674 // in C++, we do not track external visible decls for the TU, so in 1675 // that case we need to collect them all here. 1676 if (auto *ND = dyn_cast<NamedDecl>(D)) 1677 if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) && 1678 (!ND->isFromASTFile() || 1679 (isTranslationUnit() && 1680 !getParentASTContext().getLangOpts().CPlusPlus))) 1681 makeDeclVisibleInContextImpl(ND, Internal); 1682 1683 // If this declaration is itself a transparent declaration context 1684 // or inline namespace, add the members of this declaration of that 1685 // context (recursively). 1686 if (auto *InnerCtx = dyn_cast<DeclContext>(D)) 1687 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1688 buildLookupImpl(InnerCtx, Internal); 1689 } 1690 } 1691 1692 DeclContext::lookup_result 1693 DeclContext::lookup(DeclarationName Name) const { 1694 // For transparent DeclContext, we should lookup in their enclosing context. 1695 if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export) 1696 return getParent()->lookup(Name); 1697 1698 const DeclContext *PrimaryContext = getPrimaryContext(); 1699 if (PrimaryContext != this) 1700 return PrimaryContext->lookup(Name); 1701 1702 // If we have an external source, ensure that any later redeclarations of this 1703 // context have been loaded, since they may add names to the result of this 1704 // lookup (or add external visible storage). 1705 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1706 if (Source) 1707 (void)cast<Decl>(this)->getMostRecentDecl(); 1708 1709 if (hasExternalVisibleStorage()) { 1710 assert(Source && "external visible storage but no external source?"); 1711 1712 if (hasNeedToReconcileExternalVisibleStorage()) 1713 reconcileExternalVisibleStorage(); 1714 1715 StoredDeclsMap *Map = LookupPtr; 1716 1717 if (hasLazyLocalLexicalLookups() || 1718 hasLazyExternalLexicalLookups()) 1719 // FIXME: Make buildLookup const? 1720 Map = const_cast<DeclContext*>(this)->buildLookup(); 1721 1722 if (!Map) 1723 Map = CreateStoredDeclsMap(getParentASTContext()); 1724 1725 // If we have a lookup result with no external decls, we are done. 1726 std::pair<StoredDeclsMap::iterator, bool> R = 1727 Map->insert(std::make_pair(Name, StoredDeclsList())); 1728 if (!R.second && !R.first->second.hasExternalDecls()) 1729 return R.first->second.getLookupResult(); 1730 1731 if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) { 1732 if (StoredDeclsMap *Map = LookupPtr) { 1733 StoredDeclsMap::iterator I = Map->find(Name); 1734 if (I != Map->end()) 1735 return I->second.getLookupResult(); 1736 } 1737 } 1738 1739 return {}; 1740 } 1741 1742 StoredDeclsMap *Map = LookupPtr; 1743 if (hasLazyLocalLexicalLookups() || 1744 hasLazyExternalLexicalLookups()) 1745 Map = const_cast<DeclContext*>(this)->buildLookup(); 1746 1747 if (!Map) 1748 return {}; 1749 1750 StoredDeclsMap::iterator I = Map->find(Name); 1751 if (I == Map->end()) 1752 return {}; 1753 1754 return I->second.getLookupResult(); 1755 } 1756 1757 DeclContext::lookup_result 1758 DeclContext::noload_lookup(DeclarationName Name) { 1759 assert(getDeclKind() != Decl::LinkageSpec && 1760 getDeclKind() != Decl::Export && 1761 "should not perform lookups into transparent contexts"); 1762 1763 DeclContext *PrimaryContext = getPrimaryContext(); 1764 if (PrimaryContext != this) 1765 return PrimaryContext->noload_lookup(Name); 1766 1767 loadLazyLocalLexicalLookups(); 1768 StoredDeclsMap *Map = LookupPtr; 1769 if (!Map) 1770 return {}; 1771 1772 StoredDeclsMap::iterator I = Map->find(Name); 1773 return I != Map->end() ? I->second.getLookupResult() 1774 : lookup_result(); 1775 } 1776 1777 // If we have any lazy lexical declarations not in our lookup map, add them 1778 // now. Don't import any external declarations, not even if we know we have 1779 // some missing from the external visible lookups. 1780 void DeclContext::loadLazyLocalLexicalLookups() { 1781 if (hasLazyLocalLexicalLookups()) { 1782 SmallVector<DeclContext *, 2> Contexts; 1783 collectAllContexts(Contexts); 1784 for (auto *Context : Contexts) 1785 buildLookupImpl(Context, hasExternalVisibleStorage()); 1786 setHasLazyLocalLexicalLookups(false); 1787 } 1788 } 1789 1790 void DeclContext::localUncachedLookup(DeclarationName Name, 1791 SmallVectorImpl<NamedDecl *> &Results) { 1792 Results.clear(); 1793 1794 // If there's no external storage, just perform a normal lookup and copy 1795 // the results. 1796 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) { 1797 lookup_result LookupResults = lookup(Name); 1798 Results.insert(Results.end(), LookupResults.begin(), LookupResults.end()); 1799 if (!Results.empty()) 1800 return; 1801 } 1802 1803 // If we have a lookup table, check there first. Maybe we'll get lucky. 1804 // FIXME: Should we be checking these flags on the primary context? 1805 if (Name && !hasLazyLocalLexicalLookups() && 1806 !hasLazyExternalLexicalLookups()) { 1807 if (StoredDeclsMap *Map = LookupPtr) { 1808 StoredDeclsMap::iterator Pos = Map->find(Name); 1809 if (Pos != Map->end()) { 1810 Results.insert(Results.end(), 1811 Pos->second.getLookupResult().begin(), 1812 Pos->second.getLookupResult().end()); 1813 return; 1814 } 1815 } 1816 } 1817 1818 // Slow case: grovel through the declarations in our chain looking for 1819 // matches. 1820 // FIXME: If we have lazy external declarations, this will not find them! 1821 // FIXME: Should we CollectAllContexts and walk them all here? 1822 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) { 1823 if (auto *ND = dyn_cast<NamedDecl>(D)) 1824 if (ND->getDeclName() == Name) 1825 Results.push_back(ND); 1826 } 1827 } 1828 1829 DeclContext *DeclContext::getRedeclContext() { 1830 DeclContext *Ctx = this; 1831 1832 // In C, a record type is the redeclaration context for its fields only. If 1833 // we arrive at a record context after skipping anything else, we should skip 1834 // the record as well. Currently, this means skipping enumerations because 1835 // they're the only transparent context that can exist within a struct or 1836 // union. 1837 bool SkipRecords = getDeclKind() == Decl::Kind::Enum && 1838 !getParentASTContext().getLangOpts().CPlusPlus; 1839 1840 // Skip through contexts to get to the redeclaration context. Transparent 1841 // contexts are always skipped. 1842 while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext()) 1843 Ctx = Ctx->getParent(); 1844 return Ctx; 1845 } 1846 1847 DeclContext *DeclContext::getEnclosingNamespaceContext() { 1848 DeclContext *Ctx = this; 1849 // Skip through non-namespace, non-translation-unit contexts. 1850 while (!Ctx->isFileContext()) 1851 Ctx = Ctx->getParent(); 1852 return Ctx->getPrimaryContext(); 1853 } 1854 1855 RecordDecl *DeclContext::getOuterLexicalRecordContext() { 1856 // Loop until we find a non-record context. 1857 RecordDecl *OutermostRD = nullptr; 1858 DeclContext *DC = this; 1859 while (DC->isRecord()) { 1860 OutermostRD = cast<RecordDecl>(DC); 1861 DC = DC->getLexicalParent(); 1862 } 1863 return OutermostRD; 1864 } 1865 1866 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1867 // For non-file contexts, this is equivalent to Equals. 1868 if (!isFileContext()) 1869 return O->Equals(this); 1870 1871 do { 1872 if (O->Equals(this)) 1873 return true; 1874 1875 const auto *NS = dyn_cast<NamespaceDecl>(O); 1876 if (!NS || !NS->isInline()) 1877 break; 1878 O = NS->getParent(); 1879 } while (O); 1880 1881 return false; 1882 } 1883 1884 void DeclContext::makeDeclVisibleInContext(NamedDecl *D) { 1885 DeclContext *PrimaryDC = this->getPrimaryContext(); 1886 DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext(); 1887 // If the decl is being added outside of its semantic decl context, we 1888 // need to ensure that we eagerly build the lookup information for it. 1889 PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC); 1890 } 1891 1892 void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal, 1893 bool Recoverable) { 1894 assert(this == getPrimaryContext() && "expected a primary DC"); 1895 1896 if (!isLookupContext()) { 1897 if (isTransparentContext()) 1898 getParent()->getPrimaryContext() 1899 ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 1900 return; 1901 } 1902 1903 // Skip declarations which should be invisible to name lookup. 1904 if (shouldBeHidden(D)) 1905 return; 1906 1907 // If we already have a lookup data structure, perform the insertion into 1908 // it. If we might have externally-stored decls with this name, look them 1909 // up and perform the insertion. If this decl was declared outside its 1910 // semantic context, buildLookup won't add it, so add it now. 1911 // 1912 // FIXME: As a performance hack, don't add such decls into the translation 1913 // unit unless we're in C++, since qualified lookup into the TU is never 1914 // performed. 1915 if (LookupPtr || hasExternalVisibleStorage() || 1916 ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) && 1917 (getParentASTContext().getLangOpts().CPlusPlus || 1918 !isTranslationUnit()))) { 1919 // If we have lazily omitted any decls, they might have the same name as 1920 // the decl which we are adding, so build a full lookup table before adding 1921 // this decl. 1922 buildLookup(); 1923 makeDeclVisibleInContextImpl(D, Internal); 1924 } else { 1925 setHasLazyLocalLexicalLookups(true); 1926 } 1927 1928 // If we are a transparent context or inline namespace, insert into our 1929 // parent context, too. This operation is recursive. 1930 if (isTransparentContext() || isInlineNamespace()) 1931 getParent()->getPrimaryContext()-> 1932 makeDeclVisibleInContextWithFlags(D, Internal, Recoverable); 1933 1934 auto *DCAsDecl = cast<Decl>(this); 1935 // Notify that a decl was made visible unless we are a Tag being defined. 1936 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1937 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1938 L->AddedVisibleDecl(this, D); 1939 } 1940 1941 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) { 1942 // Find or create the stored declaration map. 1943 StoredDeclsMap *Map = LookupPtr; 1944 if (!Map) { 1945 ASTContext *C = &getParentASTContext(); 1946 Map = CreateStoredDeclsMap(*C); 1947 } 1948 1949 // If there is an external AST source, load any declarations it knows about 1950 // with this declaration's name. 1951 // If the lookup table contains an entry about this name it means that we 1952 // have already checked the external source. 1953 if (!Internal) 1954 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1955 if (hasExternalVisibleStorage() && 1956 Map->find(D->getDeclName()) == Map->end()) 1957 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1958 1959 // Insert this declaration into the map. 1960 StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()]; 1961 1962 if (Internal) { 1963 // If this is being added as part of loading an external declaration, 1964 // this may not be the only external declaration with this name. 1965 // In this case, we never try to replace an existing declaration; we'll 1966 // handle that when we finalize the list of declarations for this name. 1967 DeclNameEntries.setHasExternalDecls(); 1968 DeclNameEntries.prependDeclNoReplace(D); 1969 return; 1970 } 1971 1972 DeclNameEntries.addOrReplaceDecl(D); 1973 } 1974 1975 UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const { 1976 return cast<UsingDirectiveDecl>(*I); 1977 } 1978 1979 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1980 /// this context. 1981 DeclContext::udir_range DeclContext::using_directives() const { 1982 // FIXME: Use something more efficient than normal lookup for using 1983 // directives. In C++, using directives are looked up more than anything else. 1984 lookup_result Result = lookup(UsingDirectiveDecl::getName()); 1985 return udir_range(Result.begin(), Result.end()); 1986 } 1987 1988 //===----------------------------------------------------------------------===// 1989 // Creation and Destruction of StoredDeclsMaps. // 1990 //===----------------------------------------------------------------------===// 1991 1992 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1993 assert(!LookupPtr && "context already has a decls map"); 1994 assert(getPrimaryContext() == this && 1995 "creating decls map on non-primary context"); 1996 1997 StoredDeclsMap *M; 1998 bool Dependent = isDependentContext(); 1999 if (Dependent) 2000 M = new DependentStoredDeclsMap(); 2001 else 2002 M = new StoredDeclsMap(); 2003 M->Previous = C.LastSDM; 2004 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 2005 LookupPtr = M; 2006 return M; 2007 } 2008 2009 void ASTContext::ReleaseDeclContextMaps() { 2010 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 2011 // pointer because the subclass doesn't add anything that needs to 2012 // be deleted. 2013 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 2014 LastSDM.setPointer(nullptr); 2015 } 2016 2017 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 2018 while (Map) { 2019 // Advance the iteration before we invalidate memory. 2020 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 2021 2022 if (Dependent) 2023 delete static_cast<DependentStoredDeclsMap*>(Map); 2024 else 2025 delete Map; 2026 2027 Map = Next.getPointer(); 2028 Dependent = Next.getInt(); 2029 } 2030 } 2031 2032 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 2033 DeclContext *Parent, 2034 const PartialDiagnostic &PDiag) { 2035 assert(Parent->isDependentContext() 2036 && "cannot iterate dependent diagnostics of non-dependent context"); 2037 Parent = Parent->getPrimaryContext(); 2038 if (!Parent->LookupPtr) 2039 Parent->CreateStoredDeclsMap(C); 2040 2041 auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr); 2042 2043 // Allocate the copy of the PartialDiagnostic via the ASTContext's 2044 // BumpPtrAllocator, rather than the ASTContext itself. 2045 DiagnosticStorage *DiagStorage = nullptr; 2046 if (PDiag.hasStorage()) 2047 DiagStorage = new (C) DiagnosticStorage; 2048 2049 auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 2050 2051 // TODO: Maybe we shouldn't reverse the order during insertion. 2052 DD->NextDiagnostic = Map->FirstDiagnostic; 2053 Map->FirstDiagnostic = DD; 2054 2055 return DD; 2056 } 2057