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