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