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