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