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