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