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 = 0;
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 0;
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 0;
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 0;
94 }
95 
96 /// HasUserDeclaredSetterMethod - This routine returns 'true' if a user declared setter
97 /// method was 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' property.
99 /// This is because, user must provide a setter method for the category's 'readwrite'
100 /// property.
101 bool
102 ObjCContainerDecl::HasUserDeclaredSetterMethod(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 (ObjCInterfaceDecl::visible_categories_iterator
116          Cat = ID->visible_categories_begin(),
117          CatEnd = ID->visible_categories_end();
118          Cat != CatEnd;
119          ++Cat) {
120       if (ObjCMethodDecl *MD = Cat->getInstanceMethod(Sel))
121         if (!MD->isImplicit())
122           return true;
123       if (Cat->IsClassExtension())
124         continue;
125       // Also search through the categories looking for a 'readwrite' declaration
126       // of this property. If one found, presumably a setter will be provided
127       // (properties declared in categories will not get auto-synthesized).
128       for (ObjCContainerDecl::prop_iterator P = Cat->prop_begin(),
129            E = Cat->prop_end(); P != E; ++P)
130         if (P->getIdentifier() == Property->getIdentifier()) {
131           if (P->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite)
132             return true;
133           break;
134         }
135     }
136 
137     // Also look into protocols, for a user declared instance method.
138     for (ObjCInterfaceDecl::all_protocol_iterator P =
139          ID->all_referenced_protocol_begin(),
140          PE = ID->all_referenced_protocol_end(); P != PE; ++P) {
141       ObjCProtocolDecl *Proto = (*P);
142       if (Proto->HasUserDeclaredSetterMethod(Property))
143         return true;
144     }
145     // And in its super class.
146     ObjCInterfaceDecl *OSC = ID->getSuperClass();
147     while (OSC) {
148       if (OSC->HasUserDeclaredSetterMethod(Property))
149         return true;
150       OSC = OSC->getSuperClass();
151     }
152   }
153   if (const ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(this))
154     for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
155          E = PD->protocol_end(); PI != E; ++PI) {
156       if ((*PI)->HasUserDeclaredSetterMethod(Property))
157         return true;
158     }
159   return false;
160 }
161 
162 ObjCPropertyDecl *
163 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
164                                    IdentifierInfo *propertyID) {
165   // If this context is a hidden protocol definition, don't find any
166   // property.
167   if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(DC)) {
168     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
169       if (Def->isHidden())
170         return 0;
171   }
172 
173   DeclContext::lookup_const_result R = DC->lookup(propertyID);
174   for (DeclContext::lookup_const_iterator I = R.begin(), E = R.end(); I != E;
175        ++I)
176     if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(*I))
177       return PD;
178 
179   return 0;
180 }
181 
182 IdentifierInfo *
183 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const {
184   SmallString<128> ivarName;
185   {
186     llvm::raw_svector_ostream os(ivarName);
187     os << '_' << getIdentifier()->getName();
188   }
189   return &Ctx.Idents.get(ivarName.str());
190 }
191 
192 /// FindPropertyDeclaration - Finds declaration of the property given its name
193 /// in 'PropertyId' and returns it. It returns 0, if not found.
194 ObjCPropertyDecl *
195 ObjCContainerDecl::FindPropertyDeclaration(IdentifierInfo *PropertyId) const {
196   // Don't find properties within hidden protocol definitions.
197   if (const ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(this)) {
198     if (const ObjCProtocolDecl *Def = Proto->getDefinition())
199       if (Def->isHidden())
200         return 0;
201   }
202 
203   if (ObjCPropertyDecl *PD =
204         ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
205     return PD;
206 
207   switch (getKind()) {
208     default:
209       break;
210     case Decl::ObjCProtocol: {
211       const ObjCProtocolDecl *PID = cast<ObjCProtocolDecl>(this);
212       for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
213            E = PID->protocol_end(); I != E; ++I)
214         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
215           return P;
216       break;
217     }
218     case Decl::ObjCInterface: {
219       const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(this);
220       // Look through categories (but not extensions).
221       for (ObjCInterfaceDecl::visible_categories_iterator
222              Cat = OID->visible_categories_begin(),
223              CatEnd = OID->visible_categories_end();
224            Cat != CatEnd; ++Cat) {
225         if (!Cat->IsClassExtension())
226           if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(PropertyId))
227             return P;
228       }
229 
230       // Look through protocols.
231       for (ObjCInterfaceDecl::all_protocol_iterator
232             I = OID->all_referenced_protocol_begin(),
233             E = OID->all_referenced_protocol_end(); I != E; ++I)
234         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
235           return P;
236 
237       // Finally, check the super class.
238       if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
239         return superClass->FindPropertyDeclaration(PropertyId);
240       break;
241     }
242     case Decl::ObjCCategory: {
243       const ObjCCategoryDecl *OCD = cast<ObjCCategoryDecl>(this);
244       // Look through protocols.
245       if (!OCD->IsClassExtension())
246         for (ObjCCategoryDecl::protocol_iterator
247               I = OCD->protocol_begin(), E = OCD->protocol_end(); I != E; ++I)
248         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
249           return P;
250 
251       break;
252     }
253   }
254   return 0;
255 }
256 
257 void ObjCInterfaceDecl::anchor() { }
258 
259 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
260 /// with name 'PropertyId' in the primary class; including those in protocols
261 /// (direct or indirect) used by the primary class.
262 ///
263 ObjCPropertyDecl *
264 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
265                                             IdentifierInfo *PropertyId) const {
266   // FIXME: Should make sure no callers ever do this.
267   if (!hasDefinition())
268     return 0;
269 
270   if (data().ExternallyCompleted)
271     LoadExternalDefinition();
272 
273   if (ObjCPropertyDecl *PD =
274       ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
275     return PD;
276 
277   // Look through protocols.
278   for (ObjCInterfaceDecl::all_protocol_iterator
279         I = all_referenced_protocol_begin(),
280         E = all_referenced_protocol_end(); I != E; ++I)
281     if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
282       return P;
283 
284   return 0;
285 }
286 
287 void ObjCInterfaceDecl::collectPropertiesToImplement(PropertyMap &PM,
288                                                      PropertyDeclOrder &PO) const {
289   for (ObjCContainerDecl::prop_iterator P = prop_begin(),
290       E = prop_end(); P != E; ++P) {
291     ObjCPropertyDecl *Prop = *P;
292     PM[Prop->getIdentifier()] = Prop;
293     PO.push_back(Prop);
294   }
295   for (ObjCInterfaceDecl::all_protocol_iterator
296       PI = all_referenced_protocol_begin(),
297       E = all_referenced_protocol_end(); PI != E; ++PI)
298     (*PI)->collectPropertiesToImplement(PM, PO);
299   // Note, the properties declared only in class extensions are still copied
300   // into the main @interface's property list, and therefore we don't
301   // explicitly, have to search class extension properties.
302 }
303 
304 bool ObjCInterfaceDecl::isArcWeakrefUnavailable() const {
305   const ObjCInterfaceDecl *Class = this;
306   while (Class) {
307     if (Class->hasAttr<ArcWeakrefUnavailableAttr>())
308       return true;
309     Class = Class->getSuperClass();
310   }
311   return false;
312 }
313 
314 const ObjCInterfaceDecl *ObjCInterfaceDecl::isObjCRequiresPropertyDefs() const {
315   const ObjCInterfaceDecl *Class = this;
316   while (Class) {
317     if (Class->hasAttr<ObjCRequiresPropertyDefsAttr>())
318       return Class;
319     Class = Class->getSuperClass();
320   }
321   return 0;
322 }
323 
324 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
325                               ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
326                               ASTContext &C)
327 {
328   if (data().ExternallyCompleted)
329     LoadExternalDefinition();
330 
331   if (data().AllReferencedProtocols.empty() &&
332       data().ReferencedProtocols.empty()) {
333     data().AllReferencedProtocols.set(ExtList, ExtNum, C);
334     return;
335   }
336 
337   // Check for duplicate protocol in class's protocol list.
338   // This is O(n*m). But it is extremely rare and number of protocols in
339   // class or its extension are very few.
340   SmallVector<ObjCProtocolDecl*, 8> ProtocolRefs;
341   for (unsigned i = 0; i < ExtNum; i++) {
342     bool protocolExists = false;
343     ObjCProtocolDecl *ProtoInExtension = ExtList[i];
344     for (all_protocol_iterator
345           p = all_referenced_protocol_begin(),
346           e = all_referenced_protocol_end(); p != e; ++p) {
347       ObjCProtocolDecl *Proto = (*p);
348       if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
349         protocolExists = true;
350         break;
351       }
352     }
353     // Do we want to warn on a protocol in extension class which
354     // already exist in the class? Probably not.
355     if (!protocolExists)
356       ProtocolRefs.push_back(ProtoInExtension);
357   }
358 
359   if (ProtocolRefs.empty())
360     return;
361 
362   // Merge ProtocolRefs into class's protocol list;
363   for (all_protocol_iterator p = all_referenced_protocol_begin(),
364         e = all_referenced_protocol_end(); p != e; ++p) {
365     ProtocolRefs.push_back(*p);
366   }
367 
368   data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
369 }
370 
371 const ObjCInterfaceDecl *
372 ObjCInterfaceDecl::findInterfaceWithDesignatedInitializers() const {
373   const ObjCInterfaceDecl *IFace = this;
374   while (IFace) {
375     if (IFace->hasDesignatedInitializers())
376       return IFace;
377     if (!IFace->inheritsDesignatedInitializers())
378       break;
379     IFace = IFace->getSuperClass();
380   }
381   return 0;
382 }
383 
384 bool ObjCInterfaceDecl::inheritsDesignatedInitializers() const {
385   switch (data().InheritedDesignatedInitializers) {
386   case DefinitionData::IDI_Inherited:
387     return true;
388   case DefinitionData::IDI_NotInherited:
389     return false;
390   case DefinitionData::IDI_Unknown: {
391     bool isIntroducingInitializers = false;
392     for (instmeth_iterator I = instmeth_begin(),
393                            E = instmeth_end(); I != E; ++I) {
394       const ObjCMethodDecl *MD = *I;
395       if (MD->getMethodFamily() == OMF_init && !MD->isOverriding()) {
396         isIntroducingInitializers = true;
397         break;
398       }
399     }
400     // If the class introduced initializers we conservatively assume that we
401     // don't know if any of them is a designated initializer to avoid possible
402     // misleading warnings.
403     if (isIntroducingInitializers) {
404       data().InheritedDesignatedInitializers = DefinitionData::IDI_NotInherited;
405       return false;
406     } else {
407       data().InheritedDesignatedInitializers = DefinitionData::IDI_Inherited;
408       return true;
409     }
410   }
411   }
412 
413   llvm_unreachable("unexpected InheritedDesignatedInitializers value");
414 }
415 
416 void ObjCInterfaceDecl::getDesignatedInitializers(
417     llvm::SmallVectorImpl<const ObjCMethodDecl *> &Methods) const {
418   assert(hasDefinition());
419   if (data().ExternallyCompleted)
420     LoadExternalDefinition();
421 
422   const ObjCInterfaceDecl *IFace= findInterfaceWithDesignatedInitializers();
423   if (!IFace)
424     return;
425 
426   for (instmeth_iterator I = IFace->instmeth_begin(),
427                          E = IFace->instmeth_end(); I != E; ++I) {
428     const ObjCMethodDecl *MD = *I;
429     if (MD->isThisDeclarationADesignatedInitializer())
430       Methods.push_back(MD);
431   }
432 }
433 
434 bool ObjCInterfaceDecl::isDesignatedInitializer(Selector Sel,
435                                       const ObjCMethodDecl **InitMethod) const {
436   assert(hasDefinition());
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->getMethod(Sel, /*isInstance=*/true)) {
445     if (MD->isThisDeclarationADesignatedInitializer()) {
446       if (InitMethod)
447         *InitMethod = MD;
448       return true;
449     }
450   }
451   return false;
452 }
453 
454 void ObjCInterfaceDecl::allocateDefinitionData() {
455   assert(!hasDefinition() && "ObjC class already has a definition");
456   Data.setPointer(new (getASTContext()) DefinitionData());
457   Data.getPointer()->Definition = this;
458 
459   // Make the type point at the definition, now that we have one.
460   if (TypeForDecl)
461     cast<ObjCInterfaceType>(TypeForDecl)->Decl = this;
462 }
463 
464 void ObjCInterfaceDecl::startDefinition() {
465   allocateDefinitionData();
466 
467   // Update all of the declarations with a pointer to the definition.
468   for (redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
469        RD != RDEnd; ++RD) {
470     if (*RD != this)
471       RD->Data = Data;
472   }
473 }
474 
475 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
476                                               ObjCInterfaceDecl *&clsDeclared) {
477   // FIXME: Should make sure no callers ever do this.
478   if (!hasDefinition())
479     return 0;
480 
481   if (data().ExternallyCompleted)
482     LoadExternalDefinition();
483 
484   ObjCInterfaceDecl* ClassDecl = this;
485   while (ClassDecl != NULL) {
486     if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
487       clsDeclared = ClassDecl;
488       return I;
489     }
490 
491     for (ObjCInterfaceDecl::visible_extensions_iterator
492            Ext = ClassDecl->visible_extensions_begin(),
493            ExtEnd = ClassDecl->visible_extensions_end();
494          Ext != ExtEnd; ++Ext) {
495       if (ObjCIvarDecl *I = Ext->getIvarDecl(ID)) {
496         clsDeclared = ClassDecl;
497         return I;
498       }
499     }
500 
501     ClassDecl = ClassDecl->getSuperClass();
502   }
503   return NULL;
504 }
505 
506 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
507 /// class whose name is passed as argument. If it is not one of the super classes
508 /// the it returns NULL.
509 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
510                                         const IdentifierInfo*ICName) {
511   // FIXME: Should make sure no callers ever do this.
512   if (!hasDefinition())
513     return 0;
514 
515   if (data().ExternallyCompleted)
516     LoadExternalDefinition();
517 
518   ObjCInterfaceDecl* ClassDecl = this;
519   while (ClassDecl != NULL) {
520     if (ClassDecl->getIdentifier() == ICName)
521       return ClassDecl;
522     ClassDecl = ClassDecl->getSuperClass();
523   }
524   return NULL;
525 }
526 
527 ObjCProtocolDecl *
528 ObjCInterfaceDecl::lookupNestedProtocol(IdentifierInfo *Name) {
529   for (ObjCInterfaceDecl::all_protocol_iterator P =
530        all_referenced_protocol_begin(), PE = all_referenced_protocol_end();
531        P != PE; ++P)
532     if ((*P)->lookupProtocolNamed(Name))
533       return (*P);
534   ObjCInterfaceDecl *SuperClass = getSuperClass();
535   return SuperClass ? SuperClass->lookupNestedProtocol(Name) : NULL;
536 }
537 
538 /// lookupMethod - This method returns an instance/class method by looking in
539 /// the class, its categories, and its super classes (using a linear search).
540 /// When argument category "C" is specified, any implicit method found
541 /// in this category is ignored.
542 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
543                                                 bool isInstance,
544                                                 bool shallowCategoryLookup,
545                                                 bool followSuper,
546                                                 const ObjCCategoryDecl *C) const
547 {
548   // FIXME: Should make sure no callers ever do this.
549   if (!hasDefinition())
550     return 0;
551 
552   const ObjCInterfaceDecl* ClassDecl = this;
553   ObjCMethodDecl *MethodDecl = 0;
554 
555   if (data().ExternallyCompleted)
556     LoadExternalDefinition();
557 
558   while (ClassDecl) {
559     if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
560       return MethodDecl;
561 
562     // Didn't find one yet - look through protocols.
563     for (ObjCInterfaceDecl::protocol_iterator I = ClassDecl->protocol_begin(),
564                                               E = ClassDecl->protocol_end();
565            I != E; ++I)
566       if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
567         return MethodDecl;
568 
569     // Didn't find one yet - now look through categories.
570     for (ObjCInterfaceDecl::visible_categories_iterator
571          Cat = ClassDecl->visible_categories_begin(),
572          CatEnd = ClassDecl->visible_categories_end();
573          Cat != CatEnd; ++Cat) {
574       if ((MethodDecl = Cat->getMethod(Sel, isInstance)))
575         if (C != (*Cat) || !MethodDecl->isImplicit())
576           return MethodDecl;
577 
578       if (!shallowCategoryLookup) {
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 NULL;
592 
593     // Get the super class (if any).
594     ClassDecl = ClassDecl->getSuperClass();
595   }
596   return NULL;
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 0;
608 
609   if (data().ExternallyCompleted)
610     LoadExternalDefinition();
611 
612   ObjCMethodDecl *Method = 0;
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(), 0, 0);
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 = 0;
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::getNextRedeclaration() {
728   ASTContext &Ctx = getASTContext();
729   ObjCMethodDecl *Redecl = 0;
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_performSelector:
856     if (!isInstanceMethod() || !getReturnType()->isObjCIdType())
857       family = OMF_None;
858     else {
859       unsigned noParams = param_size();
860       if (noParams < 1 || noParams > 3)
861         family = OMF_None;
862       else {
863         ObjCMethodDecl::param_type_iterator it = param_type_begin();
864         QualType ArgT = (*it);
865         if (!ArgT->isObjCSelType()) {
866           family = OMF_None;
867           break;
868         }
869         while (--noParams) {
870           it++;
871           ArgT = (*it);
872           if (!ArgT->isObjCIdType()) {
873             family = OMF_None;
874             break;
875           }
876         }
877       }
878     }
879     break;
880 
881   }
882 
883   // Cache the result.
884   Family = static_cast<unsigned>(family);
885   return family;
886 }
887 
888 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
889                                           const ObjCInterfaceDecl *OID) {
890   QualType selfTy;
891   if (isInstanceMethod()) {
892     // There may be no interface context due to error in declaration
893     // of the interface (which has been reported). Recover gracefully.
894     if (OID) {
895       selfTy = Context.getObjCInterfaceType(OID);
896       selfTy = Context.getObjCObjectPointerType(selfTy);
897     } else {
898       selfTy = Context.getObjCIdType();
899     }
900   } else // we have a factory method.
901     selfTy = Context.getObjCClassType();
902 
903   bool selfIsPseudoStrong = false;
904   bool selfIsConsumed = false;
905 
906   if (Context.getLangOpts().ObjCAutoRefCount) {
907     if (isInstanceMethod()) {
908       selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
909 
910       // 'self' is always __strong.  It's actually pseudo-strong except
911       // in init methods (or methods labeled ns_consumes_self), though.
912       Qualifiers qs;
913       qs.setObjCLifetime(Qualifiers::OCL_Strong);
914       selfTy = Context.getQualifiedType(selfTy, qs);
915 
916       // In addition, 'self' is const unless this is an init method.
917       if (getMethodFamily() != OMF_init && !selfIsConsumed) {
918         selfTy = selfTy.withConst();
919         selfIsPseudoStrong = true;
920       }
921     }
922     else {
923       assert(isClassMethod());
924       // 'self' is always const in class methods.
925       selfTy = selfTy.withConst();
926       selfIsPseudoStrong = true;
927     }
928   }
929 
930   ImplicitParamDecl *self
931     = ImplicitParamDecl::Create(Context, this, SourceLocation(),
932                                 &Context.Idents.get("self"), selfTy);
933   setSelfDecl(self);
934 
935   if (selfIsConsumed)
936     self->addAttr(NSConsumedAttr::CreateImplicit(Context));
937 
938   if (selfIsPseudoStrong)
939     self->setARCPseudoStrong(true);
940 
941   setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(),
942                                        &Context.Idents.get("_cmd"),
943                                        Context.getObjCSelType()));
944 }
945 
946 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
947   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
948     return ID;
949   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
950     return CD->getClassInterface();
951   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
952     return IMD->getClassInterface();
953 
954   assert(!isa<ObjCProtocolDecl>(getDeclContext()) && "It's a protocol method");
955   llvm_unreachable("unknown method context");
956 }
957 
958 static void CollectOverriddenMethodsRecurse(const ObjCContainerDecl *Container,
959                                             const ObjCMethodDecl *Method,
960                                SmallVectorImpl<const ObjCMethodDecl *> &Methods,
961                                             bool MovedToSuper) {
962   if (!Container)
963     return;
964 
965   // In categories look for overriden methods from protocols. A method from
966   // category is not "overriden" since it is considered as the "same" method
967   // (same USR) as the one from the interface.
968   if (const ObjCCategoryDecl *
969         Category = dyn_cast<ObjCCategoryDecl>(Container)) {
970     // Check whether we have a matching method at this category but only if we
971     // are at the super class level.
972     if (MovedToSuper)
973       if (ObjCMethodDecl *
974             Overridden = Container->getMethod(Method->getSelector(),
975                                               Method->isInstanceMethod(),
976                                               /*AllowHidden=*/true))
977         if (Method != Overridden) {
978           // We found an override at this category; there is no need to look
979           // into its protocols.
980           Methods.push_back(Overridden);
981           return;
982         }
983 
984     for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
985                                           PEnd = Category->protocol_end();
986          P != PEnd; ++P)
987       CollectOverriddenMethodsRecurse(*P, Method, Methods, MovedToSuper);
988     return;
989   }
990 
991   // Check whether we have a matching method at this level.
992   if (const ObjCMethodDecl *
993         Overridden = Container->getMethod(Method->getSelector(),
994                                           Method->isInstanceMethod(),
995                                           /*AllowHidden=*/true))
996     if (Method != Overridden) {
997       // We found an override at this level; there is no need to look
998       // into other protocols or categories.
999       Methods.push_back(Overridden);
1000       return;
1001     }
1002 
1003   if (const ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)){
1004     for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
1005                                           PEnd = Protocol->protocol_end();
1006          P != PEnd; ++P)
1007       CollectOverriddenMethodsRecurse(*P, Method, Methods, MovedToSuper);
1008   }
1009 
1010   if (const ObjCInterfaceDecl *
1011         Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
1012     for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
1013                                            PEnd = Interface->protocol_end();
1014          P != PEnd; ++P)
1015       CollectOverriddenMethodsRecurse(*P, Method, Methods, MovedToSuper);
1016 
1017     for (ObjCInterfaceDecl::known_categories_iterator
1018            Cat = Interface->known_categories_begin(),
1019            CatEnd = Interface->known_categories_end();
1020          Cat != CatEnd; ++Cat) {
1021       CollectOverriddenMethodsRecurse(*Cat, Method, Methods,
1022                                       MovedToSuper);
1023     }
1024 
1025     if (const ObjCInterfaceDecl *Super = Interface->getSuperClass())
1026       return CollectOverriddenMethodsRecurse(Super, Method, Methods,
1027                                              /*MovedToSuper=*/true);
1028   }
1029 }
1030 
1031 static inline void CollectOverriddenMethods(const ObjCContainerDecl *Container,
1032                                             const ObjCMethodDecl *Method,
1033                              SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
1034   CollectOverriddenMethodsRecurse(Container, Method, Methods,
1035                                   /*MovedToSuper=*/false);
1036 }
1037 
1038 static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
1039                           SmallVectorImpl<const ObjCMethodDecl *> &overridden) {
1040   assert(Method->isOverriding());
1041 
1042   if (const ObjCProtocolDecl *
1043         ProtD = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext())) {
1044     CollectOverriddenMethods(ProtD, Method, overridden);
1045 
1046   } else if (const ObjCImplDecl *
1047                IMD = dyn_cast<ObjCImplDecl>(Method->getDeclContext())) {
1048     const ObjCInterfaceDecl *ID = IMD->getClassInterface();
1049     if (!ID)
1050       return;
1051     // Start searching for overridden methods using the method from the
1052     // interface as starting point.
1053     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1054                                                     Method->isInstanceMethod(),
1055                                                     /*AllowHidden=*/true))
1056       Method = IFaceMeth;
1057     CollectOverriddenMethods(ID, Method, overridden);
1058 
1059   } else if (const ObjCCategoryDecl *
1060                CatD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) {
1061     const ObjCInterfaceDecl *ID = CatD->getClassInterface();
1062     if (!ID)
1063       return;
1064     // Start searching for overridden methods using the method from the
1065     // interface as starting point.
1066     if (const ObjCMethodDecl *IFaceMeth = ID->getMethod(Method->getSelector(),
1067                                                      Method->isInstanceMethod(),
1068                                                      /*AllowHidden=*/true))
1069       Method = IFaceMeth;
1070     CollectOverriddenMethods(ID, Method, overridden);
1071 
1072   } else {
1073     CollectOverriddenMethods(
1074                   dyn_cast_or_null<ObjCContainerDecl>(Method->getDeclContext()),
1075                   Method, overridden);
1076   }
1077 }
1078 
1079 void ObjCMethodDecl::getOverriddenMethods(
1080                     SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
1081   const ObjCMethodDecl *Method = this;
1082 
1083   if (Method->isRedeclaration()) {
1084     Method = cast<ObjCContainerDecl>(Method->getDeclContext())->
1085                    getMethod(Method->getSelector(), Method->isInstanceMethod());
1086   }
1087 
1088   if (Method->isOverriding()) {
1089     collectOverriddenMethodsSlow(Method, Overridden);
1090     assert(!Overridden.empty() &&
1091            "ObjCMethodDecl's overriding bit is not as expected");
1092   }
1093 }
1094 
1095 const ObjCPropertyDecl *
1096 ObjCMethodDecl::findPropertyDecl(bool CheckOverrides) const {
1097   Selector Sel = getSelector();
1098   unsigned NumArgs = Sel.getNumArgs();
1099   if (NumArgs > 1)
1100     return 0;
1101 
1102   if (!isInstanceMethod() || getMethodFamily() != OMF_None)
1103     return 0;
1104 
1105   if (isPropertyAccessor()) {
1106     const ObjCContainerDecl *Container = cast<ObjCContainerDecl>(getParent());
1107     // If container is class extension, find its primary class.
1108     if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(Container))
1109       if (CatDecl->IsClassExtension())
1110         Container = CatDecl->getClassInterface();
1111 
1112     bool IsGetter = (NumArgs == 0);
1113 
1114     for (ObjCContainerDecl::prop_iterator I = Container->prop_begin(),
1115                                           E = Container->prop_end();
1116          I != E; ++I) {
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 0;
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 0;
1139 
1140 }
1141 
1142 //===----------------------------------------------------------------------===//
1143 // ObjCInterfaceDecl
1144 //===----------------------------------------------------------------------===//
1145 
1146 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
1147                                              DeclContext *DC,
1148                                              SourceLocation atLoc,
1149                                              IdentifierInfo *Id,
1150                                              ObjCInterfaceDecl *PrevDecl,
1151                                              SourceLocation ClassLoc,
1152                                              bool isInternal){
1153   ObjCInterfaceDecl *Result = new (C, DC)
1154       ObjCInterfaceDecl(DC, atLoc, Id, ClassLoc, PrevDecl, isInternal);
1155   Result->Data.setInt(!C.getLangOpts().Modules);
1156   C.getObjCInterfaceType(Result, PrevDecl);
1157   return Result;
1158 }
1159 
1160 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(ASTContext &C,
1161                                                          unsigned ID) {
1162   ObjCInterfaceDecl *Result = new (C, ID) ObjCInterfaceDecl(0, SourceLocation(),
1163                                                             0, SourceLocation(),
1164                                                             0, false);
1165   Result->Data.setInt(!C.getLangOpts().Modules);
1166   return Result;
1167 }
1168 
1169 ObjCInterfaceDecl::
1170 ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id,
1171                   SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
1172                   bool isInternal)
1173   : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, atLoc),
1174     TypeForDecl(0), Data()
1175 {
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   assert(hasDefinition() && "Forward declarations can't contain methods");
1202   data().HasDesignatedInitializers = true;
1203 }
1204 
1205 bool ObjCInterfaceDecl::hasDesignatedInitializers() const {
1206   assert(hasDefinition() && "Forward declarations can't contain methods");
1207   if (data().ExternallyCompleted)
1208     LoadExternalDefinition();
1209 
1210   return data().HasDesignatedInitializers;
1211 }
1212 
1213 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
1214   if (const ObjCInterfaceDecl *Def = getDefinition()) {
1215     if (data().ExternallyCompleted)
1216       LoadExternalDefinition();
1217 
1218     return getASTContext().getObjCImplementation(
1219              const_cast<ObjCInterfaceDecl*>(Def));
1220   }
1221 
1222   // FIXME: Should make sure no callers ever do this.
1223   return 0;
1224 }
1225 
1226 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
1227   getASTContext().setObjCImplementation(getDefinition(), ImplD);
1228 }
1229 
1230 namespace {
1231   struct SynthesizeIvarChunk {
1232     uint64_t Size;
1233     ObjCIvarDecl *Ivar;
1234     SynthesizeIvarChunk(uint64_t size, ObjCIvarDecl *ivar)
1235       : Size(size), Ivar(ivar) {}
1236   };
1237 
1238   bool operator<(const SynthesizeIvarChunk & LHS,
1239                  const SynthesizeIvarChunk &RHS) {
1240       return LHS.Size < RHS.Size;
1241   }
1242 }
1243 
1244 /// all_declared_ivar_begin - return first ivar declared in this class,
1245 /// its extensions and its implementation. Lazily build the list on first
1246 /// access.
1247 ///
1248 /// Caveat: The list returned by this method reflects the current
1249 /// state of the parser. The cache will be updated for every ivar
1250 /// added by an extension or the implementation when they are
1251 /// encountered.
1252 /// See also ObjCIvarDecl::Create().
1253 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
1254   // FIXME: Should make sure no callers ever do this.
1255   if (!hasDefinition())
1256     return 0;
1257 
1258   ObjCIvarDecl *curIvar = 0;
1259   if (!data().IvarList) {
1260     if (!ivar_empty()) {
1261       ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
1262       data().IvarList = *I; ++I;
1263       for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
1264         curIvar->setNextIvar(*I);
1265     }
1266 
1267     for (ObjCInterfaceDecl::known_extensions_iterator
1268            Ext = known_extensions_begin(),
1269            ExtEnd = known_extensions_end();
1270          Ext != ExtEnd; ++Ext) {
1271       if (!Ext->ivar_empty()) {
1272         ObjCCategoryDecl::ivar_iterator
1273           I = Ext->ivar_begin(),
1274           E = Ext->ivar_end();
1275         if (!data().IvarList) {
1276           data().IvarList = *I; ++I;
1277           curIvar = data().IvarList;
1278         }
1279         for ( ;I != E; curIvar = *I, ++I)
1280           curIvar->setNextIvar(*I);
1281       }
1282     }
1283     data().IvarListMissingImplementation = true;
1284   }
1285 
1286   // cached and complete!
1287   if (!data().IvarListMissingImplementation)
1288       return data().IvarList;
1289 
1290   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
1291     data().IvarListMissingImplementation = false;
1292     if (!ImplDecl->ivar_empty()) {
1293       SmallVector<SynthesizeIvarChunk, 16> layout;
1294       for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1295            E = ImplDecl->ivar_end(); I != E; ++I) {
1296         ObjCIvarDecl *IV = *I;
1297         if (IV->getSynthesize() && !IV->isInvalidDecl()) {
1298           layout.push_back(SynthesizeIvarChunk(
1299                              IV->getASTContext().getTypeSize(IV->getType()), IV));
1300           continue;
1301         }
1302         if (!data().IvarList)
1303           data().IvarList = *I;
1304         else
1305           curIvar->setNextIvar(*I);
1306         curIvar = *I;
1307       }
1308 
1309       if (!layout.empty()) {
1310         // Order synthesized ivars by their size.
1311         std::stable_sort(layout.begin(), layout.end());
1312         unsigned Ix = 0, EIx = layout.size();
1313         if (!data().IvarList) {
1314           data().IvarList = layout[0].Ivar; Ix++;
1315           curIvar = data().IvarList;
1316         }
1317         for ( ; Ix != EIx; curIvar = layout[Ix].Ivar, Ix++)
1318           curIvar->setNextIvar(layout[Ix].Ivar);
1319       }
1320     }
1321   }
1322   return data().IvarList;
1323 }
1324 
1325 /// FindCategoryDeclaration - Finds category declaration in the list of
1326 /// categories for this class and returns it. Name of the category is passed
1327 /// in 'CategoryId'. If category not found, return 0;
1328 ///
1329 ObjCCategoryDecl *
1330 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
1331   // FIXME: Should make sure no callers ever do this.
1332   if (!hasDefinition())
1333     return 0;
1334 
1335   if (data().ExternallyCompleted)
1336     LoadExternalDefinition();
1337 
1338   for (visible_categories_iterator Cat = visible_categories_begin(),
1339                                    CatEnd = visible_categories_end();
1340        Cat != CatEnd;
1341        ++Cat) {
1342     if (Cat->getIdentifier() == CategoryId)
1343       return *Cat;
1344   }
1345 
1346   return 0;
1347 }
1348 
1349 ObjCMethodDecl *
1350 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
1351   for (visible_categories_iterator Cat = visible_categories_begin(),
1352                                    CatEnd = visible_categories_end();
1353        Cat != CatEnd;
1354        ++Cat) {
1355     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1356       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
1357         return MD;
1358   }
1359 
1360   return 0;
1361 }
1362 
1363 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
1364   for (visible_categories_iterator Cat = visible_categories_begin(),
1365                                    CatEnd = visible_categories_end();
1366        Cat != CatEnd;
1367        ++Cat) {
1368     if (ObjCCategoryImplDecl *Impl = Cat->getImplementation())
1369       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
1370         return MD;
1371   }
1372 
1373   return 0;
1374 }
1375 
1376 /// ClassImplementsProtocol - Checks that 'lProto' protocol
1377 /// has been implemented in IDecl class, its super class or categories (if
1378 /// lookupCategory is true).
1379 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
1380                                     bool lookupCategory,
1381                                     bool RHSIsQualifiedID) {
1382   if (!hasDefinition())
1383     return false;
1384 
1385   ObjCInterfaceDecl *IDecl = this;
1386   // 1st, look up the class.
1387   for (ObjCInterfaceDecl::protocol_iterator
1388         PI = IDecl->protocol_begin(), E = IDecl->protocol_end(); PI != E; ++PI){
1389     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
1390       return true;
1391     // This is dubious and is added to be compatible with gcc.  In gcc, it is
1392     // also allowed assigning a protocol-qualified 'id' type to a LHS object
1393     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
1394     // object. This IMO, should be a bug.
1395     // FIXME: Treat this as an extension, and flag this as an error when GCC
1396     // extensions are not enabled.
1397     if (RHSIsQualifiedID &&
1398         getASTContext().ProtocolCompatibleWithProtocol(*PI, lProto))
1399       return true;
1400   }
1401 
1402   // 2nd, look up the category.
1403   if (lookupCategory)
1404     for (visible_categories_iterator Cat = visible_categories_begin(),
1405                                      CatEnd = visible_categories_end();
1406          Cat != CatEnd;
1407          ++Cat) {
1408       for (ObjCCategoryDecl::protocol_iterator PI = Cat->protocol_begin(),
1409                                                E = Cat->protocol_end();
1410            PI != E; ++PI)
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(0);
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(0, SourceLocation(), SourceLocation(), 0,
1468                                   QualType(), 0, ObjCIvarDecl::None, 0, false);
1469 }
1470 
1471 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
1472   const ObjCContainerDecl *DC = cast<ObjCContainerDecl>(getDeclContext());
1473 
1474   switch (DC->getKind()) {
1475   default:
1476   case ObjCCategoryImpl:
1477   case ObjCProtocol:
1478     llvm_unreachable("invalid ivar container!");
1479 
1480     // Ivars can only appear in class extension categories.
1481   case ObjCCategory: {
1482     const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
1483     assert(CD->IsClassExtension() && "invalid container for ivar!");
1484     return CD->getClassInterface();
1485   }
1486 
1487   case ObjCImplementation:
1488     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
1489 
1490   case ObjCInterface:
1491     return cast<ObjCInterfaceDecl>(DC);
1492   }
1493 }
1494 
1495 //===----------------------------------------------------------------------===//
1496 // ObjCAtDefsFieldDecl
1497 //===----------------------------------------------------------------------===//
1498 
1499 void ObjCAtDefsFieldDecl::anchor() { }
1500 
1501 ObjCAtDefsFieldDecl
1502 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1503                              SourceLocation StartLoc,  SourceLocation IdLoc,
1504                              IdentifierInfo *Id, QualType T, Expr *BW) {
1505   return new (C, DC) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1506 }
1507 
1508 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1509                                                              unsigned ID) {
1510   return new (C, ID) ObjCAtDefsFieldDecl(0, SourceLocation(), SourceLocation(),
1511                                          0, QualType(), 0);
1512 }
1513 
1514 //===----------------------------------------------------------------------===//
1515 // ObjCProtocolDecl
1516 //===----------------------------------------------------------------------===//
1517 
1518 void ObjCProtocolDecl::anchor() { }
1519 
1520 ObjCProtocolDecl::ObjCProtocolDecl(DeclContext *DC, IdentifierInfo *Id,
1521                                    SourceLocation nameLoc,
1522                                    SourceLocation atStartLoc,
1523                                    ObjCProtocolDecl *PrevDecl)
1524   : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc), Data()
1525 {
1526   setPreviousDecl(PrevDecl);
1527   if (PrevDecl)
1528     Data = PrevDecl->Data;
1529 }
1530 
1531 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1532                                            IdentifierInfo *Id,
1533                                            SourceLocation nameLoc,
1534                                            SourceLocation atStartLoc,
1535                                            ObjCProtocolDecl *PrevDecl) {
1536   ObjCProtocolDecl *Result =
1537       new (C, DC) ObjCProtocolDecl(DC, Id, nameLoc, atStartLoc, PrevDecl);
1538   Result->Data.setInt(!C.getLangOpts().Modules);
1539   return Result;
1540 }
1541 
1542 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1543                                                        unsigned ID) {
1544   ObjCProtocolDecl *Result =
1545       new (C, ID) ObjCProtocolDecl(0, 0, SourceLocation(), SourceLocation(), 0);
1546   Result->Data.setInt(!C.getLangOpts().Modules);
1547   return Result;
1548 }
1549 
1550 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1551   ObjCProtocolDecl *PDecl = this;
1552 
1553   if (Name == getIdentifier())
1554     return PDecl;
1555 
1556   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
1557     if ((PDecl = (*I)->lookupProtocolNamed(Name)))
1558       return PDecl;
1559 
1560   return NULL;
1561 }
1562 
1563 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1564 // it inherited.
1565 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1566                                                bool isInstance) const {
1567   ObjCMethodDecl *MethodDecl = NULL;
1568 
1569   // If there is no definition or the definition is hidden, we don't find
1570   // anything.
1571   const ObjCProtocolDecl *Def = getDefinition();
1572   if (!Def || Def->isHidden())
1573     return NULL;
1574 
1575   if ((MethodDecl = getMethod(Sel, isInstance)))
1576     return MethodDecl;
1577 
1578   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
1579     if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
1580       return MethodDecl;
1581   return NULL;
1582 }
1583 
1584 void ObjCProtocolDecl::allocateDefinitionData() {
1585   assert(!Data.getPointer() && "Protocol already has a definition!");
1586   Data.setPointer(new (getASTContext()) DefinitionData);
1587   Data.getPointer()->Definition = this;
1588 }
1589 
1590 void ObjCProtocolDecl::startDefinition() {
1591   allocateDefinitionData();
1592 
1593   // Update all of the declarations with a pointer to the definition.
1594   for (redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1595        RD != RDEnd; ++RD)
1596     RD->Data = this->Data;
1597 }
1598 
1599 void ObjCProtocolDecl::collectPropertiesToImplement(PropertyMap &PM,
1600                                                     PropertyDeclOrder &PO) const {
1601 
1602   if (const ObjCProtocolDecl *PDecl = getDefinition()) {
1603     for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1604          E = PDecl->prop_end(); P != E; ++P) {
1605       ObjCPropertyDecl *Prop = *P;
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 (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1612          E = PDecl->protocol_end(); PI != E; ++PI)
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 (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1624          E = PDecl->prop_end(); P != E; ++P) {
1625       ObjCPropertyDecl *Prop = *P;
1626       if (Prop == Property)
1627         continue;
1628       if (Prop->getIdentifier() == Property->getIdentifier()) {
1629         PM[PDecl] = Prop;
1630         MatchFound = true;
1631         break;
1632       }
1633     }
1634     // Scan through protocol's protocols which did not have a matching property.
1635     if (!MatchFound)
1636       for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1637            E = PDecl->protocol_end(); PI != E; ++PI)
1638         (*PI)->collectInheritedProtocolProperties(Property, PM);
1639   }
1640 }
1641 
1642 //===----------------------------------------------------------------------===//
1643 // ObjCCategoryDecl
1644 //===----------------------------------------------------------------------===//
1645 
1646 void ObjCCategoryDecl::anchor() { }
1647 
1648 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
1649                                            SourceLocation AtLoc,
1650                                            SourceLocation ClassNameLoc,
1651                                            SourceLocation CategoryNameLoc,
1652                                            IdentifierInfo *Id,
1653                                            ObjCInterfaceDecl *IDecl,
1654                                            SourceLocation IvarLBraceLoc,
1655                                            SourceLocation IvarRBraceLoc) {
1656   ObjCCategoryDecl *CatDecl =
1657       new (C, DC) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id,
1658                                    IDecl, IvarLBraceLoc, IvarRBraceLoc);
1659   if (IDecl) {
1660     // Link this category into its class's category list.
1661     CatDecl->NextClassCategory = IDecl->getCategoryListRaw();
1662     if (IDecl->hasDefinition()) {
1663       IDecl->setCategoryListRaw(CatDecl);
1664       if (ASTMutationListener *L = C.getASTMutationListener())
1665         L->AddedObjCCategoryToInterface(CatDecl, IDecl);
1666     }
1667   }
1668 
1669   return CatDecl;
1670 }
1671 
1672 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
1673                                                        unsigned ID) {
1674   return new (C, ID) ObjCCategoryDecl(0, SourceLocation(), SourceLocation(),
1675                                       SourceLocation(), 0, 0);
1676 }
1677 
1678 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
1679   return getASTContext().getObjCImplementation(
1680                                            const_cast<ObjCCategoryDecl*>(this));
1681 }
1682 
1683 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
1684   getASTContext().setObjCImplementation(this, ImplD);
1685 }
1686 
1687 
1688 //===----------------------------------------------------------------------===//
1689 // ObjCCategoryImplDecl
1690 //===----------------------------------------------------------------------===//
1691 
1692 void ObjCCategoryImplDecl::anchor() { }
1693 
1694 ObjCCategoryImplDecl *
1695 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
1696                              IdentifierInfo *Id,
1697                              ObjCInterfaceDecl *ClassInterface,
1698                              SourceLocation nameLoc,
1699                              SourceLocation atStartLoc,
1700                              SourceLocation CategoryNameLoc) {
1701   if (ClassInterface && ClassInterface->hasDefinition())
1702     ClassInterface = ClassInterface->getDefinition();
1703   return new (C, DC) ObjCCategoryImplDecl(DC, Id, ClassInterface, nameLoc,
1704                                           atStartLoc, CategoryNameLoc);
1705 }
1706 
1707 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
1708                                                                unsigned ID) {
1709   return new (C, ID) ObjCCategoryImplDecl(0, 0, 0, SourceLocation(),
1710                                           SourceLocation(), SourceLocation());
1711 }
1712 
1713 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
1714   // The class interface might be NULL if we are working with invalid code.
1715   if (const ObjCInterfaceDecl *ID = getClassInterface())
1716     return ID->FindCategoryDeclaration(getIdentifier());
1717   return 0;
1718 }
1719 
1720 
1721 void ObjCImplDecl::anchor() { }
1722 
1723 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
1724   // FIXME: The context should be correct before we get here.
1725   property->setLexicalDeclContext(this);
1726   addDecl(property);
1727 }
1728 
1729 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
1730   ASTContext &Ctx = getASTContext();
1731 
1732   if (ObjCImplementationDecl *ImplD
1733         = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
1734     if (IFace)
1735       Ctx.setObjCImplementation(IFace, ImplD);
1736 
1737   } else if (ObjCCategoryImplDecl *ImplD =
1738              dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
1739     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
1740       Ctx.setObjCImplementation(CD, ImplD);
1741   }
1742 
1743   ClassInterface = IFace;
1744 }
1745 
1746 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
1747 /// properties implemented in this \@implementation block and returns
1748 /// the implemented property that uses it.
1749 ///
1750 ObjCPropertyImplDecl *ObjCImplDecl::
1751 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
1752   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
1753     ObjCPropertyImplDecl *PID = *i;
1754     if (PID->getPropertyIvarDecl() &&
1755         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
1756       return PID;
1757   }
1758   return 0;
1759 }
1760 
1761 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
1762 /// added to the list of those properties \@synthesized/\@dynamic in this
1763 /// category \@implementation block.
1764 ///
1765 ObjCPropertyImplDecl *ObjCImplDecl::
1766 FindPropertyImplDecl(IdentifierInfo *Id) const {
1767   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
1768     ObjCPropertyImplDecl *PID = *i;
1769     if (PID->getPropertyDecl()->getIdentifier() == Id)
1770       return PID;
1771   }
1772   return 0;
1773 }
1774 
1775 raw_ostream &clang::operator<<(raw_ostream &OS,
1776                                const ObjCCategoryImplDecl &CID) {
1777   OS << CID.getName();
1778   return OS;
1779 }
1780 
1781 //===----------------------------------------------------------------------===//
1782 // ObjCImplementationDecl
1783 //===----------------------------------------------------------------------===//
1784 
1785 void ObjCImplementationDecl::anchor() { }
1786 
1787 ObjCImplementationDecl *
1788 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
1789                                ObjCInterfaceDecl *ClassInterface,
1790                                ObjCInterfaceDecl *SuperDecl,
1791                                SourceLocation nameLoc,
1792                                SourceLocation atStartLoc,
1793                                SourceLocation superLoc,
1794                                SourceLocation IvarLBraceLoc,
1795                                SourceLocation IvarRBraceLoc) {
1796   if (ClassInterface && ClassInterface->hasDefinition())
1797     ClassInterface = ClassInterface->getDefinition();
1798   return new (C, DC) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
1799                                             nameLoc, atStartLoc, superLoc,
1800                                             IvarLBraceLoc, IvarRBraceLoc);
1801 }
1802 
1803 ObjCImplementationDecl *
1804 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1805   return new (C, ID) ObjCImplementationDecl(0, 0, 0, SourceLocation(),
1806                                             SourceLocation());
1807 }
1808 
1809 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
1810                                              CXXCtorInitializer ** initializers,
1811                                                  unsigned numInitializers) {
1812   if (numInitializers > 0) {
1813     NumIvarInitializers = numInitializers;
1814     CXXCtorInitializer **ivarInitializers =
1815     new (C) CXXCtorInitializer*[NumIvarInitializers];
1816     memcpy(ivarInitializers, initializers,
1817            numInitializers * sizeof(CXXCtorInitializer*));
1818     IvarInitializers = ivarInitializers;
1819   }
1820 }
1821 
1822 raw_ostream &clang::operator<<(raw_ostream &OS,
1823                                const ObjCImplementationDecl &ID) {
1824   OS << ID.getName();
1825   return OS;
1826 }
1827 
1828 //===----------------------------------------------------------------------===//
1829 // ObjCCompatibleAliasDecl
1830 //===----------------------------------------------------------------------===//
1831 
1832 void ObjCCompatibleAliasDecl::anchor() { }
1833 
1834 ObjCCompatibleAliasDecl *
1835 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
1836                                 SourceLocation L,
1837                                 IdentifierInfo *Id,
1838                                 ObjCInterfaceDecl* AliasedClass) {
1839   return new (C, DC) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
1840 }
1841 
1842 ObjCCompatibleAliasDecl *
1843 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1844   return new (C, ID) ObjCCompatibleAliasDecl(0, SourceLocation(), 0, 0);
1845 }
1846 
1847 //===----------------------------------------------------------------------===//
1848 // ObjCPropertyDecl
1849 //===----------------------------------------------------------------------===//
1850 
1851 void ObjCPropertyDecl::anchor() { }
1852 
1853 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
1854                                            SourceLocation L,
1855                                            IdentifierInfo *Id,
1856                                            SourceLocation AtLoc,
1857                                            SourceLocation LParenLoc,
1858                                            TypeSourceInfo *T,
1859                                            PropertyControl propControl) {
1860   return new (C, DC) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T);
1861 }
1862 
1863 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
1864                                                        unsigned ID) {
1865   return new (C, ID) ObjCPropertyDecl(0, SourceLocation(), 0, SourceLocation(),
1866                                       SourceLocation(), 0);
1867 }
1868 
1869 //===----------------------------------------------------------------------===//
1870 // ObjCPropertyImplDecl
1871 //===----------------------------------------------------------------------===//
1872 
1873 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
1874                                                    DeclContext *DC,
1875                                                    SourceLocation atLoc,
1876                                                    SourceLocation L,
1877                                                    ObjCPropertyDecl *property,
1878                                                    Kind PK,
1879                                                    ObjCIvarDecl *ivar,
1880                                                    SourceLocation ivarLoc) {
1881   return new (C, DC) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
1882                                           ivarLoc);
1883 }
1884 
1885 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
1886                                                                unsigned ID) {
1887   return new (C, ID) ObjCPropertyImplDecl(0, SourceLocation(), SourceLocation(),
1888                                           0, Dynamic, 0, SourceLocation());
1889 }
1890 
1891 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
1892   SourceLocation EndLoc = getLocation();
1893   if (IvarLoc.isValid())
1894     EndLoc = IvarLoc;
1895 
1896   return SourceRange(AtLoc, EndLoc);
1897 }
1898