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