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/Decl.h" 16 #include "clang/AST/DeclContextInternals.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclFriend.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/DependentDiagnostic.h" 22 #include "clang/AST/ExternalASTSource.h" 23 #include "clang/AST/ASTContext.h" 24 #include "clang/AST/Type.h" 25 #include "clang/AST/Stmt.h" 26 #include "clang/AST/StmtCXX.h" 27 #include "clang/AST/ASTMutationListener.h" 28 #include "clang/Basic/TargetInfo.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <algorithm> 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Statistics 36 //===----------------------------------------------------------------------===// 37 38 #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0; 39 #define ABSTRACT_DECL(DECL) 40 #include "clang/AST/DeclNodes.inc" 41 42 static bool StatSwitch = false; 43 44 const char *Decl::getDeclKindName() const { 45 switch (DeclKind) { 46 default: assert(0 && "Declaration not in DeclNodes.inc!"); 47 #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED; 48 #define ABSTRACT_DECL(DECL) 49 #include "clang/AST/DeclNodes.inc" 50 } 51 } 52 53 void Decl::setInvalidDecl(bool Invalid) { 54 InvalidDecl = Invalid; 55 if (Invalid) { 56 // Defensive maneuver for ill-formed code: we're likely not to make it to 57 // a point where we set the access specifier, so default it to "public" 58 // to avoid triggering asserts elsewhere in the front end. 59 setAccess(AS_public); 60 } 61 } 62 63 const char *DeclContext::getDeclKindName() const { 64 switch (DeclKind) { 65 default: assert(0 && "Declaration context not in DeclNodes.inc!"); 66 #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED; 67 #define ABSTRACT_DECL(DECL) 68 #include "clang/AST/DeclNodes.inc" 69 } 70 } 71 72 bool Decl::CollectingStats(bool Enable) { 73 if (Enable) StatSwitch = true; 74 return StatSwitch; 75 } 76 77 void Decl::PrintStats() { 78 llvm::errs() << "\n*** Decl Stats:\n"; 79 80 int totalDecls = 0; 81 #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s; 82 #define ABSTRACT_DECL(DECL) 83 #include "clang/AST/DeclNodes.inc" 84 llvm::errs() << " " << totalDecls << " decls total.\n"; 85 86 int totalBytes = 0; 87 #define DECL(DERIVED, BASE) \ 88 if (n##DERIVED##s > 0) { \ 89 totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \ 90 llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \ 91 << sizeof(DERIVED##Decl) << " each (" \ 92 << n##DERIVED##s * sizeof(DERIVED##Decl) \ 93 << " bytes)\n"; \ 94 } 95 #define ABSTRACT_DECL(DECL) 96 #include "clang/AST/DeclNodes.inc" 97 98 llvm::errs() << "Total bytes = " << totalBytes << "\n"; 99 } 100 101 void Decl::add(Kind k) { 102 switch (k) { 103 default: assert(0 && "Declaration not in DeclNodes.inc!"); 104 #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break; 105 #define ABSTRACT_DECL(DECL) 106 #include "clang/AST/DeclNodes.inc" 107 } 108 } 109 110 bool Decl::isTemplateParameterPack() const { 111 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(this)) 112 return TTP->isParameterPack(); 113 if (const NonTypeTemplateParmDecl *NTTP 114 = dyn_cast<NonTypeTemplateParmDecl>(this)) 115 return NTTP->isParameterPack(); 116 if (const TemplateTemplateParmDecl *TTP 117 = dyn_cast<TemplateTemplateParmDecl>(this)) 118 return TTP->isParameterPack(); 119 return false; 120 } 121 122 bool Decl::isParameterPack() const { 123 if (const ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(this)) 124 return Parm->isParameterPack(); 125 126 return isTemplateParameterPack(); 127 } 128 129 bool Decl::isFunctionOrFunctionTemplate() const { 130 if (const UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(this)) 131 return UD->getTargetDecl()->isFunctionOrFunctionTemplate(); 132 133 return isa<FunctionDecl>(this) || isa<FunctionTemplateDecl>(this); 134 } 135 136 bool Decl::isTemplateDecl() const { 137 return isa<TemplateDecl>(this); 138 } 139 140 bool Decl::isDefinedOutsideFunctionOrMethod() const { 141 for (const DeclContext *DC = getDeclContext(); 142 DC && !DC->isTranslationUnit(); 143 DC = DC->getParent()) 144 if (DC->isFunctionOrMethod()) 145 return false; 146 147 return true; 148 } 149 150 151 //===----------------------------------------------------------------------===// 152 // PrettyStackTraceDecl Implementation 153 //===----------------------------------------------------------------------===// 154 155 void PrettyStackTraceDecl::print(raw_ostream &OS) const { 156 SourceLocation TheLoc = Loc; 157 if (TheLoc.isInvalid() && TheDecl) 158 TheLoc = TheDecl->getLocation(); 159 160 if (TheLoc.isValid()) { 161 TheLoc.print(OS, SM); 162 OS << ": "; 163 } 164 165 OS << Message; 166 167 if (const NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) 168 OS << " '" << DN->getQualifiedNameAsString() << '\''; 169 OS << '\n'; 170 } 171 172 //===----------------------------------------------------------------------===// 173 // Decl Implementation 174 //===----------------------------------------------------------------------===// 175 176 // Out-of-line virtual method providing a home for Decl. 177 Decl::~Decl() { } 178 179 void Decl::setDeclContext(DeclContext *DC) { 180 DeclCtx = DC; 181 } 182 183 void Decl::setLexicalDeclContext(DeclContext *DC) { 184 if (DC == getLexicalDeclContext()) 185 return; 186 187 if (isInSemaDC()) { 188 MultipleDC *MDC = new (getASTContext()) MultipleDC(); 189 MDC->SemanticDC = getDeclContext(); 190 MDC->LexicalDC = DC; 191 DeclCtx = MDC; 192 } else { 193 getMultipleDC()->LexicalDC = DC; 194 } 195 } 196 197 bool Decl::isInAnonymousNamespace() const { 198 const DeclContext *DC = getDeclContext(); 199 do { 200 if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC)) 201 if (ND->isAnonymousNamespace()) 202 return true; 203 } while ((DC = DC->getParent())); 204 205 return false; 206 } 207 208 TranslationUnitDecl *Decl::getTranslationUnitDecl() { 209 if (TranslationUnitDecl *TUD = dyn_cast<TranslationUnitDecl>(this)) 210 return TUD; 211 212 DeclContext *DC = getDeclContext(); 213 assert(DC && "This decl is not contained in a translation unit!"); 214 215 while (!DC->isTranslationUnit()) { 216 DC = DC->getParent(); 217 assert(DC && "This decl is not contained in a translation unit!"); 218 } 219 220 return cast<TranslationUnitDecl>(DC); 221 } 222 223 ASTContext &Decl::getASTContext() const { 224 return getTranslationUnitDecl()->getASTContext(); 225 } 226 227 ASTMutationListener *Decl::getASTMutationListener() const { 228 return getASTContext().getASTMutationListener(); 229 } 230 231 bool Decl::isUsed(bool CheckUsedAttr) const { 232 if (Used) 233 return true; 234 235 // Check for used attribute. 236 if (CheckUsedAttr && hasAttr<UsedAttr>()) 237 return true; 238 239 // Check redeclarations for used attribute. 240 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 241 if ((CheckUsedAttr && I->hasAttr<UsedAttr>()) || I->Used) 242 return true; 243 } 244 245 return false; 246 } 247 248 bool Decl::isReferenced() const { 249 if (Referenced) 250 return true; 251 252 // Check redeclarations. 253 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 254 if (I->Referenced) 255 return true; 256 257 return false; 258 } 259 260 /// \brief Determine the availability of the given declaration based on 261 /// the target platform. 262 /// 263 /// When it returns an availability result other than \c AR_Available, 264 /// if the \p Message parameter is non-NULL, it will be set to a 265 /// string describing why the entity is unavailable. 266 /// 267 /// FIXME: Make these strings localizable, since they end up in 268 /// diagnostics. 269 static AvailabilityResult CheckAvailability(ASTContext &Context, 270 const AvailabilityAttr *A, 271 std::string *Message) { 272 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 273 StringRef PrettyPlatformName 274 = AvailabilityAttr::getPrettyPlatformName(TargetPlatform); 275 if (PrettyPlatformName.empty()) 276 PrettyPlatformName = TargetPlatform; 277 278 VersionTuple TargetMinVersion = Context.getTargetInfo().getPlatformMinVersion(); 279 if (TargetMinVersion.empty()) 280 return AR_Available; 281 282 // Match the platform name. 283 if (A->getPlatform()->getName() != TargetPlatform) 284 return AR_Available; 285 286 // Make sure that this declaration has not been marked 'unavailable'. 287 if (A->getUnavailable()) { 288 if (Message) { 289 Message->clear(); 290 llvm::raw_string_ostream Out(*Message); 291 Out << "not available on " << PrettyPlatformName; 292 } 293 294 return AR_Unavailable; 295 } 296 297 // Make sure that this declaration has already been introduced. 298 if (!A->getIntroduced().empty() && 299 TargetMinVersion < A->getIntroduced()) { 300 if (Message) { 301 Message->clear(); 302 llvm::raw_string_ostream Out(*Message); 303 Out << "introduced in " << PrettyPlatformName << ' ' 304 << A->getIntroduced(); 305 } 306 307 return AR_NotYetIntroduced; 308 } 309 310 // Make sure that this declaration hasn't been obsoleted. 311 if (!A->getObsoleted().empty() && TargetMinVersion >= A->getObsoleted()) { 312 if (Message) { 313 Message->clear(); 314 llvm::raw_string_ostream Out(*Message); 315 Out << "obsoleted in " << PrettyPlatformName << ' ' 316 << A->getObsoleted(); 317 } 318 319 return AR_Unavailable; 320 } 321 322 // Make sure that this declaration hasn't been deprecated. 323 if (!A->getDeprecated().empty() && TargetMinVersion >= A->getDeprecated()) { 324 if (Message) { 325 Message->clear(); 326 llvm::raw_string_ostream Out(*Message); 327 Out << "first deprecated in " << PrettyPlatformName << ' ' 328 << A->getDeprecated(); 329 } 330 331 return AR_Deprecated; 332 } 333 334 return AR_Available; 335 } 336 337 AvailabilityResult Decl::getAvailability(std::string *Message) const { 338 AvailabilityResult Result = AR_Available; 339 std::string ResultMessage; 340 341 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) { 342 if (DeprecatedAttr *Deprecated = dyn_cast<DeprecatedAttr>(*A)) { 343 if (Result >= AR_Deprecated) 344 continue; 345 346 if (Message) 347 ResultMessage = Deprecated->getMessage(); 348 349 Result = AR_Deprecated; 350 continue; 351 } 352 353 if (UnavailableAttr *Unavailable = dyn_cast<UnavailableAttr>(*A)) { 354 if (Message) 355 *Message = Unavailable->getMessage(); 356 return AR_Unavailable; 357 } 358 359 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) { 360 AvailabilityResult AR = CheckAvailability(getASTContext(), Availability, 361 Message); 362 363 if (AR == AR_Unavailable) 364 return AR_Unavailable; 365 366 if (AR > Result) { 367 Result = AR; 368 if (Message) 369 ResultMessage.swap(*Message); 370 } 371 continue; 372 } 373 } 374 375 if (Message) 376 Message->swap(ResultMessage); 377 return Result; 378 } 379 380 bool Decl::canBeWeakImported(bool &IsDefinition) const { 381 IsDefinition = false; 382 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) { 383 if (!Var->hasExternalStorage() || Var->getInit()) { 384 IsDefinition = true; 385 return false; 386 } 387 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 388 if (FD->hasBody()) { 389 IsDefinition = true; 390 return false; 391 } 392 } else if (isa<ObjCPropertyDecl>(this) || isa<ObjCMethodDecl>(this)) 393 return false; 394 else if (!(getASTContext().getLangOptions().ObjCNonFragileABI && 395 isa<ObjCInterfaceDecl>(this))) 396 return false; 397 398 return true; 399 } 400 401 bool Decl::isWeakImported() const { 402 bool IsDefinition; 403 if (!canBeWeakImported(IsDefinition)) 404 return false; 405 406 for (attr_iterator A = attr_begin(), AEnd = attr_end(); A != AEnd; ++A) { 407 if (isa<WeakImportAttr>(*A)) 408 return true; 409 410 if (AvailabilityAttr *Availability = dyn_cast<AvailabilityAttr>(*A)) { 411 if (CheckAvailability(getASTContext(), Availability, 0) 412 == AR_NotYetIntroduced) 413 return true; 414 } 415 } 416 417 return false; 418 } 419 420 unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) { 421 switch (DeclKind) { 422 case Function: 423 case CXXMethod: 424 case CXXConstructor: 425 case CXXDestructor: 426 case CXXConversion: 427 case EnumConstant: 428 case Var: 429 case ImplicitParam: 430 case ParmVar: 431 case NonTypeTemplateParm: 432 case ObjCMethod: 433 case ObjCProperty: 434 return IDNS_Ordinary; 435 case Label: 436 return IDNS_Label; 437 case IndirectField: 438 return IDNS_Ordinary | IDNS_Member; 439 440 case ObjCCompatibleAlias: 441 case ObjCInterface: 442 return IDNS_Ordinary | IDNS_Type; 443 444 case Typedef: 445 case TypeAlias: 446 case TypeAliasTemplate: 447 case UnresolvedUsingTypename: 448 case TemplateTypeParm: 449 return IDNS_Ordinary | IDNS_Type; 450 451 case UsingShadow: 452 return 0; // we'll actually overwrite this later 453 454 case UnresolvedUsingValue: 455 return IDNS_Ordinary | IDNS_Using; 456 457 case Using: 458 return IDNS_Using; 459 460 case ObjCProtocol: 461 return IDNS_ObjCProtocol; 462 463 case Field: 464 case ObjCAtDefsField: 465 case ObjCIvar: 466 return IDNS_Member; 467 468 case Record: 469 case CXXRecord: 470 case Enum: 471 return IDNS_Tag | IDNS_Type; 472 473 case Namespace: 474 case NamespaceAlias: 475 return IDNS_Namespace; 476 477 case FunctionTemplate: 478 return IDNS_Ordinary; 479 480 case ClassTemplate: 481 case TemplateTemplateParm: 482 return IDNS_Ordinary | IDNS_Tag | IDNS_Type; 483 484 // Never have names. 485 case Friend: 486 case FriendTemplate: 487 case AccessSpec: 488 case LinkageSpec: 489 case FileScopeAsm: 490 case StaticAssert: 491 case ObjCClass: 492 case ObjCPropertyImpl: 493 case ObjCForwardProtocol: 494 case Block: 495 case TranslationUnit: 496 497 case UsingDirective: 498 case ClassTemplateSpecialization: 499 case ClassTemplatePartialSpecialization: 500 case ClassScopeFunctionSpecialization: 501 case ObjCImplementation: 502 case ObjCCategory: 503 case ObjCCategoryImpl: 504 // Never looked up by name. 505 return 0; 506 } 507 508 return 0; 509 } 510 511 void Decl::setAttrs(const AttrVec &attrs) { 512 assert(!HasAttrs && "Decl already contains attrs."); 513 514 AttrVec &AttrBlank = getASTContext().getDeclAttrs(this); 515 assert(AttrBlank.empty() && "HasAttrs was wrong?"); 516 517 AttrBlank = attrs; 518 HasAttrs = true; 519 } 520 521 void Decl::dropAttrs() { 522 if (!HasAttrs) return; 523 524 HasAttrs = false; 525 getASTContext().eraseDeclAttrs(this); 526 } 527 528 const AttrVec &Decl::getAttrs() const { 529 assert(HasAttrs && "No attrs to get!"); 530 return getASTContext().getDeclAttrs(this); 531 } 532 533 void Decl::swapAttrs(Decl *RHS) { 534 bool HasLHSAttr = this->HasAttrs; 535 bool HasRHSAttr = RHS->HasAttrs; 536 537 // Usually, neither decl has attrs, nothing to do. 538 if (!HasLHSAttr && !HasRHSAttr) return; 539 540 // If 'this' has no attrs, swap the other way. 541 if (!HasLHSAttr) 542 return RHS->swapAttrs(this); 543 544 ASTContext &Context = getASTContext(); 545 546 // Handle the case when both decls have attrs. 547 if (HasRHSAttr) { 548 std::swap(Context.getDeclAttrs(this), Context.getDeclAttrs(RHS)); 549 return; 550 } 551 552 // Otherwise, LHS has an attr and RHS doesn't. 553 Context.getDeclAttrs(RHS) = Context.getDeclAttrs(this); 554 Context.eraseDeclAttrs(this); 555 this->HasAttrs = false; 556 RHS->HasAttrs = true; 557 } 558 559 Decl *Decl::castFromDeclContext (const DeclContext *D) { 560 Decl::Kind DK = D->getDeclKind(); 561 switch(DK) { 562 #define DECL(NAME, BASE) 563 #define DECL_CONTEXT(NAME) \ 564 case Decl::NAME: \ 565 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 566 #define DECL_CONTEXT_BASE(NAME) 567 #include "clang/AST/DeclNodes.inc" 568 default: 569 #define DECL(NAME, BASE) 570 #define DECL_CONTEXT_BASE(NAME) \ 571 if (DK >= first##NAME && DK <= last##NAME) \ 572 return static_cast<NAME##Decl*>(const_cast<DeclContext*>(D)); 573 #include "clang/AST/DeclNodes.inc" 574 assert(false && "a decl that inherits DeclContext isn't handled"); 575 return 0; 576 } 577 } 578 579 DeclContext *Decl::castToDeclContext(const Decl *D) { 580 Decl::Kind DK = D->getKind(); 581 switch(DK) { 582 #define DECL(NAME, BASE) 583 #define DECL_CONTEXT(NAME) \ 584 case Decl::NAME: \ 585 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 586 #define DECL_CONTEXT_BASE(NAME) 587 #include "clang/AST/DeclNodes.inc" 588 default: 589 #define DECL(NAME, BASE) 590 #define DECL_CONTEXT_BASE(NAME) \ 591 if (DK >= first##NAME && DK <= last##NAME) \ 592 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 593 #include "clang/AST/DeclNodes.inc" 594 assert(false && "a decl that inherits DeclContext isn't handled"); 595 return 0; 596 } 597 } 598 599 SourceLocation Decl::getBodyRBrace() const { 600 // Special handling of FunctionDecl to avoid de-serializing the body from PCH. 601 // FunctionDecl stores EndRangeLoc for this purpose. 602 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 603 const FunctionDecl *Definition; 604 if (FD->hasBody(Definition)) 605 return Definition->getSourceRange().getEnd(); 606 return SourceLocation(); 607 } 608 609 if (Stmt *Body = getBody()) 610 return Body->getSourceRange().getEnd(); 611 612 return SourceLocation(); 613 } 614 615 void Decl::CheckAccessDeclContext() const { 616 #ifndef NDEBUG 617 // Suppress this check if any of the following hold: 618 // 1. this is the translation unit (and thus has no parent) 619 // 2. this is a template parameter (and thus doesn't belong to its context) 620 // 3. this is a non-type template parameter 621 // 4. the context is not a record 622 // 5. it's invalid 623 // 6. it's a C++0x static_assert. 624 if (isa<TranslationUnitDecl>(this) || 625 isa<TemplateTypeParmDecl>(this) || 626 isa<NonTypeTemplateParmDecl>(this) || 627 !isa<CXXRecordDecl>(getDeclContext()) || 628 isInvalidDecl() || 629 isa<StaticAssertDecl>(this) || 630 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 631 // as DeclContext (?). 632 isa<ParmVarDecl>(this) || 633 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 634 // AS_none as access specifier. 635 isa<CXXRecordDecl>(this) || 636 isa<ClassScopeFunctionSpecializationDecl>(this)) 637 return; 638 639 assert(Access != AS_none && 640 "Access specifier is AS_none inside a record decl"); 641 #endif 642 } 643 644 DeclContext *Decl::getNonClosureContext() { 645 DeclContext *DC = getDeclContext(); 646 647 // This is basically "while (DC->isClosure()) DC = DC->getParent();" 648 // except that it's significantly more efficient to cast to a known 649 // decl type and call getDeclContext() than to call getParent(). 650 while (isa<BlockDecl>(DC)) 651 DC = cast<BlockDecl>(DC)->getDeclContext(); 652 653 assert(!DC->isClosure()); 654 return DC; 655 } 656 657 //===----------------------------------------------------------------------===// 658 // DeclContext Implementation 659 //===----------------------------------------------------------------------===// 660 661 bool DeclContext::classof(const Decl *D) { 662 switch (D->getKind()) { 663 #define DECL(NAME, BASE) 664 #define DECL_CONTEXT(NAME) case Decl::NAME: 665 #define DECL_CONTEXT_BASE(NAME) 666 #include "clang/AST/DeclNodes.inc" 667 return true; 668 default: 669 #define DECL(NAME, BASE) 670 #define DECL_CONTEXT_BASE(NAME) \ 671 if (D->getKind() >= Decl::first##NAME && \ 672 D->getKind() <= Decl::last##NAME) \ 673 return true; 674 #include "clang/AST/DeclNodes.inc" 675 return false; 676 } 677 } 678 679 DeclContext::~DeclContext() { } 680 681 /// \brief Find the parent context of this context that will be 682 /// used for unqualified name lookup. 683 /// 684 /// Generally, the parent lookup context is the semantic context. However, for 685 /// a friend function the parent lookup context is the lexical context, which 686 /// is the class in which the friend is declared. 687 DeclContext *DeclContext::getLookupParent() { 688 // FIXME: Find a better way to identify friends 689 if (isa<FunctionDecl>(this)) 690 if (getParent()->getRedeclContext()->isFileContext() && 691 getLexicalParent()->getRedeclContext()->isRecord()) 692 return getLexicalParent(); 693 694 return getParent(); 695 } 696 697 bool DeclContext::isInlineNamespace() const { 698 return isNamespace() && 699 cast<NamespaceDecl>(this)->isInline(); 700 } 701 702 bool DeclContext::isDependentContext() const { 703 if (isFileContext()) 704 return false; 705 706 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 707 return true; 708 709 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 710 if (Record->getDescribedClassTemplate()) 711 return true; 712 713 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 714 if (Function->getDescribedFunctionTemplate()) 715 return true; 716 717 // Friend function declarations are dependent if their *lexical* 718 // context is dependent. 719 if (cast<Decl>(this)->getFriendObjectKind()) 720 return getLexicalParent()->isDependentContext(); 721 } 722 723 return getParent() && getParent()->isDependentContext(); 724 } 725 726 bool DeclContext::isTransparentContext() const { 727 if (DeclKind == Decl::Enum) 728 return !cast<EnumDecl>(this)->isScoped(); 729 else if (DeclKind == Decl::LinkageSpec) 730 return true; 731 732 return false; 733 } 734 735 bool DeclContext::isExternCContext() const { 736 const DeclContext *DC = this; 737 while (DC->DeclKind != Decl::TranslationUnit) { 738 if (DC->DeclKind == Decl::LinkageSpec) 739 return cast<LinkageSpecDecl>(DC)->getLanguage() 740 == LinkageSpecDecl::lang_c; 741 DC = DC->getParent(); 742 } 743 return false; 744 } 745 746 bool DeclContext::Encloses(const DeclContext *DC) const { 747 if (getPrimaryContext() != this) 748 return getPrimaryContext()->Encloses(DC); 749 750 for (; DC; DC = DC->getParent()) 751 if (DC->getPrimaryContext() == this) 752 return true; 753 return false; 754 } 755 756 DeclContext *DeclContext::getPrimaryContext() { 757 switch (DeclKind) { 758 case Decl::TranslationUnit: 759 case Decl::LinkageSpec: 760 case Decl::Block: 761 // There is only one DeclContext for these entities. 762 return this; 763 764 case Decl::Namespace: 765 // The original namespace is our primary context. 766 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 767 768 case Decl::ObjCMethod: 769 return this; 770 771 case Decl::ObjCInterface: 772 case Decl::ObjCProtocol: 773 case Decl::ObjCCategory: 774 // FIXME: Can Objective-C interfaces be forward-declared? 775 return this; 776 777 case Decl::ObjCImplementation: 778 case Decl::ObjCCategoryImpl: 779 return this; 780 781 default: 782 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 783 // If this is a tag type that has a definition or is currently 784 // being defined, that definition is our primary context. 785 TagDecl *Tag = cast<TagDecl>(this); 786 assert(isa<TagType>(Tag->TypeForDecl) || 787 isa<InjectedClassNameType>(Tag->TypeForDecl)); 788 789 if (TagDecl *Def = Tag->getDefinition()) 790 return Def; 791 792 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) { 793 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl); 794 if (TagTy->isBeingDefined()) 795 // FIXME: is it necessarily being defined in the decl 796 // that owns the type? 797 return TagTy->getDecl(); 798 } 799 800 return Tag; 801 } 802 803 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 804 "Unknown DeclContext kind"); 805 return this; 806 } 807 } 808 809 DeclContext *DeclContext::getNextContext() { 810 switch (DeclKind) { 811 case Decl::Namespace: 812 // Return the next namespace 813 return static_cast<NamespaceDecl*>(this)->getNextNamespace(); 814 815 default: 816 return 0; 817 } 818 } 819 820 std::pair<Decl *, Decl *> 821 DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls) { 822 // Build up a chain of declarations via the Decl::NextDeclInContext field. 823 Decl *FirstNewDecl = 0; 824 Decl *PrevDecl = 0; 825 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 826 Decl *D = Decls[I]; 827 if (PrevDecl) 828 PrevDecl->NextDeclInContext = D; 829 else 830 FirstNewDecl = D; 831 832 PrevDecl = D; 833 } 834 835 return std::make_pair(FirstNewDecl, PrevDecl); 836 } 837 838 /// \brief Load the declarations within this lexical storage from an 839 /// external source. 840 void 841 DeclContext::LoadLexicalDeclsFromExternalStorage() const { 842 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 843 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 844 845 // Notify that we have a DeclContext that is initializing. 846 ExternalASTSource::Deserializing ADeclContext(Source); 847 848 // We may have already loaded just the fields of this record, in which case 849 // we remove all of the fields from the list. The fields will be reloaded 850 // from the external source as part of re-establishing the context. 851 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) { 852 if (RD->LoadedFieldsFromExternalStorage) { 853 while (FirstDecl && isa<FieldDecl>(FirstDecl)) { 854 Decl *Next = FirstDecl->NextDeclInContext; 855 FirstDecl->NextDeclInContext = 0; 856 FirstDecl = Next; 857 } 858 859 if (!FirstDecl) 860 LastDecl = 0; 861 } 862 } 863 864 // Load the external declarations, if any. 865 SmallVector<Decl*, 64> Decls; 866 ExternalLexicalStorage = false; 867 switch (Source->FindExternalLexicalDecls(this, Decls)) { 868 case ELR_Success: 869 break; 870 871 case ELR_Failure: 872 case ELR_AlreadyLoaded: 873 return; 874 } 875 876 if (Decls.empty()) 877 return; 878 879 // Splice the newly-read declarations into the beginning of the list 880 // of declarations. 881 Decl *ExternalFirst, *ExternalLast; 882 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls); 883 ExternalLast->NextDeclInContext = FirstDecl; 884 FirstDecl = ExternalFirst; 885 if (!LastDecl) 886 LastDecl = ExternalLast; 887 } 888 889 DeclContext::lookup_result 890 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 891 DeclarationName Name) { 892 ASTContext &Context = DC->getParentASTContext(); 893 StoredDeclsMap *Map; 894 if (!(Map = DC->LookupPtr)) 895 Map = DC->CreateStoredDeclsMap(Context); 896 897 StoredDeclsList &List = (*Map)[Name]; 898 assert(List.isNull()); 899 (void) List; 900 901 return DeclContext::lookup_result(); 902 } 903 904 DeclContext::lookup_result 905 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 906 DeclarationName Name, 907 ArrayRef<NamedDecl*> Decls) { 908 ASTContext &Context = DC->getParentASTContext();; 909 910 StoredDeclsMap *Map; 911 if (!(Map = DC->LookupPtr)) 912 Map = DC->CreateStoredDeclsMap(Context); 913 914 StoredDeclsList &List = (*Map)[Name]; 915 for (ArrayRef<NamedDecl*>::iterator 916 I = Decls.begin(), E = Decls.end(); I != E; ++I) { 917 if (List.isNull()) 918 List.setOnlyValue(*I); 919 else 920 List.AddSubsequentDecl(*I); 921 } 922 923 return List.getLookupResult(); 924 } 925 926 DeclContext::decl_iterator DeclContext::noload_decls_begin() const { 927 return decl_iterator(FirstDecl); 928 } 929 930 DeclContext::decl_iterator DeclContext::noload_decls_end() const { 931 return decl_iterator(); 932 } 933 934 DeclContext::decl_iterator DeclContext::decls_begin() const { 935 if (hasExternalLexicalStorage()) 936 LoadLexicalDeclsFromExternalStorage(); 937 938 return decl_iterator(FirstDecl); 939 } 940 941 DeclContext::decl_iterator DeclContext::decls_end() const { 942 if (hasExternalLexicalStorage()) 943 LoadLexicalDeclsFromExternalStorage(); 944 945 return decl_iterator(); 946 } 947 948 bool DeclContext::decls_empty() const { 949 if (hasExternalLexicalStorage()) 950 LoadLexicalDeclsFromExternalStorage(); 951 952 return !FirstDecl; 953 } 954 955 void DeclContext::removeDecl(Decl *D) { 956 assert(D->getLexicalDeclContext() == this && 957 "decl being removed from non-lexical context"); 958 assert((D->NextDeclInContext || D == LastDecl) && 959 "decl is not in decls list"); 960 961 // Remove D from the decl chain. This is O(n) but hopefully rare. 962 if (D == FirstDecl) { 963 if (D == LastDecl) 964 FirstDecl = LastDecl = 0; 965 else 966 FirstDecl = D->NextDeclInContext; 967 } else { 968 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) { 969 assert(I && "decl not found in linked list"); 970 if (I->NextDeclInContext == D) { 971 I->NextDeclInContext = D->NextDeclInContext; 972 if (D == LastDecl) LastDecl = I; 973 break; 974 } 975 } 976 } 977 978 // Mark that D is no longer in the decl chain. 979 D->NextDeclInContext = 0; 980 981 // Remove D from the lookup table if necessary. 982 if (isa<NamedDecl>(D)) { 983 NamedDecl *ND = cast<NamedDecl>(D); 984 985 // Remove only decls that have a name 986 if (!ND->getDeclName()) return; 987 988 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr; 989 if (!Map) return; 990 991 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 992 assert(Pos != Map->end() && "no lookup entry for decl"); 993 Pos->second.remove(ND); 994 } 995 } 996 997 void DeclContext::addHiddenDecl(Decl *D) { 998 assert(D->getLexicalDeclContext() == this && 999 "Decl inserted into wrong lexical context"); 1000 assert(!D->getNextDeclInContext() && D != LastDecl && 1001 "Decl already inserted into a DeclContext"); 1002 1003 if (FirstDecl) { 1004 LastDecl->NextDeclInContext = D; 1005 LastDecl = D; 1006 } else { 1007 FirstDecl = LastDecl = D; 1008 } 1009 1010 // Notify a C++ record declaration that we've added a member, so it can 1011 // update it's class-specific state. 1012 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 1013 Record->addedMember(D); 1014 } 1015 1016 void DeclContext::addDecl(Decl *D) { 1017 addHiddenDecl(D); 1018 1019 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1020 ND->getDeclContext()->makeDeclVisibleInContext(ND); 1021 } 1022 1023 /// buildLookup - Build the lookup data structure with all of the 1024 /// declarations in DCtx (and any other contexts linked to it or 1025 /// transparent contexts nested within it). 1026 void DeclContext::buildLookup(DeclContext *DCtx) { 1027 for (; DCtx; DCtx = DCtx->getNextContext()) { 1028 for (decl_iterator D = DCtx->decls_begin(), 1029 DEnd = DCtx->decls_end(); 1030 D != DEnd; ++D) { 1031 // Insert this declaration into the lookup structure, but only 1032 // if it's semantically in its decl context. During non-lazy 1033 // lookup building, this is implicitly enforced by addDecl. 1034 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 1035 if (D->getDeclContext() == DCtx) 1036 makeDeclVisibleInContextImpl(ND); 1037 1038 // Insert any forward-declared Objective-C interface into the lookup 1039 // data structure. 1040 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) 1041 makeDeclVisibleInContextImpl(Class->getForwardInterfaceDecl()); 1042 1043 // If this declaration is itself a transparent declaration context or 1044 // inline namespace, add its members (recursively). 1045 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) 1046 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1047 buildLookup(InnerCtx->getPrimaryContext()); 1048 } 1049 } 1050 } 1051 1052 DeclContext::lookup_result 1053 DeclContext::lookup(DeclarationName Name) { 1054 DeclContext *PrimaryContext = getPrimaryContext(); 1055 if (PrimaryContext != this) 1056 return PrimaryContext->lookup(Name); 1057 1058 if (hasExternalVisibleStorage()) { 1059 // Check to see if we've already cached the lookup results. 1060 if (LookupPtr) { 1061 StoredDeclsMap::iterator I = LookupPtr->find(Name); 1062 if (I != LookupPtr->end()) 1063 return I->second.getLookupResult(); 1064 } 1065 1066 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1067 return Source->FindExternalVisibleDeclsByName(this, Name); 1068 } 1069 1070 /// If there is no lookup data structure, build one now by walking 1071 /// all of the linked DeclContexts (in declaration order!) and 1072 /// inserting their values. 1073 if (!LookupPtr) { 1074 buildLookup(this); 1075 1076 if (!LookupPtr) 1077 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1078 } 1079 1080 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 1081 if (Pos == LookupPtr->end()) 1082 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1083 return Pos->second.getLookupResult(); 1084 } 1085 1086 DeclContext::lookup_const_result 1087 DeclContext::lookup(DeclarationName Name) const { 1088 return const_cast<DeclContext*>(this)->lookup(Name); 1089 } 1090 1091 DeclContext *DeclContext::getRedeclContext() { 1092 DeclContext *Ctx = this; 1093 // Skip through transparent contexts. 1094 while (Ctx->isTransparentContext()) 1095 Ctx = Ctx->getParent(); 1096 return Ctx; 1097 } 1098 1099 DeclContext *DeclContext::getEnclosingNamespaceContext() { 1100 DeclContext *Ctx = this; 1101 // Skip through non-namespace, non-translation-unit contexts. 1102 while (!Ctx->isFileContext()) 1103 Ctx = Ctx->getParent(); 1104 return Ctx->getPrimaryContext(); 1105 } 1106 1107 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1108 // For non-file contexts, this is equivalent to Equals. 1109 if (!isFileContext()) 1110 return O->Equals(this); 1111 1112 do { 1113 if (O->Equals(this)) 1114 return true; 1115 1116 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O); 1117 if (!NS || !NS->isInline()) 1118 break; 1119 O = NS->getParent(); 1120 } while (O); 1121 1122 return false; 1123 } 1124 1125 void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) { 1126 // FIXME: This feels like a hack. Should DeclarationName support 1127 // template-ids, or is there a better way to keep specializations 1128 // from being visible? 1129 if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter()) 1130 return; 1131 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1132 if (FD->isFunctionTemplateSpecialization()) 1133 return; 1134 1135 DeclContext *PrimaryContext = getPrimaryContext(); 1136 if (PrimaryContext != this) { 1137 PrimaryContext->makeDeclVisibleInContext(D, Recoverable); 1138 return; 1139 } 1140 1141 // If we already have a lookup data structure, perform the insertion 1142 // into it. If we haven't deserialized externally stored decls, deserialize 1143 // them so we can add the decl. Otherwise, be lazy and don't build that 1144 // structure until someone asks for it. 1145 if (LookupPtr || !Recoverable || hasExternalVisibleStorage()) 1146 makeDeclVisibleInContextImpl(D); 1147 1148 // If we are a transparent context or inline namespace, insert into our 1149 // parent context, too. This operation is recursive. 1150 if (isTransparentContext() || isInlineNamespace()) 1151 getParent()->makeDeclVisibleInContext(D, Recoverable); 1152 1153 Decl *DCAsDecl = cast<Decl>(this); 1154 // Notify that a decl was made visible unless it's a Tag being defined. 1155 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1156 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1157 L->AddedVisibleDecl(this, D); 1158 } 1159 1160 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) { 1161 // Skip unnamed declarations. 1162 if (!D->getDeclName()) 1163 return; 1164 1165 // Skip entities that can't be found by name lookup into a particular 1166 // context. 1167 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1168 D->isTemplateParameter()) 1169 return; 1170 1171 ASTContext *C = 0; 1172 if (!LookupPtr) { 1173 C = &getParentASTContext(); 1174 CreateStoredDeclsMap(*C); 1175 } 1176 1177 // If there is an external AST source, load any declarations it knows about 1178 // with this declaration's name. 1179 // If the lookup table contains an entry about this name it means that we 1180 // have already checked the external source. 1181 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1182 if (hasExternalVisibleStorage() && 1183 LookupPtr->find(D->getDeclName()) == LookupPtr->end()) 1184 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1185 1186 // Insert this declaration into the map. 1187 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()]; 1188 if (DeclNameEntries.isNull()) { 1189 DeclNameEntries.setOnlyValue(D); 1190 return; 1191 } 1192 1193 // If it is possible that this is a redeclaration, check to see if there is 1194 // already a decl for which declarationReplaces returns true. If there is 1195 // one, just replace it and return. 1196 if (DeclNameEntries.HandleRedeclaration(D)) 1197 return; 1198 1199 // Put this declaration into the appropriate slot. 1200 DeclNameEntries.AddSubsequentDecl(D); 1201 } 1202 1203 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1204 /// this context. 1205 DeclContext::udir_iterator_range 1206 DeclContext::getUsingDirectives() const { 1207 lookup_const_result Result = lookup(UsingDirectiveDecl::getName()); 1208 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first), 1209 reinterpret_cast<udir_iterator>(Result.second)); 1210 } 1211 1212 //===----------------------------------------------------------------------===// 1213 // Creation and Destruction of StoredDeclsMaps. // 1214 //===----------------------------------------------------------------------===// 1215 1216 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1217 assert(!LookupPtr && "context already has a decls map"); 1218 assert(getPrimaryContext() == this && 1219 "creating decls map on non-primary context"); 1220 1221 StoredDeclsMap *M; 1222 bool Dependent = isDependentContext(); 1223 if (Dependent) 1224 M = new DependentStoredDeclsMap(); 1225 else 1226 M = new StoredDeclsMap(); 1227 M->Previous = C.LastSDM; 1228 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1229 LookupPtr = M; 1230 return M; 1231 } 1232 1233 void ASTContext::ReleaseDeclContextMaps() { 1234 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1235 // pointer because the subclass doesn't add anything that needs to 1236 // be deleted. 1237 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1238 } 1239 1240 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1241 while (Map) { 1242 // Advance the iteration before we invalidate memory. 1243 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1244 1245 if (Dependent) 1246 delete static_cast<DependentStoredDeclsMap*>(Map); 1247 else 1248 delete Map; 1249 1250 Map = Next.getPointer(); 1251 Dependent = Next.getInt(); 1252 } 1253 } 1254 1255 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1256 DeclContext *Parent, 1257 const PartialDiagnostic &PDiag) { 1258 assert(Parent->isDependentContext() 1259 && "cannot iterate dependent diagnostics of non-dependent context"); 1260 Parent = Parent->getPrimaryContext(); 1261 if (!Parent->LookupPtr) 1262 Parent->CreateStoredDeclsMap(C); 1263 1264 DependentStoredDeclsMap *Map 1265 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr); 1266 1267 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1268 // BumpPtrAllocator, rather than the ASTContext itself. 1269 PartialDiagnostic::Storage *DiagStorage = 0; 1270 if (PDiag.hasStorage()) 1271 DiagStorage = new (C) PartialDiagnostic::Storage; 1272 1273 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1274 1275 // TODO: Maybe we shouldn't reverse the order during insertion. 1276 DD->NextDiagnostic = Map->FirstDiagnostic; 1277 Map->FirstDiagnostic = DD; 1278 1279 return DD; 1280 } 1281