1 //===--- DeclObjC.cpp - ObjC Declaration AST Node Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Objective-C related Decl classes.
12 //===----------------------------------------------------------------------===//
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/Stmt.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallString.h"
21 using namespace clang;
23 //===----------------------------------------------------------------------===//
25 //===----------------------------------------------------------------------===//
27 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) {
29 if (Elts == 0) return; // Setting to an empty list is a noop.
32 List = new (Ctx) void*[Elts];
34 memcpy(List, InList, sizeof(void*)*Elts);
37 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts,
38 const SourceLocation *Locs, ASTContext &Ctx) {
42 Locations = new (Ctx) SourceLocation[Elts];
43 memcpy(Locations, Locs, sizeof(SourceLocation) * Elts);
44 set(InList, Elts, Ctx);
47 //===----------------------------------------------------------------------===//
49 //===----------------------------------------------------------------------===//
51 void ObjCContainerDecl::anchor() { }
53 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
56 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
57 lookup_const_result R = lookup(Id);
58 for (lookup_const_iterator Ivar = R.begin(), IvarEnd = R.end();
59 Ivar != IvarEnd; ++Ivar) {
60 if (ObjCIvarDecl *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
66 // Get the local instance/class method declared in this interface.
68 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance,
69 bool AllowHidden) const {
70 // If this context is a hidden protocol definition, don't find any
72 if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
73 if (const ObjCProtocolDecl *Def = Proto->getDefinition())
74 if (Def->isHidden() && !AllowHidden)
78 // Since instance & class methods can have the same name, the loop below
79 // ensures we get the correct method.
81 // @interface Whatever
82 // - (int) class_method;
83 // + (float) class_method;
86 lookup_const_result R = lookup(Sel);
87 for (lookup_const_iterator Meth = R.begin(), MethEnd = R.end();
88 Meth != MethEnd; ++Meth) {
89 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
90 if (MD && MD->isInstanceMethod() == isInstance)
96 /// HasUserDeclaredSetterMethod - This routine returns 'true' if a user declared setter
97 /// method was found in the class, its protocols, its super classes or categories.
98 /// It also returns 'true' if one of its categories has declared a 'readwrite' property.
99 /// This is because, user must provide a setter method for the category's 'readwrite'
102 ObjCContainerDecl::HasUserDeclaredSetterMethod(const ObjCPropertyDecl *Property) const {
103 Selector Sel = Property->getSetterName();
104 lookup_const_result R = lookup(Sel);
105 for (lookup_const_iterator Meth = R.begin(), MethEnd = R.end();
106 Meth != MethEnd; ++Meth) {
107 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
108 if (MD && MD->isInstanceMethod() && !MD->isImplicit())
112 if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
113 // Also look into categories, including class extensions, looking
114 // for a user declared instance method.
115 for (const auto *Cat : ID->visible_categories()) {
116 if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel))
117 if (!MD->isImplicit())
119 if (Cat->IsClassExtension())
121 // Also search through the categories looking for a 'readwrite' declaration
122 // of this property. If one found, presumably a setter will be provided
123 // (properties declared in categories will not get auto-synthesized).
124 for (const auto *P : Cat->properties())
125 if (P->getIdentifier() == Property->getIdentifier()) {
126 if (P->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite)
132 // Also look into protocols, for a user declared instance method.
133 for (const auto *Proto : ID->all_referenced_protocols())
134 if (Proto->HasUserDeclaredSetterMethod(Property))
137 // And in its super class.
138 ObjCInterfaceDecl *OSC = ID->getSuperClass();
140 if (OSC->HasUserDeclaredSetterMethod(Property))
142 OSC = OSC->getSuperClass();
145 if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(this))
146 for (const auto *PI : PD->protocols())
147 if (PI->HasUserDeclaredSetterMethod(Property))
153 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
154 IdentifierInfo *propertyID) {
155 // If this context is a hidden protocol definition, don't find any
157 if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(DC)) {
158 if (const ObjCProtocolDecl *Def = Proto->getDefinition())
163 DeclContext::lookup_const_result R = DC->lookup(propertyID);
164 for (DeclContext::lookup_const_iterator I = R.begin(), E = R.end(); I != E;
166 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(*I))
173 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const {
174 SmallString<128> ivarName;
176 llvm::raw_svector_ostream os(ivarName);
177 os << '_' << getIdentifier()->getName();
179 return &Ctx.Idents.get(ivarName.str());
182 /// FindPropertyDeclaration - Finds declaration of the property given its name
183 /// in 'PropertyId' and returns it. It returns 0, if not found.
185 ObjCContainerDecl::FindPropertyDeclaration(IdentifierInfo *PropertyId) const {
186 // Don't find properties within hidden protocol definitions.
187 if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
188 if (const ObjCProtocolDecl *Def = Proto->getDefinition())
193 if (ObjCPropertyDecl *PD =
194 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
200 case Decl::ObjCProtocol: {
201 const ObjCProtocolDecl *PID = cast<ObjCProtocolDecl>(this);
202 for (const auto *I : PID->protocols())
203 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId))
207 case Decl::ObjCInterface: {
208 const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(this);
209 // Look through categories (but not extensions).
210 for (const auto *Cat : OID->visible_categories()) {
211 if (!Cat->IsClassExtension())
212 if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(PropertyId))
216 // Look through protocols.
217 for (const auto *I : OID->all_referenced_protocols())
218 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId))
221 // Finally, check the super class.
222 if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
223 return superClass->FindPropertyDeclaration(PropertyId);
226 case Decl::ObjCCategory: {
227 const ObjCCategoryDecl *OCD = cast<ObjCCategoryDecl>(this);
228 // Look through protocols.
229 if (!OCD->IsClassExtension())
230 for (const auto *I : OCD->protocols())
231 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId))
239 void ObjCInterfaceDecl::anchor() { }
241 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
242 /// with name 'PropertyId' in the primary class; including those in protocols
243 /// (direct or indirect) used by the primary class.
246 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
247 IdentifierInfo *PropertyId) const {
248 // FIXME: Should make sure no callers ever do this.
249 if (!hasDefinition())
252 if (data().ExternallyCompleted)
253 LoadExternalDefinition();
255 if (ObjCPropertyDecl *PD =
256 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
259 // Look through protocols.
260 for (const auto *I : all_referenced_protocols())
261 if (ObjCPropertyDecl *P = I->FindPropertyDeclaration(PropertyId))
267 void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM,
268 PropertyDeclOrder &PO) const {
269 for (auto *Prop : properties()) {
270 PM[Prop->getIdentifier()] = Prop;
273 for (const auto *PI : all_referenced_protocols())
274 PI->collectPropertiesToImplement(PM, PO);
275 // Note, the properties declared only in class extensions are still copied
276 // into the main @interface's property list, and therefore we don't
277 // explicitly, have to search class extension properties.
280 bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const {
281 const ObjCInterfaceDecl *Class = this;
283 if (Class->hasAttr<ArcWeakrefUnavailableAttr>())
285 Class = Class->getSuperClass();
290 const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const {
291 const ObjCInterfaceDecl *Class = this;
293 if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>())
295 Class = Class->getSuperClass();
300 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
301 ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
304 if (data().ExternallyCompleted)
305 LoadExternalDefinition();
307 if (data().AllReferencedProtocols.empty() &&
308 data().ReferencedProtocols.empty()) {
309 data().AllReferencedProtocols.set(ExtList, ExtNum, C);
313 // Check for duplicate protocol in class's protocol list.
314 // This is O(n*m). But it is extremely rare and number of protocols in
315 // class or its extension are very few.
316 SmallVector<ObjCProtocolDecl*, 8> ProtocolRefs;
317 for (unsigned i = 0; i < ExtNum; i++) {
318 bool protocolExists = false;
319 ObjCProtocolDecl *ProtoInExtension = ExtList[i];
320 for (auto *Proto : all_referenced_protocols()) {
321 if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
322 protocolExists = true;
326 // Do we want to warn on a protocol in extension class which
327 // already exist in the class? Probably not.
329 ProtocolRefs.push_back(ProtoInExtension);
332 if (ProtocolRefs.empty())
335 // Merge ProtocolRefs into class's protocol list;
336 for (auto *P : all_referenced_protocols()) {
337 ProtocolRefs.push_back(P);
340 data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
343 const ObjCInterfaceDecl *
344 ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const {
345 const ObjCInterfaceDecl *IFace = this;
347 if (IFace->hasDesignatedInitializers())
349 if (!IFace->inheritsDesignatedInitializers())
351 IFace = IFace->getSuperClass();
356 static bool isIntroducingInitializers(const ObjCInterfaceDecl *D) {
357 for (const auto *MD : D->instance_methods()) {
358 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
361 for (const auto *Ext : D->visible_extensions()) {
362 for (const auto *MD : Ext->instance_methods()) {
363 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
367 if (const auto *ImplD = D->getImplementation()) {
368 for (const auto *MD : ImplD->instance_methods()) {
369 if (MD->getMethodFamily() == OMF_init && !MD->isOverriding())
376 bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const {
377 switch (data().InheritedDesignatedInitializers) {
378 case DefinitionData::IDI_Inherited:
380 case DefinitionData::IDI_NotInherited:
382 case DefinitionData::IDI_Unknown: {
383 // If the class introduced initializers we conservatively assume that we
384 // don't know if any of them is a designated initializer to avoid possible
385 // misleading warnings.
386 if (isIntroducingInitializers(this)) {
387 data().InheritedDesignatedInitializers = DefinitionData::IDI_NotInherited;
389 if (auto SuperD = getSuperClass()) {
390 data().InheritedDesignatedInitializers =
391 SuperD->declaresOrInheritsDesignatedInitializers() ?
392 DefinitionData::IDI_Inherited :
393 DefinitionData::IDI_NotInherited;
395 data().InheritedDesignatedInitializers =
396 DefinitionData::IDI_NotInherited;
399 assert(data().InheritedDesignatedInitializers
400 != DefinitionData::IDI_Unknown);
401 return data().InheritedDesignatedInitializers ==
402 DefinitionData::IDI_Inherited;
406 llvm_unreachable("unexpected InheritedDesignatedInitializers value");
409 void ObjCInterfaceDecl::getDesignatedInitializers(
410 llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const {
411 // Check for a complete definition and recover if not so.
412 if (!isThisDeclarationADefinition())
414 if (data().ExternallyCompleted)
415 LoadExternalDefinition();
417 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
421 for (const auto *MD : IFace->instance_methods())
422 if (MD->isThisDeclarationADesignatedInitializer())
423 Methods.push_back(MD);
424 for (const auto *Ext : IFace->visible_extensions()) {
425 for (const auto *MD : Ext->instance_methods())
426 if (MD->isThisDeclarationADesignatedInitializer())
427 Methods.push_back(MD);
431 bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel,
432 const ObjCMethodDecl **InitMethod) const {
433 // Check for a complete definition and recover if not so.
434 if (!isThisDeclarationADefinition())
436 if (data().ExternallyCompleted)
437 LoadExternalDefinition();
439 const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
443 if (const ObjCMethodDecl *MD = IFace->getInstanceMethod(Sel)) {
444 if (MD->isThisDeclarationADesignatedInitializer()) {
450 for (const auto *Ext : IFace->visible_extensions()) {
451 if (const ObjCMethodDecl *MD = Ext->getInstanceMethod(Sel)) {
452 if (MD->isThisDeclarationADesignatedInitializer()) {
462 void ObjCInterfaceDecl::allocateDefinitionData() {
463 assert(!hasDefinition() && "ObjC class already has a definition");
464 Data.setPointer(new (getASTContext()) DefinitionData());
465 Data.getPointer()->Definition = this;
467 // Make the type point at the definition, now that we have one.
469 cast<ObjCInterfaceType>(TypeForDecl)->Decl = this;
472 void ObjCInterfaceDecl::startDefinition() {
473 allocateDefinitionData();
475 // Update all of the declarations with a pointer to the definition.
476 for (auto RD : redecls()) {
482 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
483 ObjCInterfaceDecl *&clsDeclared) {
484 // FIXME: Should make sure no callers ever do this.
485 if (!hasDefinition())
488 if (data().ExternallyCompleted)
489 LoadExternalDefinition();
491 ObjCInterfaceDecl* ClassDecl = this;
492 while (ClassDecl != nullptr) {
493 if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
494 clsDeclared = ClassDecl;
498 for (const auto *Ext : ClassDecl->visible_extensions()) {
499 if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) {
500 clsDeclared = ClassDecl;
505 ClassDecl = ClassDecl->getSuperClass();
510 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
511 /// class whose name is passed as argument. If it is not one of the super classes
512 /// the it returns NULL.
513 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
514 const IdentifierInfo*ICName) {
515 // FIXME: Should make sure no callers ever do this.
516 if (!hasDefinition())
519 if (data().ExternallyCompleted)
520 LoadExternalDefinition();
522 ObjCInterfaceDecl* ClassDecl = this;
523 while (ClassDecl != nullptr) {
524 if (ClassDecl->getIdentifier() == ICName)
526 ClassDecl = ClassDecl->getSuperClass();
532 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) {
533 for (auto *P : all_referenced_protocols())
534 if (P->lookupProtocolNamed(Name))
536 ObjCInterfaceDecl *SuperClass = getSuperClass();
537 return SuperClass ? SuperClass->lookupNestedProtocol(Name) : nullptr;
540 /// lookupMethod - This method returns an instance/class method by looking in
541 /// the class, its categories, and its super classes (using a linear search).
542 /// When argument category "C" is specified, any implicit method found
543 /// in this category is ignored.
544 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
546 bool shallowCategoryLookup,
548 const ObjCCategoryDecl *C) const
550 // FIXME: Should make sure no callers ever do this.
551 if (!hasDefinition())
554 const ObjCInterfaceDecl* ClassDecl = this;
555 ObjCMethodDecl *MethodDecl = nullptr;
557 if (data().ExternallyCompleted)
558 LoadExternalDefinition();
561 if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
564 // Didn't find one yet - look through protocols.
565 for (const auto *I : ClassDecl->protocols())
566 if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
569 // Didn't find one yet - now look through categories.
570 for (const auto *Cat : ClassDecl->visible_categories()) {
571 if ((MethodDecl = Cat->getMethod(Sel, isInstance)))
572 if (C != Cat || !MethodDecl->isImplicit())
575 if (!shallowCategoryLookup) {
576 // Didn't find one yet - look through protocols.
577 const ObjCList<ObjCProtocolDecl> &Protocols =
578 Cat->getReferencedProtocols();
579 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
580 E = Protocols.end(); I != E; ++I)
581 if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
582 if (C != Cat || !MethodDecl->isImplicit())
590 // Get the super class (if any).
591 ClassDecl = ClassDecl->getSuperClass();
596 // Will search "local" class/category implementations for a method decl.
597 // If failed, then we search in class's root for an instance method.
598 // Returns 0 if no method is found.
599 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
601 bool Instance) const {
602 // FIXME: Should make sure no callers ever do this.
603 if (!hasDefinition())
606 if (data().ExternallyCompleted)
607 LoadExternalDefinition();
609 ObjCMethodDecl *Method = nullptr;
610 if (ObjCImplementationDecl *ImpDecl = getImplementation())
611 Method = Instance ? ImpDecl->getInstanceMethod(Sel)
612 : ImpDecl->getClassMethod(Sel);
614 // Look through local category implementations associated with the class.
616 Method = Instance ? getCategoryInstanceMethod(Sel)
617 : getCategoryClassMethod(Sel);
619 // Before we give up, check if the selector is an instance method.
620 // But only in the root. This matches gcc's behavior and what the
622 if (!Instance && !Method && !getSuperClass()) {
623 Method = lookupInstanceMethod(Sel);
624 // Look through local category implementations associated
625 // with the root class.
627 Method = lookupPrivateMethod(Sel, true);
630 if (!Method && getSuperClass())
631 return getSuperClass()->lookupPrivateMethod(Sel, Instance);
635 //===----------------------------------------------------------------------===//
637 //===----------------------------------------------------------------------===//
639 ObjCMethodDecl *ObjCMethodDecl::Create(
640 ASTContext &C, SourceLocation beginLoc, SourceLocation endLoc,
641 Selector SelInfo, QualType T, TypeSourceInfo *ReturnTInfo,
642 DeclContext *contextDecl, bool isInstance, bool isVariadic,
643 bool isPropertyAccessor, bool isImplicitlyDeclared, bool isDefined,
644 ImplementationControl impControl, bool HasRelatedResultType) {
645 return new (C, contextDecl) ObjCMethodDecl(
646 beginLoc, endLoc, SelInfo, T, ReturnTInfo, contextDecl, isInstance,
647 isVariadic, isPropertyAccessor, isImplicitlyDeclared, isDefined,
648 impControl, HasRelatedResultType);
651 ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
652 return new (C, ID) ObjCMethodDecl(SourceLocation(), SourceLocation(),
653 Selector(), QualType(), nullptr, nullptr);
656 bool ObjCMethodDecl::isThisDeclarationADesignatedInitializer() const {
657 return getMethodFamily() == OMF_init &&
658 hasAttr<ObjCDesignatedInitializerAttr>();
661 bool ObjCMethodDecl::isDesignatedInitializerForTheInterface(
662 const ObjCMethodDecl **InitMethod) const {
663 if (getMethodFamily() != OMF_init)
665 const DeclContext *DC = getDeclContext();
666 if (isa<ObjCProtocolDecl>(DC))
668 if (const ObjCInterfaceDecl *ID = getClassInterface())
669 return ID->isDesignatedInitializer(getSelector(), InitMethod);
673 Stmt *ObjCMethodDecl::getBody() const {
674 return Body.get(getASTContext().getExternalSource());
677 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) {
679 getASTContext().setObjCMethodRedeclaration(PrevMethod, this);
680 IsRedeclaration = true;
681 PrevMethod->HasRedeclaration = true;
684 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
685 ArrayRef<ParmVarDecl*> Params,
686 ArrayRef<SourceLocation> SelLocs) {
687 ParamsAndSelLocs = nullptr;
688 NumParams = Params.size();
689 if (Params.empty() && SelLocs.empty())
692 unsigned Size = sizeof(ParmVarDecl *) * NumParams +
693 sizeof(SourceLocation) * SelLocs.size();
694 ParamsAndSelLocs = C.Allocate(Size);
695 std::copy(Params.begin(), Params.end(), getParams());
696 std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
699 void ObjCMethodDecl::getSelectorLocs(
700 SmallVectorImpl<SourceLocation> &SelLocs) const {
701 for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
702 SelLocs.push_back(getSelectorLoc(i));
705 void ObjCMethodDecl::setMethodParams(ASTContext &C,
706 ArrayRef<ParmVarDecl*> Params,
707 ArrayRef<SourceLocation> SelLocs) {
708 assert((!SelLocs.empty() || isImplicit()) &&
709 "No selector locs for non-implicit method");
711 return setParamsAndSelLocs(C, Params, llvm::None);
713 SelLocsKind = hasStandardSelectorLocs(getSelector(), SelLocs, Params,
715 if (SelLocsKind != SelLoc_NonStandard)
716 return setParamsAndSelLocs(C, Params, llvm::None);
718 setParamsAndSelLocs(C, Params, SelLocs);
721 /// \brief A definition will return its interface declaration.
722 /// An interface declaration will return its definition.
723 /// Otherwise it will return itself.
724 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclarationImpl() {
725 ASTContext &Ctx = getASTContext();
726 ObjCMethodDecl *Redecl = nullptr;
727 if (HasRedeclaration)
728 Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this));
732 Decl *CtxD = cast<Decl>(getDeclContext());
734 if (!CtxD->isInvalidDecl()) {
735 if (ObjCInterfaceDecl *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
736 if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
737 if (!ImplD->isInvalidDecl())
738 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
740 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
741 if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
742 if (!ImplD->isInvalidDecl())
743 Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
745 } else if (ObjCImplementationDecl *ImplD =
746 dyn_cast<ObjCImplementationDecl>(CtxD)) {
747 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
748 if (!IFD->isInvalidDecl())
749 Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
751 } else if (ObjCCategoryImplDecl *CImplD =
752 dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
753 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
754 if (!CatD->isInvalidDecl())
755 Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
759 if (!Redecl && isRedeclaration()) {
760 // This is the last redeclaration, go back to the first method.
761 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
765 return Redecl ? Redecl : this;
768 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
769 Decl *CtxD = cast<Decl>(getDeclContext());
771 if (ObjCImplementationDecl *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
772 if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
773 if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
777 } else if (ObjCCategoryImplDecl *CImplD =
778 dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
779 if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
780 if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),
785 if (isRedeclaration())
786 return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
792 SourceLocation ObjCMethodDecl::getLocEnd() const {
793 if (Stmt *Body = getBody())
794 return Body->getLocEnd();
798 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
799 ObjCMethodFamily family = static_cast<ObjCMethodFamily>(Family);
800 if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
803 // Check for an explicit attribute.
804 if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
805 // The unfortunate necessity of mapping between enums here is due
806 // to the attributes framework.
807 switch (attr->getFamily()) {
808 case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
809 case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
810 case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
811 case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
812 case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
813 case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
815 Family = static_cast<unsigned>(family);
819 family = getSelector().getMethodFamily();
821 case OMF_None: break;
823 // init only has a conventional meaning for an instance method, and
824 // it has to return an object.
826 if (!isInstanceMethod() || !getReturnType()->isObjCObjectPointerType())
830 // alloc/copy/new have a conventional meaning for both class and
831 // instance methods, but they require an object return.
834 case OMF_mutableCopy:
836 if (!getReturnType()->isObjCObjectPointerType())
840 // These selectors have a conventional meaning only for instance methods.
845 case OMF_autorelease:
846 case OMF_retainCount:
848 if (!isInstanceMethod())
852 case OMF_performSelector:
853 if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
856 unsigned noParams = param_size();
857 if (noParams < 1 || noParams > 3)
860 ObjCMethodDecl::param_type_iterator it = param_type_begin();
861 QualType ArgT = (*it);
862 if (!ArgT->isObjCSelType()) {
869 if (!ArgT->isObjCIdType()) {
881 Family = static_cast<unsigned>(family);
885 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
886 const ObjCInterfaceDecl *OID) {
888 if (isInstanceMethod()) {
889 // There may be no interface context due to error in declaration
890 // of the interface (which has been reported). Recover gracefully.
892 selfTy = Context.getObjCInterfaceType(OID);
893 selfTy = Context.getObjCObjectPointerType(selfTy);
895 selfTy = Context.getObjCIdType();
897 } else // we have a factory method.
898 selfTy = Context.getObjCClassType();
900 bool selfIsPseudoStrong = false;
901 bool selfIsConsumed = false;
903 if (Context.getLangOpts().ObjCAutoRefCount) {
904 if (isInstanceMethod()) {
905 selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
907 // 'self' is always __strong. It's actually pseudo-strong except
908 // in init methods (or methods labeled ns_consumes_self), though.
910 qs.setObjCLifetime(Qualifiers::OCL_Strong);
911 selfTy = Context.getQualifiedType(selfTy, qs);
913 // In addition, 'self' is const unless this is an init method.
914 if (getMethodFamily() != OMF_init && !selfIsConsumed) {
915 selfTy = selfTy.withConst();
916 selfIsPseudoStrong = true;
920 assert(isClassMethod());
921 // 'self' is always const in class methods.
922 selfTy = selfTy.withConst();
923 selfIsPseudoStrong = true;
927 ImplicitParamDecl *self
928 = ImplicitParamDecl::Create(Context, this, SourceLocation(),
929 &Context.Idents.get("self"), selfTy);
933 self->addAttr(NSConsumedAttr::CreateImplicit(Context));
935 if (selfIsPseudoStrong)
936 self->setARCPseudoStrong(true);
938 setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(),
939 &Context.Idents.get("_cmd"),
940 Context.getObjCSelType()));
943 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
944 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
946 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
947 return CD->getClassInterface();
948 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
949 return IMD->getClassInterface();
950 if (isa<ObjCProtocolDecl>(getDeclContext()))
952 llvm_unreachable("unknown method context");
955 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container,
956 const ObjCMethodDecl *Method,
957 SmallVectorImpl<const ObjCMethodDecl *> &Methods,
962 // In categories look for overriden methods from protocols. A method from
963 // category is not "overriden" since it is considered as the "same" method
964 // (same USR) as the one from the interface.
965 if (const ObjCCategoryDecl *
966 Category = dyn_cast<ObjCCategoryDecl>(Container)) {
967 // Check whether we have a matching method at this category but only if we
968 // are at the super class level.
971 Overridden = Container->getMethod(Method->getSelector(),
972 Method->isInstanceMethod(),
973 /*AllowHidden=*/true))
974 if (Method != Overridden) {
975 // We found an override at this category; there is no need to look
976 // into its protocols.
977 Methods.push_back(Overridden);
981 for (const auto *P : Category->protocols())
982 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
986 // Check whether we have a matching method at this level.
987 if (const ObjCMethodDecl *
988 Overridden = Container->getMethod(Method->getSelector(),
989 Method->isInstanceMethod(),
990 /*AllowHidden=*/true))
991 if (Method != Overridden) {
992 // We found an override at this level; there is no need to look
993 // into other protocols or categories.
994 Methods.push_back(Overridden);
998 if (const ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){
999 for (const auto *P : Protocol->protocols())
1000 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1003 if (const ObjCInterfaceDecl *
1004 Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
1005 for (const auto *P : Interface->protocols())
1006 CollectOverriddenMethodsRecurse(P, Method, Methods, MovedToSuper);
1008 for (const auto *Cat : Interface->known_categories())
1009 CollectOverriddenMethodsRecurse(Cat, Method, Methods, MovedToSuper);
1011 if (const ObjCInterfaceDecl *Super = Interface->getSuperClass())
1012 return CollectOverriddenMethodsRecurse(Super, Method, Methods,
1013 /*MovedToSuper=*/true);
1017 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container,
1018 const ObjCMethodDecl *Method,
1019 SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
1020 CollectOverriddenMethodsRecurse(Container, Method, Methods,
1021 /*MovedToSuper=*/false);
1024 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
1025 SmallVectorImpl<const ObjCMethodDecl *> &overridden) {
1026 assert(Method->isOverriding());
1028 if (const ObjCProtocolDecl *
1029 ProtD = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
1030 CollectOverriddenMethods(ProtD, Method, overridden);
1032 } else if (const ObjCImplDecl *
1033 IMD = dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
1034 const ObjCInterfaceDecl *ID = IMD->getClassInterface();
1037 // Start searching for overridden methods using the method from the
1038 // interface as starting point.
1039 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1040 Method->isInstanceMethod(),
1041 /*AllowHidden=*/true))
1043 CollectOverriddenMethods(ID, Method, overridden);
1045 } else if (const ObjCCategoryDecl *
1046 CatD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
1047 const ObjCInterfaceDecl *ID = CatD->getClassInterface();
1050 // Start searching for overridden methods using the method from the
1051 // interface as starting point.
1052 if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1053 Method->isInstanceMethod(),
1054 /*AllowHidden=*/true))
1056 CollectOverriddenMethods(ID, Method, overridden);
1059 CollectOverriddenMethods(
1060 dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
1061 Method, overridden);
1065 void ObjCMethodDecl::getOverriddenMethods(
1066 SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
1067 const ObjCMethodDecl *Method = this;
1069 if (Method->isRedeclaration()) {
1070 Method = cast<ObjCContainerDecl>(Method->getDeclContext())->
1071 getMethod(Method->getSelector(), Method->isInstanceMethod());
1074 if (Method->isOverriding()) {
1075 collectOverriddenMethodsSlow(Method, Overridden);
1076 assert(!Overridden.empty() &&
1077 "ObjCMethodDecl's overriding bit is not as expected");
1081 const ObjCPropertyDecl *
1082 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const {
1083 Selector Sel = getSelector();
1084 unsigned NumArgs = Sel.getNumArgs();
1088 if (!isInstanceMethod() || getMethodFamily() != OMF_None)
1091 if (isPropertyAccessor()) {
1092 const ObjCContainerDecl *Container = cast<ObjCContainerDecl>(getParent());
1093 // If container is class extension, find its primary class.
1094 if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(Container))
1095 if (CatDecl->IsClassExtension())
1096 Container = CatDecl->getClassInterface();
1098 bool IsGetter = (NumArgs == 0);
1100 for (const auto *I : Container->properties()) {
1101 Selector NextSel = IsGetter ? I->getGetterName()
1102 : I->getSetterName();
1107 llvm_unreachable("Marked as a property accessor but no property found!");
1110 if (!CheckOverrides)
1113 typedef SmallVector<const ObjCMethodDecl *, 8> OverridesTy;
1114 OverridesTy Overrides;
1115 getOverriddenMethods(Overrides);
1116 for (OverridesTy::const_iterator I = Overrides.begin(), E = Overrides.end();
1118 if (const ObjCPropertyDecl *Prop = (*I)->findPropertyDecl(false))
1125 //===----------------------------------------------------------------------===//
1126 // ObjCInterfaceDecl
1127 //===----------------------------------------------------------------------===//
1129 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1131 SourceLocation atLoc,
1133 ObjCInterfaceDecl *PrevDecl,
1134 SourceLocation ClassLoc,
1136 ObjCInterfaceDecl *Result = new (C, DC)
1137 ObjCInterfaceDecl(C, DC, atLoc, Id, ClassLoc, PrevDecl, isInternal);
1138 Result->Data.setInt(!C.getLangOpts().Modules);
1139 C.getObjCInterfaceType(Result, PrevDecl);
1143 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C,
1145 ObjCInterfaceDecl *Result = new (C, ID) ObjCInterfaceDecl(C, nullptr,
1150 Result->Data.setInt(!C.getLangOpts().Modules);
1154 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC,
1155 SourceLocation AtLoc, IdentifierInfo *Id,
1156 SourceLocation CLoc,
1157 ObjCInterfaceDecl *PrevDecl,
1159 : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc),
1160 redeclarable_base(C), TypeForDecl(nullptr), Data() {
1161 setPreviousDecl(PrevDecl);
1163 // Copy the 'data' pointer over.
1165 Data = PrevDecl->Data;
1167 setImplicit(IsInternal);
1170 void ObjCInterfaceDecl::LoadExternalDefinition() const {
1171 assert(data().ExternallyCompleted && "Class is not externally completed");
1172 data().ExternallyCompleted = false;
1173 getASTContext().getExternalSource()->CompleteType(
1174 const_cast<ObjCInterfaceDecl *>(this));
1177 void ObjCInterfaceDecl::setExternallyCompleted() {
1178 assert(getASTContext().getExternalSource() &&
1179 "Class can't be externally completed without an external source");
1180 assert(hasDefinition() &&
1181 "Forward declarations can't be externally completed");
1182 data().ExternallyCompleted = true;
1185 void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1186 // Check for a complete definition and recover if not so.
1187 if (!isThisDeclarationADefinition())
1189 data().HasDesignatedInitializers = true;
1192 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1193 // Check for a complete definition and recover if not so.
1194 if (!isThisDeclarationADefinition())
1196 if (data().ExternallyCompleted)
1197 LoadExternalDefinition();
1199 return data().HasDesignatedInitializers;
1203 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1204 if (ObjCRuntimeNameAttr *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1205 return ObjCRTName->getMetadataName();
1211 ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1212 if (ObjCInterfaceDecl *ID =
1213 const_cast<ObjCImplementationDecl*>(this)->getClassInterface())
1214 return ID->getObjCRuntimeNameAsString();
1219 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1220 if (const ObjCInterfaceDecl *Def = getDefinition()) {
1221 if (data().ExternallyCompleted)
1222 LoadExternalDefinition();
1224 return getASTContext().getObjCImplementation(
1225 const_cast<ObjCInterfaceDecl*>(Def));
1228 // FIXME: Should make sure no callers ever do this.
1232 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1233 getASTContext().setObjCImplementation(getDefinition(), ImplD);
1237 struct SynthesizeIvarChunk {
1240 SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1241 : Size(size), Ivar(ivar) {}
1244 bool operator<(const SynthesizeIvarChunk & LHS,
1245 const SynthesizeIvarChunk &RHS) {
1246 return LHS.Size < RHS.Size;
1250 /// all_declared_ivar_begin - return first ivar declared in this class,
1251 /// its extensions and its implementation. Lazily build the list on first
1254 /// Caveat: The list returned by this method reflects the current
1255 /// state of the parser. The cache will be updated for every ivar
1256 /// added by an extension or the implementation when they are
1258 /// See also ObjCIvarDecl::Create().
1259 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1260 // FIXME: Should make sure no callers ever do this.
1261 if (!hasDefinition())
1264 ObjCIvarDecl *curIvar = nullptr;
1265 if (!data().IvarList) {
1266 if (!ivar_empty()) {
1267 ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1268 data().IvarList = *I; ++I;
1269 for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1270 curIvar->setNextIvar(*I);
1273 for (const auto *Ext : known_extensions()) {
1274 if (!Ext->ivar_empty()) {
1275 ObjCCategoryDecl::ivar_iterator
1276 I = Ext->ivar_begin(),
1277 E = Ext->ivar_end();
1278 if (!data().IvarList) {
1279 data().IvarList = *I; ++I;
1280 curIvar = data().IvarList;
1282 for ( ;I != E; curIvar = *I, ++I)
1283 curIvar->setNextIvar(*I);
1286 data().IvarListMissingImplementation = true;
1289 // cached and complete!
1290 if (!data().IvarListMissingImplementation)
1291 return data().IvarList;
1293 if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
1294 data().IvarListMissingImplementation = false;
1295 if (!ImplDecl->ivar_empty()) {
1296 SmallVector<SynthesizeIvarChunk, 16> layout;
1297 for (auto *IV : ImplDecl->ivars()) {
1298 if (IV->getSynthesize() && !IV->isInvalidDecl()) {
1299 layout.push_back(SynthesizeIvarChunk(
1300 IV->getASTContext().getTypeSize(IV->getType()), IV));
1303 if (!data().IvarList)
1304 data().IvarList = IV;
1306 curIvar->setNextIvar(IV);
1310 if (!layout.empty()) {
1311 // Order synthesized ivars by their size.
1312 std::stable_sort(layout.begin(), layout.end());
1313 unsigned Ix = 0, EIx = layout.size();
1314 if (!data().IvarList) {
1315 data().IvarList = layout[0].Ivar; Ix++;
1316 curIvar = data().IvarList;
1318 for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1319 curIvar->setNextIvar(layout[Ix].Ivar);
1323 return data().IvarList;
1326 /// FindCategoryDeclaration - Finds category declaration in the list of
1327 /// categories for this class and returns it. Name of the category is passed
1328 /// in 'CategoryId'. If category not found, return 0;
1331 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1332 // FIXME: Should make sure no callers ever do this.
1333 if (!hasDefinition())
1336 if (data().ExternallyCompleted)
1337 LoadExternalDefinition();
1339 for (auto *Cat : visible_categories())
1340 if (Cat->getIdentifier() == CategoryId)
1347 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1348 for (const auto *Cat : visible_categories()) {
1349 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1350 if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1357 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1358 for (const auto *Cat : visible_categories()) {
1359 if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1360 if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1367 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1368 /// has been implemented in IDecl class, its super class or categories (if
1369 /// lookupCategory is true).
1370 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1371 bool lookupCategory,
1372 bool RHSIsQualifiedID) {
1373 if (!hasDefinition())
1376 ObjCInterfaceDecl *IDecl = this;
1377 // 1st, look up the class.
1378 for (auto *PI : IDecl->protocols()){
1379 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1381 // This is dubious and is added to be compatible with gcc. In gcc, it is
1382 // also allowed assigning a protocol-qualified 'id' type to a LHS object
1383 // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1384 // object. This IMO, should be a bug.
1385 // FIXME: Treat this as an extension, and flag this as an error when GCC
1386 // extensions are not enabled.
1387 if (RHSIsQualifiedID &&
1388 getASTContext().ProtocolCompatibleWithProtocol(PI, lProto))
1392 // 2nd, look up the category.
1394 for (const auto *Cat : visible_categories()) {
1395 for (auto *PI : Cat->protocols())
1396 if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1400 // 3rd, look up the super class(s)
1401 if (IDecl->getSuperClass())
1403 IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
1409 //===----------------------------------------------------------------------===//
1411 //===----------------------------------------------------------------------===//
1413 void ObjCIvarDecl::anchor() { }
1415 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
1416 SourceLocation StartLoc,
1417 SourceLocation IdLoc, IdentifierInfo *Id,
1418 QualType T, TypeSourceInfo *TInfo,
1419 AccessControl ac, Expr *BW,
1422 // Ivar's can only appear in interfaces, implementations (via synthesized
1423 // properties), and class extensions (via direct declaration, or synthesized
1426 // FIXME: This should really be asserting this:
1427 // (isa<ObjCCategoryDecl>(DC) &&
1428 // cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1429 // but unfortunately we sometimes place ivars into non-class extension
1430 // categories on error. This breaks an AST invariant, and should not be
1432 assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
1433 isa<ObjCCategoryDecl>(DC)) &&
1434 "Invalid ivar decl context!");
1435 // Once a new ivar is created in any of class/class-extension/implementation
1436 // decl contexts, the previously built IvarList must be rebuilt.
1437 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(DC);
1439 if (ObjCImplementationDecl *IM = dyn_cast<ObjCImplementationDecl>(DC))
1440 ID = IM->getClassInterface();
1442 ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
1444 ID->setIvarList(nullptr);
1447 return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW,
1451 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1452 return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1453 nullptr, QualType(), nullptr,
1454 ObjCIvarDecl::None, nullptr, false);
1457 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1458 const ObjCContainerDecl *DC = cast<ObjCContainerDecl>(getDeclContext());
1460 switch (DC->getKind()) {
1462 case ObjCCategoryImpl:
1464 llvm_unreachable("invalid ivar container!");
1466 // Ivars can only appear in class extension categories.
1467 case ObjCCategory: {
1468 const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
1469 assert(CD->IsClassExtension() && "invalid container for ivar!");
1470 return CD->getClassInterface();
1473 case ObjCImplementation:
1474 return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1477 return cast<ObjCInterfaceDecl>(DC);
1481 //===----------------------------------------------------------------------===//
1482 // ObjCAtDefsFieldDecl
1483 //===----------------------------------------------------------------------===//
1485 void ObjCAtDefsFieldDecl::anchor() { }
1488 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1489 SourceLocation StartLoc, SourceLocation IdLoc,
1490 IdentifierInfo *Id, QualType T, Expr *BW) {
1491 return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1494 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1496 return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1497 SourceLocation(), nullptr, QualType(),
1501 //===----------------------------------------------------------------------===//
1503 //===----------------------------------------------------------------------===//
1505 void ObjCProtocolDecl::anchor() { }
1507 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC,
1508 IdentifierInfo *Id, SourceLocation nameLoc,
1509 SourceLocation atStartLoc,
1510 ObjCProtocolDecl *PrevDecl)
1511 : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
1512 redeclarable_base(C), Data() {
1513 setPreviousDecl(PrevDecl);
1515 Data = PrevDecl->Data;
1518 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1520 SourceLocation nameLoc,
1521 SourceLocation atStartLoc,
1522 ObjCProtocolDecl *PrevDecl) {
1523 ObjCProtocolDecl *Result =
1524 new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl);
1525 Result->Data.setInt(!C.getLangOpts().Modules);
1529 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1531 ObjCProtocolDecl *Result =
1532 new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(),
1533 SourceLocation(), nullptr);
1534 Result->Data.setInt(!C.getLangOpts().Modules);
1538 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1539 ObjCProtocolDecl *PDecl = this;
1541 if (Name == getIdentifier())
1544 for (auto *I : protocols())
1545 if ((PDecl = I->lookupProtocolNamed(Name)))
1551 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1553 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1554 bool isInstance) const {
1555 ObjCMethodDecl *MethodDecl = nullptr;
1557 // If there is no definition or the definition is hidden, we don't find
1559 const ObjCProtocolDecl *Def = getDefinition();
1560 if (!Def || Def->isHidden())
1563 if ((MethodDecl = getMethod(Sel, isInstance)))
1566 for (const auto *I : protocols())
1567 if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
1572 void ObjCProtocolDecl::allocateDefinitionData() {
1573 assert(!Data.getPointer() && "Protocol already has a definition!");
1574 Data.setPointer(new (getASTContext()) DefinitionData);
1575 Data.getPointer()->Definition = this;
1578 void ObjCProtocolDecl::startDefinition() {
1579 allocateDefinitionData();
1581 // Update all of the declarations with a pointer to the definition.
1582 for (auto RD : redecls())
1583 RD->Data = this->Data;
1586 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1587 PropertyDeclOrder &PO) const {
1589 if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1590 for (auto *Prop : PDecl->properties()) {
1591 // Insert into PM if not there already.
1592 PM.insert(std::make_pair(Prop->getIdentifier(), Prop));
1595 // Scan through protocol's protocols.
1596 for (const auto *PI : PDecl->protocols())
1597 PI->collectPropertiesToImplement(PM, PO);
1602 void ObjCProtocolDecl::collectInheritedProtocolProperties(
1603 const ObjCPropertyDecl *Property,
1604 ProtocolPropertyMap &PM) const {
1605 if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1606 bool MatchFound = false;
1607 for (auto *Prop : PDecl->properties()) {
1608 if (Prop == Property)
1610 if (Prop->getIdentifier() == Property->getIdentifier()) {
1616 // Scan through protocol's protocols which did not have a matching property.
1618 for (const auto *PI : PDecl->protocols())
1619 PI->collectInheritedProtocolProperties(Property, PM);
1624 ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
1625 if (ObjCRuntimeNameAttr *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1626 return ObjCRTName->getMetadataName();
1631 //===----------------------------------------------------------------------===//
1633 //===----------------------------------------------------------------------===//
1635 void ObjCCategoryDecl::anchor() { }
1637 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
1638 SourceLocation AtLoc,
1639 SourceLocation ClassNameLoc,
1640 SourceLocation CategoryNameLoc,
1642 ObjCInterfaceDecl *IDecl,
1643 SourceLocation IvarLBraceLoc,
1644 SourceLocation IvarRBraceLoc) {
1645 ObjCCategoryDecl *CatDecl =
1646 new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
1647 IDecl, IvarLBraceLoc, IvarRBraceLoc);
1649 // Link this category into its class's category list.
1650 CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
1651 if (IDecl->hasDefinition()) {
1652 IDecl->setCategoryListRaw(CatDecl);
1653 if (ASTMutationListener *L = C.getASTMutationListener())
1654 L->AddedObjCCategoryToInterface(CatDecl, IDecl);
1661 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
1663 return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(),
1664 SourceLocation(), SourceLocation(),
1668 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
1669 return getASTContext().getObjCImplementation(
1670 const_cast<ObjCCategoryDecl*>(this));
1673 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
1674 getASTContext().setObjCImplementation(this, ImplD);
1678 //===----------------------------------------------------------------------===//
1679 // ObjCCategoryImplDecl
1680 //===----------------------------------------------------------------------===//
1682 void ObjCCategoryImplDecl::anchor() { }
1684 ObjCCategoryImplDecl *
1685 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
1687 ObjCInterfaceDecl *ClassInterface,
1688 SourceLocation nameLoc,
1689 SourceLocation atStartLoc,
1690 SourceLocation CategoryNameLoc) {
1691 if (ClassInterface && ClassInterface->hasDefinition())
1692 ClassInterface = ClassInterface->getDefinition();
1693 return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
1694 atStartLoc, CategoryNameLoc);
1697 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
1699 return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
1700 SourceLocation(), SourceLocation(),
1704 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
1705 // The class interface might be NULL if we are working with invalid code.
1706 if (const ObjCInterfaceDecl *ID = getClassInterface())
1707 return ID->FindCategoryDeclaration(getIdentifier());
1712 void ObjCImplDecl::anchor() { }
1714 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
1715 // FIXME: The context should be correct before we get here.
1716 property->setLexicalDeclContext(this);
1720 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
1721 ASTContext &Ctx = getASTContext();
1723 if (ObjCImplementationDecl *ImplD
1724 = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
1726 Ctx.setObjCImplementation(IFace, ImplD);
1728 } else if (ObjCCategoryImplDecl *ImplD =
1729 dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
1730 if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
1731 Ctx.setObjCImplementation(CD, ImplD);
1734 ClassInterface = IFace;
1737 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
1738 /// properties implemented in this \@implementation block and returns
1739 /// the implemented property that uses it.
1741 ObjCPropertyImplDecl *ObjCImplDecl::
1742 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
1743 for (auto *PID : property_impls())
1744 if (PID->getPropertyIvarDecl() &&
1745 PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
1750 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
1751 /// added to the list of those properties \@synthesized/\@dynamic in this
1752 /// category \@implementation block.
1754 ObjCPropertyImplDecl *ObjCImplDecl::
1755 FindPropertyImplDecl(IdentifierInfo *Id) const {
1756 for (auto *PID : property_impls())
1757 if (PID->getPropertyDecl()->getIdentifier() == Id)
1762 raw_ostream &clang::operator<<(raw_ostream &OS,
1763 const ObjCCategoryImplDecl &CID) {
1764 OS << CID.getName();
1768 //===----------------------------------------------------------------------===//
1769 // ObjCImplementationDecl
1770 //===----------------------------------------------------------------------===//
1772 void ObjCImplementationDecl::anchor() { }
1774 ObjCImplementationDecl *
1775 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
1776 ObjCInterfaceDecl *ClassInterface,
1777 ObjCInterfaceDecl *SuperDecl,
1778 SourceLocation nameLoc,
1779 SourceLocation atStartLoc,
1780 SourceLocation superLoc,
1781 SourceLocation IvarLBraceLoc,
1782 SourceLocation IvarRBraceLoc) {
1783 if (ClassInterface && ClassInterface->hasDefinition())
1784 ClassInterface = ClassInterface->getDefinition();
1785 return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
1786 nameLoc, atStartLoc, superLoc,
1787 IvarLBraceLoc, IvarRBraceLoc);
1790 ObjCImplementationDecl *
1791 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1792 return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr,
1793 SourceLocation(), SourceLocation());
1796 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
1797 CXXCtorInitializer ** initializers,
1798 unsigned numInitializers) {
1799 if (numInitializers > 0) {
1800 NumIvarInitializers = numInitializers;
1801 CXXCtorInitializer **ivarInitializers =
1802 new (C) CXXCtorInitializer*[NumIvarInitializers];
1803 memcpy(ivarInitializers, initializers,
1804 numInitializers * sizeof(CXXCtorInitializer*));
1805 IvarInitializers = ivarInitializers;
1809 raw_ostream &clang::operator<<(raw_ostream &OS,
1810 const ObjCImplementationDecl &ID) {
1815 //===----------------------------------------------------------------------===//
1816 // ObjCCompatibleAliasDecl
1817 //===----------------------------------------------------------------------===//
1819 void ObjCCompatibleAliasDecl::anchor() { }
1821 ObjCCompatibleAliasDecl *
1822 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
1825 ObjCInterfaceDecl* AliasedClass) {
1826 return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
1829 ObjCCompatibleAliasDecl *
1830 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1831 return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
1835 //===----------------------------------------------------------------------===//
1837 //===----------------------------------------------------------------------===//
1839 void ObjCPropertyDecl::anchor() { }
1841 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
1844 SourceLocation AtLoc,
1845 SourceLocation LParenLoc,
1847 PropertyControl propControl) {
1848 return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T);
1851 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
1853 return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
1854 SourceLocation(), SourceLocation(),
1858 //===----------------------------------------------------------------------===//
1859 // ObjCPropertyImplDecl
1860 //===----------------------------------------------------------------------===//
1862 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
1864 SourceLocation atLoc,
1866 ObjCPropertyDecl *property,
1869 SourceLocation ivarLoc) {
1870 return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
1874 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
1876 return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(),
1877 SourceLocation(), nullptr, Dynamic,
1878 nullptr, SourceLocation());
1881 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
1882 SourceLocation EndLoc = getLocation();
1883 if (IvarLoc.isValid())
1886 return SourceRange(AtLoc, EndLoc);