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