SemaDeclObjC.cpp revision 781472fe99a120098c631b0cbe33c89f8cef5e70
1//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/ExternalSemaSource.h"
17#include "clang/Sema/Scope.h"
18#include "clang/Sema/ScopeInfo.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/Sema/DeclSpec.h"
23#include "llvm/ADT/DenseSet.h"
24
25using namespace clang;
26
27/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
28/// and user declared, in the method definition's AST.
29void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
30  assert(getCurMethodDecl() == 0 && "Method parsing confused");
31  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
32
33  // If we don't have a valid method decl, simply return.
34  if (!MDecl)
35    return;
36
37  // Allow the rest of sema to find private method decl implementations.
38  if (MDecl->isInstanceMethod())
39    AddInstanceMethodToGlobalPool(MDecl, true);
40  else
41    AddFactoryMethodToGlobalPool(MDecl, true);
42
43  // Allow all of Sema to see that we are entering a method definition.
44  PushDeclContext(FnBodyScope, MDecl);
45  PushFunctionScope();
46
47  // Create Decl objects for each parameter, entrring them in the scope for
48  // binding to their use.
49
50  // Insert the invisible arguments, self and _cmd!
51  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
52
53  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
54  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
55
56  // Introduce all of the other parameters into this scope.
57  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
58       E = MDecl->param_end(); PI != E; ++PI)
59    if ((*PI)->getIdentifier())
60      PushOnScopeChains(*PI, FnBodyScope);
61}
62
63Decl *Sema::
64ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
65                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
66                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
67                         Decl * const *ProtoRefs, unsigned NumProtoRefs,
68                         const SourceLocation *ProtoLocs,
69                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
70  assert(ClassName && "Missing class identifier");
71
72  // Check for another declaration kind with the same name.
73  NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
74                                         LookupOrdinaryName, ForRedeclaration);
75
76  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
77    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
78    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
79  }
80
81  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
82  if (IDecl) {
83    // Class already seen. Is it a forward declaration?
84    if (!IDecl->isForwardDecl()) {
85      IDecl->setInvalidDecl();
86      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
87      Diag(IDecl->getLocation(), diag::note_previous_definition);
88
89      // Return the previous class interface.
90      // FIXME: don't leak the objects passed in!
91      return IDecl;
92    } else {
93      IDecl->setLocation(AtInterfaceLoc);
94      IDecl->setForwardDecl(false);
95      IDecl->setClassLoc(ClassLoc);
96      // If the forward decl was in a PCH, we need to write it again in a
97      // dependent AST file.
98      IDecl->setChangedSinceDeserialization(true);
99
100      // Since this ObjCInterfaceDecl was created by a forward declaration,
101      // we now add it to the DeclContext since it wasn't added before
102      // (see ActOnForwardClassDeclaration).
103      IDecl->setLexicalDeclContext(CurContext);
104      CurContext->addDecl(IDecl);
105
106      if (AttrList)
107        ProcessDeclAttributeList(TUScope, IDecl, AttrList);
108    }
109  } else {
110    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
111                                      ClassName, ClassLoc);
112    if (AttrList)
113      ProcessDeclAttributeList(TUScope, IDecl, AttrList);
114
115    PushOnScopeChains(IDecl, TUScope);
116  }
117
118  if (SuperName) {
119    // Check if a different kind of symbol declared in this scope.
120    PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
121                                LookupOrdinaryName);
122
123    if (!PrevDecl) {
124      // Try to correct for a typo in the superclass name.
125      LookupResult R(*this, SuperName, SuperLoc, LookupOrdinaryName);
126      if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
127          (PrevDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
128        Diag(SuperLoc, diag::err_undef_superclass_suggest)
129          << SuperName << ClassName << PrevDecl->getDeclName();
130        Diag(PrevDecl->getLocation(), diag::note_previous_decl)
131          << PrevDecl->getDeclName();
132      }
133    }
134
135    if (PrevDecl == IDecl) {
136      Diag(SuperLoc, diag::err_recursive_superclass)
137        << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
138      IDecl->setLocEnd(ClassLoc);
139    } else {
140      ObjCInterfaceDecl *SuperClassDecl =
141                                dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
142
143      // Diagnose classes that inherit from deprecated classes.
144      if (SuperClassDecl)
145        (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
146
147      if (PrevDecl && SuperClassDecl == 0) {
148        // The previous declaration was not a class decl. Check if we have a
149        // typedef. If we do, get the underlying class type.
150        if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
151          QualType T = TDecl->getUnderlyingType();
152          if (T->isObjCObjectType()) {
153            if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
154              SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
155          }
156        }
157
158        // This handles the following case:
159        //
160        // typedef int SuperClass;
161        // @interface MyClass : SuperClass {} @end
162        //
163        if (!SuperClassDecl) {
164          Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
165          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
166        }
167      }
168
169      if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
170        if (!SuperClassDecl)
171          Diag(SuperLoc, diag::err_undef_superclass)
172            << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
173        else if (SuperClassDecl->isForwardDecl())
174          Diag(SuperLoc, diag::err_undef_superclass)
175            << SuperClassDecl->getDeclName() << ClassName
176            << SourceRange(AtInterfaceLoc, ClassLoc);
177      }
178      IDecl->setSuperClass(SuperClassDecl);
179      IDecl->setSuperClassLoc(SuperLoc);
180      IDecl->setLocEnd(SuperLoc);
181    }
182  } else { // we have a root class.
183    IDecl->setLocEnd(ClassLoc);
184  }
185
186  // Check then save referenced protocols.
187  if (NumProtoRefs) {
188    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
189                           ProtoLocs, Context);
190    IDecl->setLocEnd(EndProtoLoc);
191  }
192
193  CheckObjCDeclScope(IDecl);
194  return IDecl;
195}
196
197/// ActOnCompatiblityAlias - this action is called after complete parsing of
198/// @compatibility_alias declaration. It sets up the alias relationships.
199Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
200                                        IdentifierInfo *AliasName,
201                                        SourceLocation AliasLocation,
202                                        IdentifierInfo *ClassName,
203                                        SourceLocation ClassLocation) {
204  // Look for previous declaration of alias name
205  NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
206                                      LookupOrdinaryName, ForRedeclaration);
207  if (ADecl) {
208    if (isa<ObjCCompatibleAliasDecl>(ADecl))
209      Diag(AliasLocation, diag::warn_previous_alias_decl);
210    else
211      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
212    Diag(ADecl->getLocation(), diag::note_previous_declaration);
213    return 0;
214  }
215  // Check for class declaration
216  NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
217                                       LookupOrdinaryName, ForRedeclaration);
218  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
219    QualType T = TDecl->getUnderlyingType();
220    if (T->isObjCObjectType()) {
221      if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
222        ClassName = IDecl->getIdentifier();
223        CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
224                                  LookupOrdinaryName, ForRedeclaration);
225      }
226    }
227  }
228  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
229  if (CDecl == 0) {
230    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
231    if (CDeclU)
232      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
233    return 0;
234  }
235
236  // Everything checked out, instantiate a new alias declaration AST.
237  ObjCCompatibleAliasDecl *AliasDecl =
238    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
239
240  if (!CheckObjCDeclScope(AliasDecl))
241    PushOnScopeChains(AliasDecl, TUScope);
242
243  return AliasDecl;
244}
245
246void Sema::CheckForwardProtocolDeclarationForCircularDependency(
247  IdentifierInfo *PName,
248  SourceLocation &Ploc, SourceLocation PrevLoc,
249  const ObjCList<ObjCProtocolDecl> &PList) {
250  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
251       E = PList.end(); I != E; ++I) {
252
253    if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
254                                                 Ploc)) {
255      if (PDecl->getIdentifier() == PName) {
256        Diag(Ploc, diag::err_protocol_has_circular_dependency);
257        Diag(PrevLoc, diag::note_previous_definition);
258      }
259      CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
260        PDecl->getLocation(), PDecl->getReferencedProtocols());
261    }
262  }
263}
264
265Decl *
266Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
267                                  IdentifierInfo *ProtocolName,
268                                  SourceLocation ProtocolLoc,
269                                  Decl * const *ProtoRefs,
270                                  unsigned NumProtoRefs,
271                                  const SourceLocation *ProtoLocs,
272                                  SourceLocation EndProtoLoc,
273                                  AttributeList *AttrList) {
274  // FIXME: Deal with AttrList.
275  assert(ProtocolName && "Missing protocol identifier");
276  ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
277  if (PDecl) {
278    // Protocol already seen. Better be a forward protocol declaration
279    if (!PDecl->isForwardDecl()) {
280      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
281      Diag(PDecl->getLocation(), diag::note_previous_definition);
282      // Just return the protocol we already had.
283      // FIXME: don't leak the objects passed in!
284      return PDecl;
285    }
286    ObjCList<ObjCProtocolDecl> PList;
287    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
288    CheckForwardProtocolDeclarationForCircularDependency(
289      ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
290
291    // Make sure the cached decl gets a valid start location.
292    PDecl->setLocation(AtProtoInterfaceLoc);
293    PDecl->setForwardDecl(false);
294    CurContext->addDecl(PDecl);
295    // Repeat in dependent AST files.
296    PDecl->setChangedSinceDeserialization(true);
297  } else {
298    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
299                                     AtProtoInterfaceLoc,ProtocolName);
300    PushOnScopeChains(PDecl, TUScope);
301    PDecl->setForwardDecl(false);
302  }
303  if (AttrList)
304    ProcessDeclAttributeList(TUScope, PDecl, AttrList);
305  if (NumProtoRefs) {
306    /// Check then save referenced protocols.
307    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
308                           ProtoLocs, Context);
309    PDecl->setLocEnd(EndProtoLoc);
310  }
311
312  CheckObjCDeclScope(PDecl);
313  return PDecl;
314}
315
316/// FindProtocolDeclaration - This routine looks up protocols and
317/// issues an error if they are not declared. It returns list of
318/// protocol declarations in its 'Protocols' argument.
319void
320Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
321                              const IdentifierLocPair *ProtocolId,
322                              unsigned NumProtocols,
323                              llvm::SmallVectorImpl<Decl *> &Protocols) {
324  for (unsigned i = 0; i != NumProtocols; ++i) {
325    ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
326                                             ProtocolId[i].second);
327    if (!PDecl) {
328      LookupResult R(*this, ProtocolId[i].first, ProtocolId[i].second,
329                     LookupObjCProtocolName);
330      if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
331          (PDecl = R.getAsSingle<ObjCProtocolDecl>())) {
332        Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
333          << ProtocolId[i].first << R.getLookupName();
334        Diag(PDecl->getLocation(), diag::note_previous_decl)
335          << PDecl->getDeclName();
336      }
337    }
338
339    if (!PDecl) {
340      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
341        << ProtocolId[i].first;
342      continue;
343    }
344
345    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
346
347    // If this is a forward declaration and we are supposed to warn in this
348    // case, do it.
349    if (WarnOnDeclarations && PDecl->isForwardDecl())
350      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
351        << ProtocolId[i].first;
352    Protocols.push_back(PDecl);
353  }
354}
355
356/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
357/// a class method in its extension.
358///
359void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
360                                            ObjCInterfaceDecl *ID) {
361  if (!ID)
362    return;  // Possibly due to previous error
363
364  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
365  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
366       e =  ID->meth_end(); i != e; ++i) {
367    ObjCMethodDecl *MD = *i;
368    MethodMap[MD->getSelector()] = MD;
369  }
370
371  if (MethodMap.empty())
372    return;
373  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
374       e =  CAT->meth_end(); i != e; ++i) {
375    ObjCMethodDecl *Method = *i;
376    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
377    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
378      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
379            << Method->getDeclName();
380      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
381    }
382  }
383}
384
385/// ActOnForwardProtocolDeclaration - Handle @protocol foo;
386Decl *
387Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
388                                      const IdentifierLocPair *IdentList,
389                                      unsigned NumElts,
390                                      AttributeList *attrList) {
391  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
392  llvm::SmallVector<SourceLocation, 8> ProtoLocs;
393
394  for (unsigned i = 0; i != NumElts; ++i) {
395    IdentifierInfo *Ident = IdentList[i].first;
396    ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
397    bool isNew = false;
398    if (PDecl == 0) { // Not already seen?
399      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
400                                       IdentList[i].second, Ident);
401      PushOnScopeChains(PDecl, TUScope, false);
402      isNew = true;
403    }
404    if (attrList) {
405      ProcessDeclAttributeList(TUScope, PDecl, attrList);
406      if (!isNew)
407        PDecl->setChangedSinceDeserialization(true);
408    }
409    Protocols.push_back(PDecl);
410    ProtoLocs.push_back(IdentList[i].second);
411  }
412
413  ObjCForwardProtocolDecl *PDecl =
414    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
415                                    Protocols.data(), Protocols.size(),
416                                    ProtoLocs.data());
417  CurContext->addDecl(PDecl);
418  CheckObjCDeclScope(PDecl);
419  return PDecl;
420}
421
422Decl *Sema::
423ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
424                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
425                            IdentifierInfo *CategoryName,
426                            SourceLocation CategoryLoc,
427                            Decl * const *ProtoRefs,
428                            unsigned NumProtoRefs,
429                            const SourceLocation *ProtoLocs,
430                            SourceLocation EndProtoLoc) {
431  ObjCCategoryDecl *CDecl;
432  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
433
434  /// Check that class of this category is already completely declared.
435  if (!IDecl || IDecl->isForwardDecl()) {
436    // Create an invalid ObjCCategoryDecl to serve as context for
437    // the enclosing method declarations.  We mark the decl invalid
438    // to make it clear that this isn't a valid AST.
439    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
440                                     ClassLoc, CategoryLoc, CategoryName);
441    CDecl->setInvalidDecl();
442    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
443    return CDecl;
444  }
445
446  if (!CategoryName && IDecl->getImplementation()) {
447    Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
448    Diag(IDecl->getImplementation()->getLocation(),
449          diag::note_implementation_declared);
450  }
451
452  CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
453                                   ClassLoc, CategoryLoc, CategoryName);
454  // FIXME: PushOnScopeChains?
455  CurContext->addDecl(CDecl);
456
457  CDecl->setClassInterface(IDecl);
458  // Insert class extension to the list of class's categories.
459  if (!CategoryName)
460    CDecl->insertNextClassCategory();
461
462  // If the interface is deprecated, warn about it.
463  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
464
465  if (CategoryName) {
466    /// Check for duplicate interface declaration for this category
467    ObjCCategoryDecl *CDeclChain;
468    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
469         CDeclChain = CDeclChain->getNextClassCategory()) {
470      if (CDeclChain->getIdentifier() == CategoryName) {
471        // Class extensions can be declared multiple times.
472        Diag(CategoryLoc, diag::warn_dup_category_def)
473          << ClassName << CategoryName;
474        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
475        break;
476      }
477    }
478    if (!CDeclChain)
479      CDecl->insertNextClassCategory();
480  }
481
482  if (NumProtoRefs) {
483    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
484                           ProtoLocs, Context);
485    // Protocols in the class extension belong to the class.
486    if (CDecl->IsClassExtension())
487     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
488                                            NumProtoRefs, ProtoLocs,
489                                            Context);
490  }
491
492  CheckObjCDeclScope(CDecl);
493  return CDecl;
494}
495
496/// ActOnStartCategoryImplementation - Perform semantic checks on the
497/// category implementation declaration and build an ObjCCategoryImplDecl
498/// object.
499Decl *Sema::ActOnStartCategoryImplementation(
500                      SourceLocation AtCatImplLoc,
501                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
502                      IdentifierInfo *CatName, SourceLocation CatLoc) {
503  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
504  ObjCCategoryDecl *CatIDecl = 0;
505  if (IDecl) {
506    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
507    if (!CatIDecl) {
508      // Category @implementation with no corresponding @interface.
509      // Create and install one.
510      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
511                                          SourceLocation(), SourceLocation(),
512                                          CatName);
513      CatIDecl->setClassInterface(IDecl);
514      CatIDecl->insertNextClassCategory();
515    }
516  }
517
518  ObjCCategoryImplDecl *CDecl =
519    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
520                                 IDecl);
521  /// Check that class of this category is already completely declared.
522  if (!IDecl || IDecl->isForwardDecl())
523    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
524
525  // FIXME: PushOnScopeChains?
526  CurContext->addDecl(CDecl);
527
528  /// Check that CatName, category name, is not used in another implementation.
529  if (CatIDecl) {
530    if (CatIDecl->getImplementation()) {
531      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
532        << CatName;
533      Diag(CatIDecl->getImplementation()->getLocation(),
534           diag::note_previous_definition);
535    } else
536      CatIDecl->setImplementation(CDecl);
537  }
538
539  CheckObjCDeclScope(CDecl);
540  return CDecl;
541}
542
543Decl *Sema::ActOnStartClassImplementation(
544                      SourceLocation AtClassImplLoc,
545                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
546                      IdentifierInfo *SuperClassname,
547                      SourceLocation SuperClassLoc) {
548  ObjCInterfaceDecl* IDecl = 0;
549  // Check for another declaration kind with the same name.
550  NamedDecl *PrevDecl
551    = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
552                       ForRedeclaration);
553  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
554    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
555    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
556  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
557    // If this is a forward declaration of an interface, warn.
558    if (IDecl->isForwardDecl()) {
559      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
560      IDecl = 0;
561    }
562  } else {
563    // We did not find anything with the name ClassName; try to correct for
564    // typos in the class name.
565    LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
566    if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
567        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
568      // Suggest the (potentially) correct interface name. However, put the
569      // fix-it hint itself in a separate note, since changing the name in
570      // the warning would make the fix-it change semantics.However, don't
571      // provide a code-modification hint or use the typo name for recovery,
572      // because this is just a warning. The program may actually be correct.
573      Diag(ClassLoc, diag::warn_undef_interface_suggest)
574        << ClassName << R.getLookupName();
575      Diag(IDecl->getLocation(), diag::note_previous_decl)
576        << R.getLookupName()
577        << FixItHint::CreateReplacement(ClassLoc,
578                                        R.getLookupName().getAsString());
579      IDecl = 0;
580    } else {
581      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
582    }
583  }
584
585  // Check that super class name is valid class name
586  ObjCInterfaceDecl* SDecl = 0;
587  if (SuperClassname) {
588    // Check if a different kind of symbol declared in this scope.
589    PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
590                                LookupOrdinaryName);
591    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
592      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
593        << SuperClassname;
594      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
595    } else {
596      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
597      if (!SDecl)
598        Diag(SuperClassLoc, diag::err_undef_superclass)
599          << SuperClassname << ClassName;
600      else if (IDecl && IDecl->getSuperClass() != SDecl) {
601        // This implementation and its interface do not have the same
602        // super class.
603        Diag(SuperClassLoc, diag::err_conflicting_super_class)
604          << SDecl->getDeclName();
605        Diag(SDecl->getLocation(), diag::note_previous_definition);
606      }
607    }
608  }
609
610  if (!IDecl) {
611    // Legacy case of @implementation with no corresponding @interface.
612    // Build, chain & install the interface decl into the identifier.
613
614    // FIXME: Do we support attributes on the @implementation? If so we should
615    // copy them over.
616    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
617                                      ClassName, ClassLoc, false, true);
618    IDecl->setSuperClass(SDecl);
619    IDecl->setLocEnd(ClassLoc);
620
621    PushOnScopeChains(IDecl, TUScope);
622  } else {
623    // Mark the interface as being completed, even if it was just as
624    //   @class ....;
625    // declaration; the user cannot reopen it.
626    IDecl->setForwardDecl(false);
627  }
628
629  ObjCImplementationDecl* IMPDecl =
630    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
631                                   IDecl, SDecl);
632
633  if (CheckObjCDeclScope(IMPDecl))
634    return IMPDecl;
635
636  // Check that there is no duplicate implementation of this class.
637  if (IDecl->getImplementation()) {
638    // FIXME: Don't leak everything!
639    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
640    Diag(IDecl->getImplementation()->getLocation(),
641         diag::note_previous_definition);
642  } else { // add it to the list.
643    IDecl->setImplementation(IMPDecl);
644    PushOnScopeChains(IMPDecl, TUScope);
645  }
646  return IMPDecl;
647}
648
649void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
650                                    ObjCIvarDecl **ivars, unsigned numIvars,
651                                    SourceLocation RBrace) {
652  assert(ImpDecl && "missing implementation decl");
653  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
654  if (!IDecl)
655    return;
656  /// Check case of non-existing @interface decl.
657  /// (legacy objective-c @implementation decl without an @interface decl).
658  /// Add implementations's ivar to the synthesize class's ivar list.
659  if (IDecl->isImplicitInterfaceDecl()) {
660    IDecl->setLocEnd(RBrace);
661    // Add ivar's to class's DeclContext.
662    for (unsigned i = 0, e = numIvars; i != e; ++i) {
663      ivars[i]->setLexicalDeclContext(ImpDecl);
664      IDecl->makeDeclVisibleInContext(ivars[i], false);
665      ImpDecl->addDecl(ivars[i]);
666    }
667
668    return;
669  }
670  // If implementation has empty ivar list, just return.
671  if (numIvars == 0)
672    return;
673
674  assert(ivars && "missing @implementation ivars");
675  if (LangOpts.ObjCNonFragileABI2) {
676    if (ImpDecl->getSuperClass())
677      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
678    for (unsigned i = 0; i < numIvars; i++) {
679      ObjCIvarDecl* ImplIvar = ivars[i];
680      if (const ObjCIvarDecl *ClsIvar =
681            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
682        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
683        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
684        continue;
685      }
686      // Instance ivar to Implementation's DeclContext.
687      ImplIvar->setLexicalDeclContext(ImpDecl);
688      IDecl->makeDeclVisibleInContext(ImplIvar, false);
689      ImpDecl->addDecl(ImplIvar);
690    }
691    return;
692  }
693  // Check interface's Ivar list against those in the implementation.
694  // names and types must match.
695  //
696  unsigned j = 0;
697  ObjCInterfaceDecl::ivar_iterator
698    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
699  for (; numIvars > 0 && IVI != IVE; ++IVI) {
700    ObjCIvarDecl* ImplIvar = ivars[j++];
701    ObjCIvarDecl* ClsIvar = *IVI;
702    assert (ImplIvar && "missing implementation ivar");
703    assert (ClsIvar && "missing class ivar");
704
705    // First, make sure the types match.
706    if (Context.getCanonicalType(ImplIvar->getType()) !=
707        Context.getCanonicalType(ClsIvar->getType())) {
708      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
709        << ImplIvar->getIdentifier()
710        << ImplIvar->getType() << ClsIvar->getType();
711      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
712    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
713      Expr *ImplBitWidth = ImplIvar->getBitWidth();
714      Expr *ClsBitWidth = ClsIvar->getBitWidth();
715      if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
716          ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
717        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
718          << ImplIvar->getIdentifier();
719        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
720      }
721    }
722    // Make sure the names are identical.
723    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
724      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
725        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
726      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
727    }
728    --numIvars;
729  }
730
731  if (numIvars > 0)
732    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
733  else if (IVI != IVE)
734    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
735}
736
737void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
738                               bool &IncompleteImpl, unsigned DiagID) {
739  if (!IncompleteImpl) {
740    Diag(ImpLoc, diag::warn_incomplete_impl);
741    IncompleteImpl = true;
742  }
743  Diag(method->getLocation(), DiagID)
744    << method->getDeclName();
745}
746
747void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
748                                       ObjCMethodDecl *IntfMethodDecl) {
749  if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(),
750                                  ImpMethodDecl->getResultType()) &&
751      !Context.QualifiedIdConformsQualifiedId(IntfMethodDecl->getResultType(),
752                                              ImpMethodDecl->getResultType())) {
753    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types)
754      << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType()
755      << ImpMethodDecl->getResultType();
756    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
757  }
758
759  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
760       IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
761       IM != EM; ++IM, ++IF) {
762    QualType ParmDeclTy = (*IF)->getType().getUnqualifiedType();
763    QualType ParmImpTy = (*IM)->getType().getUnqualifiedType();
764    if (Context.typesAreCompatible(ParmDeclTy, ParmImpTy) ||
765        Context.QualifiedIdConformsQualifiedId(ParmDeclTy, ParmImpTy))
766      continue;
767
768    Diag((*IM)->getLocation(), diag::warn_conflicting_param_types)
769      << ImpMethodDecl->getDeclName() << (*IF)->getType()
770      << (*IM)->getType();
771    Diag((*IF)->getLocation(), diag::note_previous_definition);
772  }
773  if (ImpMethodDecl->isVariadic() != IntfMethodDecl->isVariadic()) {
774    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic);
775    Diag(IntfMethodDecl->getLocation(), diag::note_previous_declaration);
776  }
777}
778
779/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
780/// improve the efficiency of selector lookups and type checking by associating
781/// with each protocol / interface / category the flattened instance tables. If
782/// we used an immutable set to keep the table then it wouldn't add significant
783/// memory cost and it would be handy for lookups.
784
785/// CheckProtocolMethodDefs - This routine checks unimplemented methods
786/// Declared in protocol, and those referenced by it.
787void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
788                                   ObjCProtocolDecl *PDecl,
789                                   bool& IncompleteImpl,
790                                   const llvm::DenseSet<Selector> &InsMap,
791                                   const llvm::DenseSet<Selector> &ClsMap,
792                                   ObjCContainerDecl *CDecl) {
793  ObjCInterfaceDecl *IDecl;
794  if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
795    IDecl = C->getClassInterface();
796  else
797    IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
798  assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
799
800  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
801  ObjCInterfaceDecl *NSIDecl = 0;
802  if (getLangOptions().NeXTRuntime) {
803    // check to see if class implements forwardInvocation method and objects
804    // of this class are derived from 'NSProxy' so that to forward requests
805    // from one object to another.
806    // Under such conditions, which means that every method possible is
807    // implemented in the class, we should not issue "Method definition not
808    // found" warnings.
809    // FIXME: Use a general GetUnarySelector method for this.
810    IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
811    Selector fISelector = Context.Selectors.getSelector(1, &II);
812    if (InsMap.count(fISelector))
813      // Is IDecl derived from 'NSProxy'? If so, no instance methods
814      // need be implemented in the implementation.
815      NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
816  }
817
818  // If a method lookup fails locally we still need to look and see if
819  // the method was implemented by a base class or an inherited
820  // protocol. This lookup is slow, but occurs rarely in correct code
821  // and otherwise would terminate in a warning.
822
823  // check unimplemented instance methods.
824  if (!NSIDecl)
825    for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
826         E = PDecl->instmeth_end(); I != E; ++I) {
827      ObjCMethodDecl *method = *I;
828      if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
829          !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
830          (!Super ||
831           !Super->lookupInstanceMethod(method->getSelector()))) {
832            // Ugly, but necessary. Method declared in protcol might have
833            // have been synthesized due to a property declared in the class which
834            // uses the protocol.
835            ObjCMethodDecl *MethodInClass =
836            IDecl->lookupInstanceMethod(method->getSelector());
837            if (!MethodInClass || !MethodInClass->isSynthesized()) {
838              unsigned DIAG = diag::warn_unimplemented_protocol_method;
839              if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
840                WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
841                Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
842                  << PDecl->getDeclName();
843              }
844            }
845          }
846    }
847  // check unimplemented class methods
848  for (ObjCProtocolDecl::classmeth_iterator
849         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
850       I != E; ++I) {
851    ObjCMethodDecl *method = *I;
852    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
853        !ClsMap.count(method->getSelector()) &&
854        (!Super || !Super->lookupClassMethod(method->getSelector()))) {
855      unsigned DIAG = diag::warn_unimplemented_protocol_method;
856      if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
857        WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
858        Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
859          PDecl->getDeclName();
860      }
861    }
862  }
863  // Check on this protocols's referenced protocols, recursively.
864  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
865       E = PDecl->protocol_end(); PI != E; ++PI)
866    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
867}
868
869/// MatchAllMethodDeclarations - Check methods declaraed in interface or
870/// or protocol against those declared in their implementations.
871///
872void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
873                                      const llvm::DenseSet<Selector> &ClsMap,
874                                      llvm::DenseSet<Selector> &InsMapSeen,
875                                      llvm::DenseSet<Selector> &ClsMapSeen,
876                                      ObjCImplDecl* IMPDecl,
877                                      ObjCContainerDecl* CDecl,
878                                      bool &IncompleteImpl,
879                                      bool ImmediateClass) {
880  // Check and see if instance methods in class interface have been
881  // implemented in the implementation class. If so, their types match.
882  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
883       E = CDecl->instmeth_end(); I != E; ++I) {
884    if (InsMapSeen.count((*I)->getSelector()))
885        continue;
886    InsMapSeen.insert((*I)->getSelector());
887    if (!(*I)->isSynthesized() &&
888        !InsMap.count((*I)->getSelector())) {
889      if (ImmediateClass)
890        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
891                            diag::note_undef_method_impl);
892      continue;
893    } else {
894      ObjCMethodDecl *ImpMethodDecl =
895      IMPDecl->getInstanceMethod((*I)->getSelector());
896      ObjCMethodDecl *IntfMethodDecl =
897      CDecl->getInstanceMethod((*I)->getSelector());
898      assert(IntfMethodDecl &&
899             "IntfMethodDecl is null in ImplMethodsVsClassMethods");
900      // ImpMethodDecl may be null as in a @dynamic property.
901      if (ImpMethodDecl)
902        WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
903    }
904  }
905
906  // Check and see if class methods in class interface have been
907  // implemented in the implementation class. If so, their types match.
908   for (ObjCInterfaceDecl::classmeth_iterator
909       I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
910     if (ClsMapSeen.count((*I)->getSelector()))
911       continue;
912     ClsMapSeen.insert((*I)->getSelector());
913    if (!ClsMap.count((*I)->getSelector())) {
914      if (ImmediateClass)
915        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
916                            diag::note_undef_method_impl);
917    } else {
918      ObjCMethodDecl *ImpMethodDecl =
919        IMPDecl->getClassMethod((*I)->getSelector());
920      ObjCMethodDecl *IntfMethodDecl =
921        CDecl->getClassMethod((*I)->getSelector());
922      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
923    }
924  }
925  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
926    // Check for any implementation of a methods declared in protocol.
927    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
928         E = I->protocol_end(); PI != E; ++PI)
929      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
930                                 IMPDecl,
931                                 (*PI), IncompleteImpl, false);
932    if (I->getSuperClass())
933      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
934                                 IMPDecl,
935                                 I->getSuperClass(), IncompleteImpl, false);
936  }
937}
938
939void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
940                                     ObjCContainerDecl* CDecl,
941                                     bool IncompleteImpl) {
942  llvm::DenseSet<Selector> InsMap;
943  // Check and see if instance methods in class interface have been
944  // implemented in the implementation class.
945  for (ObjCImplementationDecl::instmeth_iterator
946         I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
947    InsMap.insert((*I)->getSelector());
948
949  // Check and see if properties declared in the interface have either 1)
950  // an implementation or 2) there is a @synthesize/@dynamic implementation
951  // of the property in the @implementation.
952  if (isa<ObjCInterfaceDecl>(CDecl) && !LangOpts.ObjCNonFragileABI2)
953    DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
954
955  llvm::DenseSet<Selector> ClsMap;
956  for (ObjCImplementationDecl::classmeth_iterator
957       I = IMPDecl->classmeth_begin(),
958       E = IMPDecl->classmeth_end(); I != E; ++I)
959    ClsMap.insert((*I)->getSelector());
960
961  // Check for type conflict of methods declared in a class/protocol and
962  // its implementation; if any.
963  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
964  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
965                             IMPDecl, CDecl,
966                             IncompleteImpl, true);
967
968  // Check the protocol list for unimplemented methods in the @implementation
969  // class.
970  // Check and see if class methods in class interface have been
971  // implemented in the implementation class.
972
973  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
974    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
975         E = I->protocol_end(); PI != E; ++PI)
976      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
977                              InsMap, ClsMap, I);
978    // Check class extensions (unnamed categories)
979    for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
980         Categories; Categories = Categories->getNextClassExtension())
981      ImplMethodsVsClassMethods(S, IMPDecl,
982                                const_cast<ObjCCategoryDecl*>(Categories),
983                                IncompleteImpl);
984  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
985    // For extended class, unimplemented methods in its protocols will
986    // be reported in the primary class.
987    if (!C->IsClassExtension()) {
988      for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
989           E = C->protocol_end(); PI != E; ++PI)
990        CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
991                                InsMap, ClsMap, CDecl);
992      // Report unimplemented properties in the category as well.
993      // When reporting on missing setter/getters, do not report when
994      // setter/getter is implemented in category's primary class
995      // implementation.
996      if (ObjCInterfaceDecl *ID = C->getClassInterface())
997        if (ObjCImplDecl *IMP = ID->getImplementation()) {
998          for (ObjCImplementationDecl::instmeth_iterator
999               I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1000            InsMap.insert((*I)->getSelector());
1001        }
1002      DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1003    }
1004  } else
1005    assert(false && "invalid ObjCContainerDecl type.");
1006}
1007
1008/// ActOnForwardClassDeclaration -
1009Decl *
1010Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1011                                   IdentifierInfo **IdentList,
1012                                   SourceLocation *IdentLocs,
1013                                   unsigned NumElts) {
1014  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1015
1016  for (unsigned i = 0; i != NumElts; ++i) {
1017    // Check for another declaration kind with the same name.
1018    NamedDecl *PrevDecl
1019      = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1020                         LookupOrdinaryName, ForRedeclaration);
1021    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1022      // Maybe we will complain about the shadowed template parameter.
1023      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1024      // Just pretend that we didn't see the previous declaration.
1025      PrevDecl = 0;
1026    }
1027
1028    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1029      // GCC apparently allows the following idiom:
1030      //
1031      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1032      // @class XCElementToggler;
1033      //
1034      // FIXME: Make an extension?
1035      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1036      if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1037        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1038        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1039      } else {
1040        // a forward class declaration matching a typedef name of a class refers
1041        // to the underlying class.
1042        if (const ObjCObjectType *OI =
1043              TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1044          PrevDecl = OI->getInterface();
1045      }
1046    }
1047    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1048    if (!IDecl) {  // Not already seen?  Make a forward decl.
1049      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1050                                        IdentList[i], IdentLocs[i], true);
1051
1052      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1053      // the current DeclContext.  This prevents clients that walk DeclContext
1054      // from seeing the imaginary ObjCInterfaceDecl until it is actually
1055      // declared later (if at all).  We also take care to explicitly make
1056      // sure this declaration is visible for name lookup.
1057      PushOnScopeChains(IDecl, TUScope, false);
1058      CurContext->makeDeclVisibleInContext(IDecl, true);
1059    }
1060
1061    Interfaces.push_back(IDecl);
1062  }
1063
1064  assert(Interfaces.size() == NumElts);
1065  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1066                                               Interfaces.data(), IdentLocs,
1067                                               Interfaces.size());
1068  CurContext->addDecl(CDecl);
1069  CheckObjCDeclScope(CDecl);
1070  return CDecl;
1071}
1072
1073
1074/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1075/// returns true, or false, accordingly.
1076/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1077bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1078                                      const ObjCMethodDecl *PrevMethod,
1079                                      bool matchBasedOnSizeAndAlignment,
1080                                      bool matchBasedOnStrictEqulity) {
1081  QualType T1 = Context.getCanonicalType(Method->getResultType());
1082  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1083
1084  if (T1 != T2) {
1085    // The result types are different.
1086    if (!matchBasedOnSizeAndAlignment || matchBasedOnStrictEqulity)
1087      return false;
1088    // Incomplete types don't have a size and alignment.
1089    if (T1->isIncompleteType() || T2->isIncompleteType())
1090      return false;
1091    // Check is based on size and alignment.
1092    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1093      return false;
1094  }
1095
1096  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1097       E = Method->param_end();
1098  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1099
1100  for (; ParamI != E; ++ParamI, ++PrevI) {
1101    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1102    T1 = Context.getCanonicalType((*ParamI)->getType());
1103    T2 = Context.getCanonicalType((*PrevI)->getType());
1104    if (T1 != T2) {
1105      // The result types are different.
1106      if (!matchBasedOnSizeAndAlignment || matchBasedOnStrictEqulity)
1107        return false;
1108      // Incomplete types don't have a size and alignment.
1109      if (T1->isIncompleteType() || T2->isIncompleteType())
1110        return false;
1111      // Check is based on size and alignment.
1112      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1113        return false;
1114    }
1115  }
1116  return true;
1117}
1118
1119/// \brief Read the contents of the method pool for a given selector from
1120/// external storage.
1121///
1122/// This routine should only be called once, when the method pool has no entry
1123/// for this selector.
1124Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
1125  assert(ExternalSource && "We need an external AST source");
1126  assert(MethodPool.find(Sel) == MethodPool.end() &&
1127         "Selector data already loaded into the method pool");
1128
1129  // Read the method list from the external source.
1130  GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
1131
1132  return MethodPool.insert(std::make_pair(Sel, Methods)).first;
1133}
1134
1135void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
1136                                 bool instance) {
1137  GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
1138  if (Pos == MethodPool.end()) {
1139    if (ExternalSource)
1140      Pos = ReadMethodPool(Method->getSelector());
1141    else
1142      Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
1143                                             GlobalMethods())).first;
1144  }
1145  Method->setDefined(impl);
1146  ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
1147  if (Entry.Method == 0) {
1148    // Haven't seen a method with this selector name yet - add it.
1149    Entry.Method = Method;
1150    Entry.Next = 0;
1151    return;
1152  }
1153
1154  // We've seen a method with this name, see if we have already seen this type
1155  // signature.
1156  for (ObjCMethodList *List = &Entry; List; List = List->Next)
1157    if (MatchTwoMethodDeclarations(Method, List->Method)) {
1158      List->Method->setDefined(impl);
1159      return;
1160    }
1161
1162  // We have a new signature for an existing method - add it.
1163  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1164  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1165  Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1166}
1167
1168ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1169                                               bool receiverIdOrClass,
1170                                               bool warn, bool instance) {
1171  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1172  if (Pos == MethodPool.end()) {
1173    if (ExternalSource)
1174      Pos = ReadMethodPool(Sel);
1175    else
1176      return 0;
1177  }
1178
1179  ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
1180
1181  bool strictSelectorMatch = receiverIdOrClass && warn &&
1182    (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl) !=
1183      Diagnostic::Ignored);
1184  if (warn && MethList.Method && MethList.Next) {
1185    bool issueWarning = false;
1186    if (strictSelectorMatch)
1187      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
1188        // This checks if the methods differ in type mismatch.
1189        if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, false, true))
1190          issueWarning = true;
1191      }
1192
1193    if (!issueWarning)
1194      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
1195        // This checks if the methods differ by size & alignment.
1196        if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1197          issueWarning = true;
1198      }
1199
1200    if (issueWarning) {
1201      if (strictSelectorMatch)
1202        Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
1203      else
1204        Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1205      Diag(MethList.Method->getLocStart(), diag::note_using)
1206        << MethList.Method->getSourceRange();
1207      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1208        Diag(Next->Method->getLocStart(), diag::note_also_found)
1209          << Next->Method->getSourceRange();
1210    }
1211  }
1212  return MethList.Method;
1213}
1214
1215ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
1216  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1217  if (Pos == MethodPool.end())
1218    return 0;
1219
1220  GlobalMethods &Methods = Pos->second;
1221
1222  if (Methods.first.Method && Methods.first.Method->isDefined())
1223    return Methods.first.Method;
1224  if (Methods.second.Method && Methods.second.Method->isDefined())
1225    return Methods.second.Method;
1226  return 0;
1227}
1228
1229/// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1230/// identical selector names in current and its super classes and issues
1231/// a warning if any of their argument types are incompatible.
1232void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1233                                             ObjCMethodDecl *Method,
1234                                             bool IsInstance)  {
1235  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1236  if (ID == 0) return;
1237
1238  while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1239    ObjCMethodDecl *SuperMethodDecl =
1240        SD->lookupMethod(Method->getSelector(), IsInstance);
1241    if (SuperMethodDecl == 0) {
1242      ID = SD;
1243      continue;
1244    }
1245    ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1246      E = Method->param_end();
1247    ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1248    for (; ParamI != E; ++ParamI, ++PrevI) {
1249      // Number of parameters are the same and is guaranteed by selector match.
1250      assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1251      QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1252      QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1253      // If type of arguement of method in this class does not match its
1254      // respective argument type in the super class method, issue warning;
1255      if (!Context.typesAreCompatible(T1, T2)) {
1256        Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1257          << T1 << T2;
1258        Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1259        return;
1260      }
1261    }
1262    ID = SD;
1263  }
1264}
1265
1266/// DiagnoseDuplicateIvars -
1267/// Check for duplicate ivars in the entire class at the start of
1268/// @implementation. This becomes necesssary because class extension can
1269/// add ivars to a class in random order which will not be known until
1270/// class's @implementation is seen.
1271void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
1272                                  ObjCInterfaceDecl *SID) {
1273  for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
1274       IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
1275    ObjCIvarDecl* Ivar = (*IVI);
1276    if (Ivar->isInvalidDecl())
1277      continue;
1278    if (IdentifierInfo *II = Ivar->getIdentifier()) {
1279      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
1280      if (prevIvar) {
1281        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
1282        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
1283        Ivar->setInvalidDecl();
1284      }
1285    }
1286  }
1287}
1288
1289// Note: For class/category implemenations, allMethods/allProperties is
1290// always null.
1291void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
1292                      Decl *ClassDecl,
1293                      Decl **allMethods, unsigned allNum,
1294                      Decl **allProperties, unsigned pNum,
1295                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1296  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1297  // always passing in a decl. If the decl has an error, isInvalidDecl()
1298  // should be true.
1299  if (!ClassDecl)
1300    return;
1301
1302  bool isInterfaceDeclKind =
1303        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1304         || isa<ObjCProtocolDecl>(ClassDecl);
1305  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1306
1307  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1308    // FIXME: This is wrong.  We shouldn't be pretending that there is
1309    //  an '@end' in the declaration.
1310    SourceLocation L = ClassDecl->getLocation();
1311    AtEnd.setBegin(L);
1312    AtEnd.setEnd(L);
1313    Diag(L, diag::warn_missing_atend);
1314  }
1315
1316  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1317
1318  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1319  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1320  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1321
1322  for (unsigned i = 0; i < allNum; i++ ) {
1323    ObjCMethodDecl *Method =
1324      cast_or_null<ObjCMethodDecl>(allMethods[i]);
1325
1326    if (!Method) continue;  // Already issued a diagnostic.
1327    if (Method->isInstanceMethod()) {
1328      /// Check for instance method of the same name with incompatible types
1329      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1330      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1331                              : false;
1332      if ((isInterfaceDeclKind && PrevMethod && !match)
1333          || (checkIdenticalMethods && match)) {
1334          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1335            << Method->getDeclName();
1336          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1337      } else {
1338        DC->addDecl(Method);
1339        InsMap[Method->getSelector()] = Method;
1340        /// The following allows us to typecheck messages to "id".
1341        AddInstanceMethodToGlobalPool(Method);
1342        // verify that the instance method conforms to the same definition of
1343        // parent methods if it shadows one.
1344        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1345      }
1346    } else {
1347      /// Check for class method of the same name with incompatible types
1348      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1349      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1350                              : false;
1351      if ((isInterfaceDeclKind && PrevMethod && !match)
1352          || (checkIdenticalMethods && match)) {
1353        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1354          << Method->getDeclName();
1355        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1356      } else {
1357        DC->addDecl(Method);
1358        ClsMap[Method->getSelector()] = Method;
1359        /// The following allows us to typecheck messages to "Class".
1360        AddFactoryMethodToGlobalPool(Method);
1361        // verify that the class method conforms to the same definition of
1362        // parent methods if it shadows one.
1363        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1364      }
1365    }
1366  }
1367  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1368    // Compares properties declared in this class to those of its
1369    // super class.
1370    ComparePropertiesInBaseAndSuper(I);
1371    CompareProperties(I, I);
1372  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1373    // Categories are used to extend the class by declaring new methods.
1374    // By the same token, they are also used to add new properties. No
1375    // need to compare the added property to those in the class.
1376
1377    // Compare protocol properties with those in category
1378    CompareProperties(C, C);
1379    if (C->IsClassExtension())
1380      DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1381  }
1382  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1383    if (CDecl->getIdentifier())
1384      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1385      // user-defined setter/getter. It also synthesizes setter/getter methods
1386      // and adds them to the DeclContext and global method pools.
1387      for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1388                                            E = CDecl->prop_end();
1389           I != E; ++I)
1390        ProcessPropertyDecl(*I, CDecl);
1391    CDecl->setAtEndRange(AtEnd);
1392  }
1393  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1394    IC->setAtEndRange(AtEnd);
1395    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1396      if (LangOpts.ObjCNonFragileABI2)
1397        DefaultSynthesizeProperties(S, IC, IDecl);
1398      ImplMethodsVsClassMethods(S, IC, IDecl);
1399      AtomicPropertySetterGetterRules(IC, IDecl);
1400
1401      if (LangOpts.ObjCNonFragileABI2)
1402        while (IDecl->getSuperClass()) {
1403          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
1404          IDecl = IDecl->getSuperClass();
1405        }
1406    }
1407    SetIvarInitializers(IC);
1408  } else if (ObjCCategoryImplDecl* CatImplClass =
1409                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1410    CatImplClass->setAtEndRange(AtEnd);
1411
1412    // Find category interface decl and then check that all methods declared
1413    // in this interface are implemented in the category @implementation.
1414    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1415      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1416           Categories; Categories = Categories->getNextClassCategory()) {
1417        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1418          ImplMethodsVsClassMethods(S, CatImplClass, Categories);
1419          break;
1420        }
1421      }
1422    }
1423  }
1424  if (isInterfaceDeclKind) {
1425    // Reject invalid vardecls.
1426    for (unsigned i = 0; i != tuvNum; i++) {
1427      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1428      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1429        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1430          if (!VDecl->hasExternalStorage())
1431            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1432        }
1433    }
1434  }
1435}
1436
1437
1438/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1439/// objective-c's type qualifier from the parser version of the same info.
1440static Decl::ObjCDeclQualifier
1441CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1442  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1443  if (PQTVal & ObjCDeclSpec::DQ_In)
1444    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1445  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1446    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1447  if (PQTVal & ObjCDeclSpec::DQ_Out)
1448    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1449  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1450    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1451  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1452    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1453  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1454    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1455
1456  return ret;
1457}
1458
1459static inline
1460bool containsInvalidMethodImplAttribute(const AttrVec &A) {
1461  // The 'ibaction' attribute is allowed on method definitions because of
1462  // how the IBAction macro is used on both method declarations and definitions.
1463  // If the method definitions contains any other attributes, return true.
1464  for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
1465    if ((*i)->getKind() != attr::IBAction)
1466      return true;
1467  return false;
1468}
1469
1470Decl *Sema::ActOnMethodDeclaration(
1471    SourceLocation MethodLoc, SourceLocation EndLoc,
1472    tok::TokenKind MethodType, Decl *ClassDecl,
1473    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
1474    Selector Sel,
1475    // optional arguments. The number of types/arguments is obtained
1476    // from the Sel.getNumArgs().
1477    ObjCArgInfo *ArgInfo,
1478    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
1479    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1480    bool isVariadic) {
1481  // Make sure we can establish a context for the method.
1482  if (!ClassDecl) {
1483    Diag(MethodLoc, diag::error_missing_method_context);
1484    getCurFunction()->LabelMap.clear();
1485    return 0;
1486  }
1487  QualType resultDeclType;
1488
1489  TypeSourceInfo *ResultTInfo = 0;
1490  if (ReturnType) {
1491    resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
1492
1493    // Methods cannot return interface types. All ObjC objects are
1494    // passed by reference.
1495    if (resultDeclType->isObjCObjectType()) {
1496      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1497        << 0 << resultDeclType;
1498      return 0;
1499    }
1500  } else // get the type for "id".
1501    resultDeclType = Context.getObjCIdType();
1502
1503  ObjCMethodDecl* ObjCMethod =
1504    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1505                           ResultTInfo,
1506                           cast<DeclContext>(ClassDecl),
1507                           MethodType == tok::minus, isVariadic,
1508                           false, false,
1509                           MethodDeclKind == tok::objc_optional ?
1510                           ObjCMethodDecl::Optional :
1511                           ObjCMethodDecl::Required);
1512
1513  llvm::SmallVector<ParmVarDecl*, 16> Params;
1514
1515  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1516    QualType ArgType;
1517    TypeSourceInfo *DI;
1518
1519    if (ArgInfo[i].Type == 0) {
1520      ArgType = Context.getObjCIdType();
1521      DI = 0;
1522    } else {
1523      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1524      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1525      ArgType = adjustParameterType(ArgType);
1526    }
1527
1528    ParmVarDecl* Param
1529      = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc,
1530                            ArgInfo[i].Name, ArgType, DI,
1531                            VarDecl::None, VarDecl::None, 0);
1532
1533    if (ArgType->isObjCObjectType()) {
1534      Diag(ArgInfo[i].NameLoc,
1535           diag::err_object_cannot_be_passed_returned_by_value)
1536        << 1 << ArgType;
1537      Param->setInvalidDecl();
1538    }
1539
1540    Param->setObjCDeclQualifier(
1541      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1542
1543    // Apply the attributes to the parameter.
1544    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
1545
1546    Params.push_back(Param);
1547  }
1548
1549  for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
1550    ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
1551    QualType ArgType = Param->getType();
1552    if (ArgType.isNull())
1553      ArgType = Context.getObjCIdType();
1554    else
1555      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1556      ArgType = adjustParameterType(ArgType);
1557    if (ArgType->isObjCObjectType()) {
1558      Diag(Param->getLocation(),
1559           diag::err_object_cannot_be_passed_returned_by_value)
1560      << 1 << ArgType;
1561      Param->setInvalidDecl();
1562    }
1563    Param->setDeclContext(ObjCMethod);
1564    if (Param->getDeclName())
1565      IdResolver.RemoveDecl(Param);
1566    Params.push_back(Param);
1567  }
1568
1569  ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
1570                              Sel.getNumArgs());
1571  ObjCMethod->setObjCDeclQualifier(
1572    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1573  const ObjCMethodDecl *PrevMethod = 0;
1574
1575  if (AttrList)
1576    ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
1577
1578  const ObjCMethodDecl *InterfaceMD = 0;
1579
1580  // For implementations (which can be very "coarse grain"), we add the
1581  // method now. This allows the AST to implement lookup methods that work
1582  // incrementally (without waiting until we parse the @end). It also allows
1583  // us to flag multiple declaration errors as they occur.
1584  if (ObjCImplementationDecl *ImpDecl =
1585        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1586    if (MethodType == tok::minus) {
1587      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1588      ImpDecl->addInstanceMethod(ObjCMethod);
1589    } else {
1590      PrevMethod = ImpDecl->getClassMethod(Sel);
1591      ImpDecl->addClassMethod(ObjCMethod);
1592    }
1593    InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
1594                                                   MethodType == tok::minus);
1595    if (ObjCMethod->hasAttrs() &&
1596        containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
1597      Diag(EndLoc, diag::warn_attribute_method_def);
1598  } else if (ObjCCategoryImplDecl *CatImpDecl =
1599             dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1600    if (MethodType == tok::minus) {
1601      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1602      CatImpDecl->addInstanceMethod(ObjCMethod);
1603    } else {
1604      PrevMethod = CatImpDecl->getClassMethod(Sel);
1605      CatImpDecl->addClassMethod(ObjCMethod);
1606    }
1607    if (ObjCMethod->hasAttrs() &&
1608        containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
1609      Diag(EndLoc, diag::warn_attribute_method_def);
1610  }
1611  if (PrevMethod) {
1612    // You can never have two method definitions with the same name.
1613    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1614      << ObjCMethod->getDeclName();
1615    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1616  }
1617
1618  // If the interface declared this method, and it was deprecated there,
1619  // mark it deprecated here.
1620  if (InterfaceMD)
1621   if (Attr *DA = InterfaceMD->getAttr<DeprecatedAttr>())
1622    ObjCMethod->addAttr(::new (Context) DeprecatedAttr(DA->getLocation(),
1623                                                       Context));
1624
1625  return ObjCMethod;
1626}
1627
1628bool Sema::CheckObjCDeclScope(Decl *D) {
1629  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1630    return false;
1631
1632  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1633  D->setInvalidDecl();
1634
1635  return true;
1636}
1637
1638/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1639/// instance variables of ClassName into Decls.
1640void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1641                     IdentifierInfo *ClassName,
1642                     llvm::SmallVectorImpl<Decl*> &Decls) {
1643  // Check that ClassName is a valid class
1644  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
1645  if (!Class) {
1646    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1647    return;
1648  }
1649  if (LangOpts.ObjCNonFragileABI) {
1650    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
1651    return;
1652  }
1653
1654  // Collect the instance variables
1655  llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
1656  Context.DeepCollectObjCIvars(Class, true, Ivars);
1657  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1658  for (unsigned i = 0; i < Ivars.size(); i++) {
1659    FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
1660    RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
1661    Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, ID->getLocation(),
1662                                           ID->getIdentifier(), ID->getType(),
1663                                           ID->getBitWidth());
1664    Decls.push_back(FD);
1665  }
1666
1667  // Introduce all of these fields into the appropriate scope.
1668  for (llvm::SmallVectorImpl<Decl*>::iterator D = Decls.begin();
1669       D != Decls.end(); ++D) {
1670    FieldDecl *FD = cast<FieldDecl>(*D);
1671    if (getLangOptions().CPlusPlus)
1672      PushOnScopeChains(cast<FieldDecl>(FD), S);
1673    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
1674      Record->addDecl(FD);
1675  }
1676}
1677
1678/// \brief Build a type-check a new Objective-C exception variable declaration.
1679VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo,
1680                                      QualType T,
1681                                      IdentifierInfo *Name,
1682                                      SourceLocation NameLoc,
1683                                      bool Invalid) {
1684  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
1685  // duration shall not be qualified by an address-space qualifier."
1686  // Since all parameters have automatic store duration, they can not have
1687  // an address space.
1688  if (T.getAddressSpace() != 0) {
1689    Diag(NameLoc, diag::err_arg_with_address_space);
1690    Invalid = true;
1691  }
1692
1693  // An @catch parameter must be an unqualified object pointer type;
1694  // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
1695  if (Invalid) {
1696    // Don't do any further checking.
1697  } else if (T->isDependentType()) {
1698    // Okay: we don't know what this type will instantiate to.
1699  } else if (!T->isObjCObjectPointerType()) {
1700    Invalid = true;
1701    Diag(NameLoc ,diag::err_catch_param_not_objc_type);
1702  } else if (T->isObjCQualifiedIdType()) {
1703    Invalid = true;
1704    Diag(NameLoc, diag::err_illegal_qualifiers_on_catch_parm);
1705  }
1706
1707  VarDecl *New = VarDecl::Create(Context, CurContext, NameLoc, Name, T, TInfo,
1708                                 VarDecl::None, VarDecl::None);
1709  New->setExceptionVariable(true);
1710
1711  if (Invalid)
1712    New->setInvalidDecl();
1713  return New;
1714}
1715
1716Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
1717  const DeclSpec &DS = D.getDeclSpec();
1718
1719  // We allow the "register" storage class on exception variables because
1720  // GCC did, but we drop it completely. Any other storage class is an error.
1721  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1722    Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
1723      << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
1724  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
1725    Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
1726      << DS.getStorageClassSpec();
1727  }
1728  if (D.getDeclSpec().isThreadSpecified())
1729    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
1730  D.getMutableDeclSpec().ClearStorageClassSpecs();
1731
1732  DiagnoseFunctionSpecifiers(D);
1733
1734  // Check that there are no default arguments inside the type of this
1735  // exception object (C++ only).
1736  if (getLangOptions().CPlusPlus)
1737    CheckExtraCXXDefaultArguments(D);
1738
1739  TagDecl *OwnedDecl = 0;
1740  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
1741  QualType ExceptionType = TInfo->getType();
1742
1743  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
1744    // Objective-C++: Types shall not be defined in exception types.
1745    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
1746      << Context.getTypeDeclType(OwnedDecl);
1747  }
1748
1749  VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, D.getIdentifier(),
1750                                        D.getIdentifierLoc(),
1751                                        D.isInvalidType());
1752
1753  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
1754  if (D.getCXXScopeSpec().isSet()) {
1755    Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
1756      << D.getCXXScopeSpec().getRange();
1757    New->setInvalidDecl();
1758  }
1759
1760  // Add the parameter declaration into this scope.
1761  S->AddDecl(New);
1762  if (D.getIdentifier())
1763    IdResolver.AddDecl(New);
1764
1765  ProcessDeclAttributes(S, New, D);
1766
1767  if (New->hasAttr<BlocksAttr>())
1768    Diag(New->getLocation(), diag::err_block_on_nonlocal);
1769  return New;
1770}
1771
1772/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
1773/// initialization.
1774void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
1775                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
1776  for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
1777       Iv= Iv->getNextIvar()) {
1778    QualType QT = Context.getBaseElementType(Iv->getType());
1779    if (QT->isRecordType())
1780      Ivars.push_back(Iv);
1781  }
1782}
1783
1784void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
1785                                    CXXBaseOrMemberInitializer ** initializers,
1786                                                 unsigned numInitializers) {
1787  if (numInitializers > 0) {
1788    NumIvarInitializers = numInitializers;
1789    CXXBaseOrMemberInitializer **ivarInitializers =
1790    new (C) CXXBaseOrMemberInitializer*[NumIvarInitializers];
1791    memcpy(ivarInitializers, initializers,
1792           numInitializers * sizeof(CXXBaseOrMemberInitializer*));
1793    IvarInitializers = ivarInitializers;
1794  }
1795}
1796
1797void Sema::DiagnoseUseOfUnimplementedSelectors() {
1798  if (ReferencedSelectors.empty())
1799    return;
1800  for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
1801        ReferencedSelectors.begin(),
1802       E = ReferencedSelectors.end(); S != E; ++S) {
1803    Selector Sel = (*S).first;
1804    if (!LookupImplementedMethodInGlobalPool(Sel))
1805      Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
1806  }
1807  return;
1808}
1809