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: llvm_unreachable("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: llvm_unreachable("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: llvm_unreachable("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 const DeclContext *Decl::getParentFunctionOrMethod() const { 141 for (const DeclContext *DC = getDeclContext(); 142 DC && !DC->isTranslationUnit() && !DC->isNamespace(); 143 DC = DC->getParent()) 144 if (DC->isFunctionOrMethod()) 145 return DC; 146 147 return 0; 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 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 575 } 576 } 577 578 DeclContext *Decl::castToDeclContext(const Decl *D) { 579 Decl::Kind DK = D->getKind(); 580 switch(DK) { 581 #define DECL(NAME, BASE) 582 #define DECL_CONTEXT(NAME) \ 583 case Decl::NAME: \ 584 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 585 #define DECL_CONTEXT_BASE(NAME) 586 #include "clang/AST/DeclNodes.inc" 587 default: 588 #define DECL(NAME, BASE) 589 #define DECL_CONTEXT_BASE(NAME) \ 590 if (DK >= first##NAME && DK <= last##NAME) \ 591 return static_cast<NAME##Decl*>(const_cast<Decl*>(D)); 592 #include "clang/AST/DeclNodes.inc" 593 llvm_unreachable("a decl that inherits DeclContext isn't handled"); 594 } 595 } 596 597 SourceLocation Decl::getBodyRBrace() const { 598 // Special handling of FunctionDecl to avoid de-serializing the body from PCH. 599 // FunctionDecl stores EndRangeLoc for this purpose. 600 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) { 601 const FunctionDecl *Definition; 602 if (FD->hasBody(Definition)) 603 return Definition->getSourceRange().getEnd(); 604 return SourceLocation(); 605 } 606 607 if (Stmt *Body = getBody()) 608 return Body->getSourceRange().getEnd(); 609 610 return SourceLocation(); 611 } 612 613 void Decl::CheckAccessDeclContext() const { 614 #ifndef NDEBUG 615 // Suppress this check if any of the following hold: 616 // 1. this is the translation unit (and thus has no parent) 617 // 2. this is a template parameter (and thus doesn't belong to its context) 618 // 3. this is a non-type template parameter 619 // 4. the context is not a record 620 // 5. it's invalid 621 // 6. it's a C++0x static_assert. 622 if (isa<TranslationUnitDecl>(this) || 623 isa<TemplateTypeParmDecl>(this) || 624 isa<NonTypeTemplateParmDecl>(this) || 625 !isa<CXXRecordDecl>(getDeclContext()) || 626 isInvalidDecl() || 627 isa<StaticAssertDecl>(this) || 628 // FIXME: a ParmVarDecl can have ClassTemplateSpecialization 629 // as DeclContext (?). 630 isa<ParmVarDecl>(this) || 631 // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have 632 // AS_none as access specifier. 633 isa<CXXRecordDecl>(this) || 634 isa<ClassScopeFunctionSpecializationDecl>(this)) 635 return; 636 637 assert(Access != AS_none && 638 "Access specifier is AS_none inside a record decl"); 639 #endif 640 } 641 642 DeclContext *Decl::getNonClosureContext() { 643 DeclContext *DC = getDeclContext(); 644 645 // This is basically "while (DC->isClosure()) DC = DC->getParent();" 646 // except that it's significantly more efficient to cast to a known 647 // decl type and call getDeclContext() than to call getParent(). 648 while (isa<BlockDecl>(DC)) 649 DC = cast<BlockDecl>(DC)->getDeclContext(); 650 651 assert(!DC->isClosure()); 652 return DC; 653 } 654 655 //===----------------------------------------------------------------------===// 656 // DeclContext Implementation 657 //===----------------------------------------------------------------------===// 658 659 bool DeclContext::classof(const Decl *D) { 660 switch (D->getKind()) { 661 #define DECL(NAME, BASE) 662 #define DECL_CONTEXT(NAME) case Decl::NAME: 663 #define DECL_CONTEXT_BASE(NAME) 664 #include "clang/AST/DeclNodes.inc" 665 return true; 666 default: 667 #define DECL(NAME, BASE) 668 #define DECL_CONTEXT_BASE(NAME) \ 669 if (D->getKind() >= Decl::first##NAME && \ 670 D->getKind() <= Decl::last##NAME) \ 671 return true; 672 #include "clang/AST/DeclNodes.inc" 673 return false; 674 } 675 } 676 677 DeclContext::~DeclContext() { } 678 679 /// \brief Find the parent context of this context that will be 680 /// used for unqualified name lookup. 681 /// 682 /// Generally, the parent lookup context is the semantic context. However, for 683 /// a friend function the parent lookup context is the lexical context, which 684 /// is the class in which the friend is declared. 685 DeclContext *DeclContext::getLookupParent() { 686 // FIXME: Find a better way to identify friends 687 if (isa<FunctionDecl>(this)) 688 if (getParent()->getRedeclContext()->isFileContext() && 689 getLexicalParent()->getRedeclContext()->isRecord()) 690 return getLexicalParent(); 691 692 return getParent(); 693 } 694 695 bool DeclContext::isInlineNamespace() const { 696 return isNamespace() && 697 cast<NamespaceDecl>(this)->isInline(); 698 } 699 700 bool DeclContext::isDependentContext() const { 701 if (isFileContext()) 702 return false; 703 704 if (isa<ClassTemplatePartialSpecializationDecl>(this)) 705 return true; 706 707 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 708 if (Record->getDescribedClassTemplate()) 709 return true; 710 711 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 712 if (Function->getDescribedFunctionTemplate()) 713 return true; 714 715 // Friend function declarations are dependent if their *lexical* 716 // context is dependent. 717 if (cast<Decl>(this)->getFriendObjectKind()) 718 return getLexicalParent()->isDependentContext(); 719 } 720 721 return getParent() && getParent()->isDependentContext(); 722 } 723 724 bool DeclContext::isTransparentContext() const { 725 if (DeclKind == Decl::Enum) 726 return !cast<EnumDecl>(this)->isScoped(); 727 else if (DeclKind == Decl::LinkageSpec) 728 return true; 729 730 return false; 731 } 732 733 bool DeclContext::isExternCContext() const { 734 const DeclContext *DC = this; 735 while (DC->DeclKind != Decl::TranslationUnit) { 736 if (DC->DeclKind == Decl::LinkageSpec) 737 return cast<LinkageSpecDecl>(DC)->getLanguage() 738 == LinkageSpecDecl::lang_c; 739 DC = DC->getParent(); 740 } 741 return false; 742 } 743 744 bool DeclContext::Encloses(const DeclContext *DC) const { 745 if (getPrimaryContext() != this) 746 return getPrimaryContext()->Encloses(DC); 747 748 for (; DC; DC = DC->getParent()) 749 if (DC->getPrimaryContext() == this) 750 return true; 751 return false; 752 } 753 754 DeclContext *DeclContext::getPrimaryContext() { 755 switch (DeclKind) { 756 case Decl::TranslationUnit: 757 case Decl::LinkageSpec: 758 case Decl::Block: 759 // There is only one DeclContext for these entities. 760 return this; 761 762 case Decl::Namespace: 763 // The original namespace is our primary context. 764 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace(); 765 766 case Decl::ObjCMethod: 767 return this; 768 769 case Decl::ObjCInterface: 770 case Decl::ObjCProtocol: 771 case Decl::ObjCCategory: 772 // FIXME: Can Objective-C interfaces be forward-declared? 773 return this; 774 775 case Decl::ObjCImplementation: 776 case Decl::ObjCCategoryImpl: 777 return this; 778 779 default: 780 if (DeclKind >= Decl::firstTag && DeclKind <= Decl::lastTag) { 781 // If this is a tag type that has a definition or is currently 782 // being defined, that definition is our primary context. 783 TagDecl *Tag = cast<TagDecl>(this); 784 assert(isa<TagType>(Tag->TypeForDecl) || 785 isa<InjectedClassNameType>(Tag->TypeForDecl)); 786 787 if (TagDecl *Def = Tag->getDefinition()) 788 return Def; 789 790 if (!isa<InjectedClassNameType>(Tag->TypeForDecl)) { 791 const TagType *TagTy = cast<TagType>(Tag->TypeForDecl); 792 if (TagTy->isBeingDefined()) 793 // FIXME: is it necessarily being defined in the decl 794 // that owns the type? 795 return TagTy->getDecl(); 796 } 797 798 return Tag; 799 } 800 801 assert(DeclKind >= Decl::firstFunction && DeclKind <= Decl::lastFunction && 802 "Unknown DeclContext kind"); 803 return this; 804 } 805 } 806 807 DeclContext *DeclContext::getNextContext() { 808 switch (DeclKind) { 809 case Decl::Namespace: 810 // Return the next namespace 811 return static_cast<NamespaceDecl*>(this)->getNextNamespace(); 812 813 default: 814 return 0; 815 } 816 } 817 818 std::pair<Decl *, Decl *> 819 DeclContext::BuildDeclChain(const SmallVectorImpl<Decl*> &Decls, 820 bool FieldsAlreadyLoaded) { 821 // Build up a chain of declarations via the Decl::NextDeclInContext field. 822 Decl *FirstNewDecl = 0; 823 Decl *PrevDecl = 0; 824 for (unsigned I = 0, N = Decls.size(); I != N; ++I) { 825 if (FieldsAlreadyLoaded && isa<FieldDecl>(Decls[I])) 826 continue; 827 828 Decl *D = Decls[I]; 829 if (PrevDecl) 830 PrevDecl->NextDeclInContext = D; 831 else 832 FirstNewDecl = D; 833 834 PrevDecl = D; 835 } 836 837 return std::make_pair(FirstNewDecl, PrevDecl); 838 } 839 840 /// \brief Load the declarations within this lexical storage from an 841 /// external source. 842 void 843 DeclContext::LoadLexicalDeclsFromExternalStorage() const { 844 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 845 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 846 847 // Notify that we have a DeclContext that is initializing. 848 ExternalASTSource::Deserializing ADeclContext(Source); 849 850 // Load the external declarations, if any. 851 SmallVector<Decl*, 64> Decls; 852 ExternalLexicalStorage = false; 853 switch (Source->FindExternalLexicalDecls(this, Decls)) { 854 case ELR_Success: 855 break; 856 857 case ELR_Failure: 858 case ELR_AlreadyLoaded: 859 return; 860 } 861 862 if (Decls.empty()) 863 return; 864 865 // We may have already loaded just the fields of this record, in which case 866 // we need to ignore them. 867 bool FieldsAlreadyLoaded = false; 868 if (const RecordDecl *RD = dyn_cast<RecordDecl>(this)) 869 FieldsAlreadyLoaded = RD->LoadedFieldsFromExternalStorage; 870 871 // Splice the newly-read declarations into the beginning of the list 872 // of declarations. 873 Decl *ExternalFirst, *ExternalLast; 874 llvm::tie(ExternalFirst, ExternalLast) = BuildDeclChain(Decls, 875 FieldsAlreadyLoaded); 876 ExternalLast->NextDeclInContext = FirstDecl; 877 FirstDecl = ExternalFirst; 878 if (!LastDecl) 879 LastDecl = ExternalLast; 880 } 881 882 DeclContext::lookup_result 883 ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC, 884 DeclarationName Name) { 885 ASTContext &Context = DC->getParentASTContext(); 886 StoredDeclsMap *Map; 887 if (!(Map = DC->LookupPtr)) 888 Map = DC->CreateStoredDeclsMap(Context); 889 890 StoredDeclsList &List = (*Map)[Name]; 891 assert(List.isNull()); 892 (void) List; 893 894 return DeclContext::lookup_result(); 895 } 896 897 DeclContext::lookup_result 898 ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC, 899 DeclarationName Name, 900 ArrayRef<NamedDecl*> Decls) { 901 ASTContext &Context = DC->getParentASTContext();; 902 903 StoredDeclsMap *Map; 904 if (!(Map = DC->LookupPtr)) 905 Map = DC->CreateStoredDeclsMap(Context); 906 907 StoredDeclsList &List = (*Map)[Name]; 908 for (ArrayRef<NamedDecl*>::iterator 909 I = Decls.begin(), E = Decls.end(); I != E; ++I) { 910 if (List.isNull()) 911 List.setOnlyValue(*I); 912 else 913 List.AddSubsequentDecl(*I); 914 } 915 916 return List.getLookupResult(); 917 } 918 919 DeclContext::decl_iterator DeclContext::noload_decls_begin() const { 920 return decl_iterator(FirstDecl); 921 } 922 923 DeclContext::decl_iterator DeclContext::noload_decls_end() const { 924 return decl_iterator(); 925 } 926 927 DeclContext::decl_iterator DeclContext::decls_begin() const { 928 if (hasExternalLexicalStorage()) 929 LoadLexicalDeclsFromExternalStorage(); 930 931 return decl_iterator(FirstDecl); 932 } 933 934 DeclContext::decl_iterator DeclContext::decls_end() const { 935 if (hasExternalLexicalStorage()) 936 LoadLexicalDeclsFromExternalStorage(); 937 938 return decl_iterator(); 939 } 940 941 bool DeclContext::decls_empty() const { 942 if (hasExternalLexicalStorage()) 943 LoadLexicalDeclsFromExternalStorage(); 944 945 return !FirstDecl; 946 } 947 948 void DeclContext::removeDecl(Decl *D) { 949 assert(D->getLexicalDeclContext() == this && 950 "decl being removed from non-lexical context"); 951 assert((D->NextDeclInContext || D == LastDecl) && 952 "decl is not in decls list"); 953 954 // Remove D from the decl chain. This is O(n) but hopefully rare. 955 if (D == FirstDecl) { 956 if (D == LastDecl) 957 FirstDecl = LastDecl = 0; 958 else 959 FirstDecl = D->NextDeclInContext; 960 } else { 961 for (Decl *I = FirstDecl; true; I = I->NextDeclInContext) { 962 assert(I && "decl not found in linked list"); 963 if (I->NextDeclInContext == D) { 964 I->NextDeclInContext = D->NextDeclInContext; 965 if (D == LastDecl) LastDecl = I; 966 break; 967 } 968 } 969 } 970 971 // Mark that D is no longer in the decl chain. 972 D->NextDeclInContext = 0; 973 974 // Remove D from the lookup table if necessary. 975 if (isa<NamedDecl>(D)) { 976 NamedDecl *ND = cast<NamedDecl>(D); 977 978 // Remove only decls that have a name 979 if (!ND->getDeclName()) return; 980 981 StoredDeclsMap *Map = getPrimaryContext()->LookupPtr; 982 if (!Map) return; 983 984 StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName()); 985 assert(Pos != Map->end() && "no lookup entry for decl"); 986 Pos->second.remove(ND); 987 } 988 } 989 990 void DeclContext::addHiddenDecl(Decl *D) { 991 assert(D->getLexicalDeclContext() == this && 992 "Decl inserted into wrong lexical context"); 993 assert(!D->getNextDeclInContext() && D != LastDecl && 994 "Decl already inserted into a DeclContext"); 995 996 if (FirstDecl) { 997 LastDecl->NextDeclInContext = D; 998 LastDecl = D; 999 } else { 1000 FirstDecl = LastDecl = D; 1001 } 1002 1003 // Notify a C++ record declaration that we've added a member, so it can 1004 // update it's class-specific state. 1005 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(this)) 1006 Record->addedMember(D); 1007 } 1008 1009 void DeclContext::addDecl(Decl *D) { 1010 addHiddenDecl(D); 1011 1012 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1013 ND->getDeclContext()->makeDeclVisibleInContext(ND); 1014 } 1015 1016 /// buildLookup - Build the lookup data structure with all of the 1017 /// declarations in DCtx (and any other contexts linked to it or 1018 /// transparent contexts nested within it). 1019 void DeclContext::buildLookup(DeclContext *DCtx) { 1020 for (; DCtx; DCtx = DCtx->getNextContext()) { 1021 for (decl_iterator D = DCtx->decls_begin(), 1022 DEnd = DCtx->decls_end(); 1023 D != DEnd; ++D) { 1024 // Insert this declaration into the lookup structure, but only 1025 // if it's semantically in its decl context. During non-lazy 1026 // lookup building, this is implicitly enforced by addDecl. 1027 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D)) 1028 if (D->getDeclContext() == DCtx) 1029 makeDeclVisibleInContextImpl(ND); 1030 1031 // Insert any forward-declared Objective-C interface into the lookup 1032 // data structure. 1033 if (ObjCClassDecl *Class = dyn_cast<ObjCClassDecl>(*D)) 1034 makeDeclVisibleInContextImpl(Class->getForwardInterfaceDecl()); 1035 1036 // If this declaration is itself a transparent declaration context or 1037 // inline namespace, add its members (recursively). 1038 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D)) 1039 if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace()) 1040 buildLookup(InnerCtx->getPrimaryContext()); 1041 } 1042 } 1043 } 1044 1045 DeclContext::lookup_result 1046 DeclContext::lookup(DeclarationName Name) { 1047 DeclContext *PrimaryContext = getPrimaryContext(); 1048 if (PrimaryContext != this) 1049 return PrimaryContext->lookup(Name); 1050 1051 if (hasExternalVisibleStorage()) { 1052 // Check to see if we've already cached the lookup results. 1053 if (LookupPtr) { 1054 StoredDeclsMap::iterator I = LookupPtr->find(Name); 1055 if (I != LookupPtr->end()) 1056 return I->second.getLookupResult(); 1057 } 1058 1059 ExternalASTSource *Source = getParentASTContext().getExternalSource(); 1060 return Source->FindExternalVisibleDeclsByName(this, Name); 1061 } 1062 1063 /// If there is no lookup data structure, build one now by walking 1064 /// all of the linked DeclContexts (in declaration order!) and 1065 /// inserting their values. 1066 if (!LookupPtr) { 1067 buildLookup(this); 1068 1069 if (!LookupPtr) 1070 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1071 } 1072 1073 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 1074 if (Pos == LookupPtr->end()) 1075 return lookup_result(lookup_iterator(0), lookup_iterator(0)); 1076 return Pos->second.getLookupResult(); 1077 } 1078 1079 DeclContext::lookup_const_result 1080 DeclContext::lookup(DeclarationName Name) const { 1081 return const_cast<DeclContext*>(this)->lookup(Name); 1082 } 1083 1084 void DeclContext::localUncachedLookup(DeclarationName Name, 1085 llvm::SmallVectorImpl<NamedDecl *> &Results) { 1086 Results.clear(); 1087 1088 // If there's no external storage, just perform a normal lookup and copy 1089 // the results. 1090 if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage()) { 1091 lookup_result LookupResults = lookup(Name); 1092 Results.insert(Results.end(), LookupResults.first, LookupResults.second); 1093 return; 1094 } 1095 1096 // If we have a lookup table, check there first. Maybe we'll get lucky. 1097 if (LookupPtr) { 1098 StoredDeclsMap::iterator Pos = LookupPtr->find(Name); 1099 if (Pos != LookupPtr->end()) { 1100 Results.insert(Results.end(), 1101 Pos->second.getLookupResult().first, 1102 Pos->second.getLookupResult().second); 1103 return; 1104 } 1105 } 1106 1107 // Slow case: grovel through the declarations in our chain looking for 1108 // matches. 1109 for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) { 1110 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 1111 if (ND->getDeclName() == Name) 1112 Results.push_back(ND); 1113 } 1114 } 1115 1116 DeclContext *DeclContext::getRedeclContext() { 1117 DeclContext *Ctx = this; 1118 // Skip through transparent contexts. 1119 while (Ctx->isTransparentContext()) 1120 Ctx = Ctx->getParent(); 1121 return Ctx; 1122 } 1123 1124 DeclContext *DeclContext::getEnclosingNamespaceContext() { 1125 DeclContext *Ctx = this; 1126 // Skip through non-namespace, non-translation-unit contexts. 1127 while (!Ctx->isFileContext()) 1128 Ctx = Ctx->getParent(); 1129 return Ctx->getPrimaryContext(); 1130 } 1131 1132 bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const { 1133 // For non-file contexts, this is equivalent to Equals. 1134 if (!isFileContext()) 1135 return O->Equals(this); 1136 1137 do { 1138 if (O->Equals(this)) 1139 return true; 1140 1141 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(O); 1142 if (!NS || !NS->isInline()) 1143 break; 1144 O = NS->getParent(); 1145 } while (O); 1146 1147 return false; 1148 } 1149 1150 void DeclContext::makeDeclVisibleInContext(NamedDecl *D, bool Recoverable) { 1151 // FIXME: This feels like a hack. Should DeclarationName support 1152 // template-ids, or is there a better way to keep specializations 1153 // from being visible? 1154 if (isa<ClassTemplateSpecializationDecl>(D) || D->isTemplateParameter()) 1155 return; 1156 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 1157 if (FD->isFunctionTemplateSpecialization()) 1158 return; 1159 1160 DeclContext *PrimaryContext = getPrimaryContext(); 1161 if (PrimaryContext != this) { 1162 PrimaryContext->makeDeclVisibleInContext(D, Recoverable); 1163 return; 1164 } 1165 1166 // If we already have a lookup data structure, perform the insertion 1167 // into it. If we haven't deserialized externally stored decls, deserialize 1168 // them so we can add the decl. Otherwise, be lazy and don't build that 1169 // structure until someone asks for it. 1170 if (LookupPtr || !Recoverable || hasExternalVisibleStorage()) 1171 makeDeclVisibleInContextImpl(D); 1172 1173 // If we are a transparent context or inline namespace, insert into our 1174 // parent context, too. This operation is recursive. 1175 if (isTransparentContext() || isInlineNamespace()) 1176 getParent()->makeDeclVisibleInContext(D, Recoverable); 1177 1178 Decl *DCAsDecl = cast<Decl>(this); 1179 // Notify that a decl was made visible unless it's a Tag being defined. 1180 if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined())) 1181 if (ASTMutationListener *L = DCAsDecl->getASTMutationListener()) 1182 L->AddedVisibleDecl(this, D); 1183 } 1184 1185 void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) { 1186 // Skip unnamed declarations. 1187 if (!D->getDeclName()) 1188 return; 1189 1190 // Skip entities that can't be found by name lookup into a particular 1191 // context. 1192 if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) || 1193 D->isTemplateParameter()) 1194 return; 1195 1196 ASTContext *C = 0; 1197 if (!LookupPtr) { 1198 C = &getParentASTContext(); 1199 CreateStoredDeclsMap(*C); 1200 } 1201 1202 // If there is an external AST source, load any declarations it knows about 1203 // with this declaration's name. 1204 // If the lookup table contains an entry about this name it means that we 1205 // have already checked the external source. 1206 if (ExternalASTSource *Source = getParentASTContext().getExternalSource()) 1207 if (hasExternalVisibleStorage() && 1208 LookupPtr->find(D->getDeclName()) == LookupPtr->end()) 1209 Source->FindExternalVisibleDeclsByName(this, D->getDeclName()); 1210 1211 // Insert this declaration into the map. 1212 StoredDeclsList &DeclNameEntries = (*LookupPtr)[D->getDeclName()]; 1213 if (DeclNameEntries.isNull()) { 1214 DeclNameEntries.setOnlyValue(D); 1215 return; 1216 } 1217 1218 // If it is possible that this is a redeclaration, check to see if there is 1219 // already a decl for which declarationReplaces returns true. If there is 1220 // one, just replace it and return. 1221 if (DeclNameEntries.HandleRedeclaration(D)) 1222 return; 1223 1224 // Put this declaration into the appropriate slot. 1225 DeclNameEntries.AddSubsequentDecl(D); 1226 } 1227 1228 /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within 1229 /// this context. 1230 DeclContext::udir_iterator_range 1231 DeclContext::getUsingDirectives() const { 1232 lookup_const_result Result = lookup(UsingDirectiveDecl::getName()); 1233 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first), 1234 reinterpret_cast<udir_iterator>(Result.second)); 1235 } 1236 1237 //===----------------------------------------------------------------------===// 1238 // Creation and Destruction of StoredDeclsMaps. // 1239 //===----------------------------------------------------------------------===// 1240 1241 StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const { 1242 assert(!LookupPtr && "context already has a decls map"); 1243 assert(getPrimaryContext() == this && 1244 "creating decls map on non-primary context"); 1245 1246 StoredDeclsMap *M; 1247 bool Dependent = isDependentContext(); 1248 if (Dependent) 1249 M = new DependentStoredDeclsMap(); 1250 else 1251 M = new StoredDeclsMap(); 1252 M->Previous = C.LastSDM; 1253 C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent); 1254 LookupPtr = M; 1255 return M; 1256 } 1257 1258 void ASTContext::ReleaseDeclContextMaps() { 1259 // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap 1260 // pointer because the subclass doesn't add anything that needs to 1261 // be deleted. 1262 StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt()); 1263 } 1264 1265 void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) { 1266 while (Map) { 1267 // Advance the iteration before we invalidate memory. 1268 llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous; 1269 1270 if (Dependent) 1271 delete static_cast<DependentStoredDeclsMap*>(Map); 1272 else 1273 delete Map; 1274 1275 Map = Next.getPointer(); 1276 Dependent = Next.getInt(); 1277 } 1278 } 1279 1280 DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C, 1281 DeclContext *Parent, 1282 const PartialDiagnostic &PDiag) { 1283 assert(Parent->isDependentContext() 1284 && "cannot iterate dependent diagnostics of non-dependent context"); 1285 Parent = Parent->getPrimaryContext(); 1286 if (!Parent->LookupPtr) 1287 Parent->CreateStoredDeclsMap(C); 1288 1289 DependentStoredDeclsMap *Map 1290 = static_cast<DependentStoredDeclsMap*>(Parent->LookupPtr); 1291 1292 // Allocate the copy of the PartialDiagnostic via the ASTContext's 1293 // BumpPtrAllocator, rather than the ASTContext itself. 1294 PartialDiagnostic::Storage *DiagStorage = 0; 1295 if (PDiag.hasStorage()) 1296 DiagStorage = new (C) PartialDiagnostic::Storage; 1297 1298 DependentDiagnostic *DD = new (C) DependentDiagnostic(PDiag, DiagStorage); 1299 1300 // TODO: Maybe we shouldn't reverse the order during insertion. 1301 DD->NextDiagnostic = Map->FirstDiagnostic; 1302 Map->FirstDiagnostic = DD; 1303 1304 return DD; 1305 } 1306