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