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