1 //===- DeclObjC.cpp - ObjC Declaration AST Node Implementation ------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the Objective-C related Decl classes. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/DeclObjC.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/ASTMutationListener.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/Decl.h" 18 #include "clang/AST/DeclBase.h" 19 #include "clang/AST/Stmt.h" 20 #include "clang/AST/Type.h" 21 #include "clang/AST/TypeLoc.h" 22 #include "clang/Basic/IdentifierTable.h" 23 #include "clang/Basic/LLVM.h" 24 #include "clang/Basic/LangOptions.h" 25 #include "clang/Basic/SourceLocation.h" 26 #include "llvm/ADT/None.h" 27 #include "llvm/ADT/SmallString.h" 28 #include "llvm/ADT/SmallVector.h" 29 #include "llvm/Support/Casting.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/raw_ostream.h" 32 #include <algorithm> 33 #include <cassert> 34 #include <cstdint> 35 #include <cstring> 36 #include <utility> 37 38 using namespace clang; 39 40 //===----------------------------------------------------------------------===// 41 // ObjCListBase 42 //===----------------------------------------------------------------------===// 43 44 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { 45 List = nullptr; 46 if (Elts == 0) return; // Setting to an empty list is a noop. 47 48 List = new (Ctx) void*[Elts]; 49 NumElts = Elts; 50 memcpy(List, InList, sizeof(void*)*Elts); 51 } 52 53 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, 54 const SourceLocation *Locs, ASTContext &Ctx) { 55 if (Elts == 0) 56 return; 57 58 Locations = new (Ctx) SourceLocation[Elts]; 59 memcpy(Locations, Locs, sizeof(SourceLocation) * Elts); 60 set(InList, Elts, Ctx); 61 } 62 63 //===----------------------------------------------------------------------===// 64 // ObjCInterfaceDecl 65 //===----------------------------------------------------------------------===// 66 67 ObjCContainerDecl::ObjCContainerDecl(Kind DK, DeclContext *DC, 68 IdentifierInfo *Id, SourceLocation nameLoc, 69 SourceLocation atStartLoc) 70 : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK) { 71 setAtStartLoc(atStartLoc); 72 } 73 74 void ObjCContainerDecl::anchor() {} 75 76 /// getIvarDecl - This method looks up an ivar in this ContextDecl. 77 /// 78 ObjCIvarDecl * 79 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const { 80 lookup_result R = lookup(Id); 81 for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end(); 82 Ivar != IvarEnd; ++Ivar) { 83 if (auto *ivar = dyn_cast<ObjCIvarDecl>(*Ivar)) 84 return ivar; 85 } 86 return nullptr; 87 } 88 89 // Get the local instance/class method declared in this interface. 90 ObjCMethodDecl * 91 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance, 92 bool AllowHidden) const { 93 // If this context is a hidden protocol definition, don't find any 94 // methods there. 95 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) { 96 if (const ObjCProtocolDecl *Def = Proto->getDefinition()) 97 if (!Def->isUnconditionallyVisible() && !AllowHidden) 98 return nullptr; 99 } 100 101 // Since instance & class methods can have the same name, the loop below 102 // ensures we get the correct method. 103 // 104 // @interface Whatever 105 // - (int) class_method; 106 // + (float) class_method; 107 // @end 108 lookup_result R = lookup(Sel); 109 for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); 110 Meth != MethEnd; ++Meth) { 111 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth); 112 if (MD && MD->isInstanceMethod() == isInstance) 113 return MD; 114 } 115 return nullptr; 116 } 117 118 /// This routine returns 'true' if a user declared setter method was 119 /// found in the class, its protocols, its super classes or categories. 120 /// It also returns 'true' if one of its categories has declared a 'readwrite' 121 /// property. This is because, user must provide a setter method for the 122 /// category's 'readwrite' property. 123 bool ObjCContainerDecl::HasUserDeclaredSetterMethod( 124 const ObjCPropertyDecl *Property) const { 125 Selector Sel = Property->getSetterName(); 126 lookup_result R = lookup(Sel); 127 for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); 128 Meth != MethEnd; ++Meth) { 129 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth); 130 if (MD && MD->isInstanceMethod() && !MD->isImplicit()) 131 return true; 132 } 133 134 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) { 135 // Also look into categories, including class extensions, looking 136 // for a user declared instance method. 137 for (const auto *Cat : ID->visible_categories()) { 138 if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel)) 139 if (!MD->isImplicit()) 140 return true; 141 if (Cat->IsClassExtension()) 142 continue; 143 // Also search through the categories looking for a 'readwrite' 144 // declaration of this property. If one found, presumably a setter will 145 // be provided (properties declared in categories will not get 146 // auto-synthesized). 147 for (const auto *P : Cat->properties()) 148 if (P->getIdentifier() == Property->getIdentifier()) { 149 if (P->getPropertyAttributes() & 150 ObjCPropertyAttribute::kind_readwrite) 151 return true; 152 break; 153 } 154 } 155 156 // Also look into protocols, for a user declared instance method. 157 for (const auto *Proto : ID->all_referenced_protocols()) 158 if (Proto->HasUserDeclaredSetterMethod(Property)) 159 return true; 160 161 // And in its super class. 162 ObjCInterfaceDecl *OSC = ID->getSuperClass(); 163 while (OSC) { 164 if (OSC->HasUserDeclaredSetterMethod(Property)) 165 return true; 166 OSC = OSC->getSuperClass(); 167 } 168 } 169 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(this)) 170 for (const auto *PI : PD->protocols()) 171 if (PI->HasUserDeclaredSetterMethod(Property)) 172 return true; 173 return false; 174 } 175 176 ObjCPropertyDecl * 177 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC, 178 const IdentifierInfo *propertyID, 179 ObjCPropertyQueryKind queryKind) { 180 // If this context is a hidden protocol definition, don't find any 181 // property. 182 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(DC)) { 183 if (const ObjCProtocolDecl *Def = Proto->getDefinition()) 184 if (!Def->isUnconditionallyVisible()) 185 return nullptr; 186 } 187 188 // If context is class, then lookup property in its visible extensions. 189 // This comes before property is looked up in primary class. 190 if (auto *IDecl = dyn_cast<ObjCInterfaceDecl>(DC)) { 191 for (const auto *Ext : IDecl->visible_extensions()) 192 if (ObjCPropertyDecl *PD = ObjCPropertyDecl::findPropertyDecl(Ext, 193 propertyID, 194 queryKind)) 195 return PD; 196 } 197 198 DeclContext::lookup_result R = DC->lookup(propertyID); 199 ObjCPropertyDecl *classProp = nullptr; 200 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 201 ++I) 202 if (auto *PD = dyn_cast<ObjCPropertyDecl>(*I)) { 203 // If queryKind is unknown, we return the instance property if one 204 // exists; otherwise we return the class property. 205 if ((queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown && 206 !PD->isClassProperty()) || 207 (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_class && 208 PD->isClassProperty()) || 209 (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance && 210 !PD->isClassProperty())) 211 return PD; 212 213 if (PD->isClassProperty()) 214 classProp = PD; 215 } 216 217 if (queryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown) 218 // We can't find the instance property, return the class property. 219 return classProp; 220 221 return nullptr; 222 } 223 224 IdentifierInfo * 225 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const { 226 SmallString<128> ivarName; 227 { 228 llvm::raw_svector_ostream os(ivarName); 229 os << '_' << getIdentifier()->getName(); 230 } 231 return &Ctx.Idents.get(ivarName.str()); 232 } 233 234 /// FindPropertyDeclaration - Finds declaration of the property given its name 235 /// in 'PropertyId' and returns it. It returns 0, if not found. 236 ObjCPropertyDecl *ObjCContainerDecl::FindPropertyDeclaration( 237 const IdentifierInfo *PropertyId, 238 ObjCPropertyQueryKind QueryKind) const { 239 // Don't find properties within hidden protocol definitions. 240 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) { 241 if (const ObjCProtocolDecl *Def = Proto->getDefinition()) 242 if (!Def->isUnconditionallyVisible()) 243 return nullptr; 244 } 245 246 // Search the extensions of a class first; they override what's in 247 // the class itself. 248 if (const auto *ClassDecl = dyn_cast<ObjCInterfaceDecl>(this)) { 249 for (const auto *Ext : ClassDecl->visible_extensions()) { 250 if (auto *P = Ext->FindPropertyDeclaration(PropertyId, QueryKind)) 251 return P; 252 } 253 } 254 255 if (ObjCPropertyDecl *PD = 256 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId, 257 QueryKind)) 258 return PD; 259 260 switch (getKind()) { 261 default: 262 break; 263 case Decl::ObjCProtocol: { 264 const auto *PID = cast<ObjCProtocolDecl>(this); 265 for (const auto *I : PID->protocols()) 266 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 267 QueryKind)) 268 return P; 269 break; 270 } 271 case Decl::ObjCInterface: { 272 const auto *OID = cast<ObjCInterfaceDecl>(this); 273 // Look through categories (but not extensions; they were handled above). 274 for (const auto *Cat : OID->visible_categories()) { 275 if (!Cat->IsClassExtension()) 276 if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration( 277 PropertyId, QueryKind)) 278 return P; 279 } 280 281 // Look through protocols. 282 for (const auto *I : OID->all_referenced_protocols()) 283 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 284 QueryKind)) 285 return P; 286 287 // Finally, check the super class. 288 if (const ObjCInterfaceDecl *superClass = OID->getSuperClass()) 289 return superClass->FindPropertyDeclaration(PropertyId, QueryKind); 290 break; 291 } 292 case Decl::ObjCCategory: { 293 const auto *OCD = cast<ObjCCategoryDecl>(this); 294 // Look through protocols. 295 if (!OCD->IsClassExtension()) 296 for (const auto *I : OCD->protocols()) 297 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 298 QueryKind)) 299 return P; 300 break; 301 } 302 } 303 return nullptr; 304 } 305 306 void ObjCInterfaceDecl::anchor() {} 307 308 ObjCTypeParamList *ObjCInterfaceDecl::getTypeParamList() const { 309 // If this particular declaration has a type parameter list, return it. 310 if (ObjCTypeParamList *written = getTypeParamListAsWritten()) 311 return written; 312 313 // If there is a definition, return its type parameter list. 314 if (const ObjCInterfaceDecl *def = getDefinition()) 315 return def->getTypeParamListAsWritten(); 316 317 // Otherwise, look at previous declarations to determine whether any 318 // of them has a type parameter list, skipping over those 319 // declarations that do not. 320 for (const ObjCInterfaceDecl *decl = getMostRecentDecl(); decl; 321 decl = decl->getPreviousDecl()) { 322 if (ObjCTypeParamList *written = decl->getTypeParamListAsWritten()) 323 return written; 324 } 325 326 return nullptr; 327 } 328 329 void ObjCInterfaceDecl::setTypeParamList(ObjCTypeParamList *TPL) { 330 TypeParamList = TPL; 331 if (!TPL) 332 return; 333 // Set the declaration context of each of the type parameters. 334 for (auto *typeParam : *TypeParamList) 335 typeParam->setDeclContext(this); 336 } 337 338 ObjCInterfaceDecl *ObjCInterfaceDecl::getSuperClass() const { 339 // FIXME: Should make sure no callers ever do this. 340 if (!hasDefinition()) 341 return nullptr; 342 343 if (data().ExternallyCompleted) 344 LoadExternalDefinition(); 345 346 if (const ObjCObjectType *superType = getSuperClassType()) { 347 if (ObjCInterfaceDecl *superDecl = superType->getInterface()) { 348 if (ObjCInterfaceDecl *superDef = superDecl->getDefinition()) 349 return superDef; 350 351 return superDecl; 352 } 353 } 354 355 return nullptr; 356 } 357 358 SourceLocation ObjCInterfaceDecl::getSuperClassLoc() const { 359 if (TypeSourceInfo *superTInfo = getSuperClassTInfo()) 360 return superTInfo->getTypeLoc().getBeginLoc(); 361 362 return SourceLocation(); 363 } 364 365 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property 366 /// with name 'PropertyId' in the primary class; including those in protocols 367 /// (direct or indirect) used by the primary class. 368 ObjCPropertyDecl * 369 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass( 370 IdentifierInfo *PropertyId, 371 ObjCPropertyQueryKind QueryKind) const { 372 // FIXME: Should make sure no callers ever do this. 373 if (!hasDefinition()) 374 return nullptr; 375 376 if (data().ExternallyCompleted) 377 LoadExternalDefinition(); 378 379 if (ObjCPropertyDecl *PD = 380 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId, 381 QueryKind)) 382 return PD; 383 384 // Look through protocols. 385 for (const auto *I : all_referenced_protocols()) 386 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId, 387 QueryKind)) 388 return P; 389 390 return nullptr; 391 } 392 393 void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM, 394 PropertyDeclOrder &PO) const { 395 for (auto *Prop : properties()) { 396 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; 397 PO.push_back(Prop); 398 } 399 for (const auto *Ext : known_extensions()) { 400 const ObjCCategoryDecl *ClassExt = Ext; 401 for (auto *Prop : ClassExt->properties()) { 402 PM[std::make_pair(Prop->getIdentifier(), Prop->isClassProperty())] = Prop; 403 PO.push_back(Prop); 404 } 405 } 406 for (const auto *PI : all_referenced_protocols()) 407 PI->collectPropertiesToImplement(PM, PO); 408 // Note, the properties declared only in class extensions are still copied 409 // into the main @interface's property list, and therefore we don't 410 // explicitly, have to search class extension properties. 411 } 412 413 bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const { 414 const ObjCInterfaceDecl *Class = this; 415 while (Class) { 416 if (Class->hasAttr<ArcWeakrefUnavailableAttr>()) 417 return true; 418 Class = Class->getSuperClass(); 419 } 420 return false; 421 } 422 423 const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const { 424 const ObjCInterfaceDecl *Class = this; 425 while (Class) { 426 if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>()) 427 return Class; 428 Class = Class->getSuperClass(); 429 } 430 return nullptr; 431 } 432 433 void ObjCInterfaceDecl::mergeClassExtensionProtocolList( 434 ObjCProtocolDecl *const* ExtList, unsigned ExtNum, 435 ASTContext &C) { 436 if (data().ExternallyCompleted) 437 LoadExternalDefinition(); 438 439 if (data().AllReferencedProtocols.empty() && 440 data().ReferencedProtocols.empty()) { 441 data().AllReferencedProtocols.set(ExtList, ExtNum, C); 442 return; 443 } 444 445 // Check for duplicate protocol in class's protocol list. 446 // This is O(n*m). But it is extremely rare and number of protocols in 447 // class or its extension are very few. 448 SmallVector<ObjCProtocolDecl *, 8> ProtocolRefs; 449 for (unsigned i = 0; i < ExtNum; i++) { 450 bool protocolExists = false; 451 ObjCProtocolDecl *ProtoInExtension = ExtList[i]; 452 for (auto *Proto : all_referenced_protocols()) { 453 if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) { 454 protocolExists = true; 455 break; 456 } 457 } 458 // Do we want to warn on a protocol in extension class which 459 // already exist in the class? Probably not. 460 if (!protocolExists) 461 ProtocolRefs.push_back(ProtoInExtension); 462 } 463 464 if (ProtocolRefs.empty()) 465 return; 466 467 // Merge ProtocolRefs into class's protocol list; 468 ProtocolRefs.append(all_referenced_protocol_begin(), 469 all_referenced_protocol_end()); 470 471 data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C); 472 } 473 474 const ObjCInterfaceDecl * 475 ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const { 476 const ObjCInterfaceDecl *IFace = this; 477 while (IFace) { 478 if (IFace->hasDesignatedInitializers()) 479 return IFace; 480 if (!IFace->inheritsDesignatedInitializers()) 481 break; 482 IFace = IFace->getSuperClass(); 483 } 484 return nullptr; 485 } 486 487 static bool isIntroducingInitializers(const ObjCInterfaceDecl *D) { 488 for (const auto *MD : D->instance_methods()) { 489 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) 490 return true; 491 } 492 for (const auto *Ext : D->visible_extensions()) { 493 for (const auto *MD : Ext->instance_methods()) { 494 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) 495 return true; 496 } 497 } 498 if (const auto *ImplD = D->getImplementation()) { 499 for (const auto *MD : ImplD->instance_methods()) { 500 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) 501 return true; 502 } 503 } 504 return false; 505 } 506 507 bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const { 508 switch (data().InheritedDesignatedInitializers) { 509 case DefinitionData::IDI_Inherited: 510 return true; 511 case DefinitionData::IDI_NotInherited: 512 return false; 513 case DefinitionData::IDI_Unknown: 514 // If the class introduced initializers we conservatively assume that we 515 // don't know if any of them is a designated initializer to avoid possible 516 // misleading warnings. 517 if (isIntroducingInitializers(this)) { 518 data().InheritedDesignatedInitializers = DefinitionData::IDI_NotInherited; 519 } else { 520 if (auto SuperD = getSuperClass()) { 521 data().InheritedDesignatedInitializers = 522 SuperD->declaresOrInheritsDesignatedInitializers() ? 523 DefinitionData::IDI_Inherited : 524 DefinitionData::IDI_NotInherited; 525 } else { 526 data().InheritedDesignatedInitializers = 527 DefinitionData::IDI_NotInherited; 528 } 529 } 530 assert(data().InheritedDesignatedInitializers 531 != DefinitionData::IDI_Unknown); 532 return data().InheritedDesignatedInitializers == 533 DefinitionData::IDI_Inherited; 534 } 535 536 llvm_unreachable("unexpected InheritedDesignatedInitializers value"); 537 } 538 539 void ObjCInterfaceDecl::getDesignatedInitializers( 540 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const { 541 // Check for a complete definition and recover if not so. 542 if (!isThisDeclarationADefinition()) 543 return; 544 if (data().ExternallyCompleted) 545 LoadExternalDefinition(); 546 547 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers(); 548 if (!IFace) 549 return; 550 551 for (const auto *MD : IFace->instance_methods()) 552 if (MD->isThisDeclarationADesignatedInitializer()) 553 Methods.push_back(MD); 554 for (const auto *Ext : IFace->visible_extensions()) { 555 for (const auto *MD : Ext->instance_methods()) 556 if (MD->isThisDeclarationADesignatedInitializer()) 557 Methods.push_back(MD); 558 } 559 } 560 561 bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel, 562 const ObjCMethodDecl **InitMethod) const { 563 bool HasCompleteDef = isThisDeclarationADefinition(); 564 // During deserialization the data record for the ObjCInterfaceDecl could 565 // be made invariant by reusing the canonical decl. Take this into account 566 // when checking for the complete definition. 567 if (!HasCompleteDef && getCanonicalDecl()->hasDefinition() && 568 getCanonicalDecl()->getDefinition() == getDefinition()) 569 HasCompleteDef = true; 570 571 // Check for a complete definition and recover if not so. 572 if (!HasCompleteDef) 573 return false; 574 575 if (data().ExternallyCompleted) 576 LoadExternalDefinition(); 577 578 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers(); 579 if (!IFace) 580 return false; 581 582 if (const ObjCMethodDecl *MD = IFace->getInstanceMethod(Sel)) { 583 if (MD->isThisDeclarationADesignatedInitializer()) { 584 if (InitMethod) 585 *InitMethod = MD; 586 return true; 587 } 588 } 589 for (const auto *Ext : IFace->visible_extensions()) { 590 if (const ObjCMethodDecl *MD = Ext->getInstanceMethod(Sel)) { 591 if (MD->isThisDeclarationADesignatedInitializer()) { 592 if (InitMethod) 593 *InitMethod = MD; 594 return true; 595 } 596 } 597 } 598 return false; 599 } 600 601 void ObjCInterfaceDecl::allocateDefinitionData() { 602 assert(!hasDefinition() && "ObjC class already has a definition"); 603 Data.setPointer(new (getASTContext()) DefinitionData()); 604 Data.getPointer()->Definition = this; 605 606 // Make the type point at the definition, now that we have one. 607 if (TypeForDecl) 608 cast<ObjCInterfaceType>(TypeForDecl)->Decl = this; 609 } 610 611 void ObjCInterfaceDecl::startDefinition() { 612 allocateDefinitionData(); 613 614 // Update all of the declarations with a pointer to the definition. 615 for (auto *RD : redecls()) { 616 if (RD != this) 617 RD->Data = Data; 618 } 619 } 620 621 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID, 622 ObjCInterfaceDecl *&clsDeclared) { 623 // FIXME: Should make sure no callers ever do this. 624 if (!hasDefinition()) 625 return nullptr; 626 627 if (data().ExternallyCompleted) 628 LoadExternalDefinition(); 629 630 ObjCInterfaceDecl* ClassDecl = this; 631 while (ClassDecl != nullptr) { 632 if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) { 633 clsDeclared = ClassDecl; 634 return I; 635 } 636 637 for (const auto *Ext : ClassDecl->visible_extensions()) { 638 if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) { 639 clsDeclared = ClassDecl; 640 return I; 641 } 642 } 643 644 ClassDecl = ClassDecl->getSuperClass(); 645 } 646 return nullptr; 647 } 648 649 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super 650 /// class whose name is passed as argument. If it is not one of the super classes 651 /// the it returns NULL. 652 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass( 653 const IdentifierInfo*ICName) { 654 // FIXME: Should make sure no callers ever do this. 655 if (!hasDefinition()) 656 return nullptr; 657 658 if (data().ExternallyCompleted) 659 LoadExternalDefinition(); 660 661 ObjCInterfaceDecl* ClassDecl = this; 662 while (ClassDecl != nullptr) { 663 if (ClassDecl->getIdentifier() == ICName) 664 return ClassDecl; 665 ClassDecl = ClassDecl->getSuperClass(); 666 } 667 return nullptr; 668 } 669 670 ObjCProtocolDecl * 671 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) { 672 for (auto *P : all_referenced_protocols()) 673 if (P->lookupProtocolNamed(Name)) 674 return P; 675 ObjCInterfaceDecl *SuperClass = getSuperClass(); 676 return SuperClass ? SuperClass->lookupNestedProtocol(Name) : nullptr; 677 } 678 679 /// lookupMethod - This method returns an instance/class method by looking in 680 /// the class, its categories, and its super classes (using a linear search). 681 /// When argument category "C" is specified, any implicit method found 682 /// in this category is ignored. 683 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel, 684 bool isInstance, 685 bool shallowCategoryLookup, 686 bool followSuper, 687 const ObjCCategoryDecl *C) const 688 { 689 // FIXME: Should make sure no callers ever do this. 690 if (!hasDefinition()) 691 return nullptr; 692 693 const ObjCInterfaceDecl* ClassDecl = this; 694 ObjCMethodDecl *MethodDecl = nullptr; 695 696 if (data().ExternallyCompleted) 697 LoadExternalDefinition(); 698 699 while (ClassDecl) { 700 // 1. Look through primary class. 701 if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance))) 702 return MethodDecl; 703 704 // 2. Didn't find one yet - now look through categories. 705 for (const auto *Cat : ClassDecl->visible_categories()) 706 if ((MethodDecl = Cat->getMethod(Sel, isInstance))) 707 if (C != Cat || !MethodDecl->isImplicit()) 708 return MethodDecl; 709 710 // 3. Didn't find one yet - look through primary class's protocols. 711 for (const auto *I : ClassDecl->protocols()) 712 if ((MethodDecl = I->lookupMethod(Sel, isInstance))) 713 return MethodDecl; 714 715 // 4. Didn't find one yet - now look through categories' protocols 716 if (!shallowCategoryLookup) 717 for (const auto *Cat : ClassDecl->visible_categories()) { 718 // Didn't find one yet - look through protocols. 719 const ObjCList<ObjCProtocolDecl> &Protocols = 720 Cat->getReferencedProtocols(); 721 for (auto *Protocol : Protocols) 722 if ((MethodDecl = Protocol->lookupMethod(Sel, isInstance))) 723 if (C != Cat || !MethodDecl->isImplicit()) 724 return MethodDecl; 725 } 726 727 728 if (!followSuper) 729 return nullptr; 730 731 // 5. Get to the super class (if any). 732 ClassDecl = ClassDecl->getSuperClass(); 733 } 734 return nullptr; 735 } 736 737 // Will search "local" class/category implementations for a method decl. 738 // If failed, then we search in class's root for an instance method. 739 // Returns 0 if no method is found. 740 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod( 741 const Selector &Sel, 742 bool Instance) const { 743 // FIXME: Should make sure no callers ever do this. 744 if (!hasDefinition()) 745 return nullptr; 746 747 if (data().ExternallyCompleted) 748 LoadExternalDefinition(); 749 750 ObjCMethodDecl *Method = nullptr; 751 if (ObjCImplementationDecl *ImpDecl = getImplementation()) 752 Method = Instance ? ImpDecl->getInstanceMethod(Sel) 753 : ImpDecl->getClassMethod(Sel); 754 755 // Look through local category implementations associated with the class. 756 if (!Method) 757 Method = getCategoryMethod(Sel, Instance); 758 759 // Before we give up, check if the selector is an instance method. 760 // But only in the root. This matches gcc's behavior and what the 761 // runtime expects. 762 if (!Instance && !Method && !getSuperClass()) { 763 Method = lookupInstanceMethod(Sel); 764 // Look through local category implementations associated 765 // with the root class. 766 if (!Method) 767 Method = lookupPrivateMethod(Sel, true); 768 } 769 770 if (!Method && getSuperClass()) 771 return getSuperClass()->lookupPrivateMethod(Sel, Instance); 772 return Method; 773 } 774 775 //===----------------------------------------------------------------------===// 776 // ObjCMethodDecl 777 //===----------------------------------------------------------------------===// 778 779 ObjCMethodDecl::ObjCMethodDecl( 780 SourceLocation beginLoc, SourceLocation endLoc, Selector SelInfo, 781 QualType T, TypeSourceInfo *ReturnTInfo, DeclContext *contextDecl, 782 bool isInstance, bool isVariadic, bool isPropertyAccessor, 783 bool isSynthesizedAccessorStub, bool isImplicitlyDeclared, bool isDefined, 784 ImplementationControl impControl, bool HasRelatedResultType) 785 : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo), 786 DeclContext(ObjCMethod), MethodDeclType(T), ReturnTInfo(ReturnTInfo), 787 DeclEndLoc(endLoc) { 788 789 // Initialized the bits stored in DeclContext. 790 ObjCMethodDeclBits.Family = 791 static_cast<ObjCMethodFamily>(InvalidObjCMethodFamily); 792 setInstanceMethod(isInstance); 793 setVariadic(isVariadic); 794 setPropertyAccessor(isPropertyAccessor); 795 setSynthesizedAccessorStub(isSynthesizedAccessorStub); 796 setDefined(isDefined); 797 setIsRedeclaration(false); 798 setHasRedeclaration(false); 799 setDeclImplementation(impControl); 800 setObjCDeclQualifier(OBJC_TQ_None); 801 setRelatedResultType(HasRelatedResultType); 802 setSelLocsKind(SelLoc_StandardNoSpace); 803 setOverriding(false); 804 setHasSkippedBody(false); 805 806 setImplicit(isImplicitlyDeclared); 807 } 808 809 ObjCMethodDecl *ObjCMethodDecl::Create( 810 ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, 811 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, 812 DeclContext *contextDecl, bool isInstance, bool isVariadic, 813 bool isPropertyAccessor, bool isSynthesizedAccessorStub, 814 bool isImplicitlyDeclared, bool isDefined, ImplementationControl impControl, 815 bool HasRelatedResultType) { 816 return new (C, contextDecl) ObjCMethodDecl( 817 beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance, 818 isVariadic, isPropertyAccessor, isSynthesizedAccessorStub, 819 isImplicitlyDeclared, isDefined, impControl, HasRelatedResultType); 820 } 821 822 ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 823 return new (C, ID) ObjCMethodDecl(SourceLocation(), SourceLocation(), 824 Selector(), QualType(), nullptr, nullptr); 825 } 826 827 bool ObjCMethodDecl::isDirectMethod() const { 828 return hasAttr<ObjCDirectAttr>(); 829 } 830 831 bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const { 832 return getMethodFamily() == OMF_init && 833 hasAttr<ObjCDesignatedInitializerAttr>(); 834 } 835 836 bool ObjCMethodDecl::definedInNSObject(const ASTContext &Ctx) const { 837 if (const auto *PD = dyn_cast<const ObjCProtocolDecl>(getDeclContext())) 838 return PD->getIdentifier() == Ctx.getNSObjectName(); 839 if (const auto *ID = dyn_cast<const ObjCInterfaceDecl>(getDeclContext())) 840 return ID->getIdentifier() == Ctx.getNSObjectName(); 841 return false; 842 } 843 844 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface( 845 const ObjCMethodDecl **InitMethod) const { 846 if (getMethodFamily() != OMF_init) 847 return false; 848 const DeclContext *DC = getDeclContext(); 849 if (isa<ObjCProtocolDecl>(DC)) 850 return false; 851 if (const ObjCInterfaceDecl *ID = getClassInterface()) 852 return ID->isDesignatedInitializer(getSelector(), InitMethod); 853 return false; 854 } 855 856 Stmt *ObjCMethodDecl::getBody() const { 857 return Body.get(getASTContext().getExternalSource()); 858 } 859 860 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) { 861 assert(PrevMethod); 862 getASTContext().setObjCMethodRedeclaration(PrevMethod, this); 863 setIsRedeclaration(true); 864 PrevMethod->setHasRedeclaration(true); 865 } 866 867 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C, 868 ArrayRef<ParmVarDecl*> Params, 869 ArrayRef<SourceLocation> SelLocs) { 870 ParamsAndSelLocs = nullptr; 871 NumParams = Params.size(); 872 if (Params.empty() && SelLocs.empty()) 873 return; 874 875 static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation), 876 "Alignment not sufficient for SourceLocation"); 877 878 unsigned Size = sizeof(ParmVarDecl *) * NumParams + 879 sizeof(SourceLocation) * SelLocs.size(); 880 ParamsAndSelLocs = C.Allocate(Size); 881 std::copy(Params.begin(), Params.end(), getParams()); 882 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs()); 883 } 884 885 void ObjCMethodDecl::getSelectorLocs( 886 SmallVectorImpl<SourceLocation> &SelLocs) const { 887 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) 888 SelLocs.push_back(getSelectorLoc(i)); 889 } 890 891 void ObjCMethodDecl::setMethodParams(ASTContext &C, 892 ArrayRef<ParmVarDecl*> Params, 893 ArrayRef<SourceLocation> SelLocs) { 894 assert((!SelLocs.empty() || isImplicit()) && 895 "No selector locs for non-implicit method"); 896 if (isImplicit()) 897 return setParamsAndSelLocs(C, Params, llvm::None); 898 899 setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params, 900 DeclEndLoc)); 901 if (getSelLocsKind() != SelLoc_NonStandard) 902 return setParamsAndSelLocs(C, Params, llvm::None); 903 904 setParamsAndSelLocs(C, Params, SelLocs); 905 } 906 907 /// A definition will return its interface declaration. 908 /// An interface declaration will return its definition. 909 /// Otherwise it will return itself. 910 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() { 911 ASTContext &Ctx = getASTContext(); 912 ObjCMethodDecl *Redecl = nullptr; 913 if (hasRedeclaration()) 914 Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this)); 915 if (Redecl) 916 return Redecl; 917 918 auto *CtxD = cast<Decl>(getDeclContext()); 919 920 if (!CtxD->isInvalidDecl()) { 921 if (auto *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) { 922 if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD)) 923 if (!ImplD->isInvalidDecl()) 924 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 925 926 } else if (auto *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) { 927 if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD)) 928 if (!ImplD->isInvalidDecl()) 929 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 930 931 } else if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 932 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 933 if (!IFD->isInvalidDecl()) 934 Redecl = IFD->getMethod(getSelector(), isInstanceMethod()); 935 936 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 937 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 938 if (!CatD->isInvalidDecl()) 939 Redecl = CatD->getMethod(getSelector(), isInstanceMethod()); 940 } 941 } 942 943 // Ensure that the discovered method redeclaration has a valid declaration 944 // context. Used to prevent infinite loops when iterating redeclarations in 945 // a partially invalid AST. 946 if (Redecl && cast<Decl>(Redecl->getDeclContext())->isInvalidDecl()) 947 Redecl = nullptr; 948 949 if (!Redecl && isRedeclaration()) { 950 // This is the last redeclaration, go back to the first method. 951 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(), 952 isInstanceMethod()); 953 } 954 955 return Redecl ? Redecl : this; 956 } 957 958 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() { 959 auto *CtxD = cast<Decl>(getDeclContext()); 960 const auto &Sel = getSelector(); 961 962 if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 963 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) { 964 // When the container is the ObjCImplementationDecl (the primary 965 // @implementation), then the canonical Decl is either in 966 // the class Interface, or in any of its extension. 967 // 968 // So when we don't find it in the ObjCInterfaceDecl, 969 // sift through extensions too. 970 if (ObjCMethodDecl *MD = IFD->getMethod(Sel, isInstanceMethod())) 971 return MD; 972 for (auto *Ext : IFD->known_extensions()) 973 if (ObjCMethodDecl *MD = Ext->getMethod(Sel, isInstanceMethod())) 974 return MD; 975 } 976 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 977 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 978 if (ObjCMethodDecl *MD = CatD->getMethod(Sel, isInstanceMethod())) 979 return MD; 980 } 981 982 if (isRedeclaration()) { 983 // It is possible that we have not done deserializing the ObjCMethod yet. 984 ObjCMethodDecl *MD = 985 cast<ObjCContainerDecl>(CtxD)->getMethod(Sel, isInstanceMethod()); 986 return MD ? MD : this; 987 } 988 989 return this; 990 } 991 992 SourceLocation ObjCMethodDecl::getEndLoc() const { 993 if (Stmt *Body = getBody()) 994 return Body->getEndLoc(); 995 return DeclEndLoc; 996 } 997 998 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { 999 auto family = static_cast<ObjCMethodFamily>(ObjCMethodDeclBits.Family); 1000 if (family != static_cast<unsigned>(InvalidObjCMethodFamily)) 1001 return family; 1002 1003 // Check for an explicit attribute. 1004 if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) { 1005 // The unfortunate necessity of mapping between enums here is due 1006 // to the attributes framework. 1007 switch (attr->getFamily()) { 1008 case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break; 1009 case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break; 1010 case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break; 1011 case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break; 1012 case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break; 1013 case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break; 1014 } 1015 ObjCMethodDeclBits.Family = family; 1016 return family; 1017 } 1018 1019 family = getSelector().getMethodFamily(); 1020 switch (family) { 1021 case OMF_None: break; 1022 1023 // init only has a conventional meaning for an instance method, and 1024 // it has to return an object. 1025 case OMF_init: 1026 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType()) 1027 family = OMF_None; 1028 break; 1029 1030 // alloc/copy/new have a conventional meaning for both class and 1031 // instance methods, but they require an object return. 1032 case OMF_alloc: 1033 case OMF_copy: 1034 case OMF_mutableCopy: 1035 case OMF_new: 1036 if (!getReturnType()->isObjCObjectPointerType()) 1037 family = OMF_None; 1038 break; 1039 1040 // These selectors have a conventional meaning only for instance methods. 1041 case OMF_dealloc: 1042 case OMF_finalize: 1043 case OMF_retain: 1044 case OMF_release: 1045 case OMF_autorelease: 1046 case OMF_retainCount: 1047 case OMF_self: 1048 if (!isInstanceMethod()) 1049 family = OMF_None; 1050 break; 1051 1052 case OMF_initialize: 1053 if (isInstanceMethod() || !getReturnType()->isVoidType()) 1054 family = OMF_None; 1055 break; 1056 1057 case OMF_performSelector: 1058 if (!isInstanceMethod() || !getReturnType()->isObjCIdType()) 1059 family = OMF_None; 1060 else { 1061 unsigned noParams = param_size(); 1062 if (noParams < 1 || noParams > 3) 1063 family = OMF_None; 1064 else { 1065 ObjCMethodDecl::param_type_iterator it = param_type_begin(); 1066 QualType ArgT = (*it); 1067 if (!ArgT->isObjCSelType()) { 1068 family = OMF_None; 1069 break; 1070 } 1071 while (--noParams) { 1072 it++; 1073 ArgT = (*it); 1074 if (!ArgT->isObjCIdType()) { 1075 family = OMF_None; 1076 break; 1077 } 1078 } 1079 } 1080 } 1081 break; 1082 1083 } 1084 1085 // Cache the result. 1086 ObjCMethodDeclBits.Family = family; 1087 return family; 1088 } 1089 1090 QualType ObjCMethodDecl::getSelfType(ASTContext &Context, 1091 const ObjCInterfaceDecl *OID, 1092 bool &selfIsPseudoStrong, 1093 bool &selfIsConsumed) const { 1094 QualType selfTy; 1095 selfIsPseudoStrong = false; 1096 selfIsConsumed = false; 1097 if (isInstanceMethod()) { 1098 // There may be no interface context due to error in declaration 1099 // of the interface (which has been reported). Recover gracefully. 1100 if (OID) { 1101 selfTy = Context.getObjCInterfaceType(OID); 1102 selfTy = Context.getObjCObjectPointerType(selfTy); 1103 } else { 1104 selfTy = Context.getObjCIdType(); 1105 } 1106 } else // we have a factory method. 1107 selfTy = Context.getObjCClassType(); 1108 1109 if (Context.getLangOpts().ObjCAutoRefCount) { 1110 if (isInstanceMethod()) { 1111 selfIsConsumed = hasAttr<NSConsumesSelfAttr>(); 1112 1113 // 'self' is always __strong. It's actually pseudo-strong except 1114 // in init methods (or methods labeled ns_consumes_self), though. 1115 Qualifiers qs; 1116 qs.setObjCLifetime(Qualifiers::OCL_Strong); 1117 selfTy = Context.getQualifiedType(selfTy, qs); 1118 1119 // In addition, 'self' is const unless this is an init method. 1120 if (getMethodFamily() != OMF_init && !selfIsConsumed) { 1121 selfTy = selfTy.withConst(); 1122 selfIsPseudoStrong = true; 1123 } 1124 } 1125 else { 1126 assert(isClassMethod()); 1127 // 'self' is always const in class methods. 1128 selfTy = selfTy.withConst(); 1129 selfIsPseudoStrong = true; 1130 } 1131 } 1132 return selfTy; 1133 } 1134 1135 void ObjCMethodDecl::createImplicitParams(ASTContext &Context, 1136 const ObjCInterfaceDecl *OID) { 1137 bool selfIsPseudoStrong, selfIsConsumed; 1138 QualType selfTy = 1139 getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed); 1140 auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(), 1141 &Context.Idents.get("self"), selfTy, 1142 ImplicitParamDecl::ObjCSelf); 1143 setSelfDecl(Self); 1144 1145 if (selfIsConsumed) 1146 Self->addAttr(NSConsumedAttr::CreateImplicit(Context)); 1147 1148 if (selfIsPseudoStrong) 1149 Self->setARCPseudoStrong(true); 1150 1151 setCmdDecl(ImplicitParamDecl::Create( 1152 Context, this, SourceLocation(), &Context.Idents.get("_cmd"), 1153 Context.getObjCSelType(), ImplicitParamDecl::ObjCCmd)); 1154 } 1155 1156 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() { 1157 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext())) 1158 return ID; 1159 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) 1160 return CD->getClassInterface(); 1161 if (auto *IMD = dyn_cast<ObjCImplDecl>(getDeclContext())) 1162 return IMD->getClassInterface(); 1163 if (isa<ObjCProtocolDecl>(getDeclContext())) 1164 return nullptr; 1165 llvm_unreachable("unknown method context"); 1166 } 1167 1168 ObjCCategoryDecl *ObjCMethodDecl::getCategory() { 1169 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) 1170 return CD; 1171 if (auto *IMD = dyn_cast<ObjCCategoryImplDecl>(getDeclContext())) 1172 return IMD->getCategoryDecl(); 1173 return nullptr; 1174 } 1175 1176 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const { 1177 const auto *TSI = getReturnTypeSourceInfo(); 1178 if (TSI) 1179 return TSI->getTypeLoc().getSourceRange(); 1180 return SourceRange(); 1181 } 1182 1183 QualType ObjCMethodDecl::getSendResultType() const { 1184 ASTContext &Ctx = getASTContext(); 1185 return getReturnType().getNonLValueExprType(Ctx) 1186 .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result); 1187 } 1188 1189 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const { 1190 // FIXME: Handle related result types here. 1191 1192 return getReturnType().getNonLValueExprType(getASTContext()) 1193 .substObjCMemberType(receiverType, getDeclContext(), 1194 ObjCSubstitutionContext::Result); 1195 } 1196 1197 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container, 1198 const ObjCMethodDecl *Method, 1199 SmallVectorImpl<const ObjCMethodDecl *> &Methods, 1200 bool MovedToSuper) { 1201 if (!Container) 1202 return; 1203 1204 // In categories look for overridden methods from protocols. A method from 1205 // category is not "overridden" since it is considered as the "same" method 1206 // (same USR) as the one from the interface. 1207 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1208 // Check whether we have a matching method at this category but only if we 1209 // are at the super class level. 1210 if (MovedToSuper) 1211 if (ObjCMethodDecl * 1212 Overridden = Container->getMethod(Method->getSelector(), 1213 Method->isInstanceMethod(), 1214 /*AllowHidden=*/true)) 1215 if (Method != Overridden) { 1216 // We found an override at this category; there is no need to look 1217 // into its protocols. 1218 Methods.push_back(Overridden); 1219 return; 1220 } 1221 1222 for (const auto *P : Category->protocols()) 1223 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1224 return; 1225 } 1226 1227 // Check whether we have a matching method at this level. 1228 if (const ObjCMethodDecl * 1229 Overridden = Container->getMethod(Method->getSelector(), 1230 Method->isInstanceMethod(), 1231 /*AllowHidden=*/true)) 1232 if (Method != Overridden) { 1233 // We found an override at this level; there is no need to look 1234 // into other protocols or categories. 1235 Methods.push_back(Overridden); 1236 return; 1237 } 1238 1239 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){ 1240 for (const auto *P : Protocol->protocols()) 1241 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1242 } 1243 1244 if (const auto *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 1245 for (const auto *P : Interface->protocols()) 1246 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1247 1248 for (const auto *Cat : Interface->known_categories()) 1249 CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper); 1250 1251 if (const ObjCInterfaceDecl *Super = Interface->getSuperClass()) 1252 return CollectOverriddenMethodsRecurse(Super, Method, Methods, 1253 /*MovedToSuper=*/true); 1254 } 1255 } 1256 1257 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container, 1258 const ObjCMethodDecl *Method, 1259 SmallVectorImpl<const ObjCMethodDecl *> &Methods) { 1260 CollectOverriddenMethodsRecurse(Container, Method, Methods, 1261 /*MovedToSuper=*/false); 1262 } 1263 1264 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method, 1265 SmallVectorImpl<const ObjCMethodDecl *> &overridden) { 1266 assert(Method->isOverriding()); 1267 1268 if (const auto *ProtD = 1269 dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) { 1270 CollectOverriddenMethods(ProtD, Method, overridden); 1271 1272 } else if (const auto *IMD = 1273 dyn_cast<ObjCImplDecl>(Method->getDeclContext())) { 1274 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 1275 if (!ID) 1276 return; 1277 // Start searching for overridden methods using the method from the 1278 // interface as starting point. 1279 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1280 Method->isInstanceMethod(), 1281 /*AllowHidden=*/true)) 1282 Method = IFaceMeth; 1283 CollectOverriddenMethods(ID, Method, overridden); 1284 1285 } else if (const auto *CatD = 1286 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) { 1287 const ObjCInterfaceDecl *ID = CatD->getClassInterface(); 1288 if (!ID) 1289 return; 1290 // Start searching for overridden methods using the method from the 1291 // interface as starting point. 1292 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1293 Method->isInstanceMethod(), 1294 /*AllowHidden=*/true)) 1295 Method = IFaceMeth; 1296 CollectOverriddenMethods(ID, Method, overridden); 1297 1298 } else { 1299 CollectOverriddenMethods( 1300 dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()), 1301 Method, overridden); 1302 } 1303 } 1304 1305 void ObjCMethodDecl::getOverriddenMethods( 1306 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const { 1307 const ObjCMethodDecl *Method = this; 1308 1309 if (Method->isRedeclaration()) { 1310 Method = cast<ObjCContainerDecl>(Method->getDeclContext())-> 1311 getMethod(Method->getSelector(), Method->isInstanceMethod()); 1312 } 1313 1314 if (Method->isOverriding()) { 1315 collectOverriddenMethodsSlow(Method, Overridden); 1316 assert(!Overridden.empty() && 1317 "ObjCMethodDecl's overriding bit is not as expected"); 1318 } 1319 } 1320 1321 const ObjCPropertyDecl * 1322 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const { 1323 Selector Sel = getSelector(); 1324 unsigned NumArgs = Sel.getNumArgs(); 1325 if (NumArgs > 1) 1326 return nullptr; 1327 1328 if (isPropertyAccessor()) { 1329 const auto *Container = cast<ObjCContainerDecl>(getParent()); 1330 // For accessor stubs, go back to the interface. 1331 if (auto *ImplDecl = dyn_cast<ObjCImplDecl>(Container)) 1332 if (isSynthesizedAccessorStub()) 1333 Container = ImplDecl->getClassInterface(); 1334 1335 bool IsGetter = (NumArgs == 0); 1336 bool IsInstance = isInstanceMethod(); 1337 1338 /// Local function that attempts to find a matching property within the 1339 /// given Objective-C container. 1340 auto findMatchingProperty = 1341 [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * { 1342 if (IsInstance) { 1343 for (const auto *I : Container->instance_properties()) { 1344 Selector NextSel = IsGetter ? I->getGetterName() 1345 : I->getSetterName(); 1346 if (NextSel == Sel) 1347 return I; 1348 } 1349 } else { 1350 for (const auto *I : Container->class_properties()) { 1351 Selector NextSel = IsGetter ? I->getGetterName() 1352 : I->getSetterName(); 1353 if (NextSel == Sel) 1354 return I; 1355 } 1356 } 1357 1358 return nullptr; 1359 }; 1360 1361 // Look in the container we were given. 1362 if (const auto *Found = findMatchingProperty(Container)) 1363 return Found; 1364 1365 // If we're in a category or extension, look in the main class. 1366 const ObjCInterfaceDecl *ClassDecl = nullptr; 1367 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1368 ClassDecl = Category->getClassInterface(); 1369 if (const auto *Found = findMatchingProperty(ClassDecl)) 1370 return Found; 1371 } else { 1372 // Determine whether the container is a class. 1373 ClassDecl = cast<ObjCInterfaceDecl>(Container); 1374 } 1375 assert(ClassDecl && "Failed to find main class"); 1376 1377 // If we have a class, check its visible extensions. 1378 for (const auto *Ext : ClassDecl->visible_extensions()) { 1379 if (Ext == Container) 1380 continue; 1381 if (const auto *Found = findMatchingProperty(Ext)) 1382 return Found; 1383 } 1384 1385 assert(isSynthesizedAccessorStub() && "expected an accessor stub"); 1386 1387 for (const auto *Cat : ClassDecl->known_categories()) { 1388 if (Cat == Container) 1389 continue; 1390 if (const auto *Found = findMatchingProperty(Cat)) 1391 return Found; 1392 } 1393 1394 llvm_unreachable("Marked as a property accessor but no property found!"); 1395 } 1396 1397 if (!CheckOverrides) 1398 return nullptr; 1399 1400 using OverridesTy = SmallVector<const ObjCMethodDecl *, 8>; 1401 1402 OverridesTy Overrides; 1403 getOverriddenMethods(Overrides); 1404 for (const auto *Override : Overrides) 1405 if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false)) 1406 return Prop; 1407 1408 return nullptr; 1409 } 1410 1411 //===----------------------------------------------------------------------===// 1412 // ObjCTypeParamDecl 1413 //===----------------------------------------------------------------------===// 1414 1415 void ObjCTypeParamDecl::anchor() {} 1416 1417 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc, 1418 ObjCTypeParamVariance variance, 1419 SourceLocation varianceLoc, 1420 unsigned index, 1421 SourceLocation nameLoc, 1422 IdentifierInfo *name, 1423 SourceLocation colonLoc, 1424 TypeSourceInfo *boundInfo) { 1425 auto *TPDecl = 1426 new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index, 1427 nameLoc, name, colonLoc, boundInfo); 1428 QualType TPType = ctx.getObjCTypeParamType(TPDecl, {}); 1429 TPDecl->setTypeForDecl(TPType.getTypePtr()); 1430 return TPDecl; 1431 } 1432 1433 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx, 1434 unsigned ID) { 1435 return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr, 1436 ObjCTypeParamVariance::Invariant, 1437 SourceLocation(), 0, SourceLocation(), 1438 nullptr, SourceLocation(), nullptr); 1439 } 1440 1441 SourceRange ObjCTypeParamDecl::getSourceRange() const { 1442 SourceLocation startLoc = VarianceLoc; 1443 if (startLoc.isInvalid()) 1444 startLoc = getLocation(); 1445 1446 if (hasExplicitBound()) { 1447 return SourceRange(startLoc, 1448 getTypeSourceInfo()->getTypeLoc().getEndLoc()); 1449 } 1450 1451 return SourceRange(startLoc); 1452 } 1453 1454 //===----------------------------------------------------------------------===// 1455 // ObjCTypeParamList 1456 //===----------------------------------------------------------------------===// 1457 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc, 1458 ArrayRef<ObjCTypeParamDecl *> typeParams, 1459 SourceLocation rAngleLoc) 1460 : NumParams(typeParams.size()) { 1461 Brackets.Begin = lAngleLoc.getRawEncoding(); 1462 Brackets.End = rAngleLoc.getRawEncoding(); 1463 std::copy(typeParams.begin(), typeParams.end(), begin()); 1464 } 1465 1466 ObjCTypeParamList *ObjCTypeParamList::create( 1467 ASTContext &ctx, 1468 SourceLocation lAngleLoc, 1469 ArrayRef<ObjCTypeParamDecl *> typeParams, 1470 SourceLocation rAngleLoc) { 1471 void *mem = 1472 ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()), 1473 alignof(ObjCTypeParamList)); 1474 return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc); 1475 } 1476 1477 void ObjCTypeParamList::gatherDefaultTypeArgs( 1478 SmallVectorImpl<QualType> &typeArgs) const { 1479 typeArgs.reserve(size()); 1480 for (auto typeParam : *this) 1481 typeArgs.push_back(typeParam->getUnderlyingType()); 1482 } 1483 1484 //===----------------------------------------------------------------------===// 1485 // ObjCInterfaceDecl 1486 //===----------------------------------------------------------------------===// 1487 1488 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C, 1489 DeclContext *DC, 1490 SourceLocation atLoc, 1491 IdentifierInfo *Id, 1492 ObjCTypeParamList *typeParamList, 1493 ObjCInterfaceDecl *PrevDecl, 1494 SourceLocation ClassLoc, 1495 bool isInternal){ 1496 auto *Result = new (C, DC) 1497 ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl, 1498 isInternal); 1499 Result->Data.setInt(!C.getLangOpts().Modules); 1500 C.getObjCInterfaceType(Result, PrevDecl); 1501 return Result; 1502 } 1503 1504 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C, 1505 unsigned ID) { 1506 auto *Result = new (C, ID) 1507 ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr, 1508 SourceLocation(), nullptr, false); 1509 Result->Data.setInt(!C.getLangOpts().Modules); 1510 return Result; 1511 } 1512 1513 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, 1514 SourceLocation AtLoc, IdentifierInfo *Id, 1515 ObjCTypeParamList *typeParamList, 1516 SourceLocation CLoc, 1517 ObjCInterfaceDecl *PrevDecl, 1518 bool IsInternal) 1519 : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc), 1520 redeclarable_base(C) { 1521 setPreviousDecl(PrevDecl); 1522 1523 // Copy the 'data' pointer over. 1524 if (PrevDecl) 1525 Data = PrevDecl->Data; 1526 1527 setImplicit(IsInternal); 1528 1529 setTypeParamList(typeParamList); 1530 } 1531 1532 void ObjCInterfaceDecl::LoadExternalDefinition() const { 1533 assert(data().ExternallyCompleted && "Class is not externally completed"); 1534 data().ExternallyCompleted = false; 1535 getASTContext().getExternalSource()->CompleteType( 1536 const_cast<ObjCInterfaceDecl *>(this)); 1537 } 1538 1539 void ObjCInterfaceDecl::setExternallyCompleted() { 1540 assert(getASTContext().getExternalSource() && 1541 "Class can't be externally completed without an external source"); 1542 assert(hasDefinition() && 1543 "Forward declarations can't be externally completed"); 1544 data().ExternallyCompleted = true; 1545 } 1546 1547 void ObjCInterfaceDecl::setHasDesignatedInitializers() { 1548 // Check for a complete definition and recover if not so. 1549 if (!isThisDeclarationADefinition()) 1550 return; 1551 data().HasDesignatedInitializers = true; 1552 } 1553 1554 bool ObjCInterfaceDecl::hasDesignatedInitializers() const { 1555 // Check for a complete definition and recover if not so. 1556 if (!isThisDeclarationADefinition()) 1557 return false; 1558 if (data().ExternallyCompleted) 1559 LoadExternalDefinition(); 1560 1561 return data().HasDesignatedInitializers; 1562 } 1563 1564 StringRef 1565 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const { 1566 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 1567 return ObjCRTName->getMetadataName(); 1568 1569 return getName(); 1570 } 1571 1572 StringRef 1573 ObjCImplementationDecl::getObjCRuntimeNameAsString() const { 1574 if (ObjCInterfaceDecl *ID = 1575 const_cast<ObjCImplementationDecl*>(this)->getClassInterface()) 1576 return ID->getObjCRuntimeNameAsString(); 1577 1578 return getName(); 1579 } 1580 1581 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const { 1582 if (const ObjCInterfaceDecl *Def = getDefinition()) { 1583 if (data().ExternallyCompleted) 1584 LoadExternalDefinition(); 1585 1586 return getASTContext().getObjCImplementation( 1587 const_cast<ObjCInterfaceDecl*>(Def)); 1588 } 1589 1590 // FIXME: Should make sure no callers ever do this. 1591 return nullptr; 1592 } 1593 1594 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) { 1595 getASTContext().setObjCImplementation(getDefinition(), ImplD); 1596 } 1597 1598 namespace { 1599 1600 struct SynthesizeIvarChunk { 1601 uint64_t Size; 1602 ObjCIvarDecl *Ivar; 1603 1604 SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar) 1605 : Size(size), Ivar(ivar) {} 1606 }; 1607 1608 bool operator<(const SynthesizeIvarChunk & LHS, 1609 const SynthesizeIvarChunk &RHS) { 1610 return LHS.Size < RHS.Size; 1611 } 1612 1613 } // namespace 1614 1615 /// all_declared_ivar_begin - return first ivar declared in this class, 1616 /// its extensions and its implementation. Lazily build the list on first 1617 /// access. 1618 /// 1619 /// Caveat: The list returned by this method reflects the current 1620 /// state of the parser. The cache will be updated for every ivar 1621 /// added by an extension or the implementation when they are 1622 /// encountered. 1623 /// See also ObjCIvarDecl::Create(). 1624 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { 1625 // FIXME: Should make sure no callers ever do this. 1626 if (!hasDefinition()) 1627 return nullptr; 1628 1629 ObjCIvarDecl *curIvar = nullptr; 1630 if (!data().IvarList) { 1631 if (!ivar_empty()) { 1632 ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end(); 1633 data().IvarList = *I; ++I; 1634 for (curIvar = data().IvarList; I != E; curIvar = *I, ++I) 1635 curIvar->setNextIvar(*I); 1636 } 1637 1638 for (const auto *Ext : known_extensions()) { 1639 if (!Ext->ivar_empty()) { 1640 ObjCCategoryDecl::ivar_iterator 1641 I = Ext->ivar_begin(), 1642 E = Ext->ivar_end(); 1643 if (!data().IvarList) { 1644 data().IvarList = *I; ++I; 1645 curIvar = data().IvarList; 1646 } 1647 for ( ;I != E; curIvar = *I, ++I) 1648 curIvar->setNextIvar(*I); 1649 } 1650 } 1651 data().IvarListMissingImplementation = true; 1652 } 1653 1654 // cached and complete! 1655 if (!data().IvarListMissingImplementation) 1656 return data().IvarList; 1657 1658 if (ObjCImplementationDecl *ImplDecl = getImplementation()) { 1659 data().IvarListMissingImplementation = false; 1660 if (!ImplDecl->ivar_empty()) { 1661 SmallVector<SynthesizeIvarChunk, 16> layout; 1662 for (auto *IV : ImplDecl->ivars()) { 1663 if (IV->getSynthesize() && !IV->isInvalidDecl()) { 1664 layout.push_back(SynthesizeIvarChunk( 1665 IV->getASTContext().getTypeSize(IV->getType()), IV)); 1666 continue; 1667 } 1668 if (!data().IvarList) 1669 data().IvarList = IV; 1670 else 1671 curIvar->setNextIvar(IV); 1672 curIvar = IV; 1673 } 1674 1675 if (!layout.empty()) { 1676 // Order synthesized ivars by their size. 1677 llvm::stable_sort(layout); 1678 unsigned Ix = 0, EIx = layout.size(); 1679 if (!data().IvarList) { 1680 data().IvarList = layout[0].Ivar; Ix++; 1681 curIvar = data().IvarList; 1682 } 1683 for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++) 1684 curIvar->setNextIvar(layout[Ix].Ivar); 1685 } 1686 } 1687 } 1688 return data().IvarList; 1689 } 1690 1691 /// FindCategoryDeclaration - Finds category declaration in the list of 1692 /// categories for this class and returns it. Name of the category is passed 1693 /// in 'CategoryId'. If category not found, return 0; 1694 /// 1695 ObjCCategoryDecl * 1696 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const { 1697 // FIXME: Should make sure no callers ever do this. 1698 if (!hasDefinition()) 1699 return nullptr; 1700 1701 if (data().ExternallyCompleted) 1702 LoadExternalDefinition(); 1703 1704 for (auto *Cat : visible_categories()) 1705 if (Cat->getIdentifier() == CategoryId) 1706 return Cat; 1707 1708 return nullptr; 1709 } 1710 1711 ObjCMethodDecl * 1712 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const { 1713 for (const auto *Cat : visible_categories()) { 1714 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1715 if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel)) 1716 return MD; 1717 } 1718 1719 return nullptr; 1720 } 1721 1722 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const { 1723 for (const auto *Cat : visible_categories()) { 1724 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1725 if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel)) 1726 return MD; 1727 } 1728 1729 return nullptr; 1730 } 1731 1732 /// ClassImplementsProtocol - Checks that 'lProto' protocol 1733 /// has been implemented in IDecl class, its super class or categories (if 1734 /// lookupCategory is true). 1735 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, 1736 bool lookupCategory, 1737 bool RHSIsQualifiedID) { 1738 if (!hasDefinition()) 1739 return false; 1740 1741 ObjCInterfaceDecl *IDecl = this; 1742 // 1st, look up the class. 1743 for (auto *PI : IDecl->protocols()){ 1744 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1745 return true; 1746 // This is dubious and is added to be compatible with gcc. In gcc, it is 1747 // also allowed assigning a protocol-qualified 'id' type to a LHS object 1748 // when protocol in qualified LHS is in list of protocols in the rhs 'id' 1749 // object. This IMO, should be a bug. 1750 // FIXME: Treat this as an extension, and flag this as an error when GCC 1751 // extensions are not enabled. 1752 if (RHSIsQualifiedID && 1753 getASTContext().ProtocolCompatibleWithProtocol(PI, lProto)) 1754 return true; 1755 } 1756 1757 // 2nd, look up the category. 1758 if (lookupCategory) 1759 for (const auto *Cat : visible_categories()) { 1760 for (auto *PI : Cat->protocols()) 1761 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1762 return true; 1763 } 1764 1765 // 3rd, look up the super class(s) 1766 if (IDecl->getSuperClass()) 1767 return 1768 IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory, 1769 RHSIsQualifiedID); 1770 1771 return false; 1772 } 1773 1774 //===----------------------------------------------------------------------===// 1775 // ObjCIvarDecl 1776 //===----------------------------------------------------------------------===// 1777 1778 void ObjCIvarDecl::anchor() {} 1779 1780 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC, 1781 SourceLocation StartLoc, 1782 SourceLocation IdLoc, IdentifierInfo *Id, 1783 QualType T, TypeSourceInfo *TInfo, 1784 AccessControl ac, Expr *BW, 1785 bool synthesized) { 1786 if (DC) { 1787 // Ivar's can only appear in interfaces, implementations (via synthesized 1788 // properties), and class extensions (via direct declaration, or synthesized 1789 // properties). 1790 // 1791 // FIXME: This should really be asserting this: 1792 // (isa<ObjCCategoryDecl>(DC) && 1793 // cast<ObjCCategoryDecl>(DC)->IsClassExtension())) 1794 // but unfortunately we sometimes place ivars into non-class extension 1795 // categories on error. This breaks an AST invariant, and should not be 1796 // fixed. 1797 assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) || 1798 isa<ObjCCategoryDecl>(DC)) && 1799 "Invalid ivar decl context!"); 1800 // Once a new ivar is created in any of class/class-extension/implementation 1801 // decl contexts, the previously built IvarList must be rebuilt. 1802 auto *ID = dyn_cast<ObjCInterfaceDecl>(DC); 1803 if (!ID) { 1804 if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC)) 1805 ID = IM->getClassInterface(); 1806 else 1807 ID = cast<ObjCCategoryDecl>(DC)->getClassInterface(); 1808 } 1809 ID->setIvarList(nullptr); 1810 } 1811 1812 return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW, 1813 synthesized); 1814 } 1815 1816 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1817 return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(), 1818 nullptr, QualType(), nullptr, 1819 ObjCIvarDecl::None, nullptr, false); 1820 } 1821 1822 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const { 1823 const auto *DC = cast<ObjCContainerDecl>(getDeclContext()); 1824 1825 switch (DC->getKind()) { 1826 default: 1827 case ObjCCategoryImpl: 1828 case ObjCProtocol: 1829 llvm_unreachable("invalid ivar container!"); 1830 1831 // Ivars can only appear in class extension categories. 1832 case ObjCCategory: { 1833 const auto *CD = cast<ObjCCategoryDecl>(DC); 1834 assert(CD->IsClassExtension() && "invalid container for ivar!"); 1835 return CD->getClassInterface(); 1836 } 1837 1838 case ObjCImplementation: 1839 return cast<ObjCImplementationDecl>(DC)->getClassInterface(); 1840 1841 case ObjCInterface: 1842 return cast<ObjCInterfaceDecl>(DC); 1843 } 1844 } 1845 1846 QualType ObjCIvarDecl::getUsageType(QualType objectType) const { 1847 return getType().substObjCMemberType(objectType, getDeclContext(), 1848 ObjCSubstitutionContext::Property); 1849 } 1850 1851 //===----------------------------------------------------------------------===// 1852 // ObjCAtDefsFieldDecl 1853 //===----------------------------------------------------------------------===// 1854 1855 void ObjCAtDefsFieldDecl::anchor() {} 1856 1857 ObjCAtDefsFieldDecl 1858 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC, 1859 SourceLocation StartLoc, SourceLocation IdLoc, 1860 IdentifierInfo *Id, QualType T, Expr *BW) { 1861 return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW); 1862 } 1863 1864 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C, 1865 unsigned ID) { 1866 return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(), 1867 SourceLocation(), nullptr, QualType(), 1868 nullptr); 1869 } 1870 1871 //===----------------------------------------------------------------------===// 1872 // ObjCProtocolDecl 1873 //===----------------------------------------------------------------------===// 1874 1875 void ObjCProtocolDecl::anchor() {} 1876 1877 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC, 1878 IdentifierInfo *Id, SourceLocation nameLoc, 1879 SourceLocation atStartLoc, 1880 ObjCProtocolDecl *PrevDecl) 1881 : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc), 1882 redeclarable_base(C) { 1883 setPreviousDecl(PrevDecl); 1884 if (PrevDecl) 1885 Data = PrevDecl->Data; 1886 } 1887 1888 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC, 1889 IdentifierInfo *Id, 1890 SourceLocation nameLoc, 1891 SourceLocation atStartLoc, 1892 ObjCProtocolDecl *PrevDecl) { 1893 auto *Result = 1894 new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl); 1895 Result->Data.setInt(!C.getLangOpts().Modules); 1896 return Result; 1897 } 1898 1899 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C, 1900 unsigned ID) { 1901 ObjCProtocolDecl *Result = 1902 new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(), 1903 SourceLocation(), nullptr); 1904 Result->Data.setInt(!C.getLangOpts().Modules); 1905 return Result; 1906 } 1907 1908 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) { 1909 ObjCProtocolDecl *PDecl = this; 1910 1911 if (Name == getIdentifier()) 1912 return PDecl; 1913 1914 for (auto *I : protocols()) 1915 if ((PDecl = I->lookupProtocolNamed(Name))) 1916 return PDecl; 1917 1918 return nullptr; 1919 } 1920 1921 // lookupMethod - Lookup a instance/class method in the protocol and protocols 1922 // it inherited. 1923 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel, 1924 bool isInstance) const { 1925 ObjCMethodDecl *MethodDecl = nullptr; 1926 1927 // If there is no definition or the definition is hidden, we don't find 1928 // anything. 1929 const ObjCProtocolDecl *Def = getDefinition(); 1930 if (!Def || !Def->isUnconditionallyVisible()) 1931 return nullptr; 1932 1933 if ((MethodDecl = getMethod(Sel, isInstance))) 1934 return MethodDecl; 1935 1936 for (const auto *I : protocols()) 1937 if ((MethodDecl = I->lookupMethod(Sel, isInstance))) 1938 return MethodDecl; 1939 return nullptr; 1940 } 1941 1942 void ObjCProtocolDecl::allocateDefinitionData() { 1943 assert(!Data.getPointer() && "Protocol already has a definition!"); 1944 Data.setPointer(new (getASTContext()) DefinitionData); 1945 Data.getPointer()->Definition = this; 1946 } 1947 1948 void ObjCProtocolDecl::startDefinition() { 1949 allocateDefinitionData(); 1950 1951 // Update all of the declarations with a pointer to the definition. 1952 for (auto *RD : redecls()) 1953 RD->Data = this->Data; 1954 } 1955 1956 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM, 1957 PropertyDeclOrder &PO) const { 1958 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 1959 for (auto *Prop : PDecl->properties()) { 1960 // Insert into PM if not there already. 1961 PM.insert(std::make_pair( 1962 std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()), 1963 Prop)); 1964 PO.push_back(Prop); 1965 } 1966 // Scan through protocol's protocols. 1967 for (const auto *PI : PDecl->protocols()) 1968 PI->collectPropertiesToImplement(PM, PO); 1969 } 1970 } 1971 1972 void ObjCProtocolDecl::collectInheritedProtocolProperties( 1973 const ObjCPropertyDecl *Property, ProtocolPropertySet &PS, 1974 PropertyDeclOrder &PO) const { 1975 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 1976 if (!PS.insert(PDecl).second) 1977 return; 1978 for (auto *Prop : PDecl->properties()) { 1979 if (Prop == Property) 1980 continue; 1981 if (Prop->getIdentifier() == Property->getIdentifier()) { 1982 PO.push_back(Prop); 1983 return; 1984 } 1985 } 1986 // Scan through protocol's protocols which did not have a matching property. 1987 for (const auto *PI : PDecl->protocols()) 1988 PI->collectInheritedProtocolProperties(Property, PS, PO); 1989 } 1990 } 1991 1992 StringRef 1993 ObjCProtocolDecl::getObjCRuntimeNameAsString() const { 1994 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 1995 return ObjCRTName->getMetadataName(); 1996 1997 return getName(); 1998 } 1999 2000 //===----------------------------------------------------------------------===// 2001 // ObjCCategoryDecl 2002 //===----------------------------------------------------------------------===// 2003 2004 void ObjCCategoryDecl::anchor() {} 2005 2006 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, 2007 SourceLocation ClassNameLoc, 2008 SourceLocation CategoryNameLoc, 2009 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, 2010 ObjCTypeParamList *typeParamList, 2011 SourceLocation IvarLBraceLoc, 2012 SourceLocation IvarRBraceLoc) 2013 : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc), 2014 ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc), 2015 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) { 2016 setTypeParamList(typeParamList); 2017 } 2018 2019 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC, 2020 SourceLocation AtLoc, 2021 SourceLocation ClassNameLoc, 2022 SourceLocation CategoryNameLoc, 2023 IdentifierInfo *Id, 2024 ObjCInterfaceDecl *IDecl, 2025 ObjCTypeParamList *typeParamList, 2026 SourceLocation IvarLBraceLoc, 2027 SourceLocation IvarRBraceLoc) { 2028 auto *CatDecl = 2029 new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id, 2030 IDecl, typeParamList, IvarLBraceLoc, 2031 IvarRBraceLoc); 2032 if (IDecl) { 2033 // Link this category into its class's category list. 2034 CatDecl->NextClassCategory = IDecl->getCategoryListRaw(); 2035 if (IDecl->hasDefinition()) { 2036 IDecl->setCategoryListRaw(CatDecl); 2037 if (ASTMutationListener *L = C.getASTMutationListener()) 2038 L->AddedObjCCategoryToInterface(CatDecl, IDecl); 2039 } 2040 } 2041 2042 return CatDecl; 2043 } 2044 2045 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C, 2046 unsigned ID) { 2047 return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(), 2048 SourceLocation(), SourceLocation(), 2049 nullptr, nullptr, nullptr); 2050 } 2051 2052 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const { 2053 return getASTContext().getObjCImplementation( 2054 const_cast<ObjCCategoryDecl*>(this)); 2055 } 2056 2057 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) { 2058 getASTContext().setObjCImplementation(this, ImplD); 2059 } 2060 2061 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) { 2062 TypeParamList = TPL; 2063 if (!TPL) 2064 return; 2065 // Set the declaration context of each of the type parameters. 2066 for (auto *typeParam : *TypeParamList) 2067 typeParam->setDeclContext(this); 2068 } 2069 2070 //===----------------------------------------------------------------------===// 2071 // ObjCCategoryImplDecl 2072 //===----------------------------------------------------------------------===// 2073 2074 void ObjCCategoryImplDecl::anchor() {} 2075 2076 ObjCCategoryImplDecl * 2077 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, 2078 IdentifierInfo *Id, 2079 ObjCInterfaceDecl *ClassInterface, 2080 SourceLocation nameLoc, 2081 SourceLocation atStartLoc, 2082 SourceLocation CategoryNameLoc) { 2083 if (ClassInterface && ClassInterface->hasDefinition()) 2084 ClassInterface = ClassInterface->getDefinition(); 2085 return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc, 2086 atStartLoc, CategoryNameLoc); 2087 } 2088 2089 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, 2090 unsigned ID) { 2091 return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr, 2092 SourceLocation(), SourceLocation(), 2093 SourceLocation()); 2094 } 2095 2096 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const { 2097 // The class interface might be NULL if we are working with invalid code. 2098 if (const ObjCInterfaceDecl *ID = getClassInterface()) 2099 return ID->FindCategoryDeclaration(getIdentifier()); 2100 return nullptr; 2101 } 2102 2103 void ObjCImplDecl::anchor() {} 2104 2105 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) { 2106 // FIXME: The context should be correct before we get here. 2107 property->setLexicalDeclContext(this); 2108 addDecl(property); 2109 } 2110 2111 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) { 2112 ASTContext &Ctx = getASTContext(); 2113 2114 if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) { 2115 if (IFace) 2116 Ctx.setObjCImplementation(IFace, ImplD); 2117 2118 } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) { 2119 if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier())) 2120 Ctx.setObjCImplementation(CD, ImplD); 2121 } 2122 2123 ClassInterface = IFace; 2124 } 2125 2126 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of 2127 /// properties implemented in this \@implementation block and returns 2128 /// the implemented property that uses it. 2129 ObjCPropertyImplDecl *ObjCImplDecl:: 2130 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const { 2131 for (auto *PID : property_impls()) 2132 if (PID->getPropertyIvarDecl() && 2133 PID->getPropertyIvarDecl()->getIdentifier() == ivarId) 2134 return PID; 2135 return nullptr; 2136 } 2137 2138 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl 2139 /// added to the list of those properties \@synthesized/\@dynamic in this 2140 /// category \@implementation block. 2141 ObjCPropertyImplDecl *ObjCImplDecl:: 2142 FindPropertyImplDecl(IdentifierInfo *Id, 2143 ObjCPropertyQueryKind QueryKind) const { 2144 ObjCPropertyImplDecl *ClassPropImpl = nullptr; 2145 for (auto *PID : property_impls()) 2146 // If queryKind is unknown, we return the instance property if one 2147 // exists; otherwise we return the class property. 2148 if (PID->getPropertyDecl()->getIdentifier() == Id) { 2149 if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown && 2150 !PID->getPropertyDecl()->isClassProperty()) || 2151 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class && 2152 PID->getPropertyDecl()->isClassProperty()) || 2153 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance && 2154 !PID->getPropertyDecl()->isClassProperty())) 2155 return PID; 2156 2157 if (PID->getPropertyDecl()->isClassProperty()) 2158 ClassPropImpl = PID; 2159 } 2160 2161 if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown) 2162 // We can't find the instance property, return the class property. 2163 return ClassPropImpl; 2164 2165 return nullptr; 2166 } 2167 2168 raw_ostream &clang::operator<<(raw_ostream &OS, 2169 const ObjCCategoryImplDecl &CID) { 2170 OS << CID.getName(); 2171 return OS; 2172 } 2173 2174 //===----------------------------------------------------------------------===// 2175 // ObjCImplementationDecl 2176 //===----------------------------------------------------------------------===// 2177 2178 void ObjCImplementationDecl::anchor() {} 2179 2180 ObjCImplementationDecl * 2181 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, 2182 ObjCInterfaceDecl *ClassInterface, 2183 ObjCInterfaceDecl *SuperDecl, 2184 SourceLocation nameLoc, 2185 SourceLocation atStartLoc, 2186 SourceLocation superLoc, 2187 SourceLocation IvarLBraceLoc, 2188 SourceLocation IvarRBraceLoc) { 2189 if (ClassInterface && ClassInterface->hasDefinition()) 2190 ClassInterface = ClassInterface->getDefinition(); 2191 return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl, 2192 nameLoc, atStartLoc, superLoc, 2193 IvarLBraceLoc, IvarRBraceLoc); 2194 } 2195 2196 ObjCImplementationDecl * 2197 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2198 return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr, 2199 SourceLocation(), SourceLocation()); 2200 } 2201 2202 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C, 2203 CXXCtorInitializer ** initializers, 2204 unsigned numInitializers) { 2205 if (numInitializers > 0) { 2206 NumIvarInitializers = numInitializers; 2207 auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers]; 2208 memcpy(ivarInitializers, initializers, 2209 numInitializers * sizeof(CXXCtorInitializer*)); 2210 IvarInitializers = ivarInitializers; 2211 } 2212 } 2213 2214 ObjCImplementationDecl::init_const_iterator 2215 ObjCImplementationDecl::init_begin() const { 2216 return IvarInitializers.get(getASTContext().getExternalSource()); 2217 } 2218 2219 raw_ostream &clang::operator<<(raw_ostream &OS, 2220 const ObjCImplementationDecl &ID) { 2221 OS << ID.getName(); 2222 return OS; 2223 } 2224 2225 //===----------------------------------------------------------------------===// 2226 // ObjCCompatibleAliasDecl 2227 //===----------------------------------------------------------------------===// 2228 2229 void ObjCCompatibleAliasDecl::anchor() {} 2230 2231 ObjCCompatibleAliasDecl * 2232 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC, 2233 SourceLocation L, 2234 IdentifierInfo *Id, 2235 ObjCInterfaceDecl* AliasedClass) { 2236 return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass); 2237 } 2238 2239 ObjCCompatibleAliasDecl * 2240 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2241 return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(), 2242 nullptr, nullptr); 2243 } 2244 2245 //===----------------------------------------------------------------------===// 2246 // ObjCPropertyDecl 2247 //===----------------------------------------------------------------------===// 2248 2249 void ObjCPropertyDecl::anchor() {} 2250 2251 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC, 2252 SourceLocation L, 2253 IdentifierInfo *Id, 2254 SourceLocation AtLoc, 2255 SourceLocation LParenLoc, 2256 QualType T, 2257 TypeSourceInfo *TSI, 2258 PropertyControl propControl) { 2259 return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI, 2260 propControl); 2261 } 2262 2263 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C, 2264 unsigned ID) { 2265 return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr, 2266 SourceLocation(), SourceLocation(), 2267 QualType(), nullptr, None); 2268 } 2269 2270 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const { 2271 return DeclType.substObjCMemberType(objectType, getDeclContext(), 2272 ObjCSubstitutionContext::Property); 2273 } 2274 2275 //===----------------------------------------------------------------------===// 2276 // ObjCPropertyImplDecl 2277 //===----------------------------------------------------------------------===// 2278 2279 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C, 2280 DeclContext *DC, 2281 SourceLocation atLoc, 2282 SourceLocation L, 2283 ObjCPropertyDecl *property, 2284 Kind PK, 2285 ObjCIvarDecl *ivar, 2286 SourceLocation ivarLoc) { 2287 return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar, 2288 ivarLoc); 2289 } 2290 2291 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C, 2292 unsigned ID) { 2293 return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(), 2294 SourceLocation(), nullptr, Dynamic, 2295 nullptr, SourceLocation()); 2296 } 2297 2298 SourceRange ObjCPropertyImplDecl::getSourceRange() const { 2299 SourceLocation EndLoc = getLocation(); 2300 if (IvarLoc.isValid()) 2301 EndLoc = IvarLoc; 2302 2303 return SourceRange(AtLoc, EndLoc); 2304 } 2305