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/Stmt.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallString.h"
20 using namespace clang;
21 
22 //===----------------------------------------------------------------------===//
23 // ObjCListBase
24 //===----------------------------------------------------------------------===//
25 
26 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) {
27   List = 0;
28   if (Elts == 0) return;  // Setting to an empty list is a noop.
29 
30 
31   List = new (Ctx) void*[Elts];
32   NumElts = Elts;
33   memcpy(List, InList, sizeof(void*)*Elts);
34 }
35 
36 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts,
37                            const SourceLocation *Locs, ASTContext &Ctx) {
38   if (Elts == 0)
39     return;
40 
41   Locations = new (Ctx) SourceLocation[Elts];
42   memcpy(Locations, Locs, sizeof(SourceLocation) * Elts);
43   set(InList, Elts, Ctx);
44 }
45 
46 //===----------------------------------------------------------------------===//
47 // ObjCInterfaceDecl
48 //===----------------------------------------------------------------------===//
49 
50 void ObjCContainerDecl::anchor() { }
51 
52 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
53 ///
54 ObjCIvarDecl *
55 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
56   lookup_const_iterator Ivar, IvarEnd;
57   for (llvm::tie(Ivar, IvarEnd) = lookup(Id); Ivar != IvarEnd; ++Ivar) {
58     if (ObjCIvarDecl *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
59       return ivar;
60   }
61   return 0;
62 }
63 
64 // Get the local instance/class method declared in this interface.
65 ObjCMethodDecl *
66 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance) const {
67   // Since instance & class methods can have the same name, the loop below
68   // ensures we get the correct method.
69   //
70   // @interface Whatever
71   // - (int) class_method;
72   // + (float) class_method;
73   // @end
74   //
75   lookup_const_iterator Meth, MethEnd;
76   for (llvm::tie(Meth, MethEnd) = lookup(Sel); Meth != MethEnd; ++Meth) {
77     ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
78     if (MD && MD->isInstanceMethod() == isInstance)
79       return MD;
80   }
81   return 0;
82 }
83 
84 ObjCPropertyDecl *
85 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
86                                    IdentifierInfo *propertyID) {
87 
88   DeclContext::lookup_const_iterator I, E;
89   llvm::tie(I, E) = DC->lookup(propertyID);
90   for ( ; I != E; ++I)
91     if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(*I))
92       return PD;
93 
94   return 0;
95 }
96 
97 IdentifierInfo *
98 ObjCPropertyDecl::getDefaultSynthIvarName(ASTContext &Ctx) const {
99   SmallString<128> ivarName;
100   {
101     llvm::raw_svector_ostream os(ivarName);
102     os << '_' << getIdentifier()->getName();
103   }
104   return &Ctx.Idents.get(ivarName.str());
105 }
106 
107 /// FindPropertyDeclaration - Finds declaration of the property given its name
108 /// in 'PropertyId' and returns it. It returns 0, if not found.
109 ObjCPropertyDecl *
110 ObjCContainerDecl::FindPropertyDeclaration(IdentifierInfo *PropertyId) const {
111 
112   if (ObjCPropertyDecl *PD =
113         ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
114     return PD;
115 
116   switch (getKind()) {
117     default:
118       break;
119     case Decl::ObjCProtocol: {
120       const ObjCProtocolDecl *PID = cast<ObjCProtocolDecl>(this);
121       for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
122            E = PID->protocol_end(); I != E; ++I)
123         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
124           return P;
125       break;
126     }
127     case Decl::ObjCInterface: {
128       const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(this);
129       // Look through categories.
130       for (ObjCCategoryDecl *Cat = OID->getCategoryList();
131            Cat; Cat = Cat->getNextClassCategory())
132         if (!Cat->IsClassExtension())
133           if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(PropertyId))
134             return P;
135 
136       // Look through protocols.
137       for (ObjCInterfaceDecl::all_protocol_iterator
138             I = OID->all_referenced_protocol_begin(),
139             E = OID->all_referenced_protocol_end(); I != E; ++I)
140         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
141           return P;
142 
143       // Finally, check the super class.
144       if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
145         return superClass->FindPropertyDeclaration(PropertyId);
146       break;
147     }
148     case Decl::ObjCCategory: {
149       const ObjCCategoryDecl *OCD = cast<ObjCCategoryDecl>(this);
150       // Look through protocols.
151       if (!OCD->IsClassExtension())
152         for (ObjCCategoryDecl::protocol_iterator
153               I = OCD->protocol_begin(), E = OCD->protocol_end(); I != E; ++I)
154         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
155           return P;
156 
157       break;
158     }
159   }
160   return 0;
161 }
162 
163 void ObjCInterfaceDecl::anchor() { }
164 
165 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
166 /// with name 'PropertyId' in the primary class; including those in protocols
167 /// (direct or indirect) used by the primary class.
168 ///
169 ObjCPropertyDecl *
170 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
171                                             IdentifierInfo *PropertyId) const {
172   // FIXME: Should make sure no callers ever do this.
173   if (!hasDefinition())
174     return 0;
175 
176   if (data().ExternallyCompleted)
177     LoadExternalDefinition();
178 
179   if (ObjCPropertyDecl *PD =
180       ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
181     return PD;
182 
183   // Look through protocols.
184   for (ObjCInterfaceDecl::all_protocol_iterator
185         I = all_referenced_protocol_begin(),
186         E = all_referenced_protocol_end(); I != E; ++I)
187     if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
188       return P;
189 
190   return 0;
191 }
192 
193 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
194                               ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
195                               ASTContext &C)
196 {
197   if (data().ExternallyCompleted)
198     LoadExternalDefinition();
199 
200   if (data().AllReferencedProtocols.empty() &&
201       data().ReferencedProtocols.empty()) {
202     data().AllReferencedProtocols.set(ExtList, ExtNum, C);
203     return;
204   }
205 
206   // Check for duplicate protocol in class's protocol list.
207   // This is O(n*m). But it is extremely rare and number of protocols in
208   // class or its extension are very few.
209   SmallVector<ObjCProtocolDecl*, 8> ProtocolRefs;
210   for (unsigned i = 0; i < ExtNum; i++) {
211     bool protocolExists = false;
212     ObjCProtocolDecl *ProtoInExtension = ExtList[i];
213     for (all_protocol_iterator
214           p = all_referenced_protocol_begin(),
215           e = all_referenced_protocol_end(); p != e; ++p) {
216       ObjCProtocolDecl *Proto = (*p);
217       if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
218         protocolExists = true;
219         break;
220       }
221     }
222     // Do we want to warn on a protocol in extension class which
223     // already exist in the class? Probably not.
224     if (!protocolExists)
225       ProtocolRefs.push_back(ProtoInExtension);
226   }
227 
228   if (ProtocolRefs.empty())
229     return;
230 
231   // Merge ProtocolRefs into class's protocol list;
232   for (all_protocol_iterator p = all_referenced_protocol_begin(),
233         e = all_referenced_protocol_end(); p != e; ++p) {
234     ProtocolRefs.push_back(*p);
235   }
236 
237   data().AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(),C);
238 }
239 
240 void ObjCInterfaceDecl::allocateDefinitionData() {
241   assert(!hasDefinition() && "ObjC class already has a definition");
242   Data = new (getASTContext()) DefinitionData();
243   Data->Definition = this;
244 
245   // Make the type point at the definition, now that we have one.
246   if (TypeForDecl)
247     cast<ObjCInterfaceType>(TypeForDecl)->Decl = this;
248 }
249 
250 void ObjCInterfaceDecl::startDefinition() {
251   allocateDefinitionData();
252 
253   // Update all of the declarations with a pointer to the definition.
254   for (redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
255        RD != RDEnd; ++RD) {
256     if (*RD != this)
257       RD->Data = Data;
258   }
259 }
260 
261 /// getFirstClassExtension - Find first class extension of the given class.
262 ObjCCategoryDecl* ObjCInterfaceDecl::getFirstClassExtension() const {
263   for (ObjCCategoryDecl *CDecl = getCategoryList(); CDecl;
264        CDecl = CDecl->getNextClassCategory())
265     if (CDecl->IsClassExtension())
266       return CDecl;
267   return 0;
268 }
269 
270 /// getNextClassCategory - Find next class extension in list of categories.
271 const ObjCCategoryDecl* ObjCCategoryDecl::getNextClassExtension() const {
272   for (const ObjCCategoryDecl *CDecl = getNextClassCategory(); CDecl;
273         CDecl = CDecl->getNextClassCategory())
274     if (CDecl->IsClassExtension())
275       return CDecl;
276   return 0;
277 }
278 
279 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
280                                               ObjCInterfaceDecl *&clsDeclared) {
281   // FIXME: Should make sure no callers ever do this.
282   if (!hasDefinition())
283     return 0;
284 
285   if (data().ExternallyCompleted)
286     LoadExternalDefinition();
287 
288   ObjCInterfaceDecl* ClassDecl = this;
289   while (ClassDecl != NULL) {
290     if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
291       clsDeclared = ClassDecl;
292       return I;
293     }
294     for (const ObjCCategoryDecl *CDecl = ClassDecl->getFirstClassExtension();
295          CDecl; CDecl = CDecl->getNextClassExtension()) {
296       if (ObjCIvarDecl *I = CDecl->getIvarDecl(ID)) {
297         clsDeclared = ClassDecl;
298         return I;
299       }
300     }
301 
302     ClassDecl = ClassDecl->getSuperClass();
303   }
304   return NULL;
305 }
306 
307 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
308 /// class whose name is passed as argument. If it is not one of the super classes
309 /// the it returns NULL.
310 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
311                                         const IdentifierInfo*ICName) {
312   // FIXME: Should make sure no callers ever do this.
313   if (!hasDefinition())
314     return 0;
315 
316   if (data().ExternallyCompleted)
317     LoadExternalDefinition();
318 
319   ObjCInterfaceDecl* ClassDecl = this;
320   while (ClassDecl != NULL) {
321     if (ClassDecl->getIdentifier() == ICName)
322       return ClassDecl;
323     ClassDecl = ClassDecl->getSuperClass();
324   }
325   return NULL;
326 }
327 
328 /// lookupMethod - This method returns an instance/class method by looking in
329 /// the class, its categories, and its super classes (using a linear search).
330 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
331                                      bool isInstance,
332                                      bool shallowCategoryLookup) const {
333   // FIXME: Should make sure no callers ever do this.
334   if (!hasDefinition())
335     return 0;
336 
337   const ObjCInterfaceDecl* ClassDecl = this;
338   ObjCMethodDecl *MethodDecl = 0;
339 
340   if (data().ExternallyCompleted)
341     LoadExternalDefinition();
342 
343   while (ClassDecl != NULL) {
344     if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
345       return MethodDecl;
346 
347     // Didn't find one yet - look through protocols.
348     for (ObjCInterfaceDecl::protocol_iterator I = ClassDecl->protocol_begin(),
349                                               E = ClassDecl->protocol_end();
350            I != E; ++I)
351       if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
352         return MethodDecl;
353 
354     // Didn't find one yet - now look through categories.
355     ObjCCategoryDecl *CatDecl = ClassDecl->getCategoryList();
356     while (CatDecl) {
357       if ((MethodDecl = CatDecl->getMethod(Sel, isInstance)))
358         return MethodDecl;
359 
360       if (!shallowCategoryLookup) {
361         // Didn't find one yet - look through protocols.
362         const ObjCList<ObjCProtocolDecl> &Protocols =
363           CatDecl->getReferencedProtocols();
364         for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
365              E = Protocols.end(); I != E; ++I)
366           if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
367             return MethodDecl;
368       }
369       CatDecl = CatDecl->getNextClassCategory();
370     }
371 
372     ClassDecl = ClassDecl->getSuperClass();
373   }
374   return NULL;
375 }
376 
377 // Will search "local" class/category implementations for a method decl.
378 // If failed, then we search in class's root for an instance method.
379 // Returns 0 if no method is found.
380 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
381                                    const Selector &Sel,
382                                    bool Instance) const {
383   // FIXME: Should make sure no callers ever do this.
384   if (!hasDefinition())
385     return 0;
386 
387   if (data().ExternallyCompleted)
388     LoadExternalDefinition();
389 
390   ObjCMethodDecl *Method = 0;
391   if (ObjCImplementationDecl *ImpDecl = getImplementation())
392     Method = Instance ? ImpDecl->getInstanceMethod(Sel)
393                       : ImpDecl->getClassMethod(Sel);
394 
395   // Look through local category implementations associated with the class.
396   if (!Method)
397     Method = Instance ? getCategoryInstanceMethod(Sel)
398                       : getCategoryClassMethod(Sel);
399 
400   // Before we give up, check if the selector is an instance method.
401   // But only in the root. This matches gcc's behavior and what the
402   // runtime expects.
403   if (!Instance && !Method && !getSuperClass()) {
404     Method = lookupInstanceMethod(Sel);
405     // Look through local category implementations associated
406     // with the root class.
407     if (!Method)
408       Method = lookupPrivateMethod(Sel, true);
409   }
410 
411   if (!Method && getSuperClass())
412     return getSuperClass()->lookupPrivateMethod(Sel, Instance);
413   return Method;
414 }
415 
416 //===----------------------------------------------------------------------===//
417 // ObjCMethodDecl
418 //===----------------------------------------------------------------------===//
419 
420 ObjCMethodDecl *ObjCMethodDecl::Create(ASTContext &C,
421                                        SourceLocation beginLoc,
422                                        SourceLocation endLoc,
423                                        Selector SelInfo, QualType T,
424                                        TypeSourceInfo *ResultTInfo,
425                                        DeclContext *contextDecl,
426                                        bool isInstance,
427                                        bool isVariadic,
428                                        bool isSynthesized,
429                                        bool isImplicitlyDeclared,
430                                        bool isDefined,
431                                        ImplementationControl impControl,
432                                        bool HasRelatedResultType) {
433   return new (C) ObjCMethodDecl(beginLoc, endLoc,
434                                 SelInfo, T, ResultTInfo, contextDecl,
435                                 isInstance,
436                                 isVariadic, isSynthesized, isImplicitlyDeclared,
437                                 isDefined,
438                                 impControl,
439                                 HasRelatedResultType);
440 }
441 
442 ObjCMethodDecl *ObjCMethodDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
443   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCMethodDecl));
444   return new (Mem) ObjCMethodDecl(SourceLocation(), SourceLocation(),
445                                   Selector(), QualType(), 0, 0);
446 }
447 
448 void ObjCMethodDecl::setAsRedeclaration(const ObjCMethodDecl *PrevMethod) {
449   assert(PrevMethod);
450   getASTContext().setObjCMethodRedeclaration(PrevMethod, this);
451   IsRedeclaration = true;
452   PrevMethod->HasRedeclaration = true;
453 }
454 
455 void ObjCMethodDecl::setParamsAndSelLocs(ASTContext &C,
456                                          ArrayRef<ParmVarDecl*> Params,
457                                          ArrayRef<SourceLocation> SelLocs) {
458   ParamsAndSelLocs = 0;
459   NumParams = Params.size();
460   if (Params.empty() && SelLocs.empty())
461     return;
462 
463   unsigned Size = sizeof(ParmVarDecl *) * NumParams +
464                   sizeof(SourceLocation) * SelLocs.size();
465   ParamsAndSelLocs = C.Allocate(Size);
466   std::copy(Params.begin(), Params.end(), getParams());
467   std::copy(SelLocs.begin(), SelLocs.end(), getStoredSelLocs());
468 }
469 
470 void ObjCMethodDecl::getSelectorLocs(
471                                SmallVectorImpl<SourceLocation> &SelLocs) const {
472   for (unsigned i = 0, e = getNumSelectorLocs(); i != e; ++i)
473     SelLocs.push_back(getSelectorLoc(i));
474 }
475 
476 void ObjCMethodDecl::setMethodParams(ASTContext &C,
477                                      ArrayRef<ParmVarDecl*> Params,
478                                      ArrayRef<SourceLocation> SelLocs) {
479   assert((!SelLocs.empty() || isImplicit()) &&
480          "No selector locs for non-implicit method");
481   if (isImplicit())
482     return setParamsAndSelLocs(C, Params, ArrayRef<SourceLocation>());
483 
484   SelLocsKind = hasStandardSelectorLocs(getSelector(), SelLocs, Params,
485                                         DeclEndLoc);
486   if (SelLocsKind != SelLoc_NonStandard)
487     return setParamsAndSelLocs(C, Params, ArrayRef<SourceLocation>());
488 
489   setParamsAndSelLocs(C, Params, SelLocs);
490 }
491 
492 /// \brief A definition will return its interface declaration.
493 /// An interface declaration will return its definition.
494 /// Otherwise it will return itself.
495 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclaration() {
496   ASTContext &Ctx = getASTContext();
497   ObjCMethodDecl *Redecl = 0;
498   if (HasRedeclaration)
499     Redecl = const_cast<ObjCMethodDecl*>(Ctx.getObjCMethodRedeclaration(this));
500   if (Redecl)
501     return Redecl;
502 
503   Decl *CtxD = cast<Decl>(getDeclContext());
504 
505   if (ObjCInterfaceDecl *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
506     if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
507       Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
508 
509   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
510     if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
511       Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
512 
513   } else if (ObjCImplementationDecl *ImplD =
514                dyn_cast<ObjCImplementationDecl>(CtxD)) {
515     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
516       Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
517 
518   } else if (ObjCCategoryImplDecl *CImplD =
519                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
520     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
521       Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
522   }
523 
524   if (!Redecl && isRedeclaration()) {
525     // This is the last redeclaration, go back to the first method.
526     return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
527                                                     isInstanceMethod());
528   }
529 
530   return Redecl ? Redecl : this;
531 }
532 
533 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
534   Decl *CtxD = cast<Decl>(getDeclContext());
535 
536   if (ObjCImplementationDecl *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
537     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
538       if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
539                                               isInstanceMethod()))
540         return MD;
541 
542   } else if (ObjCCategoryImplDecl *CImplD =
543                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
544     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
545       if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),
546                                                isInstanceMethod()))
547         return MD;
548   }
549 
550   if (isRedeclaration())
551     return cast<ObjCContainerDecl>(CtxD)->getMethod(getSelector(),
552                                                     isInstanceMethod());
553 
554   return this;
555 }
556 
557 SourceLocation ObjCMethodDecl::getLocEnd() const {
558   if (Stmt *Body = getBody())
559     return Body->getLocEnd();
560   return DeclEndLoc;
561 }
562 
563 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
564   ObjCMethodFamily family = static_cast<ObjCMethodFamily>(Family);
565   if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
566     return family;
567 
568   // Check for an explicit attribute.
569   if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
570     // The unfortunate necessity of mapping between enums here is due
571     // to the attributes framework.
572     switch (attr->getFamily()) {
573     case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
574     case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
575     case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
576     case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
577     case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
578     case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
579     }
580     Family = static_cast<unsigned>(family);
581     return family;
582   }
583 
584   family = getSelector().getMethodFamily();
585   switch (family) {
586   case OMF_None: break;
587 
588   // init only has a conventional meaning for an instance method, and
589   // it has to return an object.
590   case OMF_init:
591     if (!isInstanceMethod() || !getResultType()->isObjCObjectPointerType())
592       family = OMF_None;
593     break;
594 
595   // alloc/copy/new have a conventional meaning for both class and
596   // instance methods, but they require an object return.
597   case OMF_alloc:
598   case OMF_copy:
599   case OMF_mutableCopy:
600   case OMF_new:
601     if (!getResultType()->isObjCObjectPointerType())
602       family = OMF_None;
603     break;
604 
605   // These selectors have a conventional meaning only for instance methods.
606   case OMF_dealloc:
607   case OMF_finalize:
608   case OMF_retain:
609   case OMF_release:
610   case OMF_autorelease:
611   case OMF_retainCount:
612   case OMF_self:
613     if (!isInstanceMethod())
614       family = OMF_None;
615     break;
616 
617   case OMF_performSelector:
618     if (!isInstanceMethod() ||
619         !getResultType()->isObjCIdType())
620       family = OMF_None;
621     else {
622       unsigned noParams = param_size();
623       if (noParams < 1 || noParams > 3)
624         family = OMF_None;
625       else {
626         ObjCMethodDecl::arg_type_iterator it = arg_type_begin();
627         QualType ArgT = (*it);
628         if (!ArgT->isObjCSelType()) {
629           family = OMF_None;
630           break;
631         }
632         while (--noParams) {
633           it++;
634           ArgT = (*it);
635           if (!ArgT->isObjCIdType()) {
636             family = OMF_None;
637             break;
638           }
639         }
640       }
641     }
642     break;
643 
644   }
645 
646   // Cache the result.
647   Family = static_cast<unsigned>(family);
648   return family;
649 }
650 
651 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
652                                           const ObjCInterfaceDecl *OID) {
653   QualType selfTy;
654   if (isInstanceMethod()) {
655     // There may be no interface context due to error in declaration
656     // of the interface (which has been reported). Recover gracefully.
657     if (OID) {
658       selfTy = Context.getObjCInterfaceType(OID);
659       selfTy = Context.getObjCObjectPointerType(selfTy);
660     } else {
661       selfTy = Context.getObjCIdType();
662     }
663   } else // we have a factory method.
664     selfTy = Context.getObjCClassType();
665 
666   bool selfIsPseudoStrong = false;
667   bool selfIsConsumed = false;
668 
669   if (Context.getLangOpts().ObjCAutoRefCount) {
670     if (isInstanceMethod()) {
671       selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
672 
673       // 'self' is always __strong.  It's actually pseudo-strong except
674       // in init methods (or methods labeled ns_consumes_self), though.
675       Qualifiers qs;
676       qs.setObjCLifetime(Qualifiers::OCL_Strong);
677       selfTy = Context.getQualifiedType(selfTy, qs);
678 
679       // In addition, 'self' is const unless this is an init method.
680       if (getMethodFamily() != OMF_init && !selfIsConsumed) {
681         selfTy = selfTy.withConst();
682         selfIsPseudoStrong = true;
683       }
684     }
685     else {
686       assert(isClassMethod());
687       // 'self' is always const in class methods.
688       selfTy = selfTy.withConst();
689       selfIsPseudoStrong = true;
690     }
691   }
692 
693   ImplicitParamDecl *self
694     = ImplicitParamDecl::Create(Context, this, SourceLocation(),
695                                 &Context.Idents.get("self"), selfTy);
696   setSelfDecl(self);
697 
698   if (selfIsConsumed)
699     self->addAttr(new (Context) NSConsumedAttr(SourceLocation(), Context));
700 
701   if (selfIsPseudoStrong)
702     self->setARCPseudoStrong(true);
703 
704   setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(),
705                                        &Context.Idents.get("_cmd"),
706                                        Context.getObjCSelType()));
707 }
708 
709 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
710   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
711     return ID;
712   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
713     return CD->getClassInterface();
714   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
715     return IMD->getClassInterface();
716 
717   assert(!isa<ObjCProtocolDecl>(getDeclContext()) && "It's a protocol method");
718   llvm_unreachable("unknown method context");
719 }
720 
721 //===----------------------------------------------------------------------===//
722 // ObjCInterfaceDecl
723 //===----------------------------------------------------------------------===//
724 
725 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(const ASTContext &C,
726                                              DeclContext *DC,
727                                              SourceLocation atLoc,
728                                              IdentifierInfo *Id,
729                                              ObjCInterfaceDecl *PrevDecl,
730                                              SourceLocation ClassLoc,
731                                              bool isInternal){
732   ObjCInterfaceDecl *Result = new (C) ObjCInterfaceDecl(DC, atLoc, Id, ClassLoc,
733                                                         PrevDecl, isInternal);
734   C.getObjCInterfaceType(Result, PrevDecl);
735   return Result;
736 }
737 
738 ObjCInterfaceDecl *ObjCInterfaceDecl::CreateDeserialized(ASTContext &C,
739                                                          unsigned ID) {
740   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCInterfaceDecl));
741   return new (Mem) ObjCInterfaceDecl(0, SourceLocation(), 0, SourceLocation(),
742                                      0, false);
743 }
744 
745 ObjCInterfaceDecl::
746 ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id,
747                   SourceLocation CLoc, ObjCInterfaceDecl *PrevDecl,
748                   bool isInternal)
749   : ObjCContainerDecl(ObjCInterface, DC, Id, CLoc, atLoc),
750     TypeForDecl(0), Data()
751 {
752   setPreviousDeclaration(PrevDecl);
753 
754   // Copy the 'data' pointer over.
755   if (PrevDecl)
756     Data = PrevDecl->Data;
757 
758   setImplicit(isInternal);
759 }
760 
761 void ObjCInterfaceDecl::LoadExternalDefinition() const {
762   assert(data().ExternallyCompleted && "Class is not externally completed");
763   data().ExternallyCompleted = false;
764   getASTContext().getExternalSource()->CompleteType(
765                                         const_cast<ObjCInterfaceDecl *>(this));
766 }
767 
768 void ObjCInterfaceDecl::setExternallyCompleted() {
769   assert(getASTContext().getExternalSource() &&
770          "Class can't be externally completed without an external source");
771   assert(hasDefinition() &&
772          "Forward declarations can't be externally completed");
773   data().ExternallyCompleted = true;
774 }
775 
776 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
777   if (const ObjCInterfaceDecl *Def = getDefinition()) {
778     if (data().ExternallyCompleted)
779       LoadExternalDefinition();
780 
781     return getASTContext().getObjCImplementation(
782              const_cast<ObjCInterfaceDecl*>(Def));
783   }
784 
785   // FIXME: Should make sure no callers ever do this.
786   return 0;
787 }
788 
789 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
790   getASTContext().setObjCImplementation(getDefinition(), ImplD);
791 }
792 
793 /// all_declared_ivar_begin - return first ivar declared in this class,
794 /// its extensions and its implementation. Lazily build the list on first
795 /// access.
796 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
797   // FIXME: Should make sure no callers ever do this.
798   if (!hasDefinition())
799     return 0;
800 
801   if (data().IvarList)
802     return data().IvarList;
803 
804   ObjCIvarDecl *curIvar = 0;
805   if (!ivar_empty()) {
806     ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
807     data().IvarList = *I; ++I;
808     for (curIvar = data().IvarList; I != E; curIvar = *I, ++I)
809       curIvar->setNextIvar(*I);
810   }
811 
812   for (const ObjCCategoryDecl *CDecl = getFirstClassExtension(); CDecl;
813        CDecl = CDecl->getNextClassExtension()) {
814     if (!CDecl->ivar_empty()) {
815       ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
816                                           E = CDecl->ivar_end();
817       if (!data().IvarList) {
818         data().IvarList = *I; ++I;
819         curIvar = data().IvarList;
820       }
821       for ( ;I != E; curIvar = *I, ++I)
822         curIvar->setNextIvar(*I);
823     }
824   }
825 
826   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
827     if (!ImplDecl->ivar_empty()) {
828       ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
829                                             E = ImplDecl->ivar_end();
830       if (!data().IvarList) {
831         data().IvarList = *I; ++I;
832         curIvar = data().IvarList;
833       }
834       for ( ;I != E; curIvar = *I, ++I)
835         curIvar->setNextIvar(*I);
836     }
837   }
838   return data().IvarList;
839 }
840 
841 /// FindCategoryDeclaration - Finds category declaration in the list of
842 /// categories for this class and returns it. Name of the category is passed
843 /// in 'CategoryId'. If category not found, return 0;
844 ///
845 ObjCCategoryDecl *
846 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
847   // FIXME: Should make sure no callers ever do this.
848   if (!hasDefinition())
849     return 0;
850 
851   if (data().ExternallyCompleted)
852     LoadExternalDefinition();
853 
854   for (ObjCCategoryDecl *Category = getCategoryList();
855        Category; Category = Category->getNextClassCategory())
856     if (Category->getIdentifier() == CategoryId)
857       return Category;
858   return 0;
859 }
860 
861 ObjCMethodDecl *
862 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
863   for (ObjCCategoryDecl *Category = getCategoryList();
864        Category; Category = Category->getNextClassCategory())
865     if (ObjCCategoryImplDecl *Impl = Category->getImplementation())
866       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
867         return MD;
868   return 0;
869 }
870 
871 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
872   for (ObjCCategoryDecl *Category = getCategoryList();
873        Category; Category = Category->getNextClassCategory())
874     if (ObjCCategoryImplDecl *Impl = Category->getImplementation())
875       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
876         return MD;
877   return 0;
878 }
879 
880 /// ClassImplementsProtocol - Checks that 'lProto' protocol
881 /// has been implemented in IDecl class, its super class or categories (if
882 /// lookupCategory is true).
883 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
884                                     bool lookupCategory,
885                                     bool RHSIsQualifiedID) {
886   if (!hasDefinition())
887     return false;
888 
889   ObjCInterfaceDecl *IDecl = this;
890   // 1st, look up the class.
891   for (ObjCInterfaceDecl::protocol_iterator
892         PI = IDecl->protocol_begin(), E = IDecl->protocol_end(); PI != E; ++PI){
893     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
894       return true;
895     // This is dubious and is added to be compatible with gcc.  In gcc, it is
896     // also allowed assigning a protocol-qualified 'id' type to a LHS object
897     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
898     // object. This IMO, should be a bug.
899     // FIXME: Treat this as an extension, and flag this as an error when GCC
900     // extensions are not enabled.
901     if (RHSIsQualifiedID &&
902         getASTContext().ProtocolCompatibleWithProtocol(*PI, lProto))
903       return true;
904   }
905 
906   // 2nd, look up the category.
907   if (lookupCategory)
908     for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
909          CDecl = CDecl->getNextClassCategory()) {
910       for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
911            E = CDecl->protocol_end(); PI != E; ++PI)
912         if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
913           return true;
914     }
915 
916   // 3rd, look up the super class(s)
917   if (IDecl->getSuperClass())
918     return
919   IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
920                                                   RHSIsQualifiedID);
921 
922   return false;
923 }
924 
925 //===----------------------------------------------------------------------===//
926 // ObjCIvarDecl
927 //===----------------------------------------------------------------------===//
928 
929 void ObjCIvarDecl::anchor() { }
930 
931 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
932                                    SourceLocation StartLoc,
933                                    SourceLocation IdLoc, IdentifierInfo *Id,
934                                    QualType T, TypeSourceInfo *TInfo,
935                                    AccessControl ac, Expr *BW,
936                                    bool synthesized) {
937   if (DC) {
938     // Ivar's can only appear in interfaces, implementations (via synthesized
939     // properties), and class extensions (via direct declaration, or synthesized
940     // properties).
941     //
942     // FIXME: This should really be asserting this:
943     //   (isa<ObjCCategoryDecl>(DC) &&
944     //    cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
945     // but unfortunately we sometimes place ivars into non-class extension
946     // categories on error. This breaks an AST invariant, and should not be
947     // fixed.
948     assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
949             isa<ObjCCategoryDecl>(DC)) &&
950            "Invalid ivar decl context!");
951     // Once a new ivar is created in any of class/class-extension/implementation
952     // decl contexts, the previously built IvarList must be rebuilt.
953     ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(DC);
954     if (!ID) {
955       if (ObjCImplementationDecl *IM = dyn_cast<ObjCImplementationDecl>(DC))
956         ID = IM->getClassInterface();
957       else
958         ID = cast<ObjCCategoryDecl>(DC)->getClassInterface();
959     }
960     ID->setIvarList(0);
961   }
962 
963   return new (C) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo,
964                               ac, BW, synthesized);
965 }
966 
967 ObjCIvarDecl *ObjCIvarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
968   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCIvarDecl));
969   return new (Mem) ObjCIvarDecl(0, SourceLocation(), SourceLocation(), 0,
970                                 QualType(), 0, ObjCIvarDecl::None, 0, false);
971 }
972 
973 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
974   const ObjCContainerDecl *DC = cast<ObjCContainerDecl>(getDeclContext());
975 
976   switch (DC->getKind()) {
977   default:
978   case ObjCCategoryImpl:
979   case ObjCProtocol:
980     llvm_unreachable("invalid ivar container!");
981 
982     // Ivars can only appear in class extension categories.
983   case ObjCCategory: {
984     const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
985     assert(CD->IsClassExtension() && "invalid container for ivar!");
986     return CD->getClassInterface();
987   }
988 
989   case ObjCImplementation:
990     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
991 
992   case ObjCInterface:
993     return cast<ObjCInterfaceDecl>(DC);
994   }
995 }
996 
997 //===----------------------------------------------------------------------===//
998 // ObjCAtDefsFieldDecl
999 //===----------------------------------------------------------------------===//
1000 
1001 void ObjCAtDefsFieldDecl::anchor() { }
1002 
1003 ObjCAtDefsFieldDecl
1004 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
1005                              SourceLocation StartLoc,  SourceLocation IdLoc,
1006                              IdentifierInfo *Id, QualType T, Expr *BW) {
1007   return new (C) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
1008 }
1009 
1010 ObjCAtDefsFieldDecl *ObjCAtDefsFieldDecl::CreateDeserialized(ASTContext &C,
1011                                                              unsigned ID) {
1012   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCAtDefsFieldDecl));
1013   return new (Mem) ObjCAtDefsFieldDecl(0, SourceLocation(), SourceLocation(),
1014                                        0, QualType(), 0);
1015 }
1016 
1017 //===----------------------------------------------------------------------===//
1018 // ObjCProtocolDecl
1019 //===----------------------------------------------------------------------===//
1020 
1021 void ObjCProtocolDecl::anchor() { }
1022 
1023 ObjCProtocolDecl::ObjCProtocolDecl(DeclContext *DC, IdentifierInfo *Id,
1024                                    SourceLocation nameLoc,
1025                                    SourceLocation atStartLoc,
1026                                    ObjCProtocolDecl *PrevDecl)
1027   : ObjCContainerDecl(ObjCProtocol, DC, Id, nameLoc, atStartLoc), Data()
1028 {
1029   setPreviousDeclaration(PrevDecl);
1030   if (PrevDecl)
1031     Data = PrevDecl->Data;
1032 }
1033 
1034 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
1035                                            IdentifierInfo *Id,
1036                                            SourceLocation nameLoc,
1037                                            SourceLocation atStartLoc,
1038                                            ObjCProtocolDecl *PrevDecl) {
1039   ObjCProtocolDecl *Result
1040     = new (C) ObjCProtocolDecl(DC, Id, nameLoc, atStartLoc, PrevDecl);
1041 
1042   return Result;
1043 }
1044 
1045 ObjCProtocolDecl *ObjCProtocolDecl::CreateDeserialized(ASTContext &C,
1046                                                        unsigned ID) {
1047   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCProtocolDecl));
1048   return new (Mem) ObjCProtocolDecl(0, 0, SourceLocation(), SourceLocation(),
1049                                     0);
1050 }
1051 
1052 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
1053   ObjCProtocolDecl *PDecl = this;
1054 
1055   if (Name == getIdentifier())
1056     return PDecl;
1057 
1058   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
1059     if ((PDecl = (*I)->lookupProtocolNamed(Name)))
1060       return PDecl;
1061 
1062   return NULL;
1063 }
1064 
1065 // lookupMethod - Lookup a instance/class method in the protocol and protocols
1066 // it inherited.
1067 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
1068                                                bool isInstance) const {
1069   ObjCMethodDecl *MethodDecl = NULL;
1070 
1071   if ((MethodDecl = getMethod(Sel, isInstance)))
1072     return MethodDecl;
1073 
1074   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
1075     if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
1076       return MethodDecl;
1077   return NULL;
1078 }
1079 
1080 void ObjCProtocolDecl::allocateDefinitionData() {
1081   assert(!Data && "Protocol already has a definition!");
1082   Data = new (getASTContext()) DefinitionData;
1083   Data->Definition = this;
1084 }
1085 
1086 void ObjCProtocolDecl::startDefinition() {
1087   allocateDefinitionData();
1088 
1089   // Update all of the declarations with a pointer to the definition.
1090   for (redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1091        RD != RDEnd; ++RD)
1092     RD->Data = this->Data;
1093 }
1094 
1095 //===----------------------------------------------------------------------===//
1096 // ObjCCategoryDecl
1097 //===----------------------------------------------------------------------===//
1098 
1099 void ObjCCategoryDecl::anchor() { }
1100 
1101 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
1102                                            SourceLocation AtLoc,
1103                                            SourceLocation ClassNameLoc,
1104                                            SourceLocation CategoryNameLoc,
1105                                            IdentifierInfo *Id,
1106                                            ObjCInterfaceDecl *IDecl,
1107                                            SourceLocation IvarLBraceLoc,
1108                                            SourceLocation IvarRBraceLoc) {
1109   ObjCCategoryDecl *CatDecl = new (C) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc,
1110                                                        CategoryNameLoc, Id,
1111                                                        IDecl,
1112                                                        IvarLBraceLoc, IvarRBraceLoc);
1113   if (IDecl) {
1114     // Link this category into its class's category list.
1115     CatDecl->NextClassCategory = IDecl->getCategoryList();
1116     if (IDecl->hasDefinition()) {
1117       IDecl->setCategoryList(CatDecl);
1118       if (ASTMutationListener *L = C.getASTMutationListener())
1119         L->AddedObjCCategoryToInterface(CatDecl, IDecl);
1120     }
1121   }
1122 
1123   return CatDecl;
1124 }
1125 
1126 ObjCCategoryDecl *ObjCCategoryDecl::CreateDeserialized(ASTContext &C,
1127                                                        unsigned ID) {
1128   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCCategoryDecl));
1129   return new (Mem) ObjCCategoryDecl(0, SourceLocation(), SourceLocation(),
1130                                     SourceLocation(), 0, 0);
1131 }
1132 
1133 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
1134   return getASTContext().getObjCImplementation(
1135                                            const_cast<ObjCCategoryDecl*>(this));
1136 }
1137 
1138 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
1139   getASTContext().setObjCImplementation(this, ImplD);
1140 }
1141 
1142 
1143 //===----------------------------------------------------------------------===//
1144 // ObjCCategoryImplDecl
1145 //===----------------------------------------------------------------------===//
1146 
1147 void ObjCCategoryImplDecl::anchor() { }
1148 
1149 ObjCCategoryImplDecl *
1150 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
1151                              IdentifierInfo *Id,
1152                              ObjCInterfaceDecl *ClassInterface,
1153                              SourceLocation nameLoc,
1154                              SourceLocation atStartLoc,
1155                              SourceLocation CategoryNameLoc) {
1156   if (ClassInterface && ClassInterface->hasDefinition())
1157     ClassInterface = ClassInterface->getDefinition();
1158   return new (C) ObjCCategoryImplDecl(DC, Id, ClassInterface,
1159                                       nameLoc, atStartLoc, CategoryNameLoc);
1160 }
1161 
1162 ObjCCategoryImplDecl *ObjCCategoryImplDecl::CreateDeserialized(ASTContext &C,
1163                                                                unsigned ID) {
1164   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCCategoryImplDecl));
1165   return new (Mem) ObjCCategoryImplDecl(0, 0, 0, SourceLocation(),
1166                                         SourceLocation(), SourceLocation());
1167 }
1168 
1169 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
1170   // The class interface might be NULL if we are working with invalid code.
1171   if (const ObjCInterfaceDecl *ID = getClassInterface())
1172     return ID->FindCategoryDeclaration(getIdentifier());
1173   return 0;
1174 }
1175 
1176 
1177 void ObjCImplDecl::anchor() { }
1178 
1179 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
1180   // FIXME: The context should be correct before we get here.
1181   property->setLexicalDeclContext(this);
1182   addDecl(property);
1183 }
1184 
1185 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
1186   ASTContext &Ctx = getASTContext();
1187 
1188   if (ObjCImplementationDecl *ImplD
1189         = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
1190     if (IFace)
1191       Ctx.setObjCImplementation(IFace, ImplD);
1192 
1193   } else if (ObjCCategoryImplDecl *ImplD =
1194              dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
1195     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
1196       Ctx.setObjCImplementation(CD, ImplD);
1197   }
1198 
1199   ClassInterface = IFace;
1200 }
1201 
1202 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
1203 /// properties implemented in this category \@implementation block and returns
1204 /// the implemented property that uses it.
1205 ///
1206 ObjCPropertyImplDecl *ObjCImplDecl::
1207 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
1208   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
1209     ObjCPropertyImplDecl *PID = *i;
1210     if (PID->getPropertyIvarDecl() &&
1211         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
1212       return PID;
1213   }
1214   return 0;
1215 }
1216 
1217 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
1218 /// added to the list of those properties \@synthesized/\@dynamic in this
1219 /// category \@implementation block.
1220 ///
1221 ObjCPropertyImplDecl *ObjCImplDecl::
1222 FindPropertyImplDecl(IdentifierInfo *Id) const {
1223   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
1224     ObjCPropertyImplDecl *PID = *i;
1225     if (PID->getPropertyDecl()->getIdentifier() == Id)
1226       return PID;
1227   }
1228   return 0;
1229 }
1230 
1231 raw_ostream &clang::operator<<(raw_ostream &OS,
1232                                const ObjCCategoryImplDecl &CID) {
1233   OS << CID.getName();
1234   return OS;
1235 }
1236 
1237 //===----------------------------------------------------------------------===//
1238 // ObjCImplementationDecl
1239 //===----------------------------------------------------------------------===//
1240 
1241 void ObjCImplementationDecl::anchor() { }
1242 
1243 ObjCImplementationDecl *
1244 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
1245                                ObjCInterfaceDecl *ClassInterface,
1246                                ObjCInterfaceDecl *SuperDecl,
1247                                SourceLocation nameLoc,
1248                                SourceLocation atStartLoc,
1249                                SourceLocation IvarLBraceLoc,
1250                                SourceLocation IvarRBraceLoc) {
1251   if (ClassInterface && ClassInterface->hasDefinition())
1252     ClassInterface = ClassInterface->getDefinition();
1253   return new (C) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
1254                                         nameLoc, atStartLoc,
1255                                         IvarLBraceLoc, IvarRBraceLoc);
1256 }
1257 
1258 ObjCImplementationDecl *
1259 ObjCImplementationDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1260   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCImplementationDecl));
1261   return new (Mem) ObjCImplementationDecl(0, 0, 0, SourceLocation(),
1262                                           SourceLocation());
1263 }
1264 
1265 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
1266                                              CXXCtorInitializer ** initializers,
1267                                                  unsigned numInitializers) {
1268   if (numInitializers > 0) {
1269     NumIvarInitializers = numInitializers;
1270     CXXCtorInitializer **ivarInitializers =
1271     new (C) CXXCtorInitializer*[NumIvarInitializers];
1272     memcpy(ivarInitializers, initializers,
1273            numInitializers * sizeof(CXXCtorInitializer*));
1274     IvarInitializers = ivarInitializers;
1275   }
1276 }
1277 
1278 raw_ostream &clang::operator<<(raw_ostream &OS,
1279                                const ObjCImplementationDecl &ID) {
1280   OS << ID.getName();
1281   return OS;
1282 }
1283 
1284 //===----------------------------------------------------------------------===//
1285 // ObjCCompatibleAliasDecl
1286 //===----------------------------------------------------------------------===//
1287 
1288 void ObjCCompatibleAliasDecl::anchor() { }
1289 
1290 ObjCCompatibleAliasDecl *
1291 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
1292                                 SourceLocation L,
1293                                 IdentifierInfo *Id,
1294                                 ObjCInterfaceDecl* AliasedClass) {
1295   return new (C) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
1296 }
1297 
1298 ObjCCompatibleAliasDecl *
1299 ObjCCompatibleAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1300   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCCompatibleAliasDecl));
1301   return new (Mem) ObjCCompatibleAliasDecl(0, SourceLocation(), 0, 0);
1302 }
1303 
1304 //===----------------------------------------------------------------------===//
1305 // ObjCPropertyDecl
1306 //===----------------------------------------------------------------------===//
1307 
1308 void ObjCPropertyDecl::anchor() { }
1309 
1310 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
1311                                            SourceLocation L,
1312                                            IdentifierInfo *Id,
1313                                            SourceLocation AtLoc,
1314                                            SourceLocation LParenLoc,
1315                                            TypeSourceInfo *T,
1316                                            PropertyControl propControl) {
1317   return new (C) ObjCPropertyDecl(DC, L, Id, AtLoc, LParenLoc, T);
1318 }
1319 
1320 ObjCPropertyDecl *ObjCPropertyDecl::CreateDeserialized(ASTContext &C,
1321                                                        unsigned ID) {
1322   void * Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCPropertyDecl));
1323   return new (Mem) ObjCPropertyDecl(0, SourceLocation(), 0, SourceLocation(),
1324                                     SourceLocation(),
1325                                     0);
1326 }
1327 
1328 //===----------------------------------------------------------------------===//
1329 // ObjCPropertyImplDecl
1330 //===----------------------------------------------------------------------===//
1331 
1332 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
1333                                                    DeclContext *DC,
1334                                                    SourceLocation atLoc,
1335                                                    SourceLocation L,
1336                                                    ObjCPropertyDecl *property,
1337                                                    Kind PK,
1338                                                    ObjCIvarDecl *ivar,
1339                                                    SourceLocation ivarLoc) {
1340   return new (C) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
1341                                       ivarLoc);
1342 }
1343 
1344 ObjCPropertyImplDecl *ObjCPropertyImplDecl::CreateDeserialized(ASTContext &C,
1345                                                                unsigned ID) {
1346   void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ObjCPropertyImplDecl));
1347   return new (Mem) ObjCPropertyImplDecl(0, SourceLocation(), SourceLocation(),
1348                                         0, Dynamic, 0, SourceLocation());
1349 }
1350 
1351 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
1352   SourceLocation EndLoc = getLocation();
1353   if (IvarLoc.isValid())
1354     EndLoc = IvarLoc;
1355 
1356   return SourceRange(AtLoc, EndLoc);
1357 }
1358