1 //===- DeclObjC.cpp - ObjC Declaration AST Node Implementation ------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Objective-C related Decl classes. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclBase.h" 20 #include "clang/AST/Stmt.h" 21 #include "clang/AST/Type.h" 22 #include "clang/AST/TypeLoc.h" 23 #include "clang/Basic/IdentifierTable.h" 24 #include "clang/Basic/LLVM.h" 25 #include "clang/Basic/LangOptions.h" 26 #include "clang/Basic/SourceLocation.h" 27 #include "llvm/ADT/None.h" 28 #include "llvm/ADT/SmallString.h" 29 #include "llvm/ADT/SmallVector.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/raw_ostream.h" 33 #include <algorithm> 34 #include <cassert> 35 #include <cstdint> 36 #include <cstring> 37 #include <utility> 38 39 using namespace clang; 40 41 //===----------------------------------------------------------------------===// 42 // ObjCListBase 43 //===----------------------------------------------------------------------===// 44 45 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) { 46 List = nullptr; 47 if (Elts == 0) return; // Setting to an empty list is a noop. 48 49 List = new (Ctx) void*[Elts]; 50 NumElts = Elts; 51 memcpy(List, InList, sizeof(void*)*Elts); 52 } 53 54 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, 55 const SourceLocation *Locs, ASTContext &Ctx) { 56 if (Elts == 0) 57 return; 58 59 Locations = new (Ctx) SourceLocation[Elts]; 60 memcpy(Locations, Locs, sizeof(SourceLocation) * Elts); 61 set(InList, Elts, Ctx); 62 } 63 64 //===----------------------------------------------------------------------===// 65 // ObjCInterfaceDecl 66 //===----------------------------------------------------------------------===// 67 68 ObjCContainerDecl::ObjCContainerDecl(Kind DK, DeclContext *DC, 69 IdentifierInfo *Id, SourceLocation nameLoc, 70 SourceLocation atStartLoc) 71 : NamedDecl(DK, DC, nameLoc, Id), DeclContext(DK) { 72 setAtStartLoc(atStartLoc); 73 } 74 75 void ObjCContainerDecl::anchor() {} 76 77 /// getIvarDecl - This method looks up an ivar in this ContextDecl. 78 /// 79 ObjCIvarDecl * 80 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const { 81 lookup_result R = lookup(Id); 82 for (lookup_iterator Ivar = R.begin(), IvarEnd = R.end(); 83 Ivar != IvarEnd; ++Ivar) { 84 if (auto *ivar = dyn_cast<ObjCIvarDecl>(*Ivar)) 85 return ivar; 86 } 87 return nullptr; 88 } 89 90 // Get the local instance/class method declared in this interface. 91 ObjCMethodDecl * 92 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance, 93 bool AllowHidden) const { 94 // If this context is a hidden protocol definition, don't find any 95 // methods there. 96 if (const auto *Proto = dyn_cast<ObjCProtocolDecl>(this)) { 97 if (const ObjCProtocolDecl *Def = Proto->getDefinition()) 98 if (Def->isHidden() && !AllowHidden) 99 return nullptr; 100 } 101 102 // Since instance & class methods can have the same name, the loop below 103 // ensures we get the correct method. 104 // 105 // @interface Whatever 106 // - (int) class_method; 107 // + (float) class_method; 108 // @end 109 lookup_result R = lookup(Sel); 110 for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); 111 Meth != MethEnd; ++Meth) { 112 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth); 113 if (MD && MD->isInstanceMethod() == isInstance) 114 return MD; 115 } 116 return nullptr; 117 } 118 119 /// This routine returns 'true' if a user declared setter method was 120 /// found in the class, its protocols, its super classes or categories. 121 /// It also returns 'true' if one of its categories has declared a 'readwrite' 122 /// property. This is because, user must provide a setter method for the 123 /// category's 'readwrite' property. 124 bool ObjCContainerDecl::HasUserDeclaredSetterMethod( 125 const ObjCPropertyDecl *Property) const { 126 Selector Sel = Property->getSetterName(); 127 lookup_result R = lookup(Sel); 128 for (lookup_iterator Meth = R.begin(), MethEnd = R.end(); 129 Meth != MethEnd; ++Meth) { 130 auto *MD = dyn_cast<ObjCMethodDecl>(*Meth); 131 if (MD && MD->isInstanceMethod() && !MD->isImplicit()) 132 return true; 133 } 134 135 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) { 136 // Also look into categories, including class extensions, looking 137 // for a user declared instance method. 138 for (const auto *Cat : ID->visible_categories()) { 139 if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel)) 140 if (!MD->isImplicit()) 141 return true; 142 if (Cat->IsClassExtension()) 143 continue; 144 // Also search through the categories looking for a 'readwrite' 145 // declaration of this property. If one found, presumably a setter will 146 // be provided (properties declared in categories will not get 147 // auto-synthesized). 148 for (const auto *P : Cat->properties()) 149 if (P->getIdentifier() == Property->getIdentifier()) { 150 if (P->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_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->isHidden()) 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->isHidden()) 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(SourceLocation beginLoc, SourceLocation endLoc, 780 Selector SelInfo, QualType T, 781 TypeSourceInfo *ReturnTInfo, 782 DeclContext *contextDecl, bool isInstance, 783 bool isVariadic, bool isPropertyAccessor, 784 bool isImplicitlyDeclared, bool isDefined, 785 ImplementationControl impControl, 786 bool HasRelatedResultType) 787 : NamedDecl(ObjCMethod, contextDecl, beginLoc, SelInfo), 788 DeclContext(ObjCMethod), MethodDeclType(T), ReturnTInfo(ReturnTInfo), 789 DeclEndLoc(endLoc) { 790 791 // Initialized the bits stored in DeclContext. 792 ObjCMethodDeclBits.Family = 793 static_cast<ObjCMethodFamily>(InvalidObjCMethodFamily); 794 setInstanceMethod(isInstance); 795 setVariadic(isVariadic); 796 setPropertyAccessor(isPropertyAccessor); 797 setDefined(isDefined); 798 setIsRedeclaration(false); 799 setHasRedeclaration(false); 800 setDeclImplementation(impControl); 801 setObjCDeclQualifier(OBJC_TQ_None); 802 setRelatedResultType(HasRelatedResultType); 803 setSelLocsKind(SelLoc_StandardNoSpace); 804 setOverriding(false); 805 setHasSkippedBody(false); 806 807 setImplicit(isImplicitlyDeclared); 808 } 809 810 ObjCMethodDecl *ObjCMethodDecl::Create( 811 ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc, 812 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo, 813 DeclContext *contextDecl, bool isInstance, bool isVariadic, 814 bool isPropertyAccessor, bool isImplicitlyDeclared, bool isDefined, 815 ImplementationControl impControl, bool HasRelatedResultType) { 816 return new (C, contextDecl) ObjCMethodDecl( 817 beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance, 818 isVariadic, isPropertyAccessor, isImplicitlyDeclared, isDefined, 819 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::isThisDeclarationADesignatedInitializer() const { 828 return getMethodFamily() == OMF_init && 829 hasAttr<ObjCDesignatedInitializerAttr>(); 830 } 831 832 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface( 833 const ObjCMethodDecl **InitMethod) const { 834 if (getMethodFamily() != OMF_init) 835 return false; 836 const DeclContext *DC = getDeclContext(); 837 if (isa<ObjCProtocolDecl>(DC)) 838 return false; 839 if (const ObjCInterfaceDecl *ID = getClassInterface()) 840 return ID->isDesignatedInitializer(getSelector(), InitMethod); 841 return false; 842 } 843 844 Stmt *ObjCMethodDecl::getBody() const { 845 return Body.get(getASTContext().getExternalSource()); 846 } 847 848 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) { 849 assert(PrevMethod); 850 getASTContext().setObjCMethodRedeclaration(PrevMethod, this); 851 setIsRedeclaration(true); 852 PrevMethod->setHasRedeclaration(true); 853 } 854 855 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C, 856 ArrayRef<ParmVarDecl*> Params, 857 ArrayRef<SourceLocation> SelLocs) { 858 ParamsAndSelLocs = nullptr; 859 NumParams = Params.size(); 860 if (Params.empty() && SelLocs.empty()) 861 return; 862 863 static_assert(alignof(ParmVarDecl *) >= alignof(SourceLocation), 864 "Alignment not sufficient for SourceLocation"); 865 866 unsigned Size = sizeof(ParmVarDecl *) * NumParams + 867 sizeof(SourceLocation) * SelLocs.size(); 868 ParamsAndSelLocs = C.Allocate(Size); 869 std::copy(Params.begin(), Params.end(), getParams()); 870 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs()); 871 } 872 873 void ObjCMethodDecl::getSelectorLocs( 874 SmallVectorImpl<SourceLocation> &SelLocs) const { 875 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i) 876 SelLocs.push_back(getSelectorLoc(i)); 877 } 878 879 void ObjCMethodDecl::setMethodParams(ASTContext &C, 880 ArrayRef<ParmVarDecl*> Params, 881 ArrayRef<SourceLocation> SelLocs) { 882 assert((!SelLocs.empty() || isImplicit()) && 883 "No selector locs for non-implicit method"); 884 if (isImplicit()) 885 return setParamsAndSelLocs(C, Params, llvm::None); 886 887 setSelLocsKind(hasStandardSelectorLocs(getSelector(), SelLocs, Params, 888 DeclEndLoc)); 889 if (getSelLocsKind() != SelLoc_NonStandard) 890 return setParamsAndSelLocs(C, Params, llvm::None); 891 892 setParamsAndSelLocs(C, Params, SelLocs); 893 } 894 895 /// A definition will return its interface declaration. 896 /// An interface declaration will return its definition. 897 /// Otherwise it will return itself. 898 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() { 899 ASTContext &Ctx = getASTContext(); 900 ObjCMethodDecl *Redecl = nullptr; 901 if (hasRedeclaration()) 902 Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this)); 903 if (Redecl) 904 return Redecl; 905 906 auto *CtxD = cast<Decl>(getDeclContext()); 907 908 if (!CtxD->isInvalidDecl()) { 909 if (auto *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) { 910 if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD)) 911 if (!ImplD->isInvalidDecl()) 912 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 913 914 } else if (auto *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) { 915 if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD)) 916 if (!ImplD->isInvalidDecl()) 917 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod()); 918 919 } else if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 920 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 921 if (!IFD->isInvalidDecl()) 922 Redecl = IFD->getMethod(getSelector(), isInstanceMethod()); 923 924 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 925 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 926 if (!CatD->isInvalidDecl()) 927 Redecl = CatD->getMethod(getSelector(), isInstanceMethod()); 928 } 929 } 930 931 // Ensure that the discovered method redeclaration has a valid declaration 932 // context. Used to prevent infinite loops when iterating redeclarations in 933 // a partially invalid AST. 934 if (Redecl && cast<Decl>(Redecl->getDeclContext())->isInvalidDecl()) 935 Redecl = nullptr; 936 937 if (!Redecl && isRedeclaration()) { 938 // This is the last redeclaration, go back to the first method. 939 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(), 940 isInstanceMethod()); 941 } 942 943 return Redecl ? Redecl : this; 944 } 945 946 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() { 947 auto *CtxD = cast<Decl>(getDeclContext()); 948 949 if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) { 950 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface()) 951 if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(), 952 isInstanceMethod())) 953 return MD; 954 } else if (auto *CImplD = dyn_cast<ObjCCategoryImplDecl>(CtxD)) { 955 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl()) 956 if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(), 957 isInstanceMethod())) 958 return MD; 959 } 960 961 if (isRedeclaration()) { 962 // It is possible that we have not done deserializing the ObjCMethod yet. 963 ObjCMethodDecl *MD = 964 cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(), 965 isInstanceMethod()); 966 return MD ? MD : this; 967 } 968 969 return this; 970 } 971 972 SourceLocation ObjCMethodDecl::getEndLoc() const { 973 if (Stmt *Body = getBody()) 974 return Body->getEndLoc(); 975 return DeclEndLoc; 976 } 977 978 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const { 979 auto family = static_cast<ObjCMethodFamily>(ObjCMethodDeclBits.Family); 980 if (family != static_cast<unsigned>(InvalidObjCMethodFamily)) 981 return family; 982 983 // Check for an explicit attribute. 984 if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) { 985 // The unfortunate necessity of mapping between enums here is due 986 // to the attributes framework. 987 switch (attr->getFamily()) { 988 case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break; 989 case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break; 990 case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break; 991 case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break; 992 case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break; 993 case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break; 994 } 995 ObjCMethodDeclBits.Family = family; 996 return family; 997 } 998 999 family = getSelector().getMethodFamily(); 1000 switch (family) { 1001 case OMF_None: break; 1002 1003 // init only has a conventional meaning for an instance method, and 1004 // it has to return an object. 1005 case OMF_init: 1006 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType()) 1007 family = OMF_None; 1008 break; 1009 1010 // alloc/copy/new have a conventional meaning for both class and 1011 // instance methods, but they require an object return. 1012 case OMF_alloc: 1013 case OMF_copy: 1014 case OMF_mutableCopy: 1015 case OMF_new: 1016 if (!getReturnType()->isObjCObjectPointerType()) 1017 family = OMF_None; 1018 break; 1019 1020 // These selectors have a conventional meaning only for instance methods. 1021 case OMF_dealloc: 1022 case OMF_finalize: 1023 case OMF_retain: 1024 case OMF_release: 1025 case OMF_autorelease: 1026 case OMF_retainCount: 1027 case OMF_self: 1028 if (!isInstanceMethod()) 1029 family = OMF_None; 1030 break; 1031 1032 case OMF_initialize: 1033 if (isInstanceMethod() || !getReturnType()->isVoidType()) 1034 family = OMF_None; 1035 break; 1036 1037 case OMF_performSelector: 1038 if (!isInstanceMethod() || !getReturnType()->isObjCIdType()) 1039 family = OMF_None; 1040 else { 1041 unsigned noParams = param_size(); 1042 if (noParams < 1 || noParams > 3) 1043 family = OMF_None; 1044 else { 1045 ObjCMethodDecl::param_type_iterator it = param_type_begin(); 1046 QualType ArgT = (*it); 1047 if (!ArgT->isObjCSelType()) { 1048 family = OMF_None; 1049 break; 1050 } 1051 while (--noParams) { 1052 it++; 1053 ArgT = (*it); 1054 if (!ArgT->isObjCIdType()) { 1055 family = OMF_None; 1056 break; 1057 } 1058 } 1059 } 1060 } 1061 break; 1062 1063 } 1064 1065 // Cache the result. 1066 ObjCMethodDeclBits.Family = family; 1067 return family; 1068 } 1069 1070 QualType ObjCMethodDecl::getSelfType(ASTContext &Context, 1071 const ObjCInterfaceDecl *OID, 1072 bool &selfIsPseudoStrong, 1073 bool &selfIsConsumed) { 1074 QualType selfTy; 1075 selfIsPseudoStrong = false; 1076 selfIsConsumed = false; 1077 if (isInstanceMethod()) { 1078 // There may be no interface context due to error in declaration 1079 // of the interface (which has been reported). Recover gracefully. 1080 if (OID) { 1081 selfTy = Context.getObjCInterfaceType(OID); 1082 selfTy = Context.getObjCObjectPointerType(selfTy); 1083 } else { 1084 selfTy = Context.getObjCIdType(); 1085 } 1086 } else // we have a factory method. 1087 selfTy = Context.getObjCClassType(); 1088 1089 if (Context.getLangOpts().ObjCAutoRefCount) { 1090 if (isInstanceMethod()) { 1091 selfIsConsumed = hasAttr<NSConsumesSelfAttr>(); 1092 1093 // 'self' is always __strong. It's actually pseudo-strong except 1094 // in init methods (or methods labeled ns_consumes_self), though. 1095 Qualifiers qs; 1096 qs.setObjCLifetime(Qualifiers::OCL_Strong); 1097 selfTy = Context.getQualifiedType(selfTy, qs); 1098 1099 // In addition, 'self' is const unless this is an init method. 1100 if (getMethodFamily() != OMF_init && !selfIsConsumed) { 1101 selfTy = selfTy.withConst(); 1102 selfIsPseudoStrong = true; 1103 } 1104 } 1105 else { 1106 assert(isClassMethod()); 1107 // 'self' is always const in class methods. 1108 selfTy = selfTy.withConst(); 1109 selfIsPseudoStrong = true; 1110 } 1111 } 1112 return selfTy; 1113 } 1114 1115 void ObjCMethodDecl::createImplicitParams(ASTContext &Context, 1116 const ObjCInterfaceDecl *OID) { 1117 bool selfIsPseudoStrong, selfIsConsumed; 1118 QualType selfTy = 1119 getSelfType(Context, OID, selfIsPseudoStrong, selfIsConsumed); 1120 auto *Self = ImplicitParamDecl::Create(Context, this, SourceLocation(), 1121 &Context.Idents.get("self"), selfTy, 1122 ImplicitParamDecl::ObjCSelf); 1123 setSelfDecl(Self); 1124 1125 if (selfIsConsumed) 1126 Self->addAttr(NSConsumedAttr::CreateImplicit(Context)); 1127 1128 if (selfIsPseudoStrong) 1129 Self->setARCPseudoStrong(true); 1130 1131 setCmdDecl(ImplicitParamDecl::Create( 1132 Context, this, SourceLocation(), &Context.Idents.get("_cmd"), 1133 Context.getObjCSelType(), ImplicitParamDecl::ObjCCmd)); 1134 } 1135 1136 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() { 1137 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext())) 1138 return ID; 1139 if (auto *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext())) 1140 return CD->getClassInterface(); 1141 if (auto *IMD = dyn_cast<ObjCImplDecl>(getDeclContext())) 1142 return IMD->getClassInterface(); 1143 if (isa<ObjCProtocolDecl>(getDeclContext())) 1144 return nullptr; 1145 llvm_unreachable("unknown method context"); 1146 } 1147 1148 SourceRange ObjCMethodDecl::getReturnTypeSourceRange() const { 1149 const auto *TSI = getReturnTypeSourceInfo(); 1150 if (TSI) 1151 return TSI->getTypeLoc().getSourceRange(); 1152 return SourceRange(); 1153 } 1154 1155 QualType ObjCMethodDecl::getSendResultType() const { 1156 ASTContext &Ctx = getASTContext(); 1157 return getReturnType().getNonLValueExprType(Ctx) 1158 .substObjCTypeArgs(Ctx, {}, ObjCSubstitutionContext::Result); 1159 } 1160 1161 QualType ObjCMethodDecl::getSendResultType(QualType receiverType) const { 1162 // FIXME: Handle related result types here. 1163 1164 return getReturnType().getNonLValueExprType(getASTContext()) 1165 .substObjCMemberType(receiverType, getDeclContext(), 1166 ObjCSubstitutionContext::Result); 1167 } 1168 1169 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container, 1170 const ObjCMethodDecl *Method, 1171 SmallVectorImpl<const ObjCMethodDecl *> &Methods, 1172 bool MovedToSuper) { 1173 if (!Container) 1174 return; 1175 1176 // In categories look for overridden methods from protocols. A method from 1177 // category is not "overridden" since it is considered as the "same" method 1178 // (same USR) as the one from the interface. 1179 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1180 // Check whether we have a matching method at this category but only if we 1181 // are at the super class level. 1182 if (MovedToSuper) 1183 if (ObjCMethodDecl * 1184 Overridden = Container->getMethod(Method->getSelector(), 1185 Method->isInstanceMethod(), 1186 /*AllowHidden=*/true)) 1187 if (Method != Overridden) { 1188 // We found an override at this category; there is no need to look 1189 // into its protocols. 1190 Methods.push_back(Overridden); 1191 return; 1192 } 1193 1194 for (const auto *P : Category->protocols()) 1195 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1196 return; 1197 } 1198 1199 // Check whether we have a matching method at this level. 1200 if (const ObjCMethodDecl * 1201 Overridden = Container->getMethod(Method->getSelector(), 1202 Method->isInstanceMethod(), 1203 /*AllowHidden=*/true)) 1204 if (Method != Overridden) { 1205 // We found an override at this level; there is no need to look 1206 // into other protocols or categories. 1207 Methods.push_back(Overridden); 1208 return; 1209 } 1210 1211 if (const auto *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){ 1212 for (const auto *P : Protocol->protocols()) 1213 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1214 } 1215 1216 if (const auto *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) { 1217 for (const auto *P : Interface->protocols()) 1218 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper); 1219 1220 for (const auto *Cat : Interface->known_categories()) 1221 CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper); 1222 1223 if (const ObjCInterfaceDecl *Super = Interface->getSuperClass()) 1224 return CollectOverriddenMethodsRecurse(Super, Method, Methods, 1225 /*MovedToSuper=*/true); 1226 } 1227 } 1228 1229 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container, 1230 const ObjCMethodDecl *Method, 1231 SmallVectorImpl<const ObjCMethodDecl *> &Methods) { 1232 CollectOverriddenMethodsRecurse(Container, Method, Methods, 1233 /*MovedToSuper=*/false); 1234 } 1235 1236 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method, 1237 SmallVectorImpl<const ObjCMethodDecl *> &overridden) { 1238 assert(Method->isOverriding()); 1239 1240 if (const auto *ProtD = 1241 dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) { 1242 CollectOverriddenMethods(ProtD, Method, overridden); 1243 1244 } else if (const auto *IMD = 1245 dyn_cast<ObjCImplDecl>(Method->getDeclContext())) { 1246 const ObjCInterfaceDecl *ID = IMD->getClassInterface(); 1247 if (!ID) 1248 return; 1249 // Start searching for overridden methods using the method from the 1250 // interface as starting point. 1251 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1252 Method->isInstanceMethod(), 1253 /*AllowHidden=*/true)) 1254 Method = IFaceMeth; 1255 CollectOverriddenMethods(ID, Method, overridden); 1256 1257 } else if (const auto *CatD = 1258 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) { 1259 const ObjCInterfaceDecl *ID = CatD->getClassInterface(); 1260 if (!ID) 1261 return; 1262 // Start searching for overridden methods using the method from the 1263 // interface as starting point. 1264 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(), 1265 Method->isInstanceMethod(), 1266 /*AllowHidden=*/true)) 1267 Method = IFaceMeth; 1268 CollectOverriddenMethods(ID, Method, overridden); 1269 1270 } else { 1271 CollectOverriddenMethods( 1272 dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()), 1273 Method, overridden); 1274 } 1275 } 1276 1277 void ObjCMethodDecl::getOverriddenMethods( 1278 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const { 1279 const ObjCMethodDecl *Method = this; 1280 1281 if (Method->isRedeclaration()) { 1282 Method = cast<ObjCContainerDecl>(Method->getDeclContext())-> 1283 getMethod(Method->getSelector(), Method->isInstanceMethod()); 1284 } 1285 1286 if (Method->isOverriding()) { 1287 collectOverriddenMethodsSlow(Method, Overridden); 1288 assert(!Overridden.empty() && 1289 "ObjCMethodDecl's overriding bit is not as expected"); 1290 } 1291 } 1292 1293 const ObjCPropertyDecl * 1294 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const { 1295 Selector Sel = getSelector(); 1296 unsigned NumArgs = Sel.getNumArgs(); 1297 if (NumArgs > 1) 1298 return nullptr; 1299 1300 if (isPropertyAccessor()) { 1301 const auto *Container = cast<ObjCContainerDecl>(getParent()); 1302 bool IsGetter = (NumArgs == 0); 1303 bool IsInstance = isInstanceMethod(); 1304 1305 /// Local function that attempts to find a matching property within the 1306 /// given Objective-C container. 1307 auto findMatchingProperty = 1308 [&](const ObjCContainerDecl *Container) -> const ObjCPropertyDecl * { 1309 if (IsInstance) { 1310 for (const auto *I : Container->instance_properties()) { 1311 Selector NextSel = IsGetter ? I->getGetterName() 1312 : I->getSetterName(); 1313 if (NextSel == Sel) 1314 return I; 1315 } 1316 } else { 1317 for (const auto *I : Container->class_properties()) { 1318 Selector NextSel = IsGetter ? I->getGetterName() 1319 : I->getSetterName(); 1320 if (NextSel == Sel) 1321 return I; 1322 } 1323 } 1324 1325 return nullptr; 1326 }; 1327 1328 // Look in the container we were given. 1329 if (const auto *Found = findMatchingProperty(Container)) 1330 return Found; 1331 1332 // If we're in a category or extension, look in the main class. 1333 const ObjCInterfaceDecl *ClassDecl = nullptr; 1334 if (const auto *Category = dyn_cast<ObjCCategoryDecl>(Container)) { 1335 ClassDecl = Category->getClassInterface(); 1336 if (const auto *Found = findMatchingProperty(ClassDecl)) 1337 return Found; 1338 } else { 1339 // Determine whether the container is a class. 1340 ClassDecl = dyn_cast<ObjCInterfaceDecl>(Container); 1341 } 1342 1343 // If we have a class, check its visible extensions. 1344 if (ClassDecl) { 1345 for (const auto *Ext : ClassDecl->visible_extensions()) { 1346 if (Ext == Container) 1347 continue; 1348 1349 if (const auto *Found = findMatchingProperty(Ext)) 1350 return Found; 1351 } 1352 } 1353 1354 llvm_unreachable("Marked as a property accessor but no property found!"); 1355 } 1356 1357 if (!CheckOverrides) 1358 return nullptr; 1359 1360 using OverridesTy = SmallVector<const ObjCMethodDecl *, 8>; 1361 1362 OverridesTy Overrides; 1363 getOverriddenMethods(Overrides); 1364 for (const auto *Override : Overrides) 1365 if (const ObjCPropertyDecl *Prop = Override->findPropertyDecl(false)) 1366 return Prop; 1367 1368 return nullptr; 1369 } 1370 1371 //===----------------------------------------------------------------------===// 1372 // ObjCTypeParamDecl 1373 //===----------------------------------------------------------------------===// 1374 1375 void ObjCTypeParamDecl::anchor() {} 1376 1377 ObjCTypeParamDecl *ObjCTypeParamDecl::Create(ASTContext &ctx, DeclContext *dc, 1378 ObjCTypeParamVariance variance, 1379 SourceLocation varianceLoc, 1380 unsigned index, 1381 SourceLocation nameLoc, 1382 IdentifierInfo *name, 1383 SourceLocation colonLoc, 1384 TypeSourceInfo *boundInfo) { 1385 auto *TPDecl = 1386 new (ctx, dc) ObjCTypeParamDecl(ctx, dc, variance, varianceLoc, index, 1387 nameLoc, name, colonLoc, boundInfo); 1388 QualType TPType = ctx.getObjCTypeParamType(TPDecl, {}); 1389 TPDecl->setTypeForDecl(TPType.getTypePtr()); 1390 return TPDecl; 1391 } 1392 1393 ObjCTypeParamDecl *ObjCTypeParamDecl::CreateDeserialized(ASTContext &ctx, 1394 unsigned ID) { 1395 return new (ctx, ID) ObjCTypeParamDecl(ctx, nullptr, 1396 ObjCTypeParamVariance::Invariant, 1397 SourceLocation(), 0, SourceLocation(), 1398 nullptr, SourceLocation(), nullptr); 1399 } 1400 1401 SourceRange ObjCTypeParamDecl::getSourceRange() const { 1402 SourceLocation startLoc = VarianceLoc; 1403 if (startLoc.isInvalid()) 1404 startLoc = getLocation(); 1405 1406 if (hasExplicitBound()) { 1407 return SourceRange(startLoc, 1408 getTypeSourceInfo()->getTypeLoc().getEndLoc()); 1409 } 1410 1411 return SourceRange(startLoc); 1412 } 1413 1414 //===----------------------------------------------------------------------===// 1415 // ObjCTypeParamList 1416 //===----------------------------------------------------------------------===// 1417 ObjCTypeParamList::ObjCTypeParamList(SourceLocation lAngleLoc, 1418 ArrayRef<ObjCTypeParamDecl *> typeParams, 1419 SourceLocation rAngleLoc) 1420 : NumParams(typeParams.size()) { 1421 Brackets.Begin = lAngleLoc.getRawEncoding(); 1422 Brackets.End = rAngleLoc.getRawEncoding(); 1423 std::copy(typeParams.begin(), typeParams.end(), begin()); 1424 } 1425 1426 ObjCTypeParamList *ObjCTypeParamList::create( 1427 ASTContext &ctx, 1428 SourceLocation lAngleLoc, 1429 ArrayRef<ObjCTypeParamDecl *> typeParams, 1430 SourceLocation rAngleLoc) { 1431 void *mem = 1432 ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()), 1433 alignof(ObjCTypeParamList)); 1434 return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc); 1435 } 1436 1437 void ObjCTypeParamList::gatherDefaultTypeArgs( 1438 SmallVectorImpl<QualType> &typeArgs) const { 1439 typeArgs.reserve(size()); 1440 for (auto typeParam : *this) 1441 typeArgs.push_back(typeParam->getUnderlyingType()); 1442 } 1443 1444 //===----------------------------------------------------------------------===// 1445 // ObjCInterfaceDecl 1446 //===----------------------------------------------------------------------===// 1447 1448 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C, 1449 DeclContext *DC, 1450 SourceLocation atLoc, 1451 IdentifierInfo *Id, 1452 ObjCTypeParamList *typeParamList, 1453 ObjCInterfaceDecl *PrevDecl, 1454 SourceLocation ClassLoc, 1455 bool isInternal){ 1456 auto *Result = new (C, DC) 1457 ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl, 1458 isInternal); 1459 Result->Data.setInt(!C.getLangOpts().Modules); 1460 C.getObjCInterfaceType(Result, PrevDecl); 1461 return Result; 1462 } 1463 1464 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C, 1465 unsigned ID) { 1466 auto *Result = new (C, ID) 1467 ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr, 1468 SourceLocation(), nullptr, false); 1469 Result->Data.setInt(!C.getLangOpts().Modules); 1470 return Result; 1471 } 1472 1473 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC, 1474 SourceLocation AtLoc, IdentifierInfo *Id, 1475 ObjCTypeParamList *typeParamList, 1476 SourceLocation CLoc, 1477 ObjCInterfaceDecl *PrevDecl, 1478 bool IsInternal) 1479 : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc), 1480 redeclarable_base(C) { 1481 setPreviousDecl(PrevDecl); 1482 1483 // Copy the 'data' pointer over. 1484 if (PrevDecl) 1485 Data = PrevDecl->Data; 1486 1487 setImplicit(IsInternal); 1488 1489 setTypeParamList(typeParamList); 1490 } 1491 1492 void ObjCInterfaceDecl::LoadExternalDefinition() const { 1493 assert(data().ExternallyCompleted && "Class is not externally completed"); 1494 data().ExternallyCompleted = false; 1495 getASTContext().getExternalSource()->CompleteType( 1496 const_cast<ObjCInterfaceDecl *>(this)); 1497 } 1498 1499 void ObjCInterfaceDecl::setExternallyCompleted() { 1500 assert(getASTContext().getExternalSource() && 1501 "Class can't be externally completed without an external source"); 1502 assert(hasDefinition() && 1503 "Forward declarations can't be externally completed"); 1504 data().ExternallyCompleted = true; 1505 } 1506 1507 void ObjCInterfaceDecl::setHasDesignatedInitializers() { 1508 // Check for a complete definition and recover if not so. 1509 if (!isThisDeclarationADefinition()) 1510 return; 1511 data().HasDesignatedInitializers = true; 1512 } 1513 1514 bool ObjCInterfaceDecl::hasDesignatedInitializers() const { 1515 // Check for a complete definition and recover if not so. 1516 if (!isThisDeclarationADefinition()) 1517 return false; 1518 if (data().ExternallyCompleted) 1519 LoadExternalDefinition(); 1520 1521 return data().HasDesignatedInitializers; 1522 } 1523 1524 StringRef 1525 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const { 1526 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 1527 return ObjCRTName->getMetadataName(); 1528 1529 return getName(); 1530 } 1531 1532 StringRef 1533 ObjCImplementationDecl::getObjCRuntimeNameAsString() const { 1534 if (ObjCInterfaceDecl *ID = 1535 const_cast<ObjCImplementationDecl*>(this)->getClassInterface()) 1536 return ID->getObjCRuntimeNameAsString(); 1537 1538 return getName(); 1539 } 1540 1541 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const { 1542 if (const ObjCInterfaceDecl *Def = getDefinition()) { 1543 if (data().ExternallyCompleted) 1544 LoadExternalDefinition(); 1545 1546 return getASTContext().getObjCImplementation( 1547 const_cast<ObjCInterfaceDecl*>(Def)); 1548 } 1549 1550 // FIXME: Should make sure no callers ever do this. 1551 return nullptr; 1552 } 1553 1554 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) { 1555 getASTContext().setObjCImplementation(getDefinition(), ImplD); 1556 } 1557 1558 namespace { 1559 1560 struct SynthesizeIvarChunk { 1561 uint64_t Size; 1562 ObjCIvarDecl *Ivar; 1563 1564 SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar) 1565 : Size(size), Ivar(ivar) {} 1566 }; 1567 1568 bool operator<(const SynthesizeIvarChunk & LHS, 1569 const SynthesizeIvarChunk &RHS) { 1570 return LHS.Size < RHS.Size; 1571 } 1572 1573 } // namespace 1574 1575 /// all_declared_ivar_begin - return first ivar declared in this class, 1576 /// its extensions and its implementation. Lazily build the list on first 1577 /// access. 1578 /// 1579 /// Caveat: The list returned by this method reflects the current 1580 /// state of the parser. The cache will be updated for every ivar 1581 /// added by an extension or the implementation when they are 1582 /// encountered. 1583 /// See also ObjCIvarDecl::Create(). 1584 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() { 1585 // FIXME: Should make sure no callers ever do this. 1586 if (!hasDefinition()) 1587 return nullptr; 1588 1589 ObjCIvarDecl *curIvar = nullptr; 1590 if (!data().IvarList) { 1591 if (!ivar_empty()) { 1592 ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end(); 1593 data().IvarList = *I; ++I; 1594 for (curIvar = data().IvarList; I != E; curIvar = *I, ++I) 1595 curIvar->setNextIvar(*I); 1596 } 1597 1598 for (const auto *Ext : known_extensions()) { 1599 if (!Ext->ivar_empty()) { 1600 ObjCCategoryDecl::ivar_iterator 1601 I = Ext->ivar_begin(), 1602 E = Ext->ivar_end(); 1603 if (!data().IvarList) { 1604 data().IvarList = *I; ++I; 1605 curIvar = data().IvarList; 1606 } 1607 for ( ;I != E; curIvar = *I, ++I) 1608 curIvar->setNextIvar(*I); 1609 } 1610 } 1611 data().IvarListMissingImplementation = true; 1612 } 1613 1614 // cached and complete! 1615 if (!data().IvarListMissingImplementation) 1616 return data().IvarList; 1617 1618 if (ObjCImplementationDecl *ImplDecl = getImplementation()) { 1619 data().IvarListMissingImplementation = false; 1620 if (!ImplDecl->ivar_empty()) { 1621 SmallVector<SynthesizeIvarChunk, 16> layout; 1622 for (auto *IV : ImplDecl->ivars()) { 1623 if (IV->getSynthesize() && !IV->isInvalidDecl()) { 1624 layout.push_back(SynthesizeIvarChunk( 1625 IV->getASTContext().getTypeSize(IV->getType()), IV)); 1626 continue; 1627 } 1628 if (!data().IvarList) 1629 data().IvarList = IV; 1630 else 1631 curIvar->setNextIvar(IV); 1632 curIvar = IV; 1633 } 1634 1635 if (!layout.empty()) { 1636 // Order synthesized ivars by their size. 1637 std::stable_sort(layout.begin(), layout.end()); 1638 unsigned Ix = 0, EIx = layout.size(); 1639 if (!data().IvarList) { 1640 data().IvarList = layout[0].Ivar; Ix++; 1641 curIvar = data().IvarList; 1642 } 1643 for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++) 1644 curIvar->setNextIvar(layout[Ix].Ivar); 1645 } 1646 } 1647 } 1648 return data().IvarList; 1649 } 1650 1651 /// FindCategoryDeclaration - Finds category declaration in the list of 1652 /// categories for this class and returns it. Name of the category is passed 1653 /// in 'CategoryId'. If category not found, return 0; 1654 /// 1655 ObjCCategoryDecl * 1656 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const { 1657 // FIXME: Should make sure no callers ever do this. 1658 if (!hasDefinition()) 1659 return nullptr; 1660 1661 if (data().ExternallyCompleted) 1662 LoadExternalDefinition(); 1663 1664 for (auto *Cat : visible_categories()) 1665 if (Cat->getIdentifier() == CategoryId) 1666 return Cat; 1667 1668 return nullptr; 1669 } 1670 1671 ObjCMethodDecl * 1672 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const { 1673 for (const auto *Cat : visible_categories()) { 1674 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1675 if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel)) 1676 return MD; 1677 } 1678 1679 return nullptr; 1680 } 1681 1682 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const { 1683 for (const auto *Cat : visible_categories()) { 1684 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation()) 1685 if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel)) 1686 return MD; 1687 } 1688 1689 return nullptr; 1690 } 1691 1692 /// ClassImplementsProtocol - Checks that 'lProto' protocol 1693 /// has been implemented in IDecl class, its super class or categories (if 1694 /// lookupCategory is true). 1695 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto, 1696 bool lookupCategory, 1697 bool RHSIsQualifiedID) { 1698 if (!hasDefinition()) 1699 return false; 1700 1701 ObjCInterfaceDecl *IDecl = this; 1702 // 1st, look up the class. 1703 for (auto *PI : IDecl->protocols()){ 1704 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1705 return true; 1706 // This is dubious and is added to be compatible with gcc. In gcc, it is 1707 // also allowed assigning a protocol-qualified 'id' type to a LHS object 1708 // when protocol in qualified LHS is in list of protocols in the rhs 'id' 1709 // object. This IMO, should be a bug. 1710 // FIXME: Treat this as an extension, and flag this as an error when GCC 1711 // extensions are not enabled. 1712 if (RHSIsQualifiedID && 1713 getASTContext().ProtocolCompatibleWithProtocol(PI, lProto)) 1714 return true; 1715 } 1716 1717 // 2nd, look up the category. 1718 if (lookupCategory) 1719 for (const auto *Cat : visible_categories()) { 1720 for (auto *PI : Cat->protocols()) 1721 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI)) 1722 return true; 1723 } 1724 1725 // 3rd, look up the super class(s) 1726 if (IDecl->getSuperClass()) 1727 return 1728 IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory, 1729 RHSIsQualifiedID); 1730 1731 return false; 1732 } 1733 1734 //===----------------------------------------------------------------------===// 1735 // ObjCIvarDecl 1736 //===----------------------------------------------------------------------===// 1737 1738 void ObjCIvarDecl::anchor() {} 1739 1740 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC, 1741 SourceLocation StartLoc, 1742 SourceLocation IdLoc, IdentifierInfo *Id, 1743 QualType T, TypeSourceInfo *TInfo, 1744 AccessControl ac, Expr *BW, 1745 bool synthesized) { 1746 if (DC) { 1747 // Ivar's can only appear in interfaces, implementations (via synthesized 1748 // properties), and class extensions (via direct declaration, or synthesized 1749 // properties). 1750 // 1751 // FIXME: This should really be asserting this: 1752 // (isa<ObjCCategoryDecl>(DC) && 1753 // cast<ObjCCategoryDecl>(DC)->IsClassExtension())) 1754 // but unfortunately we sometimes place ivars into non-class extension 1755 // categories on error. This breaks an AST invariant, and should not be 1756 // fixed. 1757 assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) || 1758 isa<ObjCCategoryDecl>(DC)) && 1759 "Invalid ivar decl context!"); 1760 // Once a new ivar is created in any of class/class-extension/implementation 1761 // decl contexts, the previously built IvarList must be rebuilt. 1762 auto *ID = dyn_cast<ObjCInterfaceDecl>(DC); 1763 if (!ID) { 1764 if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC)) 1765 ID = IM->getClassInterface(); 1766 else 1767 ID = cast<ObjCCategoryDecl>(DC)->getClassInterface(); 1768 } 1769 ID->setIvarList(nullptr); 1770 } 1771 1772 return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW, 1773 synthesized); 1774 } 1775 1776 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1777 return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(), 1778 nullptr, QualType(), nullptr, 1779 ObjCIvarDecl::None, nullptr, false); 1780 } 1781 1782 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const { 1783 const auto *DC = cast<ObjCContainerDecl>(getDeclContext()); 1784 1785 switch (DC->getKind()) { 1786 default: 1787 case ObjCCategoryImpl: 1788 case ObjCProtocol: 1789 llvm_unreachable("invalid ivar container!"); 1790 1791 // Ivars can only appear in class extension categories. 1792 case ObjCCategory: { 1793 const auto *CD = cast<ObjCCategoryDecl>(DC); 1794 assert(CD->IsClassExtension() && "invalid container for ivar!"); 1795 return CD->getClassInterface(); 1796 } 1797 1798 case ObjCImplementation: 1799 return cast<ObjCImplementationDecl>(DC)->getClassInterface(); 1800 1801 case ObjCInterface: 1802 return cast<ObjCInterfaceDecl>(DC); 1803 } 1804 } 1805 1806 QualType ObjCIvarDecl::getUsageType(QualType objectType) const { 1807 return getType().substObjCMemberType(objectType, getDeclContext(), 1808 ObjCSubstitutionContext::Property); 1809 } 1810 1811 //===----------------------------------------------------------------------===// 1812 // ObjCAtDefsFieldDecl 1813 //===----------------------------------------------------------------------===// 1814 1815 void ObjCAtDefsFieldDecl::anchor() {} 1816 1817 ObjCAtDefsFieldDecl 1818 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC, 1819 SourceLocation StartLoc, SourceLocation IdLoc, 1820 IdentifierInfo *Id, QualType T, Expr *BW) { 1821 return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW); 1822 } 1823 1824 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C, 1825 unsigned ID) { 1826 return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(), 1827 SourceLocation(), nullptr, QualType(), 1828 nullptr); 1829 } 1830 1831 //===----------------------------------------------------------------------===// 1832 // ObjCProtocolDecl 1833 //===----------------------------------------------------------------------===// 1834 1835 void ObjCProtocolDecl::anchor() {} 1836 1837 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC, 1838 IdentifierInfo *Id, SourceLocation nameLoc, 1839 SourceLocation atStartLoc, 1840 ObjCProtocolDecl *PrevDecl) 1841 : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc), 1842 redeclarable_base(C) { 1843 setPreviousDecl(PrevDecl); 1844 if (PrevDecl) 1845 Data = PrevDecl->Data; 1846 } 1847 1848 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC, 1849 IdentifierInfo *Id, 1850 SourceLocation nameLoc, 1851 SourceLocation atStartLoc, 1852 ObjCProtocolDecl *PrevDecl) { 1853 auto *Result = 1854 new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl); 1855 Result->Data.setInt(!C.getLangOpts().Modules); 1856 return Result; 1857 } 1858 1859 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C, 1860 unsigned ID) { 1861 ObjCProtocolDecl *Result = 1862 new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(), 1863 SourceLocation(), nullptr); 1864 Result->Data.setInt(!C.getLangOpts().Modules); 1865 return Result; 1866 } 1867 1868 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) { 1869 ObjCProtocolDecl *PDecl = this; 1870 1871 if (Name == getIdentifier()) 1872 return PDecl; 1873 1874 for (auto *I : protocols()) 1875 if ((PDecl = I->lookupProtocolNamed(Name))) 1876 return PDecl; 1877 1878 return nullptr; 1879 } 1880 1881 // lookupMethod - Lookup a instance/class method in the protocol and protocols 1882 // it inherited. 1883 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel, 1884 bool isInstance) const { 1885 ObjCMethodDecl *MethodDecl = nullptr; 1886 1887 // If there is no definition or the definition is hidden, we don't find 1888 // anything. 1889 const ObjCProtocolDecl *Def = getDefinition(); 1890 if (!Def || Def->isHidden()) 1891 return nullptr; 1892 1893 if ((MethodDecl = getMethod(Sel, isInstance))) 1894 return MethodDecl; 1895 1896 for (const auto *I : protocols()) 1897 if ((MethodDecl = I->lookupMethod(Sel, isInstance))) 1898 return MethodDecl; 1899 return nullptr; 1900 } 1901 1902 void ObjCProtocolDecl::allocateDefinitionData() { 1903 assert(!Data.getPointer() && "Protocol already has a definition!"); 1904 Data.setPointer(new (getASTContext()) DefinitionData); 1905 Data.getPointer()->Definition = this; 1906 } 1907 1908 void ObjCProtocolDecl::startDefinition() { 1909 allocateDefinitionData(); 1910 1911 // Update all of the declarations with a pointer to the definition. 1912 for (auto *RD : redecls()) 1913 RD->Data = this->Data; 1914 } 1915 1916 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM, 1917 PropertyDeclOrder &PO) const { 1918 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 1919 for (auto *Prop : PDecl->properties()) { 1920 // Insert into PM if not there already. 1921 PM.insert(std::make_pair( 1922 std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()), 1923 Prop)); 1924 PO.push_back(Prop); 1925 } 1926 // Scan through protocol's protocols. 1927 for (const auto *PI : PDecl->protocols()) 1928 PI->collectPropertiesToImplement(PM, PO); 1929 } 1930 } 1931 1932 void ObjCProtocolDecl::collectInheritedProtocolProperties( 1933 const ObjCPropertyDecl *Property, ProtocolPropertySet &PS, 1934 PropertyDeclOrder &PO) const { 1935 if (const ObjCProtocolDecl *PDecl = getDefinition()) { 1936 if (!PS.insert(PDecl).second) 1937 return; 1938 for (auto *Prop : PDecl->properties()) { 1939 if (Prop == Property) 1940 continue; 1941 if (Prop->getIdentifier() == Property->getIdentifier()) { 1942 PO.push_back(Prop); 1943 return; 1944 } 1945 } 1946 // Scan through protocol's protocols which did not have a matching property. 1947 for (const auto *PI : PDecl->protocols()) 1948 PI->collectInheritedProtocolProperties(Property, PS, PO); 1949 } 1950 } 1951 1952 StringRef 1953 ObjCProtocolDecl::getObjCRuntimeNameAsString() const { 1954 if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>()) 1955 return ObjCRTName->getMetadataName(); 1956 1957 return getName(); 1958 } 1959 1960 //===----------------------------------------------------------------------===// 1961 // ObjCCategoryDecl 1962 //===----------------------------------------------------------------------===// 1963 1964 void ObjCCategoryDecl::anchor() {} 1965 1966 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc, 1967 SourceLocation ClassNameLoc, 1968 SourceLocation CategoryNameLoc, 1969 IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, 1970 ObjCTypeParamList *typeParamList, 1971 SourceLocation IvarLBraceLoc, 1972 SourceLocation IvarRBraceLoc) 1973 : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc), 1974 ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc), 1975 IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) { 1976 setTypeParamList(typeParamList); 1977 } 1978 1979 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC, 1980 SourceLocation AtLoc, 1981 SourceLocation ClassNameLoc, 1982 SourceLocation CategoryNameLoc, 1983 IdentifierInfo *Id, 1984 ObjCInterfaceDecl *IDecl, 1985 ObjCTypeParamList *typeParamList, 1986 SourceLocation IvarLBraceLoc, 1987 SourceLocation IvarRBraceLoc) { 1988 auto *CatDecl = 1989 new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id, 1990 IDecl, typeParamList, IvarLBraceLoc, 1991 IvarRBraceLoc); 1992 if (IDecl) { 1993 // Link this category into its class's category list. 1994 CatDecl->NextClassCategory = IDecl->getCategoryListRaw(); 1995 if (IDecl->hasDefinition()) { 1996 IDecl->setCategoryListRaw(CatDecl); 1997 if (ASTMutationListener *L = C.getASTMutationListener()) 1998 L->AddedObjCCategoryToInterface(CatDecl, IDecl); 1999 } 2000 } 2001 2002 return CatDecl; 2003 } 2004 2005 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C, 2006 unsigned ID) { 2007 return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(), 2008 SourceLocation(), SourceLocation(), 2009 nullptr, nullptr, nullptr); 2010 } 2011 2012 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const { 2013 return getASTContext().getObjCImplementation( 2014 const_cast<ObjCCategoryDecl*>(this)); 2015 } 2016 2017 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) { 2018 getASTContext().setObjCImplementation(this, ImplD); 2019 } 2020 2021 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) { 2022 TypeParamList = TPL; 2023 if (!TPL) 2024 return; 2025 // Set the declaration context of each of the type parameters. 2026 for (auto *typeParam : *TypeParamList) 2027 typeParam->setDeclContext(this); 2028 } 2029 2030 //===----------------------------------------------------------------------===// 2031 // ObjCCategoryImplDecl 2032 //===----------------------------------------------------------------------===// 2033 2034 void ObjCCategoryImplDecl::anchor() {} 2035 2036 ObjCCategoryImplDecl * 2037 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC, 2038 IdentifierInfo *Id, 2039 ObjCInterfaceDecl *ClassInterface, 2040 SourceLocation nameLoc, 2041 SourceLocation atStartLoc, 2042 SourceLocation CategoryNameLoc) { 2043 if (ClassInterface && ClassInterface->hasDefinition()) 2044 ClassInterface = ClassInterface->getDefinition(); 2045 return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc, 2046 atStartLoc, CategoryNameLoc); 2047 } 2048 2049 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C, 2050 unsigned ID) { 2051 return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr, 2052 SourceLocation(), SourceLocation(), 2053 SourceLocation()); 2054 } 2055 2056 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const { 2057 // The class interface might be NULL if we are working with invalid code. 2058 if (const ObjCInterfaceDecl *ID = getClassInterface()) 2059 return ID->FindCategoryDeclaration(getIdentifier()); 2060 return nullptr; 2061 } 2062 2063 void ObjCImplDecl::anchor() {} 2064 2065 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) { 2066 // FIXME: The context should be correct before we get here. 2067 property->setLexicalDeclContext(this); 2068 addDecl(property); 2069 } 2070 2071 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) { 2072 ASTContext &Ctx = getASTContext(); 2073 2074 if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) { 2075 if (IFace) 2076 Ctx.setObjCImplementation(IFace, ImplD); 2077 2078 } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) { 2079 if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier())) 2080 Ctx.setObjCImplementation(CD, ImplD); 2081 } 2082 2083 ClassInterface = IFace; 2084 } 2085 2086 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of 2087 /// properties implemented in this \@implementation block and returns 2088 /// the implemented property that uses it. 2089 ObjCPropertyImplDecl *ObjCImplDecl:: 2090 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const { 2091 for (auto *PID : property_impls()) 2092 if (PID->getPropertyIvarDecl() && 2093 PID->getPropertyIvarDecl()->getIdentifier() == ivarId) 2094 return PID; 2095 return nullptr; 2096 } 2097 2098 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl 2099 /// added to the list of those properties \@synthesized/\@dynamic in this 2100 /// category \@implementation block. 2101 ObjCPropertyImplDecl *ObjCImplDecl:: 2102 FindPropertyImplDecl(IdentifierInfo *Id, 2103 ObjCPropertyQueryKind QueryKind) const { 2104 ObjCPropertyImplDecl *ClassPropImpl = nullptr; 2105 for (auto *PID : property_impls()) 2106 // If queryKind is unknown, we return the instance property if one 2107 // exists; otherwise we return the class property. 2108 if (PID->getPropertyDecl()->getIdentifier() == Id) { 2109 if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown && 2110 !PID->getPropertyDecl()->isClassProperty()) || 2111 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class && 2112 PID->getPropertyDecl()->isClassProperty()) || 2113 (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance && 2114 !PID->getPropertyDecl()->isClassProperty())) 2115 return PID; 2116 2117 if (PID->getPropertyDecl()->isClassProperty()) 2118 ClassPropImpl = PID; 2119 } 2120 2121 if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown) 2122 // We can't find the instance property, return the class property. 2123 return ClassPropImpl; 2124 2125 return nullptr; 2126 } 2127 2128 raw_ostream &clang::operator<<(raw_ostream &OS, 2129 const ObjCCategoryImplDecl &CID) { 2130 OS << CID.getName(); 2131 return OS; 2132 } 2133 2134 //===----------------------------------------------------------------------===// 2135 // ObjCImplementationDecl 2136 //===----------------------------------------------------------------------===// 2137 2138 void ObjCImplementationDecl::anchor() {} 2139 2140 ObjCImplementationDecl * 2141 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC, 2142 ObjCInterfaceDecl *ClassInterface, 2143 ObjCInterfaceDecl *SuperDecl, 2144 SourceLocation nameLoc, 2145 SourceLocation atStartLoc, 2146 SourceLocation superLoc, 2147 SourceLocation IvarLBraceLoc, 2148 SourceLocation IvarRBraceLoc) { 2149 if (ClassInterface && ClassInterface->hasDefinition()) 2150 ClassInterface = ClassInterface->getDefinition(); 2151 return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl, 2152 nameLoc, atStartLoc, superLoc, 2153 IvarLBraceLoc, IvarRBraceLoc); 2154 } 2155 2156 ObjCImplementationDecl * 2157 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2158 return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr, 2159 SourceLocation(), SourceLocation()); 2160 } 2161 2162 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C, 2163 CXXCtorInitializer ** initializers, 2164 unsigned numInitializers) { 2165 if (numInitializers > 0) { 2166 NumIvarInitializers = numInitializers; 2167 auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers]; 2168 memcpy(ivarInitializers, initializers, 2169 numInitializers * sizeof(CXXCtorInitializer*)); 2170 IvarInitializers = ivarInitializers; 2171 } 2172 } 2173 2174 ObjCImplementationDecl::init_const_iterator 2175 ObjCImplementationDecl::init_begin() const { 2176 return IvarInitializers.get(getASTContext().getExternalSource()); 2177 } 2178 2179 raw_ostream &clang::operator<<(raw_ostream &OS, 2180 const ObjCImplementationDecl &ID) { 2181 OS << ID.getName(); 2182 return OS; 2183 } 2184 2185 //===----------------------------------------------------------------------===// 2186 // ObjCCompatibleAliasDecl 2187 //===----------------------------------------------------------------------===// 2188 2189 void ObjCCompatibleAliasDecl::anchor() {} 2190 2191 ObjCCompatibleAliasDecl * 2192 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC, 2193 SourceLocation L, 2194 IdentifierInfo *Id, 2195 ObjCInterfaceDecl* AliasedClass) { 2196 return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass); 2197 } 2198 2199 ObjCCompatibleAliasDecl * 2200 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2201 return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(), 2202 nullptr, nullptr); 2203 } 2204 2205 //===----------------------------------------------------------------------===// 2206 // ObjCPropertyDecl 2207 //===----------------------------------------------------------------------===// 2208 2209 void ObjCPropertyDecl::anchor() {} 2210 2211 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC, 2212 SourceLocation L, 2213 IdentifierInfo *Id, 2214 SourceLocation AtLoc, 2215 SourceLocation LParenLoc, 2216 QualType T, 2217 TypeSourceInfo *TSI, 2218 PropertyControl propControl) { 2219 return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI, 2220 propControl); 2221 } 2222 2223 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C, 2224 unsigned ID) { 2225 return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr, 2226 SourceLocation(), SourceLocation(), 2227 QualType(), nullptr, None); 2228 } 2229 2230 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const { 2231 return DeclType.substObjCMemberType(objectType, getDeclContext(), 2232 ObjCSubstitutionContext::Property); 2233 } 2234 2235 //===----------------------------------------------------------------------===// 2236 // ObjCPropertyImplDecl 2237 //===----------------------------------------------------------------------===// 2238 2239 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C, 2240 DeclContext *DC, 2241 SourceLocation atLoc, 2242 SourceLocation L, 2243 ObjCPropertyDecl *property, 2244 Kind PK, 2245 ObjCIvarDecl *ivar, 2246 SourceLocation ivarLoc) { 2247 return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar, 2248 ivarLoc); 2249 } 2250 2251 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C, 2252 unsigned ID) { 2253 return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(), 2254 SourceLocation(), nullptr, Dynamic, 2255 nullptr, SourceLocation()); 2256 } 2257 2258 SourceRange ObjCPropertyImplDecl::getSourceRange() const { 2259 SourceLocation EndLoc = getLocation(); 2260 if (IvarLoc.isValid()) 2261 EndLoc = IvarLoc; 2262 2263 return SourceRange(AtLoc, EndLoc); 2264 } 2265