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