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