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