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