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