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