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