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