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