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     : NumParams(typeParams.size()) {
1465   Brackets.Begin = lAngleLoc.getRawEncoding();
1466   Brackets.End = rAngleLoc.getRawEncoding();
1467   std::copy(typeParams.begin(), typeParams.end(), begin());
1468 }
1469 
create(ASTContext & ctx,SourceLocation lAngleLoc,ArrayRef<ObjCTypeParamDecl * > typeParams,SourceLocation rAngleLoc)1470 ObjCTypeParamList *ObjCTypeParamList::create(
1471                      ASTContext &ctx,
1472                      SourceLocation lAngleLoc,
1473                      ArrayRef<ObjCTypeParamDecl *> typeParams,
1474                      SourceLocation rAngleLoc) {
1475   void *mem =
1476       ctx.Allocate(totalSizeToAlloc<ObjCTypeParamDecl *>(typeParams.size()),
1477                    alignof(ObjCTypeParamList));
1478   return new (mem) ObjCTypeParamList(lAngleLoc, typeParams, rAngleLoc);
1479 }
1480 
gatherDefaultTypeArgs(SmallVectorImpl<QualType> & typeArgs) const1481 void ObjCTypeParamList::gatherDefaultTypeArgs(
1482        SmallVectorImpl<QualType> &typeArgs) const {
1483   typeArgs.reserve(size());
1484   for (auto typeParam : *this)
1485     typeArgs.push_back(typeParam->getUnderlyingType());
1486 }
1487 
1488 //===----------------------------------------------------------------------===//
1489 // ObjCInterfaceDecl
1490 //===----------------------------------------------------------------------===//
1491 
Create(const ASTContext & C,DeclContext * DC,SourceLocation atLoc,IdentifierInfo * Id,ObjCTypeParamList * typeParamList,ObjCInterfaceDecl * PrevDecl,SourceLocation ClassLoc,bool isInternal)1492 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1493                                              DeclContext *DC,
1494                                              SourceLocation atLoc,
1495                                              IdentifierInfo *Id,
1496                                              ObjCTypeParamList *typeParamList,
1497                                              ObjCInterfaceDecl *PrevDecl,
1498                                              SourceLocation ClassLoc,
1499                                              bool isInternal){
1500   auto *Result = new (C, DC)
1501       ObjCInterfaceDecl(C, DC, atLoc, Id, typeParamList, ClassLoc, PrevDecl,
1502                         isInternal);
1503   Result->Data.setInt(!C.getLangOpts().Modules);
1504   C.getObjCInterfaceType(Result, PrevDecl);
1505   return Result;
1506 }
1507 
CreateDeserialized(const ASTContext & C,unsigned ID)1508 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(const ASTContext &C,
1509                                                          unsigned ID) {
1510   auto *Result = new (C, ID)
1511       ObjCInterfaceDecl(C, nullptr, SourceLocation(), nullptr, nullptr,
1512                         SourceLocation(), nullptr, false);
1513   Result->Data.setInt(!C.getLangOpts().Modules);
1514   return Result;
1515 }
1516 
ObjCInterfaceDecl(const ASTContext & C,DeclContext * DC,SourceLocation AtLoc,IdentifierInfo * Id,ObjCTypeParamList * typeParamList,SourceLocation CLoc,ObjCInterfaceDecl * PrevDecl,bool IsInternal)1517 ObjCInterfaceDecl::ObjCInterfaceDecl(const ASTContext &C, DeclContext *DC,
1518                                      SourceLocation AtLoc, IdentifierInfo *Id,
1519                                      ObjCTypeParamList *typeParamList,
1520                                      SourceLocation CLoc,
1521                                      ObjCInterfaceDecl *PrevDecl,
1522                                      bool IsInternal)
1523     : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, AtLoc),
1524       redeclarable_base(C) {
1525   setPreviousDecl(PrevDecl);
1526 
1527   // Copy the 'data' pointer over.
1528   if (PrevDecl)
1529     Data = PrevDecl->Data;
1530 
1531   setImplicit(IsInternal);
1532 
1533   setTypeParamList(typeParamList);
1534 }
1535 
LoadExternalDefinition() const1536 void ObjCInterfaceDecl::LoadExternalDefinition() const {
1537   assert(data().ExternallyCompleted && "Class is not externally completed");
1538   data().ExternallyCompleted = false;
1539   getASTContext().getExternalSource()->CompleteType(
1540                                         const_cast<ObjCInterfaceDecl *>(this));
1541 }
1542 
setExternallyCompleted()1543 void ObjCInterfaceDecl::setExternallyCompleted() {
1544   assert(getASTContext().getExternalSource() &&
1545          "Class can't be externally completed without an external source");
1546   assert(hasDefinition() &&
1547          "Forward declarations can't be externally completed");
1548   data().ExternallyCompleted = true;
1549 }
1550 
setHasDesignatedInitializers()1551 void ObjCInterfaceDecl::setHasDesignatedInitializers() {
1552   // Check for a complete definition and recover if not so.
1553   if (!isThisDeclarationADefinition())
1554     return;
1555   data().HasDesignatedInitializers = true;
1556 }
1557 
hasDesignatedInitializers() const1558 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1559   // Check for a complete definition and recover if not so.
1560   if (!isThisDeclarationADefinition())
1561     return false;
1562   if (data().ExternallyCompleted)
1563     LoadExternalDefinition();
1564 
1565   return data().HasDesignatedInitializers;
1566 }
1567 
1568 StringRef
getObjCRuntimeNameAsString() const1569 ObjCInterfaceDecl::getObjCRuntimeNameAsString() const {
1570   if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
1571     return ObjCRTName->getMetadataName();
1572 
1573   return getName();
1574 }
1575 
1576 StringRef
getObjCRuntimeNameAsString() const1577 ObjCImplementationDecl::getObjCRuntimeNameAsString() const {
1578   if (ObjCInterfaceDecl *ID =
1579       const_cast<ObjCImplementationDecl*>(this)->getClassInterface())
1580     return ID->getObjCRuntimeNameAsString();
1581 
1582   return getName();
1583 }
1584 
getImplementation() const1585 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1586   if (const ObjCInterfaceDecl *Def = getDefinition()) {
1587     if (data().ExternallyCompleted)
1588       LoadExternalDefinition();
1589 
1590     return getASTContext().getObjCImplementation(
1591              const_cast<ObjCInterfaceDecl*>(Def));
1592   }
1593 
1594   // FIXME: Should make sure no callers ever do this.
1595   return nullptr;
1596 }
1597 
setImplementation(ObjCImplementationDecl * ImplD)1598 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1599   getASTContext().setObjCImplementation(getDefinition(), ImplD);
1600 }
1601 
1602 namespace {
1603 
1604 struct SynthesizeIvarChunk {
1605   uint64_t Size;
1606   ObjCIvarDecl *Ivar;
1607 
SynthesizeIvarChunk__anon2fb454600211::SynthesizeIvarChunk1608   SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1609       : Size(size), Ivar(ivar) {}
1610 };
1611 
operator <(const SynthesizeIvarChunk & LHS,const SynthesizeIvarChunk & RHS)1612 bool operator<(const SynthesizeIvarChunk & LHS,
1613                const SynthesizeIvarChunk &RHS) {
1614     return LHS.Size < RHS.Size;
1615 }
1616 
1617 } // namespace
1618 
1619 /// all_declared_ivar_begin - return first ivar declared in this class,
1620 /// its extensions and its implementation. Lazily build the list on first
1621 /// access.
1622 ///
1623 /// Caveat: The list returned by this method reflects the current
1624 /// state of the parser. The cache will be updated for every ivar
1625 /// added by an extension or the implementation when they are
1626 /// encountered.
1627 /// See also ObjCIvarDecl::Create().
all_declared_ivar_begin()1628 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1629   // FIXME: Should make sure no callers ever do this.
1630   if (!hasDefinition())
1631     return nullptr;
1632 
1633   ObjCIvarDecl *curIvar = nullptr;
1634   if (!data().IvarList) {
1635     if (!ivar_empty()) {
1636       ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1637       data().IvarList = *I; ++I;
1638       for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1639         curIvar->setNextIvar(*I);
1640     }
1641 
1642     for (const auto *Ext : known_extensions()) {
1643       if (!Ext->ivar_empty()) {
1644         ObjCCategoryDecl::ivar_iterator
1645           I = Ext->ivar_begin(),
1646           E = Ext->ivar_end();
1647         if (!data().IvarList) {
1648           data().IvarList = *I; ++I;
1649           curIvar = data().IvarList;
1650         }
1651         for ( ;I != E; curIvar = *I, ++I)
1652           curIvar->setNextIvar(*I);
1653       }
1654     }
1655     data().IvarListMissingImplementation = true;
1656   }
1657 
1658   // cached and complete!
1659   if (!data().IvarListMissingImplementation)
1660       return data().IvarList;
1661 
1662   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
1663     data().IvarListMissingImplementation = false;
1664     if (!ImplDecl->ivar_empty()) {
1665       SmallVector<SynthesizeIvarChunk, 16> layout;
1666       for (auto *IV : ImplDecl->ivars()) {
1667         if (IV->getSynthesize() && !IV->isInvalidDecl()) {
1668           layout.push_back(SynthesizeIvarChunk(
1669                              IV->getASTContext().getTypeSize(IV->getType()), IV));
1670           continue;
1671         }
1672         if (!data().IvarList)
1673           data().IvarList = IV;
1674         else
1675           curIvar->setNextIvar(IV);
1676         curIvar = IV;
1677       }
1678 
1679       if (!layout.empty()) {
1680         // Order synthesized ivars by their size.
1681         llvm::stable_sort(layout);
1682         unsigned Ix = 0, EIx = layout.size();
1683         if (!data().IvarList) {
1684           data().IvarList = layout[0].Ivar; Ix++;
1685           curIvar = data().IvarList;
1686         }
1687         for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1688           curIvar->setNextIvar(layout[Ix].Ivar);
1689       }
1690     }
1691   }
1692   return data().IvarList;
1693 }
1694 
1695 /// FindCategoryDeclaration - Finds category declaration in the list of
1696 /// categories for this class and returns it. Name of the category is passed
1697 /// in 'CategoryId'. If category not found, return 0;
1698 ///
1699 ObjCCategoryDecl *
FindCategoryDeclaration(IdentifierInfo * CategoryId) const1700 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1701   // FIXME: Should make sure no callers ever do this.
1702   if (!hasDefinition())
1703     return nullptr;
1704 
1705   if (data().ExternallyCompleted)
1706     LoadExternalDefinition();
1707 
1708   for (auto *Cat : visible_categories())
1709     if (Cat->getIdentifier() == CategoryId)
1710       return Cat;
1711 
1712   return nullptr;
1713 }
1714 
1715 ObjCMethodDecl *
getCategoryInstanceMethod(Selector Sel) const1716 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1717   for (const auto *Cat : visible_categories()) {
1718     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1719       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1720         return MD;
1721   }
1722 
1723   return nullptr;
1724 }
1725 
getCategoryClassMethod(Selector Sel) const1726 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1727   for (const auto *Cat : visible_categories()) {
1728     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1729       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1730         return MD;
1731   }
1732 
1733   return nullptr;
1734 }
1735 
1736 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1737 /// has been implemented in IDecl class, its super class or categories (if
1738 /// lookupCategory is true).
ClassImplementsProtocol(ObjCProtocolDecl * lProto,bool lookupCategory,bool RHSIsQualifiedID)1739 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1740                                     bool lookupCategory,
1741                                     bool RHSIsQualifiedID) {
1742   if (!hasDefinition())
1743     return false;
1744 
1745   ObjCInterfaceDecl *IDecl = this;
1746   // 1st, look up the class.
1747   for (auto *PI : IDecl->protocols()){
1748     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1749       return true;
1750     // This is dubious and is added to be compatible with gcc.  In gcc, it is
1751     // also allowed assigning a protocol-qualified 'id' type to a LHS object
1752     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1753     // object. This IMO, should be a bug.
1754     // FIXME: Treat this as an extension, and flag this as an error when GCC
1755     // extensions are not enabled.
1756     if (RHSIsQualifiedID &&
1757         getASTContext().ProtocolCompatibleWithProtocol(PI, lProto))
1758       return true;
1759   }
1760 
1761   // 2nd, look up the category.
1762   if (lookupCategory)
1763     for (const auto *Cat : visible_categories()) {
1764       for (auto *PI : Cat->protocols())
1765         if (getASTContext().ProtocolCompatibleWithProtocol(lProto, PI))
1766           return true;
1767     }
1768 
1769   // 3rd, look up the super class(s)
1770   if (IDecl->getSuperClass())
1771     return
1772   IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
1773                                                   RHSIsQualifiedID);
1774 
1775   return false;
1776 }
1777 
1778 //===----------------------------------------------------------------------===//
1779 // ObjCIvarDecl
1780 //===----------------------------------------------------------------------===//
1781 
anchor()1782 void ObjCIvarDecl::anchor() {}
1783 
Create(ASTContext & C,ObjCContainerDecl * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,AccessControl ac,Expr * BW,bool synthesized)1784 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
1785                                    SourceLocation StartLoc,
1786                                    SourceLocation IdLoc, IdentifierInfo *Id,
1787                                    QualType T, TypeSourceInfo *TInfo,
1788                                    AccessControl ac, Expr *BW,
1789                                    bool synthesized) {
1790   if (DC) {
1791     // Ivar's can only appear in interfaces, implementations (via synthesized
1792     // properties), and class extensions (via direct declaration, or synthesized
1793     // properties).
1794     //
1795     // FIXME: This should really be asserting this:
1796     //   (isa<ObjCCategoryDecl>(DC) &&
1797     //    cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
1798     // but unfortunately we sometimes place ivars into non-class extension
1799     // categories on error. This breaks an AST invariant, and should not be
1800     // fixed.
1801     assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
1802             isa<ObjCCategoryDecl>(DC)) &&
1803            "Invalid ivar decl context!");
1804     // Once a new ivar is created in any of class/class-extension/implementation
1805     // decl contexts, the previously built IvarList must be rebuilt.
1806     auto *ID = dyn_cast<ObjCInterfaceDecl>(DC);
1807     if (!ID) {
1808       if (auto *IM = dyn_cast<ObjCImplementationDecl>(DC))
1809         ID = IM->getClassInterface();
1810       else
1811         ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
1812     }
1813     ID->setIvarList(nullptr);
1814   }
1815 
1816   return new (C, DC) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo, ac, BW,
1817                                   synthesized);
1818 }
1819 
CreateDeserialized(ASTContext & C,unsigned ID)1820 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1821   return new (C, ID) ObjCIvarDecl(nullptr, SourceLocation(), SourceLocation(),
1822                                   nullptr, QualType(), nullptr,
1823                                   ObjCIvarDecl::None, nullptr, false);
1824 }
1825 
getContainingInterface() const1826 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1827   const auto *DC = cast<ObjCContainerDecl>(getDeclContext());
1828 
1829   switch (DC->getKind()) {
1830   default:
1831   case ObjCCategoryImpl:
1832   case ObjCProtocol:
1833     llvm_unreachable("invalid ivar container!");
1834 
1835     // Ivars can only appear in class extension categories.
1836   case ObjCCategory: {
1837     const auto *CD = cast<ObjCCategoryDecl>(DC);
1838     assert(CD->IsClassExtension() && "invalid container for ivar!");
1839     return CD->getClassInterface();
1840   }
1841 
1842   case ObjCImplementation:
1843     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1844 
1845   case ObjCInterface:
1846     return cast<ObjCInterfaceDecl>(DC);
1847   }
1848 }
1849 
getUsageType(QualType objectType) const1850 QualType ObjCIvarDecl::getUsageType(QualType objectType) const {
1851   return getType().substObjCMemberType(objectType, getDeclContext(),
1852                                        ObjCSubstitutionContext::Property);
1853 }
1854 
1855 //===----------------------------------------------------------------------===//
1856 // ObjCAtDefsFieldDecl
1857 //===----------------------------------------------------------------------===//
1858 
anchor()1859 void ObjCAtDefsFieldDecl::anchor() {}
1860 
1861 ObjCAtDefsFieldDecl
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,Expr * BW)1862 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1863                              SourceLocation StartLoc,  SourceLocation IdLoc,
1864                              IdentifierInfo *Id, QualType T, Expr *BW) {
1865   return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1866 }
1867 
CreateDeserialized(ASTContext & C,unsigned ID)1868 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1869                                                              unsigned ID) {
1870   return new (C, ID) ObjCAtDefsFieldDecl(nullptr, SourceLocation(),
1871                                          SourceLocation(), nullptr, QualType(),
1872                                          nullptr);
1873 }
1874 
1875 //===----------------------------------------------------------------------===//
1876 // ObjCProtocolDecl
1877 //===----------------------------------------------------------------------===//
1878 
anchor()1879 void ObjCProtocolDecl::anchor() {}
1880 
ObjCProtocolDecl(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc,ObjCProtocolDecl * PrevDecl)1881 ObjCProtocolDecl::ObjCProtocolDecl(ASTContext &C, DeclContext *DC,
1882                                    IdentifierInfo *Id, SourceLocation nameLoc,
1883                                    SourceLocation atStartLoc,
1884                                    ObjCProtocolDecl *PrevDecl)
1885     : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc),
1886       redeclarable_base(C) {
1887   setPreviousDecl(PrevDecl);
1888   if (PrevDecl)
1889     Data = PrevDecl->Data;
1890 }
1891 
Create(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,SourceLocation nameLoc,SourceLocation atStartLoc,ObjCProtocolDecl * PrevDecl)1892 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1893                                            IdentifierInfo *Id,
1894                                            SourceLocation nameLoc,
1895                                            SourceLocation atStartLoc,
1896                                            ObjCProtocolDecl *PrevDecl) {
1897   auto *Result =
1898       new (C, DC) ObjCProtocolDecl(C, DC, Id, nameLoc, atStartLoc, PrevDecl);
1899   Result->Data.setInt(!C.getLangOpts().Modules);
1900   return Result;
1901 }
1902 
CreateDeserialized(ASTContext & C,unsigned ID)1903 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1904                                                        unsigned ID) {
1905   ObjCProtocolDecl *Result =
1906       new (C, ID) ObjCProtocolDecl(C, nullptr, nullptr, SourceLocation(),
1907                                    SourceLocation(), nullptr);
1908   Result->Data.setInt(!C.getLangOpts().Modules);
1909   return Result;
1910 }
1911 
isNonRuntimeProtocol() const1912 bool ObjCProtocolDecl::isNonRuntimeProtocol() const {
1913   return hasAttr<ObjCNonRuntimeProtocolAttr>();
1914 }
1915 
getImpliedProtocols(llvm::DenseSet<const ObjCProtocolDecl * > & IPs) const1916 void ObjCProtocolDecl::getImpliedProtocols(
1917     llvm::DenseSet<const ObjCProtocolDecl *> &IPs) const {
1918   std::queue<const ObjCProtocolDecl *> WorkQueue;
1919   WorkQueue.push(this);
1920 
1921   while (!WorkQueue.empty()) {
1922     const auto *PD = WorkQueue.front();
1923     WorkQueue.pop();
1924     for (const auto *Parent : PD->protocols()) {
1925       const auto *Can = Parent->getCanonicalDecl();
1926       auto Result = IPs.insert(Can);
1927       if (Result.second)
1928         WorkQueue.push(Parent);
1929     }
1930   }
1931 }
1932 
lookupProtocolNamed(IdentifierInfo * Name)1933 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1934   ObjCProtocolDecl *PDecl = this;
1935 
1936   if (Name == getIdentifier())
1937     return PDecl;
1938 
1939   for (auto *I : protocols())
1940     if ((PDecl = I->lookupProtocolNamed(Name)))
1941       return PDecl;
1942 
1943   return nullptr;
1944 }
1945 
1946 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1947 // it inherited.
lookupMethod(Selector Sel,bool isInstance) const1948 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1949                                                bool isInstance) const {
1950   ObjCMethodDecl *MethodDecl = nullptr;
1951 
1952   // If there is no definition or the definition is hidden, we don't find
1953   // anything.
1954   const ObjCProtocolDecl *Def = getDefinition();
1955   if (!Def || !Def->isUnconditionallyVisible())
1956     return nullptr;
1957 
1958   if ((MethodDecl = getMethod(Sel, isInstance)))
1959     return MethodDecl;
1960 
1961   for (const auto *I : protocols())
1962     if ((MethodDecl = I->lookupMethod(Sel, isInstance)))
1963       return MethodDecl;
1964   return nullptr;
1965 }
1966 
allocateDefinitionData()1967 void ObjCProtocolDecl::allocateDefinitionData() {
1968   assert(!Data.getPointer() && "Protocol already has a definition!");
1969   Data.setPointer(new (getASTContext()) DefinitionData);
1970   Data.getPointer()->Definition = this;
1971 }
1972 
startDefinition()1973 void ObjCProtocolDecl::startDefinition() {
1974   allocateDefinitionData();
1975 
1976   // Update all of the declarations with a pointer to the definition.
1977   for (auto *RD : redecls())
1978     RD->Data = this->Data;
1979 }
1980 
collectPropertiesToImplement(PropertyMap & PM,PropertyDeclOrder & PO) const1981 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1982                                                     PropertyDeclOrder &PO) const {
1983   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1984     for (auto *Prop : PDecl->properties()) {
1985       // Insert into PM if not there already.
1986       PM.insert(std::make_pair(
1987           std::make_pair(Prop->getIdentifier(), Prop->isClassProperty()),
1988           Prop));
1989       PO.push_back(Prop);
1990     }
1991     // Scan through protocol's protocols.
1992     for (const auto *PI : PDecl->protocols())
1993       PI->collectPropertiesToImplement(PM, PO);
1994   }
1995 }
1996 
collectInheritedProtocolProperties(const ObjCPropertyDecl * Property,ProtocolPropertySet & PS,PropertyDeclOrder & PO) const1997 void ObjCProtocolDecl::collectInheritedProtocolProperties(
1998     const ObjCPropertyDecl *Property, ProtocolPropertySet &PS,
1999     PropertyDeclOrder &PO) const {
2000   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
2001     if (!PS.insert(PDecl).second)
2002       return;
2003     for (auto *Prop : PDecl->properties()) {
2004       if (Prop == Property)
2005         continue;
2006       if (Prop->getIdentifier() == Property->getIdentifier()) {
2007         PO.push_back(Prop);
2008         return;
2009       }
2010     }
2011     // Scan through protocol's protocols which did not have a matching property.
2012     for (const auto *PI : PDecl->protocols())
2013       PI->collectInheritedProtocolProperties(Property, PS, PO);
2014   }
2015 }
2016 
2017 StringRef
getObjCRuntimeNameAsString() const2018 ObjCProtocolDecl::getObjCRuntimeNameAsString() const {
2019   if (const auto *ObjCRTName = getAttr<ObjCRuntimeNameAttr>())
2020     return ObjCRTName->getMetadataName();
2021 
2022   return getName();
2023 }
2024 
2025 //===----------------------------------------------------------------------===//
2026 // ObjCCategoryDecl
2027 //===----------------------------------------------------------------------===//
2028 
anchor()2029 void ObjCCategoryDecl::anchor() {}
2030 
ObjCCategoryDecl(DeclContext * DC,SourceLocation AtLoc,SourceLocation ClassNameLoc,SourceLocation CategoryNameLoc,IdentifierInfo * Id,ObjCInterfaceDecl * IDecl,ObjCTypeParamList * typeParamList,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2031 ObjCCategoryDecl::ObjCCategoryDecl(DeclContext *DC, SourceLocation AtLoc,
2032                                    SourceLocation ClassNameLoc,
2033                                    SourceLocation CategoryNameLoc,
2034                                    IdentifierInfo *Id, ObjCInterfaceDecl *IDecl,
2035                                    ObjCTypeParamList *typeParamList,
2036                                    SourceLocation IvarLBraceLoc,
2037                                    SourceLocation IvarRBraceLoc)
2038     : ObjCContainerDecl(ObjCCategory, DC, Id, ClassNameLoc, AtLoc),
2039       ClassInterface(IDecl), CategoryNameLoc(CategoryNameLoc),
2040       IvarLBraceLoc(IvarLBraceLoc), IvarRBraceLoc(IvarRBraceLoc) {
2041   setTypeParamList(typeParamList);
2042 }
2043 
Create(ASTContext & C,DeclContext * DC,SourceLocation AtLoc,SourceLocation ClassNameLoc,SourceLocation CategoryNameLoc,IdentifierInfo * Id,ObjCInterfaceDecl * IDecl,ObjCTypeParamList * typeParamList,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2044 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
2045                                            SourceLocation AtLoc,
2046                                            SourceLocation ClassNameLoc,
2047                                            SourceLocation CategoryNameLoc,
2048                                            IdentifierInfo *Id,
2049                                            ObjCInterfaceDecl *IDecl,
2050                                            ObjCTypeParamList *typeParamList,
2051                                            SourceLocation IvarLBraceLoc,
2052                                            SourceLocation IvarRBraceLoc) {
2053   auto *CatDecl =
2054       new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
2055                                    IDecl, typeParamList, IvarLBraceLoc,
2056                                    IvarRBraceLoc);
2057   if (IDecl) {
2058     // Link this category into its class's category list.
2059     CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
2060     if (IDecl->hasDefinition()) {
2061       IDecl->setCategoryListRaw(CatDecl);
2062       if (ASTMutationListener *L = C.getASTMutationListener())
2063         L->AddedObjCCategoryToInterface(CatDecl, IDecl);
2064     }
2065   }
2066 
2067   return CatDecl;
2068 }
2069 
CreateDeserialized(ASTContext & C,unsigned ID)2070 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
2071                                                        unsigned ID) {
2072   return new (C, ID) ObjCCategoryDecl(nullptr, SourceLocation(),
2073                                       SourceLocation(), SourceLocation(),
2074                                       nullptr, nullptr, nullptr);
2075 }
2076 
getImplementation() const2077 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
2078   return getASTContext().getObjCImplementation(
2079                                            const_cast<ObjCCategoryDecl*>(this));
2080 }
2081 
setImplementation(ObjCCategoryImplDecl * ImplD)2082 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
2083   getASTContext().setObjCImplementation(this, ImplD);
2084 }
2085 
setTypeParamList(ObjCTypeParamList * TPL)2086 void ObjCCategoryDecl::setTypeParamList(ObjCTypeParamList *TPL) {
2087   TypeParamList = TPL;
2088   if (!TPL)
2089     return;
2090   // Set the declaration context of each of the type parameters.
2091   for (auto *typeParam : *TypeParamList)
2092     typeParam->setDeclContext(this);
2093 }
2094 
2095 //===----------------------------------------------------------------------===//
2096 // ObjCCategoryImplDecl
2097 //===----------------------------------------------------------------------===//
2098 
anchor()2099 void ObjCCategoryImplDecl::anchor() {}
2100 
2101 ObjCCategoryImplDecl *
Create(ASTContext & C,DeclContext * DC,IdentifierInfo * Id,ObjCInterfaceDecl * ClassInterface,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation CategoryNameLoc)2102 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
2103                              IdentifierInfo *Id,
2104                              ObjCInterfaceDecl *ClassInterface,
2105                              SourceLocation nameLoc,
2106                              SourceLocation atStartLoc,
2107                              SourceLocation CategoryNameLoc) {
2108   if (ClassInterface && ClassInterface->hasDefinition())
2109     ClassInterface = ClassInterface->getDefinition();
2110   return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
2111                                           atStartLoc, CategoryNameLoc);
2112 }
2113 
CreateDeserialized(ASTContext & C,unsigned ID)2114 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
2115                                                                unsigned ID) {
2116   return new (C, ID) ObjCCategoryImplDecl(nullptr, nullptr, nullptr,
2117                                           SourceLocation(), SourceLocation(),
2118                                           SourceLocation());
2119 }
2120 
getCategoryDecl() const2121 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
2122   // The class interface might be NULL if we are working with invalid code.
2123   if (const ObjCInterfaceDecl *ID = getClassInterface())
2124     return ID->FindCategoryDeclaration(getIdentifier());
2125   return nullptr;
2126 }
2127 
anchor()2128 void ObjCImplDecl::anchor() {}
2129 
addPropertyImplementation(ObjCPropertyImplDecl * property)2130 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
2131   // FIXME: The context should be correct before we get here.
2132   property->setLexicalDeclContext(this);
2133   addDecl(property);
2134 }
2135 
setClassInterface(ObjCInterfaceDecl * IFace)2136 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
2137   ASTContext &Ctx = getASTContext();
2138 
2139   if (auto *ImplD = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
2140     if (IFace)
2141       Ctx.setObjCImplementation(IFace, ImplD);
2142 
2143   } else if (auto *ImplD = dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
2144     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
2145       Ctx.setObjCImplementation(CD, ImplD);
2146   }
2147 
2148   ClassInterface = IFace;
2149 }
2150 
2151 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
2152 /// properties implemented in this \@implementation block and returns
2153 /// the implemented property that uses it.
2154 ObjCPropertyImplDecl *ObjCImplDecl::
FindPropertyImplIvarDecl(IdentifierInfo * ivarId) const2155 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
2156   for (auto *PID : property_impls())
2157     if (PID->getPropertyIvarDecl() &&
2158         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
2159       return PID;
2160   return nullptr;
2161 }
2162 
2163 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
2164 /// added to the list of those properties \@synthesized/\@dynamic in this
2165 /// category \@implementation block.
2166 ObjCPropertyImplDecl *ObjCImplDecl::
FindPropertyImplDecl(IdentifierInfo * Id,ObjCPropertyQueryKind QueryKind) const2167 FindPropertyImplDecl(IdentifierInfo *Id,
2168                      ObjCPropertyQueryKind QueryKind) const {
2169   ObjCPropertyImplDecl *ClassPropImpl = nullptr;
2170   for (auto *PID : property_impls())
2171     // If queryKind is unknown, we return the instance property if one
2172     // exists; otherwise we return the class property.
2173     if (PID->getPropertyDecl()->getIdentifier() == Id) {
2174       if ((QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown &&
2175            !PID->getPropertyDecl()->isClassProperty()) ||
2176           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_class &&
2177            PID->getPropertyDecl()->isClassProperty()) ||
2178           (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_instance &&
2179            !PID->getPropertyDecl()->isClassProperty()))
2180         return PID;
2181 
2182       if (PID->getPropertyDecl()->isClassProperty())
2183         ClassPropImpl = PID;
2184     }
2185 
2186   if (QueryKind == ObjCPropertyQueryKind::OBJC_PR_query_unknown)
2187     // We can't find the instance property, return the class property.
2188     return ClassPropImpl;
2189 
2190   return nullptr;
2191 }
2192 
operator <<(raw_ostream & OS,const ObjCCategoryImplDecl & CID)2193 raw_ostream &clang::operator<<(raw_ostream &OS,
2194                                const ObjCCategoryImplDecl &CID) {
2195   OS << CID.getName();
2196   return OS;
2197 }
2198 
2199 //===----------------------------------------------------------------------===//
2200 // ObjCImplementationDecl
2201 //===----------------------------------------------------------------------===//
2202 
anchor()2203 void ObjCImplementationDecl::anchor() {}
2204 
2205 ObjCImplementationDecl *
Create(ASTContext & C,DeclContext * DC,ObjCInterfaceDecl * ClassInterface,ObjCInterfaceDecl * SuperDecl,SourceLocation nameLoc,SourceLocation atStartLoc,SourceLocation superLoc,SourceLocation IvarLBraceLoc,SourceLocation IvarRBraceLoc)2206 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
2207                                ObjCInterfaceDecl *ClassInterface,
2208                                ObjCInterfaceDecl *SuperDecl,
2209                                SourceLocation nameLoc,
2210                                SourceLocation atStartLoc,
2211                                SourceLocation superLoc,
2212                                SourceLocation IvarLBraceLoc,
2213                                SourceLocation IvarRBraceLoc) {
2214   if (ClassInterface && ClassInterface->hasDefinition())
2215     ClassInterface = ClassInterface->getDefinition();
2216   return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
2217                                             nameLoc, atStartLoc, superLoc,
2218                                             IvarLBraceLoc, IvarRBraceLoc);
2219 }
2220 
2221 ObjCImplementationDecl *
CreateDeserialized(ASTContext & C,unsigned ID)2222 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2223   return new (C, ID) ObjCImplementationDecl(nullptr, nullptr, nullptr,
2224                                             SourceLocation(), SourceLocation());
2225 }
2226 
setIvarInitializers(ASTContext & C,CXXCtorInitializer ** initializers,unsigned numInitializers)2227 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2228                                              CXXCtorInitializer ** initializers,
2229                                                  unsigned numInitializers) {
2230   if (numInitializers > 0) {
2231     NumIvarInitializers = numInitializers;
2232     auto **ivarInitializers = new (C) CXXCtorInitializer*[NumIvarInitializers];
2233     memcpy(ivarInitializers, initializers,
2234            numInitializers * sizeof(CXXCtorInitializer*));
2235     IvarInitializers = ivarInitializers;
2236   }
2237 }
2238 
2239 ObjCImplementationDecl::init_const_iterator
init_begin() const2240 ObjCImplementationDecl::init_begin() const {
2241   return IvarInitializers.get(getASTContext().getExternalSource());
2242 }
2243 
operator <<(raw_ostream & OS,const ObjCImplementationDecl & ID)2244 raw_ostream &clang::operator<<(raw_ostream &OS,
2245                                const ObjCImplementationDecl &ID) {
2246   OS << ID.getName();
2247   return OS;
2248 }
2249 
2250 //===----------------------------------------------------------------------===//
2251 // ObjCCompatibleAliasDecl
2252 //===----------------------------------------------------------------------===//
2253 
anchor()2254 void ObjCCompatibleAliasDecl::anchor() {}
2255 
2256 ObjCCompatibleAliasDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,ObjCInterfaceDecl * AliasedClass)2257 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
2258                                 SourceLocation L,
2259                                 IdentifierInfo *Id,
2260                                 ObjCInterfaceDecl* AliasedClass) {
2261   return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
2262 }
2263 
2264 ObjCCompatibleAliasDecl *
CreateDeserialized(ASTContext & C,unsigned ID)2265 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2266   return new (C, ID) ObjCCompatibleAliasDecl(nullptr, SourceLocation(),
2267                                              nullptr, nullptr);
2268 }
2269 
2270 //===----------------------------------------------------------------------===//
2271 // ObjCPropertyDecl
2272 //===----------------------------------------------------------------------===//
2273 
anchor()2274 void ObjCPropertyDecl::anchor() {}
2275 
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,SourceLocation AtLoc,SourceLocation LParenLoc,QualType T,TypeSourceInfo * TSI,PropertyControl propControl)2276 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
2277                                            SourceLocation L,
2278                                            IdentifierInfo *Id,
2279                                            SourceLocation AtLoc,
2280                                            SourceLocation LParenLoc,
2281                                            QualType T,
2282                                            TypeSourceInfo *TSI,
2283                                            PropertyControl propControl) {
2284   return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T, TSI,
2285                                       propControl);
2286 }
2287 
CreateDeserialized(ASTContext & C,unsigned ID)2288 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
2289                                                        unsigned ID) {
2290   return new (C, ID) ObjCPropertyDecl(nullptr, SourceLocation(), nullptr,
2291                                       SourceLocation(), SourceLocation(),
2292                                       QualType(), nullptr, None);
2293 }
2294 
getUsageType(QualType objectType) const2295 QualType ObjCPropertyDecl::getUsageType(QualType objectType) const {
2296   return DeclType.substObjCMemberType(objectType, getDeclContext(),
2297                                       ObjCSubstitutionContext::Property);
2298 }
2299 
2300 //===----------------------------------------------------------------------===//
2301 // ObjCPropertyImplDecl
2302 //===----------------------------------------------------------------------===//
2303 
Create(ASTContext & C,DeclContext * DC,SourceLocation atLoc,SourceLocation L,ObjCPropertyDecl * property,Kind PK,ObjCIvarDecl * ivar,SourceLocation ivarLoc)2304 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
2305                                                    DeclContext *DC,
2306                                                    SourceLocation atLoc,
2307                                                    SourceLocation L,
2308                                                    ObjCPropertyDecl *property,
2309                                                    Kind PK,
2310                                                    ObjCIvarDecl *ivar,
2311                                                    SourceLocation ivarLoc) {
2312   return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
2313                                           ivarLoc);
2314 }
2315 
CreateDeserialized(ASTContext & C,unsigned ID)2316 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
2317                                                                unsigned ID) {
2318   return new (C, ID) ObjCPropertyImplDecl(nullptr, SourceLocation(),
2319                                           SourceLocation(), nullptr, Dynamic,
2320                                           nullptr, SourceLocation());
2321 }
2322 
getSourceRange() const2323 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
2324   SourceLocation EndLoc = getLocation();
2325   if (IvarLoc.isValid())
2326     EndLoc = IvarLoc;
2327 
2328   return SourceRange(AtLoc, EndLoc);
2329 }
2330