SemaDeclObjC.cpp revision 0701bbb228dfd87e1fe82a0a4b7b9facfecb43da
1//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
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 semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Parse/DeclSpec.h"
19
20using namespace clang;
21
22/// ObjCActOnStartOfMethodDef - This routine sets up parameters; invisible
23/// and user declared, in the method definition's AST.
24void Sema::ObjCActOnStartOfMethodDef(Scope *FnBodyScope, DeclTy *D) {
25  assert(getCurMethodDecl() == 0 && "Method parsing confused");
26  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>((Decl *)D);
27
28  // If we don't have a valid method decl, simply return.
29  if (!MDecl)
30    return;
31
32  // Allow the rest of sema to find private method decl implementations.
33  if (MDecl->isInstance())
34    AddInstanceMethodToGlobalPool(MDecl);
35  else
36    AddFactoryMethodToGlobalPool(MDecl);
37
38  // Allow all of Sema to see that we are entering a method definition.
39  PushDeclContext(FnBodyScope, MDecl);
40
41  // Create Decl objects for each parameter, entrring them in the scope for
42  // binding to their use.
43
44  // Insert the invisible arguments, self and _cmd!
45  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
46
47  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
48  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
49
50  // Introduce all of the other parameters into this scope.
51  for (unsigned i = 0, e = MDecl->getNumParams(); i != e; ++i) {
52    ParmVarDecl *PDecl = MDecl->getParamDecl(i);
53    IdentifierInfo *II = PDecl->getIdentifier();
54    if (II)
55      PushOnScopeChains(PDecl, FnBodyScope);
56  }
57}
58
59Sema::DeclTy *Sema::
60ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
61                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
62                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
63                         DeclTy * const *ProtoRefs, unsigned NumProtoRefs,
64                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
65  assert(ClassName && "Missing class identifier");
66
67  // Check for another declaration kind with the same name.
68  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
69  if (PrevDecl && PrevDecl->isTemplateParameter()) {
70    // Maybe we will complain about the shadowed template parameter.
71    DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
72    // Just pretend that we didn't see the previous declaration.
73    PrevDecl = 0;
74  }
75
76  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
77    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
78    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
79  }
80
81  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
82  if (IDecl) {
83    // Class already seen. Is it a forward declaration?
84    if (!IDecl->isForwardDecl()) {
85      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
86      Diag(IDecl->getLocation(), diag::note_previous_definition);
87
88      // Return the previous class interface.
89      // FIXME: don't leak the objects passed in!
90      return IDecl;
91    } else {
92      IDecl->setLocation(AtInterfaceLoc);
93      IDecl->setForwardDecl(false);
94    }
95  } else {
96    IDecl = ObjCInterfaceDecl::Create(Context, AtInterfaceLoc,
97                                      ClassName, ClassLoc);
98    if (AttrList)
99      ProcessDeclAttributeList(IDecl, AttrList);
100
101    ObjCInterfaceDecls[ClassName] = IDecl;
102    // Remember that this needs to be removed when the scope is popped.
103    TUScope->AddDecl(IDecl);
104  }
105
106  if (SuperName) {
107    ObjCInterfaceDecl* SuperClassEntry = 0;
108    // Check if a different kind of symbol declared in this scope.
109    PrevDecl = LookupDecl(SuperName, Decl::IDNS_Ordinary, TUScope);
110    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
111      Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
112      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
113    }
114    else {
115      // Check that super class is previously defined
116      SuperClassEntry = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
117
118      if (!SuperClassEntry)
119        Diag(SuperLoc, diag::err_undef_superclass)
120          << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
121      else if (SuperClassEntry->isForwardDecl())
122        Diag(SuperLoc, diag::err_undef_superclass)
123          << SuperClassEntry->getDeclName() << ClassName
124          << SourceRange(AtInterfaceLoc, ClassLoc);
125    }
126    IDecl->setSuperClass(SuperClassEntry);
127    IDecl->setSuperClassLoc(SuperLoc);
128    IDecl->setLocEnd(SuperLoc);
129  } else { // we have a root class.
130    IDecl->setLocEnd(ClassLoc);
131  }
132
133  /// Check then save referenced protocols.
134  if (NumProtoRefs) {
135    IDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
136    IDecl->setLocEnd(EndProtoLoc);
137  }
138
139  CheckObjCDeclScope(IDecl);
140  return IDecl;
141}
142
143/// ActOnCompatiblityAlias - this action is called after complete parsing of
144/// @compatibility_alias declaration. It sets up the alias relationships.
145Sema::DeclTy *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
146                                           IdentifierInfo *AliasName,
147                                           SourceLocation AliasLocation,
148                                           IdentifierInfo *ClassName,
149                                           SourceLocation ClassLocation) {
150  // Look for previous declaration of alias name
151  Decl *ADecl = LookupDecl(AliasName, Decl::IDNS_Ordinary, TUScope);
152  if (ADecl) {
153    if (isa<ObjCCompatibleAliasDecl>(ADecl))
154      Diag(AliasLocation, diag::warn_previous_alias_decl);
155    else
156      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
157    Diag(ADecl->getLocation(), diag::note_previous_declaration);
158    return 0;
159  }
160  // Check for class declaration
161  Decl *CDeclU = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
162  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
163    QualType T = TDecl->getUnderlyingType();
164    if (T->isObjCInterfaceType()) {
165      if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl()) {
166        ClassName = IDecl->getIdentifier();
167        CDeclU = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
168      }
169    }
170  }
171  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
172  if (CDecl == 0) {
173    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
174    if (CDeclU)
175      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
176    return 0;
177  }
178
179  // Everything checked out, instantiate a new alias declaration AST.
180  ObjCCompatibleAliasDecl *AliasDecl =
181    ObjCCompatibleAliasDecl::Create(Context, AtLoc, AliasName, CDecl);
182
183  ObjCAliasDecls[AliasName] = AliasDecl;
184
185  if (!CheckObjCDeclScope(AliasDecl))
186    TUScope->AddDecl(AliasDecl);
187
188  return AliasDecl;
189}
190
191Sema::DeclTy *
192Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
193                                  IdentifierInfo *ProtocolName,
194                                  SourceLocation ProtocolLoc,
195                                  DeclTy * const *ProtoRefs,
196                                  unsigned NumProtoRefs,
197                                  SourceLocation EndProtoLoc,
198                                  AttributeList *AttrList) {
199  // FIXME: Deal with AttrList.
200  assert(ProtocolName && "Missing protocol identifier");
201  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
202  if (PDecl) {
203    // Protocol already seen. Better be a forward protocol declaration
204    if (!PDecl->isForwardDecl()) {
205      Diag(ProtocolLoc, diag::err_duplicate_protocol_def) << ProtocolName;
206      Diag(PDecl->getLocation(), diag::note_previous_definition);
207      // Just return the protocol we already had.
208      // FIXME: don't leak the objects passed in!
209      return PDecl;
210    }
211    // Make sure the cached decl gets a valid start location.
212    PDecl->setLocation(AtProtoInterfaceLoc);
213    PDecl->setForwardDecl(false);
214  } else {
215    PDecl = ObjCProtocolDecl::Create(Context, AtProtoInterfaceLoc,ProtocolName);
216    PDecl->setForwardDecl(false);
217    ObjCProtocols[ProtocolName] = PDecl;
218  }
219  if (AttrList)
220    ProcessDeclAttributeList(PDecl, AttrList);
221  if (NumProtoRefs) {
222    /// Check then save referenced protocols.
223    PDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
224    PDecl->setLocEnd(EndProtoLoc);
225  }
226
227  CheckObjCDeclScope(PDecl);
228  return PDecl;
229}
230
231/// FindProtocolDeclaration - This routine looks up protocols and
232/// issues an error if they are not declared. It returns list of
233/// protocol declarations in its 'Protocols' argument.
234void
235Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
236                              const IdentifierLocPair *ProtocolId,
237                              unsigned NumProtocols,
238                              llvm::SmallVectorImpl<DeclTy*> &Protocols) {
239  for (unsigned i = 0; i != NumProtocols; ++i) {
240    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first];
241    if (!PDecl) {
242      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
243        << ProtocolId[i].first;
244      continue;
245    }
246    for (const Attr *attr = PDecl->getAttrs(); attr; attr = attr->getNext()) {
247      if (attr->getKind() == Attr::Unavailable)
248        Diag(ProtocolId[i].second, diag::warn_unavailable) <<
249          PDecl->getDeclName();
250      if (attr->getKind() == Attr::Deprecated)
251        Diag(ProtocolId[i].second, diag::warn_deprecated) <<
252          PDecl->getDeclName();
253    }
254
255    // If this is a forward declaration and we are supposed to warn in this
256    // case, do it.
257    if (WarnOnDeclarations && PDecl->isForwardDecl())
258      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
259        << ProtocolId[i].first;
260    Protocols.push_back(PDecl);
261  }
262}
263
264/// DiagnosePropertyMismatch - Compares two properties for their
265/// attributes and types and warns on a variety of inconsistencies.
266///
267void
268Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
269                               ObjCPropertyDecl *SuperProperty,
270                               const IdentifierInfo *inheritedName) {
271  ObjCPropertyDecl::PropertyAttributeKind CAttr =
272  Property->getPropertyAttributes();
273  ObjCPropertyDecl::PropertyAttributeKind SAttr =
274  SuperProperty->getPropertyAttributes();
275  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
276      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
277    Diag(Property->getLocation(), diag::warn_readonly_property)
278      << Property->getDeclName() << inheritedName;
279  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
280      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
281    Diag(Property->getLocation(), diag::warn_property_attribute)
282      << Property->getDeclName() << "copy" << inheritedName;
283  else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
284           != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
285    Diag(Property->getLocation(), diag::warn_property_attribute)
286      << Property->getDeclName() << "retain" << inheritedName;
287
288  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
289      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
290    Diag(Property->getLocation(), diag::warn_property_attribute)
291      << Property->getDeclName() << "atomic" << inheritedName;
292  if (Property->getSetterName() != SuperProperty->getSetterName())
293    Diag(Property->getLocation(), diag::warn_property_attribute)
294      << Property->getDeclName() << "setter" << inheritedName;
295  if (Property->getGetterName() != SuperProperty->getGetterName())
296    Diag(Property->getLocation(), diag::warn_property_attribute)
297      << Property->getDeclName() << "getter" << inheritedName;
298
299  if (Context.getCanonicalType(Property->getType()) !=
300          Context.getCanonicalType(SuperProperty->getType()))
301    Diag(Property->getLocation(), diag::warn_property_type)
302      << Property->getType() << inheritedName;
303
304}
305
306/// ComparePropertiesInBaseAndSuper - This routine compares property
307/// declarations in base and its super class, if any, and issues
308/// diagnostics in a variety of inconsistant situations.
309///
310void
311Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
312  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
313  if (!SDecl)
314    return;
315  // FIXME: O(N^2)
316  for (ObjCInterfaceDecl::classprop_iterator S = SDecl->classprop_begin(),
317       E = SDecl->classprop_end(); S != E; ++S) {
318    ObjCPropertyDecl *SuperPDecl = (*S);
319    // Does property in super class has declaration in current class?
320    for (ObjCInterfaceDecl::classprop_iterator I = IDecl->classprop_begin(),
321         E = IDecl->classprop_end(); I != E; ++I) {
322      ObjCPropertyDecl *PDecl = (*I);
323      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
324          DiagnosePropertyMismatch(PDecl, SuperPDecl,
325                                   SDecl->getIdentifier());
326    }
327  }
328}
329
330/// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list
331/// of properties declared in a protocol and adds them to the list
332/// of properties for current class/category if it is not there already.
333void
334Sema::MergeOneProtocolPropertiesIntoClass(Decl *CDecl,
335                                          ObjCProtocolDecl *PDecl) {
336  llvm::SmallVector<ObjCPropertyDecl*, 16> mergeProperties;
337  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
338  if (!IDecl) {
339    // Category
340    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
341    assert (CatDecl && "MergeOneProtocolPropertiesIntoClass");
342    for (ObjCProtocolDecl::classprop_iterator P = PDecl->classprop_begin(),
343         E = PDecl->classprop_end(); P != E; ++P) {
344      ObjCPropertyDecl *Pr = (*P);
345      ObjCCategoryDecl::classprop_iterator CP, CE;
346      // Is this property already in  category's list of properties?
347      for (CP = CatDecl->classprop_begin(), CE = CatDecl->classprop_end();
348           CP != CE; ++CP)
349        if ((*CP)->getIdentifier() == Pr->getIdentifier())
350          break;
351      if (CP == CE)
352        // Add this property to list of properties for thie class.
353        mergeProperties.push_back(Pr);
354      else
355        // Property protocol already exist in class. Diagnose any mismatch.
356        DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
357    }
358    CatDecl->mergeProperties(&mergeProperties[0], mergeProperties.size());
359    return;
360  }
361  for (ObjCProtocolDecl::classprop_iterator P = PDecl->classprop_begin(),
362       E = PDecl->classprop_end(); P != E; ++P) {
363    ObjCPropertyDecl *Pr = (*P);
364    ObjCInterfaceDecl::classprop_iterator CP, CE;
365    // Is this property already in  class's list of properties?
366    for (CP = IDecl->classprop_begin(), CE = IDecl->classprop_end();
367         CP != CE; ++CP)
368      if ((*CP)->getIdentifier() == Pr->getIdentifier())
369        break;
370    if (CP == CE)
371      // Add this property to list of properties for thie class.
372      mergeProperties.push_back(Pr);
373    else
374      // Property protocol already exist in class. Diagnose any mismatch.
375      DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
376    }
377  IDecl->mergeProperties(&mergeProperties[0], mergeProperties.size());
378}
379
380/// MergeProtocolPropertiesIntoClass - This routine merges properties
381/// declared in 'MergeItsProtocols' objects (which can be a class or an
382/// inherited protocol into the list of properties for class/category 'CDecl'
383///
384
385void
386Sema::MergeProtocolPropertiesIntoClass(Decl *CDecl,
387                                       DeclTy *MergeItsProtocols) {
388  Decl *ClassDecl = static_cast<Decl *>(MergeItsProtocols);
389  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
390
391  if (!IDecl) {
392    // Category
393    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
394    assert (CatDecl && "MergeProtocolPropertiesIntoClass");
395    if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
396      for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
397           E = MDecl->protocol_end(); P != E; ++P)
398      // Merge properties of category (*P) into IDECL's
399      MergeOneProtocolPropertiesIntoClass(CatDecl, *P);
400
401      // Go thru the list of protocols for this category and recursively merge
402      // their properties into this class as well.
403      for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
404           E = CatDecl->protocol_end(); P != E; ++P)
405        MergeProtocolPropertiesIntoClass(CatDecl, *P);
406    } else {
407      ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
408      for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
409           E = MD->protocol_end(); P != E; ++P)
410        MergeOneProtocolPropertiesIntoClass(CatDecl, (*P));
411    }
412    return;
413  }
414
415  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
416    for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
417         E = MDecl->protocol_end(); P != E; ++P)
418      // Merge properties of class (*P) into IDECL's
419      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
420
421    // Go thru the list of protocols for this class and recursively merge
422    // their properties into this class as well.
423    for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
424         E = IDecl->protocol_end(); P != E; ++P)
425      MergeProtocolPropertiesIntoClass(IDecl, *P);
426  } else {
427    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
428    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
429         E = MD->protocol_end(); P != E; ++P)
430      MergeOneProtocolPropertiesIntoClass(IDecl, (*P));
431  }
432}
433
434/// ActOnForwardProtocolDeclaration -
435Action::DeclTy *
436Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
437                                      const IdentifierLocPair *IdentList,
438                                      unsigned NumElts,
439                                      AttributeList *attrList) {
440  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
441
442  for (unsigned i = 0; i != NumElts; ++i) {
443    IdentifierInfo *Ident = IdentList[i].first;
444    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
445    if (PDecl == 0) // Not already seen?
446      PDecl = ObjCProtocolDecl::Create(Context, IdentList[i].second, Ident);
447    if (attrList)
448      ProcessDeclAttributeList(PDecl, attrList);
449    Protocols.push_back(PDecl);
450  }
451
452  ObjCForwardProtocolDecl *PDecl =
453    ObjCForwardProtocolDecl::Create(Context, AtProtocolLoc,
454                                    &Protocols[0], Protocols.size());
455
456  CheckObjCDeclScope(PDecl);
457  return PDecl;
458}
459
460Sema::DeclTy *Sema::
461ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
462                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
463                            IdentifierInfo *CategoryName,
464                            SourceLocation CategoryLoc,
465                            DeclTy * const *ProtoRefs,
466                            unsigned NumProtoRefs,
467                            SourceLocation EndProtoLoc) {
468  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
469
470  ObjCCategoryDecl *CDecl =
471    ObjCCategoryDecl::Create(Context, AtInterfaceLoc, CategoryName);
472  CDecl->setClassInterface(IDecl);
473
474  /// Check that class of this category is already completely declared.
475  if (!IDecl || IDecl->isForwardDecl())
476    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
477  else {
478    /// Check for duplicate interface declaration for this category
479    ObjCCategoryDecl *CDeclChain;
480    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
481         CDeclChain = CDeclChain->getNextClassCategory()) {
482      if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
483        Diag(CategoryLoc, diag::warn_dup_category_def)
484          << ClassName << CategoryName;
485        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
486        break;
487      }
488    }
489    if (!CDeclChain)
490      CDecl->insertNextClassCategory();
491  }
492
493  if (NumProtoRefs) {
494    CDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
495    CDecl->setLocEnd(EndProtoLoc);
496  }
497
498  CheckObjCDeclScope(CDecl);
499  return CDecl;
500}
501
502/// ActOnStartCategoryImplementation - Perform semantic checks on the
503/// category implementation declaration and build an ObjCCategoryImplDecl
504/// object.
505Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
506                      SourceLocation AtCatImplLoc,
507                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
508                      IdentifierInfo *CatName, SourceLocation CatLoc) {
509  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
510  ObjCCategoryImplDecl *CDecl =
511    ObjCCategoryImplDecl::Create(Context, AtCatImplLoc, CatName, IDecl);
512  /// Check that class of this category is already completely declared.
513  if (!IDecl || IDecl->isForwardDecl())
514    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
515
516  /// TODO: Check that CatName, category name, is not used in another
517  // implementation.
518  ObjCCategoryImpls.push_back(CDecl);
519
520  CheckObjCDeclScope(CDecl);
521  return CDecl;
522}
523
524Sema::DeclTy *Sema::ActOnStartClassImplementation(
525                      SourceLocation AtClassImplLoc,
526                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
527                      IdentifierInfo *SuperClassname,
528                      SourceLocation SuperClassLoc) {
529  ObjCInterfaceDecl* IDecl = 0;
530  // Check for another declaration kind with the same name.
531  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
532  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
533    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
534    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
535  }
536  else {
537    // Is there an interface declaration of this class; if not, warn!
538    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
539    if (!IDecl)
540      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
541  }
542
543  // Check that super class name is valid class name
544  ObjCInterfaceDecl* SDecl = 0;
545  if (SuperClassname) {
546    // Check if a different kind of symbol declared in this scope.
547    PrevDecl = LookupDecl(SuperClassname, Decl::IDNS_Ordinary, TUScope);
548    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
549      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
550        << SuperClassname;
551      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
552    } else {
553      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
554      if (!SDecl)
555        Diag(SuperClassLoc, diag::err_undef_superclass)
556          << SuperClassname << ClassName;
557      else if (IDecl && IDecl->getSuperClass() != SDecl) {
558        // This implementation and its interface do not have the same
559        // super class.
560        Diag(SuperClassLoc, diag::err_conflicting_super_class)
561          << SDecl->getDeclName();
562        Diag(SDecl->getLocation(), diag::note_previous_definition);
563      }
564    }
565  }
566
567  if (!IDecl) {
568    // Legacy case of @implementation with no corresponding @interface.
569    // Build, chain & install the interface decl into the identifier.
570
571    // FIXME: Do we support attributes on the @implementation? If so
572    // we should copy them over.
573    IDecl = ObjCInterfaceDecl::Create(Context, AtClassImplLoc, ClassName,
574                                      ClassLoc, false, true);
575    ObjCInterfaceDecls[ClassName] = IDecl;
576    IDecl->setSuperClass(SDecl);
577    IDecl->setLocEnd(ClassLoc);
578
579    // Remember that this needs to be removed when the scope is popped.
580    TUScope->AddDecl(IDecl);
581  }
582
583  ObjCImplementationDecl* IMPDecl =
584    ObjCImplementationDecl::Create(Context, AtClassImplLoc, ClassName,
585                                   IDecl, SDecl);
586
587  if (CheckObjCDeclScope(IMPDecl))
588    return IMPDecl;
589
590  // Check that there is no duplicate implementation of this class.
591  if (ObjCImplementations[ClassName])
592    // FIXME: Don't leak everything!
593    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
594  else // add it to the list.
595    ObjCImplementations[ClassName] = IMPDecl;
596  return IMPDecl;
597}
598
599void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
600                                    ObjCIvarDecl **ivars, unsigned numIvars,
601                                    SourceLocation RBrace) {
602  assert(ImpDecl && "missing implementation decl");
603  ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
604  if (!IDecl)
605    return;
606  /// Check case of non-existing @interface decl.
607  /// (legacy objective-c @implementation decl without an @interface decl).
608  /// Add implementations's ivar to the synthesize class's ivar list.
609  if (IDecl->ImplicitInterfaceDecl()) {
610    IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
611    return;
612  }
613  // If implementation has empty ivar list, just return.
614  if (numIvars == 0)
615    return;
616
617  assert(ivars && "missing @implementation ivars");
618
619  // Check interface's Ivar list against those in the implementation.
620  // names and types must match.
621  //
622  unsigned j = 0;
623  ObjCInterfaceDecl::ivar_iterator
624    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
625  for (; numIvars > 0 && IVI != IVE; ++IVI) {
626    ObjCIvarDecl* ImplIvar = ivars[j++];
627    ObjCIvarDecl* ClsIvar = *IVI;
628    assert (ImplIvar && "missing implementation ivar");
629    assert (ClsIvar && "missing class ivar");
630    if (Context.getCanonicalType(ImplIvar->getType()) !=
631        Context.getCanonicalType(ClsIvar->getType())) {
632      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
633        << ImplIvar->getIdentifier()
634        << ImplIvar->getType() << ClsIvar->getType();
635      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
636    }
637    // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
638    // as error.
639    else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
640      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
641        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
642      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
643      return;
644    }
645    --numIvars;
646  }
647
648  if (numIvars > 0)
649    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
650  else if (IVI != IVE)
651    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
652}
653
654void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
655                               bool &IncompleteImpl) {
656  if (!IncompleteImpl) {
657    Diag(ImpLoc, diag::warn_incomplete_impl);
658    IncompleteImpl = true;
659  }
660  Diag(ImpLoc, diag::warn_undef_method_impl) << method->getDeclName();
661}
662
663void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
664                                       ObjCMethodDecl *IntfMethodDecl) {
665  bool err = false;
666  QualType ImpMethodQType =
667    Context.getCanonicalType(ImpMethodDecl->getResultType());
668  QualType IntfMethodQType =
669    Context.getCanonicalType(IntfMethodDecl->getResultType());
670  if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType))
671    err = true;
672  else for (ObjCMethodDecl::param_iterator IM=ImpMethodDecl->param_begin(),
673            IF=IntfMethodDecl->param_begin(),
674            EM=ImpMethodDecl->param_end(); IM!=EM; ++IM, IF++) {
675    ImpMethodQType = Context.getCanonicalType((*IM)->getType());
676    IntfMethodQType = Context.getCanonicalType((*IF)->getType());
677    if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType)) {
678      err = true;
679      break;
680    }
681  }
682  if (err) {
683    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_types)
684    << ImpMethodDecl->getDeclName();
685    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
686  }
687}
688
689/// FIXME: Type hierarchies in Objective-C can be deep. We could most
690/// likely improve the efficiency of selector lookups and type
691/// checking by associating with each protocol / interface / category
692/// the flattened instance tables. If we used an immutable set to keep
693/// the table then it wouldn't add significant memory cost and it
694/// would be handy for lookups.
695
696/// CheckProtocolMethodDefs - This routine checks unimplemented methods
697/// Declared in protocol, and those referenced by it.
698void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
699                                   ObjCProtocolDecl *PDecl,
700                                   bool& IncompleteImpl,
701                                   const llvm::DenseSet<Selector> &InsMap,
702                                   const llvm::DenseSet<Selector> &ClsMap,
703                                   ObjCInterfaceDecl *IDecl) {
704  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
705
706  // If a method lookup fails locally we still need to look and see if
707  // the method was implemented by a base class or an inherited
708  // protocol. This lookup is slow, but occurs rarely in correct code
709  // and otherwise would terminate in a warning.
710
711  // check unimplemented instance methods.
712  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
713       E = PDecl->instmeth_end(); I != E; ++I) {
714    ObjCMethodDecl *method = *I;
715    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
716        !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
717        (!Super || !Super->lookupInstanceMethod(method->getSelector())))
718      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
719  }
720  // check unimplemented class methods
721  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
722       E = PDecl->classmeth_end(); I != E; ++I) {
723    ObjCMethodDecl *method = *I;
724    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
725        !ClsMap.count(method->getSelector()) &&
726        (!Super || !Super->lookupClassMethod(method->getSelector())))
727      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
728  }
729  // Check on this protocols's referenced protocols, recursively.
730  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
731       E = PDecl->protocol_end(); PI != E; ++PI)
732    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
733}
734
735void Sema::ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl,
736                                     ObjCInterfaceDecl* IDecl) {
737  llvm::DenseSet<Selector> InsMap;
738  // Check and see if instance methods in class interface have been
739  // implemented in the implementation class.
740  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
741       E = IMPDecl->instmeth_end(); I != E; ++I)
742    InsMap.insert((*I)->getSelector());
743
744  bool IncompleteImpl = false;
745  for (ObjCInterfaceDecl::instmeth_iterator I = IDecl->instmeth_begin(),
746       E = IDecl->instmeth_end(); I != E; ++I)
747    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector()))
748      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
749    else {
750      ObjCMethodDecl *ImpMethodDecl =
751        IMPDecl->getInstanceMethod((*I)->getSelector());
752      ObjCMethodDecl *IntfMethodDecl =
753        IDecl->getInstanceMethod((*I)->getSelector());
754      assert(IntfMethodDecl &&
755             "IntfMethodDecl is null in ImplMethodsVsClassMethods");
756      // ImpMethodDecl may be null as in a @dynamic property.
757      if (ImpMethodDecl)
758        WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
759    }
760
761  llvm::DenseSet<Selector> ClsMap;
762  // Check and see if class methods in class interface have been
763  // implemented in the implementation class.
764  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
765       E = IMPDecl->classmeth_end(); I != E; ++I)
766    ClsMap.insert((*I)->getSelector());
767
768  for (ObjCInterfaceDecl::classmeth_iterator I = IDecl->classmeth_begin(),
769       E = IDecl->classmeth_end(); I != E; ++I)
770    if (!ClsMap.count((*I)->getSelector()))
771      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
772    else {
773      ObjCMethodDecl *ImpMethodDecl =
774        IMPDecl->getClassMethod((*I)->getSelector());
775      ObjCMethodDecl *IntfMethodDecl =
776        IDecl->getClassMethod((*I)->getSelector());
777      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
778    }
779
780
781  // Check the protocol list for unimplemented methods in the @implementation
782  // class.
783  const ObjCList<ObjCProtocolDecl> &Protocols =
784    IDecl->getReferencedProtocols();
785  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
786       E = Protocols.end(); I != E; ++I)
787    CheckProtocolMethodDefs(IMPDecl->getLocation(), *I,
788                            IncompleteImpl, InsMap, ClsMap, IDecl);
789}
790
791/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
792/// category interface are implemented in the category @implementation.
793void Sema::ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
794                                            ObjCCategoryDecl *CatClassDecl) {
795  llvm::DenseSet<Selector> InsMap;
796  // Check and see if instance methods in category interface have been
797  // implemented in its implementation class.
798  for (ObjCCategoryImplDecl::instmeth_iterator I =CatImplDecl->instmeth_begin(),
799       E = CatImplDecl->instmeth_end(); I != E; ++I)
800    InsMap.insert((*I)->getSelector());
801
802  bool IncompleteImpl = false;
803  for (ObjCCategoryDecl::instmeth_iterator I = CatClassDecl->instmeth_begin(),
804       E = CatClassDecl->instmeth_end(); I != E; ++I)
805    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector()))
806      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
807    else {
808      ObjCMethodDecl *ImpMethodDecl =
809        CatImplDecl->getInstanceMethod((*I)->getSelector());
810      ObjCMethodDecl *IntfMethodDecl =
811        CatClassDecl->getInstanceMethod((*I)->getSelector());
812      assert(IntfMethodDecl &&
813             "IntfMethodDecl is null in ImplCategoryMethodsVsIntfMethods");
814      // ImpMethodDecl may be null as in a @dynamic property.
815      if (ImpMethodDecl)
816        WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
817    }
818
819  llvm::DenseSet<Selector> ClsMap;
820  // Check and see if class methods in category interface have been
821  // implemented in its implementation class.
822  for (ObjCCategoryImplDecl::classmeth_iterator
823       I = CatImplDecl->classmeth_begin(), E = CatImplDecl->classmeth_end();
824       I != E; ++I)
825    ClsMap.insert((*I)->getSelector());
826
827  for (ObjCCategoryDecl::classmeth_iterator I = CatClassDecl->classmeth_begin(),
828       E = CatClassDecl->classmeth_end(); I != E; ++I)
829    if (!ClsMap.count((*I)->getSelector()))
830      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
831    else {
832      ObjCMethodDecl *ImpMethodDecl =
833        CatImplDecl->getClassMethod((*I)->getSelector());
834      ObjCMethodDecl *IntfMethodDecl =
835        CatClassDecl->getClassMethod((*I)->getSelector());
836      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
837    }
838  // Check the protocol list for unimplemented methods in the @implementation
839  // class.
840  for (ObjCCategoryDecl::protocol_iterator PI = CatClassDecl->protocol_begin(),
841       E = CatClassDecl->protocol_end(); PI != E; ++PI)
842    CheckProtocolMethodDefs(CatImplDecl->getLocation(), *PI, IncompleteImpl,
843                            InsMap, ClsMap, CatClassDecl->getClassInterface());
844}
845
846/// ActOnForwardClassDeclaration -
847Action::DeclTy *
848Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
849                                   IdentifierInfo **IdentList, unsigned NumElts)
850{
851  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
852
853  for (unsigned i = 0; i != NumElts; ++i) {
854    // Check for another declaration kind with the same name.
855    Decl *PrevDecl = LookupDecl(IdentList[i], Decl::IDNS_Ordinary, TUScope);
856    if (PrevDecl && PrevDecl->isTemplateParameter()) {
857      // Maybe we will complain about the shadowed template parameter.
858      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
859      // Just pretend that we didn't see the previous declaration.
860      PrevDecl = 0;
861    }
862
863    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
864      // GCC apparently allows the following idiom:
865      //
866      // typedef NSObject < XCElementTogglerP > XCElementToggler;
867      // @class XCElementToggler;
868      //
869      // FIXME: Make an extension?
870      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
871      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
872        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
873        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
874      }
875    }
876    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
877    if (!IDecl) {  // Not already seen?  Make a forward decl.
878      IDecl = ObjCInterfaceDecl::Create(Context, AtClassLoc, IdentList[i],
879                                        SourceLocation(), true);
880      ObjCInterfaceDecls[IdentList[i]] = IDecl;
881
882      // Remember that this needs to be removed when the scope is popped.
883      TUScope->AddDecl(IDecl);
884    }
885
886    Interfaces.push_back(IDecl);
887  }
888
889  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, AtClassLoc,
890                                               &Interfaces[0],
891                                               Interfaces.size());
892
893  CheckObjCDeclScope(CDecl);
894  return CDecl;
895}
896
897
898/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
899/// returns true, or false, accordingly.
900/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
901bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
902                                      const ObjCMethodDecl *PrevMethod,
903                                      bool matchBasedOnSizeAndAlignment) {
904  QualType T1 = Context.getCanonicalType(Method->getResultType());
905  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
906
907  if (T1 != T2) {
908    // The result types are different.
909    if (!matchBasedOnSizeAndAlignment)
910      return false;
911    // Incomplete types don't have a size and alignment.
912    if (T1->isIncompleteType() || T2->isIncompleteType())
913      return false;
914    // Check is based on size and alignment.
915    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
916      return false;
917  }
918  for (unsigned i = 0, e = Method->getNumParams(); i != e; ++i) {
919    T1 = Context.getCanonicalType(Method->getParamDecl(i)->getType());
920    T2 = Context.getCanonicalType(PrevMethod->getParamDecl(i)->getType());
921    if (T1 != T2) {
922      // The result types are different.
923      if (!matchBasedOnSizeAndAlignment)
924        return false;
925      // Incomplete types don't have a size and alignment.
926      if (T1->isIncompleteType() || T2->isIncompleteType())
927        return false;
928      // Check is based on size and alignment.
929      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
930        return false;
931    }
932  }
933  return true;
934}
935
936void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
937  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
938  if (!FirstMethod.Method) {
939    // Haven't seen a method with this selector name yet - add it.
940    FirstMethod.Method = Method;
941    FirstMethod.Next = 0;
942  } else {
943    // We've seen a method with this name, now check the type signature(s).
944    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
945
946    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
947         Next = Next->Next)
948      match = MatchTwoMethodDeclarations(Method, Next->Method);
949
950    if (!match) {
951      // We have a new signature for an existing method - add it.
952      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
953      FirstMethod.Next = new ObjCMethodList(Method, FirstMethod.Next);;
954    }
955  }
956}
957
958// FIXME: Finish implementing -Wno-strict-selector-match.
959ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
960                                                       SourceRange R) {
961  ObjCMethodList &MethList = InstanceMethodPool[Sel];
962  bool issueWarning = false;
963
964  if (MethList.Method && MethList.Next) {
965    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
966      // This checks if the methods differ by size & alignment.
967      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
968        issueWarning = true;
969  }
970  if (issueWarning && (MethList.Method && MethList.Next)) {
971    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
972    Diag(MethList.Method->getLocStart(), diag::note_using_decl)
973      << MethList.Method->getSourceRange();
974    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
975      Diag(Next->Method->getLocStart(), diag::note_also_found_decl)
976        << Next->Method->getSourceRange();
977  }
978  return MethList.Method;
979}
980
981void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
982  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
983  if (!FirstMethod.Method) {
984    // Haven't seen a method with this selector name yet - add it.
985    FirstMethod.Method = Method;
986    FirstMethod.Next = 0;
987  } else {
988    // We've seen a method with this name, now check the type signature(s).
989    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
990
991    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
992         Next = Next->Next)
993      match = MatchTwoMethodDeclarations(Method, Next->Method);
994
995    if (!match) {
996      // We have a new signature for an existing method - add it.
997      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
998      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
999      FirstMethod.Next = OMI;
1000    }
1001  }
1002}
1003
1004/// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1005/// have the property type and issue diagnostics if they don't.
1006/// Also synthesize a getter/setter method if none exist (and update the
1007/// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1008/// methods is the "right" thing to do.
1009void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1010                               ObjCContainerDecl *CD) {
1011  ObjCMethodDecl *GetterMethod, *SetterMethod;
1012
1013  GetterMethod = CD->getInstanceMethod(property->getGetterName());
1014  SetterMethod = CD->getInstanceMethod(property->getSetterName());
1015
1016  if (GetterMethod &&
1017      GetterMethod->getResultType() != property->getType()) {
1018    Diag(property->getLocation(),
1019         diag::err_accessor_property_type_mismatch)
1020      << property->getDeclName()
1021      << GetterMethod->getSelector().getAsIdentifierInfo();
1022    Diag(GetterMethod->getLocation(), diag::note_declared_at);
1023  }
1024
1025  if (SetterMethod) {
1026    if (Context.getCanonicalType(SetterMethod->getResultType())
1027        != Context.VoidTy)
1028      Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1029    if (SetterMethod->getNumParams() != 1 ||
1030        (SetterMethod->getParamDecl(0)->getType() != property->getType())) {
1031      Diag(property->getLocation(),
1032           diag::err_accessor_property_type_mismatch)
1033        << property->getDeclName()
1034        << SetterMethod->getSelector().getAsIdentifierInfo();
1035      Diag(SetterMethod->getLocation(), diag::note_declared_at);
1036    }
1037  }
1038
1039  // Synthesize getter/setter methods if none exist.
1040  // Add any synthesized methods to the global pool. This allows us to
1041  // handle the following, which is supported by GCC (and part of the design).
1042  //
1043  // @interface Foo
1044  // @property double bar;
1045  // @end
1046  //
1047  // void thisIsUnfortunate() {
1048  //   id foo;
1049  //   double bar = [foo bar];
1050  // }
1051  //
1052  CD->getPropertyMethods(Context, property, GetterMethod, SetterMethod);
1053  if (GetterMethod) {
1054    CD->addDecl(Context, GetterMethod);
1055    AddInstanceMethodToGlobalPool(GetterMethod);
1056  }
1057  if (SetterMethod) {
1058    CD->addDecl(Context, SetterMethod);
1059    AddInstanceMethodToGlobalPool(SetterMethod);
1060  }
1061}
1062
1063// Note: For class/category implemenations, allMethods/allProperties is
1064// always null.
1065void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
1066                      DeclTy **allMethods, unsigned allNum,
1067                      DeclTy **allProperties, unsigned pNum) {
1068  Decl *ClassDecl = static_cast<Decl *>(classDecl);
1069
1070  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1071  // always passing in a decl. If the decl has an error, isInvalidDecl()
1072  // should be true.
1073  if (!ClassDecl)
1074    return;
1075
1076  bool isInterfaceDeclKind =
1077        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1078         || isa<ObjCProtocolDecl>(ClassDecl);
1079  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1080
1081
1082  if (pNum != 0) {
1083    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl))
1084      IDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
1085    else if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
1086      CDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
1087    else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(ClassDecl))
1088      PDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
1089    else
1090      assert(false && "ActOnAtEnd - property declaration misplaced");
1091  }
1092
1093  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1094  assert(DC && "Missing DeclContext");
1095
1096  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1097  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1098  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1099
1100  for (unsigned i = 0; i < allNum; i++ ) {
1101    ObjCMethodDecl *Method =
1102      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
1103
1104    if (!Method) continue;  // Already issued a diagnostic.
1105    if (Method->isInstance()) {
1106      /// Check for instance method of the same name with incompatible types
1107      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1108      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1109                              : false;
1110      if ((isInterfaceDeclKind && PrevMethod && !match)
1111          || (checkIdenticalMethods && match)) {
1112          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1113            << Method->getDeclName();
1114          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1115      } else {
1116        DC->addDecl(Context, Method);
1117        InsMap[Method->getSelector()] = Method;
1118        /// The following allows us to typecheck messages to "id".
1119        AddInstanceMethodToGlobalPool(Method);
1120      }
1121    }
1122    else {
1123      /// Check for class method of the same name with incompatible types
1124      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1125      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1126                              : false;
1127      if ((isInterfaceDeclKind && PrevMethod && !match)
1128          || (checkIdenticalMethods && match)) {
1129        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1130          << Method->getDeclName();
1131        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1132      } else {
1133        DC->addDecl(Context, Method);
1134        ClsMap[Method->getSelector()] = Method;
1135        /// The following allows us to typecheck messages to "Class".
1136        AddFactoryMethodToGlobalPool(Method);
1137      }
1138    }
1139  }
1140  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1141    // Compares properties declared in this class to those of its
1142    // super class.
1143    ComparePropertiesInBaseAndSuper(I);
1144    MergeProtocolPropertiesIntoClass(I, I);
1145    for (ObjCInterfaceDecl::classprop_iterator i = I->classprop_begin(),
1146         e = I->classprop_end(); i != e; ++i) {
1147      ProcessPropertyDecl((*i), I);
1148    }
1149    I->setAtEndLoc(AtEndLoc);
1150  } else if (ObjCProtocolDecl *P = dyn_cast<ObjCProtocolDecl>(ClassDecl)) {
1151    for (ObjCProtocolDecl::classprop_iterator i = P->classprop_begin(),
1152         e = P->classprop_end(); i != e; ++i) {
1153      ProcessPropertyDecl((*i), P);
1154    }
1155    P->setAtEndLoc(AtEndLoc);
1156  }
1157  else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1158    // Categories are used to extend the class by declaring new methods.
1159    // By the same token, they are also used to add new properties. No
1160    // need to compare the added property to those in the class.
1161
1162    // Merge protocol properties into category
1163    MergeProtocolPropertiesIntoClass(C, C);
1164    for (ObjCCategoryDecl::classprop_iterator i = C->classprop_begin(),
1165         e = C->classprop_end(); i != e; ++i) {
1166      ProcessPropertyDecl((*i), C);
1167    }
1168    C->setAtEndLoc(AtEndLoc);
1169  }
1170  else if (ObjCImplementationDecl *IC =
1171                dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1172    IC->setLocEnd(AtEndLoc);
1173    if (ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
1174      ImplMethodsVsClassMethods(IC, IDecl);
1175  } else {
1176    ObjCCategoryImplDecl* CatImplClass = cast<ObjCCategoryImplDecl>(ClassDecl);
1177    CatImplClass->setLocEnd(AtEndLoc);
1178    ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface();
1179    // Find category interface decl and then check that all methods declared
1180    // in this interface are implemented in the category @implementation.
1181    if (IDecl) {
1182      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1183           Categories; Categories = Categories->getNextClassCategory()) {
1184        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1185          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1186          break;
1187        }
1188      }
1189    }
1190  }
1191}
1192
1193
1194/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1195/// objective-c's type qualifier from the parser version of the same info.
1196static Decl::ObjCDeclQualifier
1197CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1198  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1199  if (PQTVal & ObjCDeclSpec::DQ_In)
1200    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1201  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1202    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1203  if (PQTVal & ObjCDeclSpec::DQ_Out)
1204    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1205  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1206    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1207  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1208    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1209  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1210    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1211
1212  return ret;
1213}
1214
1215Sema::DeclTy *Sema::ActOnMethodDeclaration(
1216    SourceLocation MethodLoc, SourceLocation EndLoc,
1217    tok::TokenKind MethodType, DeclTy *classDecl,
1218    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1219    Selector Sel,
1220    // optional arguments. The number of types/arguments is obtained
1221    // from the Sel.getNumArgs().
1222    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1223    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1224    bool isVariadic) {
1225  Decl *ClassDecl = static_cast<Decl*>(classDecl);
1226
1227  // Make sure we can establish a context for the method.
1228  if (!ClassDecl) {
1229    Diag(MethodLoc, diag::error_missing_method_context);
1230    return 0;
1231  }
1232  QualType resultDeclType;
1233
1234  if (ReturnType)
1235    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1236  else // get the type for "id".
1237    resultDeclType = Context.getObjCIdType();
1238
1239  ObjCMethodDecl* ObjCMethod =
1240    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1241                           dyn_cast<DeclContext>(ClassDecl),
1242                           MethodType == tok::minus, isVariadic,
1243                           false,
1244                           MethodDeclKind == tok::objc_optional ?
1245                           ObjCMethodDecl::Optional :
1246                           ObjCMethodDecl::Required);
1247
1248  llvm::SmallVector<ParmVarDecl*, 16> Params;
1249
1250  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
1251    // FIXME: arg->AttrList must be stored too!
1252    QualType argType, originalArgType;
1253
1254    if (ArgTypes[i]) {
1255      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
1256      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1257      if (argType->isArrayType())  { // (char *[]) -> (char **)
1258        originalArgType = argType;
1259        argType = Context.getArrayDecayedType(argType);
1260      }
1261      else if (argType->isFunctionType())
1262        argType = Context.getPointerType(argType);
1263    } else
1264      argType = Context.getObjCIdType();
1265    ParmVarDecl* Param;
1266    if (originalArgType.isNull())
1267      Param = ParmVarDecl::Create(Context, ObjCMethod,
1268                                  SourceLocation(/*FIXME*/),
1269                                  ArgNames[i], argType,
1270                                  VarDecl::None, 0, 0);
1271    else
1272      Param = ParmVarWithOriginalTypeDecl::Create(Context, ObjCMethod,
1273                                  SourceLocation(/*FIXME*/),
1274                                  ArgNames[i], argType, originalArgType,
1275                                  VarDecl::None, 0, 0);
1276
1277    Param->setObjCDeclQualifier(
1278      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
1279    Params.push_back(Param);
1280  }
1281
1282  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
1283  ObjCMethod->setObjCDeclQualifier(
1284    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1285  const ObjCMethodDecl *PrevMethod = 0;
1286
1287  if (AttrList)
1288    ProcessDeclAttributeList(ObjCMethod, AttrList);
1289
1290  // For implementations (which can be very "coarse grain"), we add the
1291  // method now. This allows the AST to implement lookup methods that work
1292  // incrementally (without waiting until we parse the @end). It also allows
1293  // us to flag multiple declaration errors as they occur.
1294  if (ObjCImplementationDecl *ImpDecl =
1295        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1296    if (MethodType == tok::minus) {
1297      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1298      ImpDecl->addInstanceMethod(ObjCMethod);
1299    } else {
1300      PrevMethod = ImpDecl->getClassMethod(Sel);
1301      ImpDecl->addClassMethod(ObjCMethod);
1302    }
1303  }
1304  else if (ObjCCategoryImplDecl *CatImpDecl =
1305            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1306    if (MethodType == tok::minus) {
1307      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1308      CatImpDecl->addInstanceMethod(ObjCMethod);
1309    } else {
1310      PrevMethod = CatImpDecl->getClassMethod(Sel);
1311      CatImpDecl->addClassMethod(ObjCMethod);
1312    }
1313  }
1314  if (PrevMethod) {
1315    // You can never have two method definitions with the same name.
1316    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1317      << ObjCMethod->getDeclName();
1318    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1319  }
1320  return ObjCMethod;
1321}
1322
1323void Sema::CheckObjCPropertyAttributes(QualType PropertyTy,
1324                                       SourceLocation Loc,
1325                                       unsigned &Attributes) {
1326  // FIXME: Improve the reported location.
1327
1328  // readonly and readwrite/assign/retain/copy conflict.
1329  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1330      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1331                     ObjCDeclSpec::DQ_PR_assign |
1332                     ObjCDeclSpec::DQ_PR_copy |
1333                     ObjCDeclSpec::DQ_PR_retain))) {
1334    const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1335                          "readwrite" :
1336                         (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1337                          "assign" :
1338                         (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
1339                          "copy" : "retain";
1340
1341    Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
1342                 diag::err_objc_property_attr_mutually_exclusive :
1343                 diag::warn_objc_property_attr_mutually_exclusive)
1344      << "readonly" << which;
1345  }
1346
1347  // Check for copy or retain on non-object types.
1348  if ((Attributes & (ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) &&
1349      !Context.isObjCObjectPointerType(PropertyTy)) {
1350    Diag(Loc, diag::err_objc_property_requires_object)
1351      << (Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain");
1352    Attributes &= ~(ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain);
1353  }
1354
1355  // Check for more than one of { assign, copy, retain }.
1356  if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
1357    if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1358      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1359        << "assign" << "copy";
1360      Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1361    }
1362    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1363      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1364        << "assign" << "retain";
1365      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1366    }
1367  } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1368    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1369      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1370        << "copy" << "retain";
1371      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1372    }
1373  }
1374
1375  // Warn if user supplied no assignment attribute, property is
1376  // readwrite, and this is an object type.
1377  if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
1378                      ObjCDeclSpec::DQ_PR_retain)) &&
1379      !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1380      Context.isObjCObjectPointerType(PropertyTy)) {
1381    // Skip this warning in gc-only mode.
1382    if (getLangOptions().getGCMode() != LangOptions::GCOnly)
1383      Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
1384
1385    // If non-gc code warn that this is likely inappropriate.
1386    if (getLangOptions().getGCMode() == LangOptions::NonGC)
1387      Diag(Loc, diag::warn_objc_property_default_assign_on_object);
1388
1389    // FIXME: Implement warning dependent on NSCopying being
1390    // implemented. See also:
1391    // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
1392    // (please trim this list while you are at it).
1393  }
1394}
1395
1396Sema::DeclTy *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
1397                                  FieldDeclarator &FD,
1398                                  ObjCDeclSpec &ODS,
1399                                  Selector GetterSel,
1400                                  Selector SetterSel,
1401                                  DeclTy *ClassCategory,
1402                                  bool *isOverridingProperty,
1403                                  tok::ObjCKeywordKind MethodImplKind) {
1404  unsigned Attributes = ODS.getPropertyAttributes();
1405  bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
1406                      // default is readwrite!
1407                      !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
1408  // property is defaulted to 'assign' if it is readwrite and is
1409  // not retain or copy
1410  bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
1411                   (isReadWrite &&
1412                    !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
1413                    !(Attributes & ObjCDeclSpec::DQ_PR_copy)));
1414  QualType T = GetTypeForDeclarator(FD.D, S);
1415  Decl *ClassDecl = static_cast<Decl *>(ClassCategory);
1416
1417  // May modify Attributes.
1418  CheckObjCPropertyAttributes(T, AtLoc, Attributes);
1419
1420  if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
1421    if (!CDecl->getIdentifier()) {
1422      // This is an anonymous category. property requires special
1423      // handling.
1424      if (ObjCInterfaceDecl *ICDecl = CDecl->getClassInterface()) {
1425        if (ObjCPropertyDecl *PIDecl =
1426            ICDecl->FindPropertyDeclaration(FD.D.getIdentifier())) {
1427          // property 'PIDecl's readonly attribute will be over-ridden
1428          // with anonymous category's readwrite property attribute!
1429          unsigned PIkind = PIDecl->getPropertyAttributes();
1430          if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
1431            if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) !=
1432                (PIkind & ObjCPropertyDecl::OBJC_PR_nonatomic))
1433              Diag(AtLoc, diag::warn_property_attr_mismatch);
1434            PIDecl->makeitReadWriteAttribute();
1435            if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1436              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1437            if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1438              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1439            PIDecl->setSetterName(SetterSel);
1440            // FIXME: use a common routine with addPropertyMethods.
1441            ObjCMethodDecl *SetterDecl =
1442              ObjCMethodDecl::Create(Context, AtLoc, AtLoc, SetterSel,
1443                                     Context.VoidTy,
1444                                     ICDecl,
1445                                     true, false, true,
1446                                     ObjCMethodDecl::Required);
1447            ParmVarDecl *Argument = ParmVarDecl::Create(Context,
1448                                                        SetterDecl,
1449                                                        SourceLocation(),
1450                                                        FD.D.getIdentifier(),
1451                                                        T,
1452                                                        VarDecl::None,
1453                                                        0, 0);
1454            SetterDecl->setMethodParams(&Argument, 1);
1455            PIDecl->setSetterMethodDecl(SetterDecl);
1456          }
1457          else
1458            Diag(AtLoc, diag::err_use_continuation_class) << ICDecl->getDeclName();
1459          *isOverridingProperty = true;
1460          return 0;
1461        }
1462        // No matching property found in the main class. Just fall thru
1463        // and add property to the anonymous category. It looks like
1464	// it works as is. This category becomes just like a category
1465	// for its primary class.
1466      } else {
1467          Diag(CDecl->getLocation(), diag::err_continuation_class);
1468          *isOverridingProperty = true;
1469          return 0;
1470      }
1471    }
1472
1473  Type *t = T.getTypePtr();
1474  if (t->isArrayType() || t->isFunctionType())
1475    Diag(AtLoc, diag::err_property_type) << T;
1476
1477  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, AtLoc,
1478                                                     FD.D.getIdentifier(), T);
1479  // Regardless of setter/getter attribute, we save the default getter/setter
1480  // selector names in anticipation of declaration of setter/getter methods.
1481  PDecl->setGetterName(GetterSel);
1482  PDecl->setSetterName(SetterSel);
1483
1484  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
1485    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
1486
1487  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
1488    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
1489
1490  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
1491    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
1492
1493  if (isReadWrite)
1494    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
1495
1496  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1497    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1498
1499  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1500    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1501
1502  if (isAssign)
1503    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
1504
1505  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
1506    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
1507
1508  if (MethodImplKind == tok::objc_required)
1509    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
1510  else if (MethodImplKind == tok::objc_optional)
1511    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
1512
1513  return PDecl;
1514}
1515
1516/// ActOnPropertyImplDecl - This routine performs semantic checks and
1517/// builds the AST node for a property implementation declaration; declared
1518/// as @synthesize or @dynamic.
1519///
1520Sema::DeclTy *Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
1521                                          SourceLocation PropertyLoc,
1522                                          bool Synthesize,
1523                                          DeclTy *ClassCatImpDecl,
1524                                          IdentifierInfo *PropertyId,
1525                                          IdentifierInfo *PropertyIvar) {
1526  Decl *ClassImpDecl = static_cast<Decl*>(ClassCatImpDecl);
1527  // Make sure we have a context for the property implementation declaration.
1528  if (!ClassImpDecl) {
1529    Diag(AtLoc, diag::error_missing_property_context);
1530    return 0;
1531  }
1532  ObjCPropertyDecl *property = 0;
1533  ObjCInterfaceDecl* IDecl = 0;
1534  // Find the class or category class where this property must have
1535  // a declaration.
1536  ObjCImplementationDecl *IC = 0;
1537  ObjCCategoryImplDecl* CatImplClass = 0;
1538  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1539    IDecl = getObjCInterfaceDecl(IC->getIdentifier());
1540    // We always synthesize an interface for an implementation
1541    // without an interface decl. So, IDecl is always non-zero.
1542    assert(IDecl &&
1543           "ActOnPropertyImplDecl - @implementation without @interface");
1544
1545    // Look for this property declaration in the @implementation's @interface
1546    property = IDecl->FindPropertyDeclaration(PropertyId);
1547    if (!property) {
1548      Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
1549      return 0;
1550    }
1551  }
1552  else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1553    if (Synthesize) {
1554      Diag(AtLoc, diag::error_synthesize_category_decl);
1555      return 0;
1556    }
1557    IDecl = CatImplClass->getClassInterface();
1558    if (!IDecl) {
1559      Diag(AtLoc, diag::error_missing_property_interface);
1560      return 0;
1561    }
1562    ObjCCategoryDecl *Category =
1563      IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1564
1565    // If category for this implementation not found, it is an error which
1566    // has already been reported eralier.
1567    if (!Category)
1568      return 0;
1569    // Look for this property declaration in @implementation's category
1570    property = Category->FindPropertyDeclaration(PropertyId);
1571    if (!property) {
1572      Diag(PropertyLoc, diag::error_bad_category_property_decl)
1573        << Category->getDeclName();
1574      return 0;
1575    }
1576  }
1577  else {
1578    Diag(AtLoc, diag::error_bad_property_context);
1579    return 0;
1580  }
1581  ObjCIvarDecl *Ivar = 0;
1582  // Check that we have a valid, previously declared ivar for @synthesize
1583  if (Synthesize) {
1584    // @synthesize
1585    if (!PropertyIvar)
1586      PropertyIvar = PropertyId;
1587    // Check that this is a previously declared 'ivar' in 'IDecl' interface
1588    Ivar = IDecl->FindIvarDeclaration(PropertyIvar);
1589    if (!Ivar) {
1590      Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId;
1591      return 0;
1592    }
1593    QualType PropType = Context.getCanonicalType(property->getType());
1594    QualType IvarType = Context.getCanonicalType(Ivar->getType());
1595
1596    // Check that type of property and its ivar are type compatible.
1597    if (PropType != IvarType) {
1598      if (CheckAssignmentConstraints(PropType, IvarType) != Compatible) {
1599        Diag(PropertyLoc, diag::error_property_ivar_type)
1600          << property->getDeclName() << Ivar->getDeclName();
1601        return 0;
1602      }
1603    }
1604  } else if (PropertyIvar) {
1605    // @dynamic
1606    Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
1607    return 0;
1608  }
1609  assert (property && "ActOnPropertyImplDecl - property declaration missing");
1610  ObjCPropertyImplDecl *PIDecl =
1611    ObjCPropertyImplDecl::Create(Context, AtLoc, PropertyLoc, property,
1612                                 (Synthesize ?
1613                                  ObjCPropertyImplDecl::Synthesize
1614                                  : ObjCPropertyImplDecl::Dynamic),
1615                                 Ivar);
1616  if (IC) {
1617    if (Synthesize)
1618      if (ObjCPropertyImplDecl *PPIDecl =
1619          IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1620        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1621          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1622          << PropertyIvar;
1623        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1624      }
1625
1626    if (ObjCPropertyImplDecl *PPIDecl = IC->FindPropertyImplDecl(PropertyId)) {
1627      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1628      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1629      return 0;
1630    }
1631    IC->addPropertyImplementation(PIDecl);
1632  }
1633  else {
1634    if (Synthesize)
1635      if (ObjCPropertyImplDecl *PPIDecl =
1636          CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1637        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1638          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1639          << PropertyIvar;
1640        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1641      }
1642
1643    if (ObjCPropertyImplDecl *PPIDecl =
1644          CatImplClass->FindPropertyImplDecl(PropertyId)) {
1645      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1646      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1647      return 0;
1648    }
1649    CatImplClass->addPropertyImplementation(PIDecl);
1650  }
1651
1652  return PIDecl;
1653}
1654
1655bool Sema::CheckObjCDeclScope(Decl *D) {
1656  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1657    return false;
1658
1659  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1660  D->setInvalidDecl();
1661
1662  return true;
1663}
1664
1665/// Collect the instance variables declared in an Objective-C object.  Used in
1666/// the creation of structures from objects using the @defs directive.
1667/// FIXME: This should be consolidated with CollectObjCIvars as it is also
1668/// part of the AST generation logic of @defs.
1669static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
1670                         ASTContext& Ctx,
1671                         llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
1672  if (Class->getSuperClass())
1673    CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
1674
1675  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1676  for (ObjCInterfaceDecl::ivar_iterator
1677       I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1678
1679    ObjCIvarDecl* ID = *I;
1680    ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record,
1681                                                ID->getLocation(),
1682                                                ID->getIdentifier(),
1683                                                ID->getType(),
1684                                                ID->getBitWidth()));
1685  }
1686}
1687
1688/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1689/// instance variables of ClassName into Decls.
1690void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart,
1691                     IdentifierInfo *ClassName,
1692                     llvm::SmallVectorImpl<DeclTy*> &Decls) {
1693  // Check that ClassName is a valid class
1694  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1695  if (!Class) {
1696    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1697    return;
1698  }
1699  // Collect the instance variables
1700  CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls);
1701
1702  // Introduce all of these fields into the appropriate scope.
1703  for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin();
1704       D != Decls.end(); ++D) {
1705    FieldDecl *FD = cast<FieldDecl>((Decl*)*D);
1706    if (getLangOptions().CPlusPlus)
1707      PushOnScopeChains(cast<FieldDecl>(FD), S);
1708    else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD))
1709      Record->addDecl(Context, FD);
1710  }
1711}
1712
1713