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