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