]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/AST/DeclObjC.cpp
Copy head to stable/9 as part of 9.0-RELEASE release cycle.
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / AST / DeclObjC.cpp
1 //===--- DeclObjC.cpp - ObjC Declaration AST Node Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Objective-C related Decl classes.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Stmt.h"
17 #include "llvm/ADT/STLExtras.h"
18 using namespace clang;
19
20 //===----------------------------------------------------------------------===//
21 // ObjCListBase
22 //===----------------------------------------------------------------------===//
23
24 void ObjCListBase::set(void *const* InList, unsigned Elts, ASTContext &Ctx) {
25   List = 0;
26   if (Elts == 0) return;  // Setting to an empty list is a noop.
27
28
29   List = new (Ctx) void*[Elts];
30   NumElts = Elts;
31   memcpy(List, InList, sizeof(void*)*Elts);
32 }
33
34 void ObjCProtocolList::set(ObjCProtocolDecl* const* InList, unsigned Elts, 
35                            const SourceLocation *Locs, ASTContext &Ctx) {
36   if (Elts == 0)
37     return;
38
39   Locations = new (Ctx) SourceLocation[Elts];
40   memcpy(Locations, Locs, sizeof(SourceLocation) * Elts);
41   set(InList, Elts, Ctx);
42 }
43
44 //===----------------------------------------------------------------------===//
45 // ObjCInterfaceDecl
46 //===----------------------------------------------------------------------===//
47
48 /// getIvarDecl - This method looks up an ivar in this ContextDecl.
49 ///
50 ObjCIvarDecl *
51 ObjCContainerDecl::getIvarDecl(IdentifierInfo *Id) const {
52   lookup_const_iterator Ivar, IvarEnd;
53   for (llvm::tie(Ivar, IvarEnd) = lookup(Id); Ivar != IvarEnd; ++Ivar) {
54     if (ObjCIvarDecl *ivar = dyn_cast<ObjCIvarDecl>(*Ivar))
55       return ivar;
56   }
57   return 0;
58 }
59
60 // Get the local instance/class method declared in this interface.
61 ObjCMethodDecl *
62 ObjCContainerDecl::getMethod(Selector Sel, bool isInstance) const {
63   // Since instance & class methods can have the same name, the loop below
64   // ensures we get the correct method.
65   //
66   // @interface Whatever
67   // - (int) class_method;
68   // + (float) class_method;
69   // @end
70   //
71   lookup_const_iterator Meth, MethEnd;
72   for (llvm::tie(Meth, MethEnd) = lookup(Sel); Meth != MethEnd; ++Meth) {
73     ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(*Meth);
74     if (MD && MD->isInstanceMethod() == isInstance)
75       return MD;
76   }
77   return 0;
78 }
79
80 ObjCPropertyDecl *
81 ObjCPropertyDecl::findPropertyDecl(const DeclContext *DC,
82                                    IdentifierInfo *propertyID) {
83
84   DeclContext::lookup_const_iterator I, E;
85   llvm::tie(I, E) = DC->lookup(propertyID);
86   for ( ; I != E; ++I)
87     if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(*I))
88       return PD;
89
90   return 0;
91 }
92
93 /// FindPropertyDeclaration - Finds declaration of the property given its name
94 /// in 'PropertyId' and returns it. It returns 0, if not found.
95 ObjCPropertyDecl *
96 ObjCContainerDecl::FindPropertyDeclaration(IdentifierInfo *PropertyId) const {
97
98   if (ObjCPropertyDecl *PD =
99         ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
100     return PD;
101
102   switch (getKind()) {
103     default:
104       break;
105     case Decl::ObjCProtocol: {
106       const ObjCProtocolDecl *PID = cast<ObjCProtocolDecl>(this);
107       for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
108            E = PID->protocol_end(); I != E; ++I)
109         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
110           return P;
111       break;
112     }
113     case Decl::ObjCInterface: {
114       const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(this);
115       // Look through categories.
116       for (ObjCCategoryDecl *Cat = OID->getCategoryList();
117            Cat; Cat = Cat->getNextClassCategory())
118         if (!Cat->IsClassExtension())
119           if (ObjCPropertyDecl *P = Cat->FindPropertyDeclaration(PropertyId))
120             return P;
121
122       // Look through protocols.
123       for (ObjCInterfaceDecl::all_protocol_iterator
124             I = OID->all_referenced_protocol_begin(),
125             E = OID->all_referenced_protocol_end(); I != E; ++I)
126         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
127           return P;
128
129       // Finally, check the super class.
130       if (const ObjCInterfaceDecl *superClass = OID->getSuperClass())
131         return superClass->FindPropertyDeclaration(PropertyId);
132       break;
133     }
134     case Decl::ObjCCategory: {
135       const ObjCCategoryDecl *OCD = cast<ObjCCategoryDecl>(this);
136       // Look through protocols.
137       if (!OCD->IsClassExtension())
138         for (ObjCCategoryDecl::protocol_iterator
139               I = OCD->protocol_begin(), E = OCD->protocol_end(); I != E; ++I)
140         if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
141           return P;
142
143       break;
144     }
145   }
146   return 0;
147 }
148
149 /// FindPropertyVisibleInPrimaryClass - Finds declaration of the property
150 /// with name 'PropertyId' in the primary class; including those in protocols
151 /// (direct or indirect) used by the primary class.
152 ///
153 ObjCPropertyDecl *
154 ObjCInterfaceDecl::FindPropertyVisibleInPrimaryClass(
155                                             IdentifierInfo *PropertyId) const {
156   if (ExternallyCompleted)
157     LoadExternalDefinition();
158
159   if (ObjCPropertyDecl *PD =
160       ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(this), PropertyId))
161     return PD;
162
163   // Look through protocols.
164   for (ObjCInterfaceDecl::all_protocol_iterator
165         I = all_referenced_protocol_begin(),
166         E = all_referenced_protocol_end(); I != E; ++I)
167     if (ObjCPropertyDecl *P = (*I)->FindPropertyDeclaration(PropertyId))
168       return P;
169
170   return 0;
171 }
172
173 void ObjCInterfaceDecl::mergeClassExtensionProtocolList(
174                               ObjCProtocolDecl *const* ExtList, unsigned ExtNum,
175                               ASTContext &C)
176 {
177   if (ExternallyCompleted)
178     LoadExternalDefinition();
179
180   if (AllReferencedProtocols.empty() && ReferencedProtocols.empty()) {
181     AllReferencedProtocols.set(ExtList, ExtNum, C);
182     return;
183   }
184   
185   // Check for duplicate protocol in class's protocol list.
186   // This is O(n*m). But it is extremely rare and number of protocols in
187   // class or its extension are very few.
188   llvm::SmallVector<ObjCProtocolDecl*, 8> ProtocolRefs;
189   for (unsigned i = 0; i < ExtNum; i++) {
190     bool protocolExists = false;
191     ObjCProtocolDecl *ProtoInExtension = ExtList[i];
192     for (all_protocol_iterator
193           p = all_referenced_protocol_begin(),
194           e = all_referenced_protocol_end(); p != e; ++p) {
195       ObjCProtocolDecl *Proto = (*p);
196       if (C.ProtocolCompatibleWithProtocol(ProtoInExtension, Proto)) {
197         protocolExists = true;
198         break;
199       }      
200     }
201     // Do we want to warn on a protocol in extension class which
202     // already exist in the class? Probably not.
203     if (!protocolExists)
204       ProtocolRefs.push_back(ProtoInExtension);
205   }
206
207   if (ProtocolRefs.empty())
208     return;
209
210   // Merge ProtocolRefs into class's protocol list;
211   for (all_protocol_iterator p = all_referenced_protocol_begin(), 
212         e = all_referenced_protocol_end(); p != e; ++p) {
213     ProtocolRefs.push_back(*p);
214   }
215
216   AllReferencedProtocols.set(ProtocolRefs.data(), ProtocolRefs.size(), C);
217 }
218
219 /// getFirstClassExtension - Find first class extension of the given class.
220 ObjCCategoryDecl* ObjCInterfaceDecl::getFirstClassExtension() const {
221   for (ObjCCategoryDecl *CDecl = getCategoryList(); CDecl;
222        CDecl = CDecl->getNextClassCategory())
223     if (CDecl->IsClassExtension())
224       return CDecl;
225   return 0;
226 }
227
228 /// getNextClassCategory - Find next class extension in list of categories.
229 const ObjCCategoryDecl* ObjCCategoryDecl::getNextClassExtension() const {
230   for (const ObjCCategoryDecl *CDecl = getNextClassCategory(); CDecl; 
231         CDecl = CDecl->getNextClassCategory())
232     if (CDecl->IsClassExtension())
233       return CDecl;
234   return 0;
235 }
236
237 ObjCIvarDecl *ObjCInterfaceDecl::lookupInstanceVariable(IdentifierInfo *ID,
238                                               ObjCInterfaceDecl *&clsDeclared) {
239   ObjCInterfaceDecl* ClassDecl = this;
240   while (ClassDecl != NULL) {
241     if (ObjCIvarDecl *I = ClassDecl->getIvarDecl(ID)) {
242       clsDeclared = ClassDecl;
243       return I;
244     }
245     for (const ObjCCategoryDecl *CDecl = ClassDecl->getFirstClassExtension();
246          CDecl; CDecl = CDecl->getNextClassExtension()) {
247       if (ObjCIvarDecl *I = CDecl->getIvarDecl(ID)) {
248         clsDeclared = ClassDecl;
249         return I;
250       }
251     }
252       
253     ClassDecl = ClassDecl->getSuperClass();
254   }
255   return NULL;
256 }
257
258 /// lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super
259 /// class whose name is passed as argument. If it is not one of the super classes
260 /// the it returns NULL.
261 ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
262                                         const IdentifierInfo*ICName) {
263   ObjCInterfaceDecl* ClassDecl = this;
264   while (ClassDecl != NULL) {
265     if (ClassDecl->getIdentifier() == ICName)
266       return ClassDecl;
267     ClassDecl = ClassDecl->getSuperClass();
268   }
269   return NULL;
270 }
271
272 /// lookupMethod - This method returns an instance/class method by looking in
273 /// the class, its categories, and its super classes (using a linear search).
274 ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
275                                                 bool isInstance) const {
276   const ObjCInterfaceDecl* ClassDecl = this;
277   ObjCMethodDecl *MethodDecl = 0;
278
279   if (ExternallyCompleted)
280     LoadExternalDefinition();
281
282   while (ClassDecl != NULL) {
283     if ((MethodDecl = ClassDecl->getMethod(Sel, isInstance)))
284       return MethodDecl;
285
286     // Didn't find one yet - look through protocols.
287     const ObjCList<ObjCProtocolDecl> &Protocols =
288       ClassDecl->getReferencedProtocols();
289     for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
290          E = Protocols.end(); I != E; ++I)
291       if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
292         return MethodDecl;
293
294     // Didn't find one yet - now look through categories.
295     ObjCCategoryDecl *CatDecl = ClassDecl->getCategoryList();
296     while (CatDecl) {
297       if ((MethodDecl = CatDecl->getMethod(Sel, isInstance)))
298         return MethodDecl;
299
300       // Didn't find one yet - look through protocols.
301       const ObjCList<ObjCProtocolDecl> &Protocols =
302         CatDecl->getReferencedProtocols();
303       for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
304            E = Protocols.end(); I != E; ++I)
305         if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
306           return MethodDecl;
307       CatDecl = CatDecl->getNextClassCategory();
308     }
309     ClassDecl = ClassDecl->getSuperClass();
310   }
311   return NULL;
312 }
313
314 ObjCMethodDecl *ObjCInterfaceDecl::lookupPrivateMethod(
315                                    const Selector &Sel,
316                                    bool Instance) {
317   ObjCMethodDecl *Method = 0;
318   if (ObjCImplementationDecl *ImpDecl = getImplementation())
319     Method = Instance ? ImpDecl->getInstanceMethod(Sel) 
320                       : ImpDecl->getClassMethod(Sel);
321   
322   if (!Method && getSuperClass())
323     return getSuperClass()->lookupPrivateMethod(Sel, Instance);
324   return Method;
325 }
326
327 //===----------------------------------------------------------------------===//
328 // ObjCMethodDecl
329 //===----------------------------------------------------------------------===//
330
331 ObjCMethodDecl *ObjCMethodDecl::Create(ASTContext &C,
332                                        SourceLocation beginLoc,
333                                        SourceLocation endLoc,
334                                        Selector SelInfo, QualType T,
335                                        TypeSourceInfo *ResultTInfo,
336                                        DeclContext *contextDecl,
337                                        bool isInstance,
338                                        bool isVariadic,
339                                        bool isSynthesized,
340                                        bool isDefined,
341                                        ImplementationControl impControl,
342                                        bool HasRelatedResultType,
343                                        unsigned numSelectorArgs) {
344   return new (C) ObjCMethodDecl(beginLoc, endLoc,
345                                 SelInfo, T, ResultTInfo, contextDecl,
346                                 isInstance,
347                                 isVariadic, isSynthesized, isDefined,
348                                 impControl,
349                                 HasRelatedResultType,
350                                 numSelectorArgs);
351 }
352
353 /// \brief A definition will return its interface declaration.
354 /// An interface declaration will return its definition.
355 /// Otherwise it will return itself.
356 ObjCMethodDecl *ObjCMethodDecl::getNextRedeclaration() {
357   ASTContext &Ctx = getASTContext();
358   ObjCMethodDecl *Redecl = 0;
359   Decl *CtxD = cast<Decl>(getDeclContext());
360
361   if (ObjCInterfaceDecl *IFD = dyn_cast<ObjCInterfaceDecl>(CtxD)) {
362     if (ObjCImplementationDecl *ImplD = Ctx.getObjCImplementation(IFD))
363       Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
364
365   } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CtxD)) {
366     if (ObjCCategoryImplDecl *ImplD = Ctx.getObjCImplementation(CD))
367       Redecl = ImplD->getMethod(getSelector(), isInstanceMethod());
368
369   } else if (ObjCImplementationDecl *ImplD =
370                dyn_cast<ObjCImplementationDecl>(CtxD)) {
371     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
372       Redecl = IFD->getMethod(getSelector(), isInstanceMethod());
373
374   } else if (ObjCCategoryImplDecl *CImplD =
375                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
376     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
377       Redecl = CatD->getMethod(getSelector(), isInstanceMethod());
378   }
379
380   return Redecl ? Redecl : this;
381 }
382
383 ObjCMethodDecl *ObjCMethodDecl::getCanonicalDecl() {
384   Decl *CtxD = cast<Decl>(getDeclContext());
385
386   if (ObjCImplementationDecl *ImplD = dyn_cast<ObjCImplementationDecl>(CtxD)) {
387     if (ObjCInterfaceDecl *IFD = ImplD->getClassInterface())
388       if (ObjCMethodDecl *MD = IFD->getMethod(getSelector(),
389                                               isInstanceMethod()))
390         return MD;
391
392   } else if (ObjCCategoryImplDecl *CImplD =
393                dyn_cast<ObjCCategoryImplDecl>(CtxD)) {
394     if (ObjCCategoryDecl *CatD = CImplD->getCategoryDecl())
395       if (ObjCMethodDecl *MD = CatD->getMethod(getSelector(),
396                                                isInstanceMethod()))
397         return MD;
398   }
399
400   return this;
401 }
402
403 ObjCMethodFamily ObjCMethodDecl::getMethodFamily() const {
404   ObjCMethodFamily family = static_cast<ObjCMethodFamily>(Family);
405   if (family != static_cast<unsigned>(InvalidObjCMethodFamily))
406     return family;
407
408   // Check for an explicit attribute.
409   if (const ObjCMethodFamilyAttr *attr = getAttr<ObjCMethodFamilyAttr>()) {
410     // The unfortunate necessity of mapping between enums here is due
411     // to the attributes framework.
412     switch (attr->getFamily()) {
413     case ObjCMethodFamilyAttr::OMF_None: family = OMF_None; break;
414     case ObjCMethodFamilyAttr::OMF_alloc: family = OMF_alloc; break;
415     case ObjCMethodFamilyAttr::OMF_copy: family = OMF_copy; break;
416     case ObjCMethodFamilyAttr::OMF_init: family = OMF_init; break;
417     case ObjCMethodFamilyAttr::OMF_mutableCopy: family = OMF_mutableCopy; break;
418     case ObjCMethodFamilyAttr::OMF_new: family = OMF_new; break;
419     }
420     Family = static_cast<unsigned>(family);
421     return family;
422   }
423
424   family = getSelector().getMethodFamily();
425   switch (family) {
426   case OMF_None: break;
427
428   // init only has a conventional meaning for an instance method, and
429   // it has to return an object.
430   case OMF_init:
431     if (!isInstanceMethod() || !getResultType()->isObjCObjectPointerType())
432       family = OMF_None;
433     break;
434
435   // alloc/copy/new have a conventional meaning for both class and
436   // instance methods, but they require an object return.
437   case OMF_alloc:
438   case OMF_copy:
439   case OMF_mutableCopy:
440   case OMF_new:
441     if (!getResultType()->isObjCObjectPointerType())
442       family = OMF_None;
443     break;
444
445   // These selectors have a conventional meaning only for instance methods.
446   case OMF_dealloc:
447   case OMF_retain:
448   case OMF_release:
449   case OMF_autorelease:
450   case OMF_retainCount:
451   case OMF_self:
452     if (!isInstanceMethod())
453       family = OMF_None;
454     break;
455       
456   case OMF_performSelector:
457     if (!isInstanceMethod() ||
458         !getResultType()->isObjCIdType())
459       family = OMF_None;
460     else {
461       unsigned noParams = param_size();
462       if (noParams < 1 || noParams > 3)
463         family = OMF_None;
464       else {
465         ObjCMethodDecl::arg_type_iterator it = arg_type_begin();
466         QualType ArgT = (*it);
467         if (!ArgT->isObjCSelType()) {
468           family = OMF_None;
469           break;
470         }
471         while (--noParams) {
472           it++;
473           ArgT = (*it);
474           if (!ArgT->isObjCIdType()) {
475             family = OMF_None;
476             break;
477           }
478         }
479       }
480     }
481     break;
482       
483   }
484
485   // Cache the result.
486   Family = static_cast<unsigned>(family);
487   return family;
488 }
489
490 void ObjCMethodDecl::createImplicitParams(ASTContext &Context,
491                                           const ObjCInterfaceDecl *OID) {
492   QualType selfTy;
493   if (isInstanceMethod()) {
494     // There may be no interface context due to error in declaration
495     // of the interface (which has been reported). Recover gracefully.
496     if (OID) {
497       selfTy = Context.getObjCInterfaceType(OID);
498       selfTy = Context.getObjCObjectPointerType(selfTy);
499     } else {
500       selfTy = Context.getObjCIdType();
501     }
502   } else // we have a factory method.
503     selfTy = Context.getObjCClassType();
504
505   bool selfIsPseudoStrong = false;
506   bool selfIsConsumed = false;
507   if (isInstanceMethod() && Context.getLangOptions().ObjCAutoRefCount) {
508     selfIsConsumed = hasAttr<NSConsumesSelfAttr>();
509
510     // 'self' is always __strong.  It's actually pseudo-strong except
511     // in init methods, though.
512     Qualifiers qs;
513     qs.setObjCLifetime(Qualifiers::OCL_Strong);
514     selfTy = Context.getQualifiedType(selfTy, qs);
515
516     // In addition, 'self' is const unless this is an init method.
517     if (getMethodFamily() != OMF_init) {
518       selfTy = selfTy.withConst();
519       selfIsPseudoStrong = true;
520     }
521   }
522
523   ImplicitParamDecl *self
524     = ImplicitParamDecl::Create(Context, this, SourceLocation(),
525                                 &Context.Idents.get("self"), selfTy);
526   setSelfDecl(self);
527
528   if (selfIsConsumed)
529     self->addAttr(new (Context) NSConsumedAttr(SourceLocation(), Context));
530
531   if (selfIsPseudoStrong)
532     self->setARCPseudoStrong(true);
533
534   setCmdDecl(ImplicitParamDecl::Create(Context, this, SourceLocation(),
535                                        &Context.Idents.get("_cmd"),
536                                        Context.getObjCSelType()));
537 }
538
539 ObjCInterfaceDecl *ObjCMethodDecl::getClassInterface() {
540   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(getDeclContext()))
541     return ID;
542   if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(getDeclContext()))
543     return CD->getClassInterface();
544   if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(getDeclContext()))
545     return IMD->getClassInterface();
546
547   assert(!isa<ObjCProtocolDecl>(getDeclContext()) && "It's a protocol method");
548   assert(false && "unknown method context");
549   return 0;
550 }
551
552 //===----------------------------------------------------------------------===//
553 // ObjCInterfaceDecl
554 //===----------------------------------------------------------------------===//
555
556 ObjCInterfaceDecl *ObjCInterfaceDecl::Create(ASTContext &C,
557                                              DeclContext *DC,
558                                              SourceLocation atLoc,
559                                              IdentifierInfo *Id,
560                                              SourceLocation ClassLoc,
561                                              bool ForwardDecl, bool isInternal){
562   return new (C) ObjCInterfaceDecl(DC, atLoc, Id, ClassLoc, ForwardDecl,
563                                      isInternal);
564 }
565
566 ObjCInterfaceDecl::
567 ObjCInterfaceDecl(DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id,
568                   SourceLocation CLoc, bool FD, bool isInternal)
569   : ObjCContainerDecl(ObjCInterface, DC, atLoc, Id),
570     TypeForDecl(0), SuperClass(0),
571     CategoryList(0), IvarList(0), 
572     ForwardDecl(FD), InternalInterface(isInternal), ExternallyCompleted(false),
573     ClassLoc(CLoc) {
574 }
575
576 void ObjCInterfaceDecl::LoadExternalDefinition() const {
577   assert(ExternallyCompleted && "Class is not externally completed");
578   ExternallyCompleted = false;
579   getASTContext().getExternalSource()->CompleteType(
580                                         const_cast<ObjCInterfaceDecl *>(this));
581 }
582
583 void ObjCInterfaceDecl::setExternallyCompleted() {
584   assert(getASTContext().getExternalSource() && 
585          "Class can't be externally completed without an external source");
586   assert(!ForwardDecl && 
587          "Forward declarations can't be externally completed");
588   ExternallyCompleted = true;
589 }
590
591 ObjCImplementationDecl *ObjCInterfaceDecl::getImplementation() const {
592   if (ExternallyCompleted)
593     LoadExternalDefinition();
594
595   return getASTContext().getObjCImplementation(
596                                           const_cast<ObjCInterfaceDecl*>(this));
597 }
598
599 void ObjCInterfaceDecl::setImplementation(ObjCImplementationDecl *ImplD) {
600   getASTContext().setObjCImplementation(this, ImplD);
601 }
602
603 /// all_declared_ivar_begin - return first ivar declared in this class,
604 /// its extensions and its implementation. Lazily build the list on first
605 /// access.
606 ObjCIvarDecl *ObjCInterfaceDecl::all_declared_ivar_begin() {
607   if (IvarList)
608     return IvarList;
609   
610   ObjCIvarDecl *curIvar = 0;
611   if (!ivar_empty()) {
612     ObjCInterfaceDecl::ivar_iterator I = ivar_begin(), E = ivar_end();
613     IvarList = (*I); ++I;
614     for (curIvar = IvarList; I != E; curIvar = *I, ++I)
615       curIvar->setNextIvar(*I);
616   }
617   
618   for (const ObjCCategoryDecl *CDecl = getFirstClassExtension(); CDecl;
619        CDecl = CDecl->getNextClassExtension()) {
620     if (!CDecl->ivar_empty()) {
621       ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
622                                           E = CDecl->ivar_end();
623       if (!IvarList) {
624         IvarList = (*I); ++I;
625         curIvar = IvarList;
626       }
627       for ( ;I != E; curIvar = *I, ++I)
628         curIvar->setNextIvar(*I);
629     }
630   }
631   
632   if (ObjCImplementationDecl *ImplDecl = getImplementation()) {
633     if (!ImplDecl->ivar_empty()) {
634       ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
635                                             E = ImplDecl->ivar_end();
636       if (!IvarList) {
637         IvarList = (*I); ++I;
638         curIvar = IvarList;
639       }
640       for ( ;I != E; curIvar = *I, ++I)
641         curIvar->setNextIvar(*I);
642     }
643   }
644   return IvarList;
645 }
646
647 /// FindCategoryDeclaration - Finds category declaration in the list of
648 /// categories for this class and returns it. Name of the category is passed
649 /// in 'CategoryId'. If category not found, return 0;
650 ///
651 ObjCCategoryDecl *
652 ObjCInterfaceDecl::FindCategoryDeclaration(IdentifierInfo *CategoryId) const {
653   if (ExternallyCompleted)
654     LoadExternalDefinition();
655
656   for (ObjCCategoryDecl *Category = getCategoryList();
657        Category; Category = Category->getNextClassCategory())
658     if (Category->getIdentifier() == CategoryId)
659       return Category;
660   return 0;
661 }
662
663 ObjCMethodDecl *
664 ObjCInterfaceDecl::getCategoryInstanceMethod(Selector Sel) const {
665   for (ObjCCategoryDecl *Category = getCategoryList();
666        Category; Category = Category->getNextClassCategory())
667     if (ObjCCategoryImplDecl *Impl = Category->getImplementation())
668       if (ObjCMethodDecl *MD = Impl->getInstanceMethod(Sel))
669         return MD;
670   return 0;
671 }
672
673 ObjCMethodDecl *ObjCInterfaceDecl::getCategoryClassMethod(Selector Sel) const {
674   for (ObjCCategoryDecl *Category = getCategoryList();
675        Category; Category = Category->getNextClassCategory())
676     if (ObjCCategoryImplDecl *Impl = Category->getImplementation())
677       if (ObjCMethodDecl *MD = Impl->getClassMethod(Sel))
678         return MD;
679   return 0;
680 }
681
682 /// ClassImplementsProtocol - Checks that 'lProto' protocol
683 /// has been implemented in IDecl class, its super class or categories (if
684 /// lookupCategory is true).
685 bool ObjCInterfaceDecl::ClassImplementsProtocol(ObjCProtocolDecl *lProto,
686                                     bool lookupCategory,
687                                     bool RHSIsQualifiedID) {
688   ObjCInterfaceDecl *IDecl = this;
689   // 1st, look up the class.
690   const ObjCList<ObjCProtocolDecl> &Protocols =
691   IDecl->getReferencedProtocols();
692
693   for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(),
694        E = Protocols.end(); PI != E; ++PI) {
695     if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
696       return true;
697     // This is dubious and is added to be compatible with gcc.  In gcc, it is
698     // also allowed assigning a protocol-qualified 'id' type to a LHS object
699     // when protocol in qualified LHS is in list of protocols in the rhs 'id'
700     // object. This IMO, should be a bug.
701     // FIXME: Treat this as an extension, and flag this as an error when GCC
702     // extensions are not enabled.
703     if (RHSIsQualifiedID &&
704         getASTContext().ProtocolCompatibleWithProtocol(*PI, lProto))
705       return true;
706   }
707
708   // 2nd, look up the category.
709   if (lookupCategory)
710     for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl;
711          CDecl = CDecl->getNextClassCategory()) {
712       for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(),
713            E = CDecl->protocol_end(); PI != E; ++PI)
714         if (getASTContext().ProtocolCompatibleWithProtocol(lProto, *PI))
715           return true;
716     }
717
718   // 3rd, look up the super class(s)
719   if (IDecl->getSuperClass())
720     return
721   IDecl->getSuperClass()->ClassImplementsProtocol(lProto, lookupCategory,
722                                                   RHSIsQualifiedID);
723
724   return false;
725 }
726
727 //===----------------------------------------------------------------------===//
728 // ObjCIvarDecl
729 //===----------------------------------------------------------------------===//
730
731 ObjCIvarDecl *ObjCIvarDecl::Create(ASTContext &C, ObjCContainerDecl *DC,
732                                    SourceLocation StartLoc,
733                                    SourceLocation IdLoc, IdentifierInfo *Id,
734                                    QualType T, TypeSourceInfo *TInfo,
735                                    AccessControl ac, Expr *BW,
736                                    bool synthesized) {
737   if (DC) {
738     // Ivar's can only appear in interfaces, implementations (via synthesized
739     // properties), and class extensions (via direct declaration, or synthesized
740     // properties).
741     //
742     // FIXME: This should really be asserting this:
743     //   (isa<ObjCCategoryDecl>(DC) &&
744     //    cast<ObjCCategoryDecl>(DC)->IsClassExtension()))
745     // but unfortunately we sometimes place ivars into non-class extension
746     // categories on error. This breaks an AST invariant, and should not be
747     // fixed.
748     assert((isa<ObjCInterfaceDecl>(DC) || isa<ObjCImplementationDecl>(DC) ||
749             isa<ObjCCategoryDecl>(DC)) &&
750            "Invalid ivar decl context!");
751     // Once a new ivar is created in any of class/class-extension/implementation
752     // decl contexts, the previously built IvarList must be rebuilt.
753     ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(DC);
754     if (!ID) {
755       if (ObjCImplementationDecl *IM = dyn_cast<ObjCImplementationDecl>(DC)) {
756         ID = IM->getClassInterface();
757         if (BW)
758           IM->setHasSynthBitfield(true);
759       }
760       else {
761         ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
762         ID = CD->getClassInterface();
763         if (BW)
764           CD->setHasSynthBitfield(true);
765       }
766     }
767     ID->setIvarList(0);
768   }
769
770   return new (C) ObjCIvarDecl(DC, StartLoc, IdLoc, Id, T, TInfo,
771                               ac, BW, synthesized);
772 }
773
774 const ObjCInterfaceDecl *ObjCIvarDecl::getContainingInterface() const {
775   const ObjCContainerDecl *DC = cast<ObjCContainerDecl>(getDeclContext());
776
777   switch (DC->getKind()) {
778   default:
779   case ObjCCategoryImpl:
780   case ObjCProtocol:
781     assert(0 && "invalid ivar container!");
782     return 0;
783
784     // Ivars can only appear in class extension categories.
785   case ObjCCategory: {
786     const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(DC);
787     assert(CD->IsClassExtension() && "invalid container for ivar!");
788     return CD->getClassInterface();
789   }
790
791   case ObjCImplementation:
792     return cast<ObjCImplementationDecl>(DC)->getClassInterface();
793
794   case ObjCInterface:
795     return cast<ObjCInterfaceDecl>(DC);
796   }
797 }
798
799 //===----------------------------------------------------------------------===//
800 // ObjCAtDefsFieldDecl
801 //===----------------------------------------------------------------------===//
802
803 ObjCAtDefsFieldDecl
804 *ObjCAtDefsFieldDecl::Create(ASTContext &C, DeclContext *DC,
805                              SourceLocation StartLoc,  SourceLocation IdLoc,
806                              IdentifierInfo *Id, QualType T, Expr *BW) {
807   return new (C) ObjCAtDefsFieldDecl(DC, StartLoc, IdLoc, Id, T, BW);
808 }
809
810 //===----------------------------------------------------------------------===//
811 // ObjCProtocolDecl
812 //===----------------------------------------------------------------------===//
813
814 ObjCProtocolDecl *ObjCProtocolDecl::Create(ASTContext &C, DeclContext *DC,
815                                            SourceLocation L,
816                                            IdentifierInfo *Id) {
817   return new (C) ObjCProtocolDecl(DC, L, Id);
818 }
819
820 ObjCProtocolDecl *ObjCProtocolDecl::lookupProtocolNamed(IdentifierInfo *Name) {
821   ObjCProtocolDecl *PDecl = this;
822
823   if (Name == getIdentifier())
824     return PDecl;
825
826   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
827     if ((PDecl = (*I)->lookupProtocolNamed(Name)))
828       return PDecl;
829
830   return NULL;
831 }
832
833 // lookupMethod - Lookup a instance/class method in the protocol and protocols
834 // it inherited.
835 ObjCMethodDecl *ObjCProtocolDecl::lookupMethod(Selector Sel,
836                                                bool isInstance) const {
837   ObjCMethodDecl *MethodDecl = NULL;
838
839   if ((MethodDecl = getMethod(Sel, isInstance)))
840     return MethodDecl;
841
842   for (protocol_iterator I = protocol_begin(), E = protocol_end(); I != E; ++I)
843     if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
844       return MethodDecl;
845   return NULL;
846 }
847
848 //===----------------------------------------------------------------------===//
849 // ObjCClassDecl
850 //===----------------------------------------------------------------------===//
851
852 ObjCClassDecl::ObjCClassDecl(DeclContext *DC, SourceLocation L,
853                              ObjCInterfaceDecl *const *Elts,
854                              const SourceLocation *Locs,
855                              unsigned nElts,
856                              ASTContext &C)
857   : Decl(ObjCClass, DC, L) {
858   setClassList(C, Elts, Locs, nElts);
859 }
860
861 void ObjCClassDecl::setClassList(ASTContext &C, ObjCInterfaceDecl*const*List,
862                                  const SourceLocation *Locs, unsigned Num) {
863   ForwardDecls = (ObjCClassRef*) C.Allocate(sizeof(ObjCClassRef)*Num,
864                                             llvm::alignOf<ObjCClassRef>());
865   for (unsigned i = 0; i < Num; ++i)
866     new (&ForwardDecls[i]) ObjCClassRef(List[i], Locs[i]);
867   
868   NumDecls = Num;
869 }
870
871 ObjCClassDecl *ObjCClassDecl::Create(ASTContext &C, DeclContext *DC,
872                                      SourceLocation L,
873                                      ObjCInterfaceDecl *const *Elts,
874                                      const SourceLocation *Locs,
875                                      unsigned nElts) {
876   return new (C) ObjCClassDecl(DC, L, Elts, Locs, nElts, C);
877 }
878
879 SourceRange ObjCClassDecl::getSourceRange() const {
880   // FIXME: We should include the semicolon
881   assert(NumDecls);
882   return SourceRange(getLocation(), ForwardDecls[NumDecls-1].getLocation());
883 }
884
885 //===----------------------------------------------------------------------===//
886 // ObjCForwardProtocolDecl
887 //===----------------------------------------------------------------------===//
888
889 ObjCForwardProtocolDecl::
890 ObjCForwardProtocolDecl(DeclContext *DC, SourceLocation L,
891                         ObjCProtocolDecl *const *Elts, unsigned nElts,
892                         const SourceLocation *Locs, ASTContext &C)
893 : Decl(ObjCForwardProtocol, DC, L) {
894   ReferencedProtocols.set(Elts, nElts, Locs, C);
895 }
896
897
898 ObjCForwardProtocolDecl *
899 ObjCForwardProtocolDecl::Create(ASTContext &C, DeclContext *DC,
900                                 SourceLocation L,
901                                 ObjCProtocolDecl *const *Elts,
902                                 unsigned NumElts,
903                                 const SourceLocation *Locs) {
904   return new (C) ObjCForwardProtocolDecl(DC, L, Elts, NumElts, Locs, C);
905 }
906
907 //===----------------------------------------------------------------------===//
908 // ObjCCategoryDecl
909 //===----------------------------------------------------------------------===//
910
911 ObjCCategoryDecl *ObjCCategoryDecl::Create(ASTContext &C, DeclContext *DC,
912                                            SourceLocation AtLoc, 
913                                            SourceLocation ClassNameLoc,
914                                            SourceLocation CategoryNameLoc,
915                                            IdentifierInfo *Id) {
916   return new (C) ObjCCategoryDecl(DC, AtLoc, ClassNameLoc, CategoryNameLoc, Id);
917 }
918
919 ObjCCategoryImplDecl *ObjCCategoryDecl::getImplementation() const {
920   return getASTContext().getObjCImplementation(
921                                            const_cast<ObjCCategoryDecl*>(this));
922 }
923
924 void ObjCCategoryDecl::setImplementation(ObjCCategoryImplDecl *ImplD) {
925   getASTContext().setObjCImplementation(this, ImplD);
926 }
927
928
929 //===----------------------------------------------------------------------===//
930 // ObjCCategoryImplDecl
931 //===----------------------------------------------------------------------===//
932
933 ObjCCategoryImplDecl *
934 ObjCCategoryImplDecl::Create(ASTContext &C, DeclContext *DC,
935                              SourceLocation L,IdentifierInfo *Id,
936                              ObjCInterfaceDecl *ClassInterface) {
937   return new (C) ObjCCategoryImplDecl(DC, L, Id, ClassInterface);
938 }
939
940 ObjCCategoryDecl *ObjCCategoryImplDecl::getCategoryDecl() const {
941   // The class interface might be NULL if we are working with invalid code.
942   if (const ObjCInterfaceDecl *ID = getClassInterface())
943     return ID->FindCategoryDeclaration(getIdentifier());
944   return 0;
945 }
946
947
948 void ObjCImplDecl::addPropertyImplementation(ObjCPropertyImplDecl *property) {
949   // FIXME: The context should be correct before we get here.
950   property->setLexicalDeclContext(this);
951   addDecl(property);
952 }
953
954 void ObjCImplDecl::setClassInterface(ObjCInterfaceDecl *IFace) {
955   ASTContext &Ctx = getASTContext();
956
957   if (ObjCImplementationDecl *ImplD
958         = dyn_cast_or_null<ObjCImplementationDecl>(this)) {
959     if (IFace)
960       Ctx.setObjCImplementation(IFace, ImplD);
961
962   } else if (ObjCCategoryImplDecl *ImplD =
963              dyn_cast_or_null<ObjCCategoryImplDecl>(this)) {
964     if (ObjCCategoryDecl *CD = IFace->FindCategoryDeclaration(getIdentifier()))
965       Ctx.setObjCImplementation(CD, ImplD);
966   }
967
968   ClassInterface = IFace;
969 }
970
971 /// FindPropertyImplIvarDecl - This method lookup the ivar in the list of
972 /// properties implemented in this category @implementation block and returns
973 /// the implemented property that uses it.
974 ///
975 ObjCPropertyImplDecl *ObjCImplDecl::
976 FindPropertyImplIvarDecl(IdentifierInfo *ivarId) const {
977   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
978     ObjCPropertyImplDecl *PID = *i;
979     if (PID->getPropertyIvarDecl() &&
980         PID->getPropertyIvarDecl()->getIdentifier() == ivarId)
981       return PID;
982   }
983   return 0;
984 }
985
986 /// FindPropertyImplDecl - This method looks up a previous ObjCPropertyImplDecl
987 /// added to the list of those properties @synthesized/@dynamic in this
988 /// category @implementation block.
989 ///
990 ObjCPropertyImplDecl *ObjCImplDecl::
991 FindPropertyImplDecl(IdentifierInfo *Id) const {
992   for (propimpl_iterator i = propimpl_begin(), e = propimpl_end(); i != e; ++i){
993     ObjCPropertyImplDecl *PID = *i;
994     if (PID->getPropertyDecl()->getIdentifier() == Id)
995       return PID;
996   }
997   return 0;
998 }
999
1000 llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
1001                                      const ObjCCategoryImplDecl *CID) {
1002   OS << CID->getName();
1003   return OS;
1004 }
1005
1006 //===----------------------------------------------------------------------===//
1007 // ObjCImplementationDecl
1008 //===----------------------------------------------------------------------===//
1009
1010 ObjCImplementationDecl *
1011 ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
1012                                SourceLocation L,
1013                                ObjCInterfaceDecl *ClassInterface,
1014                                ObjCInterfaceDecl *SuperDecl) {
1015   return new (C) ObjCImplementationDecl(DC, L, ClassInterface, SuperDecl);
1016 }
1017
1018 llvm::raw_ostream &clang::operator<<(llvm::raw_ostream &OS,
1019                                      const ObjCImplementationDecl *ID) {
1020   OS << ID->getName();
1021   return OS;
1022 }
1023
1024 //===----------------------------------------------------------------------===//
1025 // ObjCCompatibleAliasDecl
1026 //===----------------------------------------------------------------------===//
1027
1028 ObjCCompatibleAliasDecl *
1029 ObjCCompatibleAliasDecl::Create(ASTContext &C, DeclContext *DC,
1030                                 SourceLocation L,
1031                                 IdentifierInfo *Id,
1032                                 ObjCInterfaceDecl* AliasedClass) {
1033   return new (C) ObjCCompatibleAliasDecl(DC, L, Id, AliasedClass);
1034 }
1035
1036 //===----------------------------------------------------------------------===//
1037 // ObjCPropertyDecl
1038 //===----------------------------------------------------------------------===//
1039
1040 ObjCPropertyDecl *ObjCPropertyDecl::Create(ASTContext &C, DeclContext *DC,
1041                                            SourceLocation L,
1042                                            IdentifierInfo *Id,
1043                                            SourceLocation AtLoc,
1044                                            TypeSourceInfo *T,
1045                                            PropertyControl propControl) {
1046   return new (C) ObjCPropertyDecl(DC, L, Id, AtLoc, T);
1047 }
1048
1049 //===----------------------------------------------------------------------===//
1050 // ObjCPropertyImplDecl
1051 //===----------------------------------------------------------------------===//
1052
1053 ObjCPropertyImplDecl *ObjCPropertyImplDecl::Create(ASTContext &C,
1054                                                    DeclContext *DC,
1055                                                    SourceLocation atLoc,
1056                                                    SourceLocation L,
1057                                                    ObjCPropertyDecl *property,
1058                                                    Kind PK,
1059                                                    ObjCIvarDecl *ivar,
1060                                                    SourceLocation ivarLoc) {
1061   return new (C) ObjCPropertyImplDecl(DC, atLoc, L, property, PK, ivar,
1062                                       ivarLoc);
1063 }
1064
1065 SourceRange ObjCPropertyImplDecl::getSourceRange() const {
1066   SourceLocation EndLoc = getLocation();
1067   if (IvarLoc.isValid())
1068     EndLoc = IvarLoc;
1069
1070   return SourceRange(AtLoc, EndLoc);
1071 }