SemaDeclObjC.cpp revision 7ca13ef64136929df852c038ebbddee070dc5119
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/ASTConsumer.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Sema/DeclSpec.h"
26#include "llvm/ADT/DenseSet.h"
27
28using namespace clang;
29
30/// Check whether the given method, which must be in the 'init'
31/// family, is a valid member of that family.
32///
33/// \param receiverTypeIfCall - if null, check this as if declaring it;
34///   if non-null, check this as if making a call to it with the given
35///   receiver type
36///
37/// \return true to indicate that there was an error and appropriate
38///   actions were taken
39bool Sema::checkInitMethod(ObjCMethodDecl *method,
40                           QualType receiverTypeIfCall) {
41  if (method->isInvalidDecl()) return true;
42
43  // This castAs is safe: methods that don't return an object
44  // pointer won't be inferred as inits and will reject an explicit
45  // objc_method_family(init).
46
47  // We ignore protocols here.  Should we?  What about Class?
48
49  const ObjCObjectType *result = method->getResultType()
50    ->castAs<ObjCObjectPointerType>()->getObjectType();
51
52  if (result->isObjCId()) {
53    return false;
54  } else if (result->isObjCClass()) {
55    // fall through: always an error
56  } else {
57    ObjCInterfaceDecl *resultClass = result->getInterface();
58    assert(resultClass && "unexpected object type!");
59
60    // It's okay for the result type to still be a forward declaration
61    // if we're checking an interface declaration.
62    if (resultClass->isForwardDecl()) {
63      if (receiverTypeIfCall.isNull() &&
64          !isa<ObjCImplementationDecl>(method->getDeclContext()))
65        return false;
66
67    // Otherwise, we try to compare class types.
68    } else {
69      // If this method was declared in a protocol, we can't check
70      // anything unless we have a receiver type that's an interface.
71      const ObjCInterfaceDecl *receiverClass = 0;
72      if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
73        if (receiverTypeIfCall.isNull())
74          return false;
75
76        receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
77          ->getInterfaceDecl();
78
79        // This can be null for calls to e.g. id<Foo>.
80        if (!receiverClass) return false;
81      } else {
82        receiverClass = method->getClassInterface();
83        assert(receiverClass && "method not associated with a class!");
84      }
85
86      // If either class is a subclass of the other, it's fine.
87      if (receiverClass->isSuperClassOf(resultClass) ||
88          resultClass->isSuperClassOf(receiverClass))
89        return false;
90    }
91  }
92
93  SourceLocation loc = method->getLocation();
94
95  // If we're in a system header, and this is not a call, just make
96  // the method unusable.
97  if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
98    method->addAttr(new (Context) UnavailableAttr(loc, Context,
99                "init method returns a type unrelated to its receiver type"));
100    return true;
101  }
102
103  // Otherwise, it's an error.
104  Diag(loc, diag::err_arc_init_method_unrelated_result_type);
105  method->setInvalidDecl();
106  return true;
107}
108
109bool Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
110                                   const ObjCMethodDecl *Overridden,
111                                   bool IsImplementation) {
112  if (Overridden->hasRelatedResultType() &&
113      !NewMethod->hasRelatedResultType()) {
114    // This can only happen when the method follows a naming convention that
115    // implies a related result type, and the original (overridden) method has
116    // a suitable return type, but the new (overriding) method does not have
117    // a suitable return type.
118    QualType ResultType = NewMethod->getResultType();
119    SourceRange ResultTypeRange;
120    if (const TypeSourceInfo *ResultTypeInfo
121                                        = NewMethod->getResultTypeSourceInfo())
122      ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
123
124    // Figure out which class this method is part of, if any.
125    ObjCInterfaceDecl *CurrentClass
126      = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
127    if (!CurrentClass) {
128      DeclContext *DC = NewMethod->getDeclContext();
129      if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
130        CurrentClass = Cat->getClassInterface();
131      else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
132        CurrentClass = Impl->getClassInterface();
133      else if (ObjCCategoryImplDecl *CatImpl
134               = dyn_cast<ObjCCategoryImplDecl>(DC))
135        CurrentClass = CatImpl->getClassInterface();
136    }
137
138    if (CurrentClass) {
139      Diag(NewMethod->getLocation(),
140           diag::warn_related_result_type_compatibility_class)
141        << Context.getObjCInterfaceType(CurrentClass)
142        << ResultType
143        << ResultTypeRange;
144    } else {
145      Diag(NewMethod->getLocation(),
146           diag::warn_related_result_type_compatibility_protocol)
147        << ResultType
148        << ResultTypeRange;
149    }
150
151    Diag(Overridden->getLocation(), diag::note_related_result_type_overridden)
152      << Overridden->getMethodFamily();
153  }
154
155  return false;
156}
157
158/// \brief Check a method declaration for compatibility with the Objective-C
159/// ARC conventions.
160static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) {
161  ObjCMethodFamily family = method->getMethodFamily();
162  switch (family) {
163  case OMF_None:
164  case OMF_dealloc:
165  case OMF_retain:
166  case OMF_release:
167  case OMF_autorelease:
168  case OMF_retainCount:
169  case OMF_self:
170  case OMF_performSelector:
171    return false;
172
173  case OMF_init:
174    // If the method doesn't obey the init rules, don't bother annotating it.
175    if (S.checkInitMethod(method, QualType()))
176      return true;
177
178    method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(),
179                                                       S.Context));
180
181    // Don't add a second copy of this attribute, but otherwise don't
182    // let it be suppressed.
183    if (method->hasAttr<NSReturnsRetainedAttr>())
184      return false;
185    break;
186
187  case OMF_alloc:
188  case OMF_copy:
189  case OMF_mutableCopy:
190  case OMF_new:
191    if (method->hasAttr<NSReturnsRetainedAttr>() ||
192        method->hasAttr<NSReturnsNotRetainedAttr>() ||
193        method->hasAttr<NSReturnsAutoreleasedAttr>())
194      return false;
195    break;
196  }
197
198  method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(),
199                                                        S.Context));
200  return false;
201}
202
203static void DiagnoseObjCImplementedDeprecations(Sema &S,
204                                                NamedDecl *ND,
205                                                SourceLocation ImplLoc,
206                                                int select) {
207  if (ND && ND->isDeprecated()) {
208    S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
209    if (select == 0)
210      S.Diag(ND->getLocation(), diag::note_method_declared_at);
211    else
212      S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
213  }
214}
215
216/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
217/// and user declared, in the method definition's AST.
218void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
219  assert(getCurMethodDecl() == 0 && "Method parsing confused");
220  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
221
222  // If we don't have a valid method decl, simply return.
223  if (!MDecl)
224    return;
225
226  // Allow the rest of sema to find private method decl implementations.
227  if (MDecl->isInstanceMethod())
228    AddInstanceMethodToGlobalPool(MDecl, true);
229  else
230    AddFactoryMethodToGlobalPool(MDecl, true);
231
232  // Allow all of Sema to see that we are entering a method definition.
233  PushDeclContext(FnBodyScope, MDecl);
234  PushFunctionScope();
235
236  // Create Decl objects for each parameter, entrring them in the scope for
237  // binding to their use.
238
239  // Insert the invisible arguments, self and _cmd!
240  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
241
242  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
243  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
244
245  // Introduce all of the other parameters into this scope.
246  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
247       E = MDecl->param_end(); PI != E; ++PI) {
248    ParmVarDecl *Param = (*PI);
249    if (!Param->isInvalidDecl() &&
250        RequireCompleteType(Param->getLocation(), Param->getType(),
251                            diag::err_typecheck_decl_incomplete_type))
252          Param->setInvalidDecl();
253    if ((*PI)->getIdentifier())
254      PushOnScopeChains(*PI, FnBodyScope);
255  }
256
257  // In ARC, disallow definition of retain/release/autorelease/retainCount
258  if (getLangOptions().ObjCAutoRefCount) {
259    switch (MDecl->getMethodFamily()) {
260    case OMF_retain:
261    case OMF_retainCount:
262    case OMF_release:
263    case OMF_autorelease:
264      Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
265        << MDecl->getSelector();
266      break;
267
268    case OMF_None:
269    case OMF_dealloc:
270    case OMF_alloc:
271    case OMF_init:
272    case OMF_mutableCopy:
273    case OMF_copy:
274    case OMF_new:
275    case OMF_self:
276    case OMF_performSelector:
277      break;
278    }
279  }
280
281  // Warn on implementating deprecated methods under
282  // -Wdeprecated-implementations flag.
283  if (ObjCInterfaceDecl *IC = MDecl->getClassInterface())
284    if (ObjCMethodDecl *IMD =
285          IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
286      DiagnoseObjCImplementedDeprecations(*this,
287                                          dyn_cast<NamedDecl>(IMD),
288                                          MDecl->getLocation(), 0);
289}
290
291Decl *Sema::
292ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
293                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
294                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
295                         Decl * const *ProtoRefs, unsigned NumProtoRefs,
296                         const SourceLocation *ProtoLocs,
297                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
298  assert(ClassName && "Missing class identifier");
299
300  // Check for another declaration kind with the same name.
301  NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
302                                         LookupOrdinaryName, ForRedeclaration);
303
304  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
305    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
306    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
307  }
308
309  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
310  if (IDecl) {
311    // Class already seen. Is it a forward declaration?
312    if (!IDecl->isForwardDecl()) {
313      IDecl->setInvalidDecl();
314      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
315      Diag(IDecl->getLocation(), diag::note_previous_definition);
316
317      // Return the previous class interface.
318      // FIXME: don't leak the objects passed in!
319      return IDecl;
320    } else {
321      IDecl->setLocation(AtInterfaceLoc);
322      IDecl->setForwardDecl(false);
323      IDecl->setClassLoc(ClassLoc);
324      // If the forward decl was in a PCH, we need to write it again in a
325      // dependent AST file.
326      IDecl->setChangedSinceDeserialization(true);
327
328      // Since this ObjCInterfaceDecl was created by a forward declaration,
329      // we now add it to the DeclContext since it wasn't added before
330      // (see ActOnForwardClassDeclaration).
331      IDecl->setLexicalDeclContext(CurContext);
332      CurContext->addDecl(IDecl);
333
334      if (AttrList)
335        ProcessDeclAttributeList(TUScope, IDecl, AttrList);
336    }
337  } else {
338    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
339                                      ClassName, ClassLoc);
340    if (AttrList)
341      ProcessDeclAttributeList(TUScope, IDecl, AttrList);
342
343    PushOnScopeChains(IDecl, TUScope);
344  }
345
346  if (SuperName) {
347    // Check if a different kind of symbol declared in this scope.
348    PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
349                                LookupOrdinaryName);
350
351    if (!PrevDecl) {
352      // Try to correct for a typo in the superclass name.
353      TypoCorrection Corrected = CorrectTypo(
354          DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
355          NULL, NULL, false, CTC_NoKeywords);
356      if ((PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
357        Diag(SuperLoc, diag::err_undef_superclass_suggest)
358          << SuperName << ClassName << PrevDecl->getDeclName();
359        Diag(PrevDecl->getLocation(), diag::note_previous_decl)
360          << PrevDecl->getDeclName();
361      }
362    }
363
364    if (PrevDecl == IDecl) {
365      Diag(SuperLoc, diag::err_recursive_superclass)
366        << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
367      IDecl->setLocEnd(ClassLoc);
368    } else {
369      ObjCInterfaceDecl *SuperClassDecl =
370                                dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
371
372      // Diagnose classes that inherit from deprecated classes.
373      if (SuperClassDecl)
374        (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
375
376      if (PrevDecl && SuperClassDecl == 0) {
377        // The previous declaration was not a class decl. Check if we have a
378        // typedef. If we do, get the underlying class type.
379        if (const TypedefNameDecl *TDecl =
380              dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
381          QualType T = TDecl->getUnderlyingType();
382          if (T->isObjCObjectType()) {
383            if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
384              SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
385          }
386        }
387
388        // This handles the following case:
389        //
390        // typedef int SuperClass;
391        // @interface MyClass : SuperClass {} @end
392        //
393        if (!SuperClassDecl) {
394          Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
395          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
396        }
397      }
398
399      if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
400        if (!SuperClassDecl)
401          Diag(SuperLoc, diag::err_undef_superclass)
402            << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
403        else if (SuperClassDecl->isForwardDecl()) {
404          Diag(SuperLoc, diag::err_forward_superclass)
405            << SuperClassDecl->getDeclName() << ClassName
406            << SourceRange(AtInterfaceLoc, ClassLoc);
407          Diag(SuperClassDecl->getLocation(), diag::note_forward_class);
408          SuperClassDecl = 0;
409        }
410      }
411      IDecl->setSuperClass(SuperClassDecl);
412      IDecl->setSuperClassLoc(SuperLoc);
413      IDecl->setLocEnd(SuperLoc);
414    }
415  } else { // we have a root class.
416    IDecl->setLocEnd(ClassLoc);
417  }
418
419  // Check then save referenced protocols.
420  if (NumProtoRefs) {
421    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
422                           ProtoLocs, Context);
423    IDecl->setLocEnd(EndProtoLoc);
424  }
425
426  CheckObjCDeclScope(IDecl);
427  return IDecl;
428}
429
430/// ActOnCompatiblityAlias - this action is called after complete parsing of
431/// @compatibility_alias declaration. It sets up the alias relationships.
432Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
433                                        IdentifierInfo *AliasName,
434                                        SourceLocation AliasLocation,
435                                        IdentifierInfo *ClassName,
436                                        SourceLocation ClassLocation) {
437  // Look for previous declaration of alias name
438  NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
439                                      LookupOrdinaryName, ForRedeclaration);
440  if (ADecl) {
441    if (isa<ObjCCompatibleAliasDecl>(ADecl))
442      Diag(AliasLocation, diag::warn_previous_alias_decl);
443    else
444      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
445    Diag(ADecl->getLocation(), diag::note_previous_declaration);
446    return 0;
447  }
448  // Check for class declaration
449  NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
450                                       LookupOrdinaryName, ForRedeclaration);
451  if (const TypedefNameDecl *TDecl =
452        dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
453    QualType T = TDecl->getUnderlyingType();
454    if (T->isObjCObjectType()) {
455      if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
456        ClassName = IDecl->getIdentifier();
457        CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
458                                  LookupOrdinaryName, ForRedeclaration);
459      }
460    }
461  }
462  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
463  if (CDecl == 0) {
464    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
465    if (CDeclU)
466      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
467    return 0;
468  }
469
470  // Everything checked out, instantiate a new alias declaration AST.
471  ObjCCompatibleAliasDecl *AliasDecl =
472    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
473
474  if (!CheckObjCDeclScope(AliasDecl))
475    PushOnScopeChains(AliasDecl, TUScope);
476
477  return AliasDecl;
478}
479
480bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
481  IdentifierInfo *PName,
482  SourceLocation &Ploc, SourceLocation PrevLoc,
483  const ObjCList<ObjCProtocolDecl> &PList) {
484
485  bool res = false;
486  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
487       E = PList.end(); I != E; ++I) {
488    if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
489                                                 Ploc)) {
490      if (PDecl->getIdentifier() == PName) {
491        Diag(Ploc, diag::err_protocol_has_circular_dependency);
492        Diag(PrevLoc, diag::note_previous_definition);
493        res = true;
494      }
495      if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
496            PDecl->getLocation(), PDecl->getReferencedProtocols()))
497        res = true;
498    }
499  }
500  return res;
501}
502
503Decl *
504Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
505                                  IdentifierInfo *ProtocolName,
506                                  SourceLocation ProtocolLoc,
507                                  Decl * const *ProtoRefs,
508                                  unsigned NumProtoRefs,
509                                  const SourceLocation *ProtoLocs,
510                                  SourceLocation EndProtoLoc,
511                                  AttributeList *AttrList) {
512  bool err = false;
513  // FIXME: Deal with AttrList.
514  assert(ProtocolName && "Missing protocol identifier");
515  ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
516  if (PDecl) {
517    // Protocol already seen. Better be a forward protocol declaration
518    if (!PDecl->isForwardDecl()) {
519      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
520      Diag(PDecl->getLocation(), diag::note_previous_definition);
521      // Just return the protocol we already had.
522      // FIXME: don't leak the objects passed in!
523      return PDecl;
524    }
525    ObjCList<ObjCProtocolDecl> PList;
526    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
527    err = CheckForwardProtocolDeclarationForCircularDependency(
528            ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
529
530    // Make sure the cached decl gets a valid start location.
531    PDecl->setLocation(AtProtoInterfaceLoc);
532    PDecl->setForwardDecl(false);
533    CurContext->addDecl(PDecl);
534    // Repeat in dependent AST files.
535    PDecl->setChangedSinceDeserialization(true);
536  } else {
537    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
538                                     AtProtoInterfaceLoc,ProtocolName);
539    PushOnScopeChains(PDecl, TUScope);
540    PDecl->setForwardDecl(false);
541  }
542  if (AttrList)
543    ProcessDeclAttributeList(TUScope, PDecl, AttrList);
544  if (!err && NumProtoRefs ) {
545    /// Check then save referenced protocols.
546    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
547                           ProtoLocs, Context);
548    PDecl->setLocEnd(EndProtoLoc);
549  }
550
551  CheckObjCDeclScope(PDecl);
552  return PDecl;
553}
554
555/// FindProtocolDeclaration - This routine looks up protocols and
556/// issues an error if they are not declared. It returns list of
557/// protocol declarations in its 'Protocols' argument.
558void
559Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
560                              const IdentifierLocPair *ProtocolId,
561                              unsigned NumProtocols,
562                              SmallVectorImpl<Decl *> &Protocols) {
563  for (unsigned i = 0; i != NumProtocols; ++i) {
564    ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
565                                             ProtocolId[i].second);
566    if (!PDecl) {
567      TypoCorrection Corrected = CorrectTypo(
568          DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
569          LookupObjCProtocolName, TUScope, NULL, NULL, false, CTC_NoKeywords);
570      if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
571        Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
572          << ProtocolId[i].first << Corrected.getCorrection();
573        Diag(PDecl->getLocation(), diag::note_previous_decl)
574          << PDecl->getDeclName();
575      }
576    }
577
578    if (!PDecl) {
579      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
580        << ProtocolId[i].first;
581      continue;
582    }
583
584    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
585
586    // If this is a forward declaration and we are supposed to warn in this
587    // case, do it.
588    if (WarnOnDeclarations && PDecl->isForwardDecl())
589      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
590        << ProtocolId[i].first;
591    Protocols.push_back(PDecl);
592  }
593}
594
595/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
596/// a class method in its extension.
597///
598void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
599                                            ObjCInterfaceDecl *ID) {
600  if (!ID)
601    return;  // Possibly due to previous error
602
603  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
604  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
605       e =  ID->meth_end(); i != e; ++i) {
606    ObjCMethodDecl *MD = *i;
607    MethodMap[MD->getSelector()] = MD;
608  }
609
610  if (MethodMap.empty())
611    return;
612  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
613       e =  CAT->meth_end(); i != e; ++i) {
614    ObjCMethodDecl *Method = *i;
615    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
616    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
617      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
618            << Method->getDeclName();
619      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
620    }
621  }
622}
623
624/// ActOnForwardProtocolDeclaration - Handle @protocol foo;
625Decl *
626Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
627                                      const IdentifierLocPair *IdentList,
628                                      unsigned NumElts,
629                                      AttributeList *attrList) {
630  SmallVector<ObjCProtocolDecl*, 32> Protocols;
631  SmallVector<SourceLocation, 8> ProtoLocs;
632
633  for (unsigned i = 0; i != NumElts; ++i) {
634    IdentifierInfo *Ident = IdentList[i].first;
635    ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
636    bool isNew = false;
637    if (PDecl == 0) { // Not already seen?
638      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
639                                       IdentList[i].second, Ident);
640      PushOnScopeChains(PDecl, TUScope, false);
641      isNew = true;
642    }
643    if (attrList) {
644      ProcessDeclAttributeList(TUScope, PDecl, attrList);
645      if (!isNew)
646        PDecl->setChangedSinceDeserialization(true);
647    }
648    Protocols.push_back(PDecl);
649    ProtoLocs.push_back(IdentList[i].second);
650  }
651
652  ObjCForwardProtocolDecl *PDecl =
653    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
654                                    Protocols.data(), Protocols.size(),
655                                    ProtoLocs.data());
656  CurContext->addDecl(PDecl);
657  CheckObjCDeclScope(PDecl);
658  return PDecl;
659}
660
661Decl *Sema::
662ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
663                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
664                            IdentifierInfo *CategoryName,
665                            SourceLocation CategoryLoc,
666                            Decl * const *ProtoRefs,
667                            unsigned NumProtoRefs,
668                            const SourceLocation *ProtoLocs,
669                            SourceLocation EndProtoLoc) {
670  ObjCCategoryDecl *CDecl;
671  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
672
673  /// Check that class of this category is already completely declared.
674  if (!IDecl || IDecl->isForwardDecl()) {
675    // Create an invalid ObjCCategoryDecl to serve as context for
676    // the enclosing method declarations.  We mark the decl invalid
677    // to make it clear that this isn't a valid AST.
678    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
679                                     ClassLoc, CategoryLoc, CategoryName);
680    CDecl->setInvalidDecl();
681    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
682    return CDecl;
683  }
684
685  if (!CategoryName && IDecl->getImplementation()) {
686    Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
687    Diag(IDecl->getImplementation()->getLocation(),
688          diag::note_implementation_declared);
689  }
690
691  CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
692                                   ClassLoc, CategoryLoc, CategoryName);
693  // FIXME: PushOnScopeChains?
694  CurContext->addDecl(CDecl);
695
696  CDecl->setClassInterface(IDecl);
697  // Insert class extension to the list of class's categories.
698  if (!CategoryName)
699    CDecl->insertNextClassCategory();
700
701  // If the interface is deprecated, warn about it.
702  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
703
704  if (CategoryName) {
705    /// Check for duplicate interface declaration for this category
706    ObjCCategoryDecl *CDeclChain;
707    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
708         CDeclChain = CDeclChain->getNextClassCategory()) {
709      if (CDeclChain->getIdentifier() == CategoryName) {
710        // Class extensions can be declared multiple times.
711        Diag(CategoryLoc, diag::warn_dup_category_def)
712          << ClassName << CategoryName;
713        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
714        break;
715      }
716    }
717    if (!CDeclChain)
718      CDecl->insertNextClassCategory();
719  }
720
721  if (NumProtoRefs) {
722    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
723                           ProtoLocs, Context);
724    // Protocols in the class extension belong to the class.
725    if (CDecl->IsClassExtension())
726     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
727                                            NumProtoRefs, Context);
728  }
729
730  CheckObjCDeclScope(CDecl);
731  return CDecl;
732}
733
734/// ActOnStartCategoryImplementation - Perform semantic checks on the
735/// category implementation declaration and build an ObjCCategoryImplDecl
736/// object.
737Decl *Sema::ActOnStartCategoryImplementation(
738                      SourceLocation AtCatImplLoc,
739                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
740                      IdentifierInfo *CatName, SourceLocation CatLoc) {
741  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
742  ObjCCategoryDecl *CatIDecl = 0;
743  if (IDecl) {
744    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
745    if (!CatIDecl) {
746      // Category @implementation with no corresponding @interface.
747      // Create and install one.
748      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
749                                          SourceLocation(), SourceLocation(),
750                                          CatName);
751      CatIDecl->setClassInterface(IDecl);
752      CatIDecl->insertNextClassCategory();
753    }
754  }
755
756  ObjCCategoryImplDecl *CDecl =
757    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
758                                 IDecl);
759  /// Check that class of this category is already completely declared.
760  if (!IDecl || IDecl->isForwardDecl()) {
761    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
762    CDecl->setInvalidDecl();
763  }
764
765  // FIXME: PushOnScopeChains?
766  CurContext->addDecl(CDecl);
767
768  /// Check that CatName, category name, is not used in another implementation.
769  if (CatIDecl) {
770    if (CatIDecl->getImplementation()) {
771      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
772        << CatName;
773      Diag(CatIDecl->getImplementation()->getLocation(),
774           diag::note_previous_definition);
775    } else {
776      CatIDecl->setImplementation(CDecl);
777      // Warn on implementating category of deprecated class under
778      // -Wdeprecated-implementations flag.
779      DiagnoseObjCImplementedDeprecations(*this,
780                                          dyn_cast<NamedDecl>(IDecl),
781                                          CDecl->getLocation(), 2);
782    }
783  }
784
785  CheckObjCDeclScope(CDecl);
786  return CDecl;
787}
788
789Decl *Sema::ActOnStartClassImplementation(
790                      SourceLocation AtClassImplLoc,
791                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
792                      IdentifierInfo *SuperClassname,
793                      SourceLocation SuperClassLoc) {
794  ObjCInterfaceDecl* IDecl = 0;
795  // Check for another declaration kind with the same name.
796  NamedDecl *PrevDecl
797    = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
798                       ForRedeclaration);
799  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
800    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
801    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
802  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
803    // If this is a forward declaration of an interface, warn.
804    if (IDecl->isForwardDecl()) {
805      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
806      IDecl = 0;
807    }
808  } else {
809    // We did not find anything with the name ClassName; try to correct for
810    // typos in the class name.
811    TypoCorrection Corrected = CorrectTypo(
812        DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
813        NULL, NULL, false, CTC_NoKeywords);
814    if ((IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
815      // Suggest the (potentially) correct interface name. However, put the
816      // fix-it hint itself in a separate note, since changing the name in
817      // the warning would make the fix-it change semantics.However, don't
818      // provide a code-modification hint or use the typo name for recovery,
819      // because this is just a warning. The program may actually be correct.
820      DeclarationName CorrectedName = Corrected.getCorrection();
821      Diag(ClassLoc, diag::warn_undef_interface_suggest)
822        << ClassName << CorrectedName;
823      Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
824        << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
825      IDecl = 0;
826    } else {
827      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
828    }
829  }
830
831  // Check that super class name is valid class name
832  ObjCInterfaceDecl* SDecl = 0;
833  if (SuperClassname) {
834    // Check if a different kind of symbol declared in this scope.
835    PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
836                                LookupOrdinaryName);
837    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
838      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
839        << SuperClassname;
840      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
841    } else {
842      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
843      if (!SDecl)
844        Diag(SuperClassLoc, diag::err_undef_superclass)
845          << SuperClassname << ClassName;
846      else if (IDecl && IDecl->getSuperClass() != SDecl) {
847        // This implementation and its interface do not have the same
848        // super class.
849        Diag(SuperClassLoc, diag::err_conflicting_super_class)
850          << SDecl->getDeclName();
851        Diag(SDecl->getLocation(), diag::note_previous_definition);
852      }
853    }
854  }
855
856  if (!IDecl) {
857    // Legacy case of @implementation with no corresponding @interface.
858    // Build, chain & install the interface decl into the identifier.
859
860    // FIXME: Do we support attributes on the @implementation? If so we should
861    // copy them over.
862    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
863                                      ClassName, ClassLoc, false, true);
864    IDecl->setSuperClass(SDecl);
865    IDecl->setLocEnd(ClassLoc);
866
867    PushOnScopeChains(IDecl, TUScope);
868  } else {
869    // Mark the interface as being completed, even if it was just as
870    //   @class ....;
871    // declaration; the user cannot reopen it.
872    IDecl->setForwardDecl(false);
873  }
874
875  ObjCImplementationDecl* IMPDecl =
876    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
877                                   IDecl, SDecl);
878
879  if (CheckObjCDeclScope(IMPDecl))
880    return IMPDecl;
881
882  // Check that there is no duplicate implementation of this class.
883  if (IDecl->getImplementation()) {
884    // FIXME: Don't leak everything!
885    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
886    Diag(IDecl->getImplementation()->getLocation(),
887         diag::note_previous_definition);
888  } else { // add it to the list.
889    IDecl->setImplementation(IMPDecl);
890    PushOnScopeChains(IMPDecl, TUScope);
891    // Warn on implementating deprecated class under
892    // -Wdeprecated-implementations flag.
893    DiagnoseObjCImplementedDeprecations(*this,
894                                        dyn_cast<NamedDecl>(IDecl),
895                                        IMPDecl->getLocation(), 1);
896  }
897  return IMPDecl;
898}
899
900void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
901                                    ObjCIvarDecl **ivars, unsigned numIvars,
902                                    SourceLocation RBrace) {
903  assert(ImpDecl && "missing implementation decl");
904  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
905  if (!IDecl)
906    return;
907  /// Check case of non-existing @interface decl.
908  /// (legacy objective-c @implementation decl without an @interface decl).
909  /// Add implementations's ivar to the synthesize class's ivar list.
910  if (IDecl->isImplicitInterfaceDecl()) {
911    IDecl->setLocEnd(RBrace);
912    // Add ivar's to class's DeclContext.
913    for (unsigned i = 0, e = numIvars; i != e; ++i) {
914      ivars[i]->setLexicalDeclContext(ImpDecl);
915      IDecl->makeDeclVisibleInContext(ivars[i], false);
916      ImpDecl->addDecl(ivars[i]);
917    }
918
919    return;
920  }
921  // If implementation has empty ivar list, just return.
922  if (numIvars == 0)
923    return;
924
925  assert(ivars && "missing @implementation ivars");
926  if (LangOpts.ObjCNonFragileABI2) {
927    if (ImpDecl->getSuperClass())
928      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
929    for (unsigned i = 0; i < numIvars; i++) {
930      ObjCIvarDecl* ImplIvar = ivars[i];
931      if (const ObjCIvarDecl *ClsIvar =
932            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
933        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
934        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
935        continue;
936      }
937      // Instance ivar to Implementation's DeclContext.
938      ImplIvar->setLexicalDeclContext(ImpDecl);
939      IDecl->makeDeclVisibleInContext(ImplIvar, false);
940      ImpDecl->addDecl(ImplIvar);
941    }
942    return;
943  }
944  // Check interface's Ivar list against those in the implementation.
945  // names and types must match.
946  //
947  unsigned j = 0;
948  ObjCInterfaceDecl::ivar_iterator
949    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
950  for (; numIvars > 0 && IVI != IVE; ++IVI) {
951    ObjCIvarDecl* ImplIvar = ivars[j++];
952    ObjCIvarDecl* ClsIvar = *IVI;
953    assert (ImplIvar && "missing implementation ivar");
954    assert (ClsIvar && "missing class ivar");
955
956    // First, make sure the types match.
957    if (Context.getCanonicalType(ImplIvar->getType()) !=
958        Context.getCanonicalType(ClsIvar->getType())) {
959      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
960        << ImplIvar->getIdentifier()
961        << ImplIvar->getType() << ClsIvar->getType();
962      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
963    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
964      Expr *ImplBitWidth = ImplIvar->getBitWidth();
965      Expr *ClsBitWidth = ClsIvar->getBitWidth();
966      if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
967          ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
968        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
969          << ImplIvar->getIdentifier();
970        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
971      }
972    }
973    // Make sure the names are identical.
974    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
975      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
976        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
977      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
978    }
979    --numIvars;
980  }
981
982  if (numIvars > 0)
983    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
984  else if (IVI != IVE)
985    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
986}
987
988void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
989                               bool &IncompleteImpl, unsigned DiagID) {
990  // No point warning no definition of method which is 'unavailable'.
991  if (method->hasAttr<UnavailableAttr>())
992    return;
993  if (!IncompleteImpl) {
994    Diag(ImpLoc, diag::warn_incomplete_impl);
995    IncompleteImpl = true;
996  }
997  if (DiagID == diag::warn_unimplemented_protocol_method)
998    Diag(ImpLoc, DiagID) << method->getDeclName();
999  else
1000    Diag(method->getLocation(), DiagID) << method->getDeclName();
1001}
1002
1003/// Determines if type B can be substituted for type A.  Returns true if we can
1004/// guarantee that anything that the user will do to an object of type A can
1005/// also be done to an object of type B.  This is trivially true if the two
1006/// types are the same, or if B is a subclass of A.  It becomes more complex
1007/// in cases where protocols are involved.
1008///
1009/// Object types in Objective-C describe the minimum requirements for an
1010/// object, rather than providing a complete description of a type.  For
1011/// example, if A is a subclass of B, then B* may refer to an instance of A.
1012/// The principle of substitutability means that we may use an instance of A
1013/// anywhere that we may use an instance of B - it will implement all of the
1014/// ivars of B and all of the methods of B.
1015///
1016/// This substitutability is important when type checking methods, because
1017/// the implementation may have stricter type definitions than the interface.
1018/// The interface specifies minimum requirements, but the implementation may
1019/// have more accurate ones.  For example, a method may privately accept
1020/// instances of B, but only publish that it accepts instances of A.  Any
1021/// object passed to it will be type checked against B, and so will implicitly
1022/// by a valid A*.  Similarly, a method may return a subclass of the class that
1023/// it is declared as returning.
1024///
1025/// This is most important when considering subclassing.  A method in a
1026/// subclass must accept any object as an argument that its superclass's
1027/// implementation accepts.  It may, however, accept a more general type
1028/// without breaking substitutability (i.e. you can still use the subclass
1029/// anywhere that you can use the superclass, but not vice versa).  The
1030/// converse requirement applies to return types: the return type for a
1031/// subclass method must be a valid object of the kind that the superclass
1032/// advertises, but it may be specified more accurately.  This avoids the need
1033/// for explicit down-casting by callers.
1034///
1035/// Note: This is a stricter requirement than for assignment.
1036static bool isObjCTypeSubstitutable(ASTContext &Context,
1037                                    const ObjCObjectPointerType *A,
1038                                    const ObjCObjectPointerType *B,
1039                                    bool rejectId) {
1040  // Reject a protocol-unqualified id.
1041  if (rejectId && B->isObjCIdType()) return false;
1042
1043  // If B is a qualified id, then A must also be a qualified id and it must
1044  // implement all of the protocols in B.  It may not be a qualified class.
1045  // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1046  // stricter definition so it is not substitutable for id<A>.
1047  if (B->isObjCQualifiedIdType()) {
1048    return A->isObjCQualifiedIdType() &&
1049           Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1050                                                     QualType(B,0),
1051                                                     false);
1052  }
1053
1054  /*
1055  // id is a special type that bypasses type checking completely.  We want a
1056  // warning when it is used in one place but not another.
1057  if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1058
1059
1060  // If B is a qualified id, then A must also be a qualified id (which it isn't
1061  // if we've got this far)
1062  if (B->isObjCQualifiedIdType()) return false;
1063  */
1064
1065  // Now we know that A and B are (potentially-qualified) class types.  The
1066  // normal rules for assignment apply.
1067  return Context.canAssignObjCInterfaces(A, B);
1068}
1069
1070static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1071  return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1072}
1073
1074static bool CheckMethodOverrideReturn(Sema &S,
1075                                      ObjCMethodDecl *MethodImpl,
1076                                      ObjCMethodDecl *MethodDecl,
1077                                      bool IsProtocolMethodDecl,
1078                                      bool IsDeclaration,
1079                                      bool Warn) {
1080  if (IsProtocolMethodDecl &&
1081      (MethodDecl->getObjCDeclQualifier() !=
1082       MethodImpl->getObjCDeclQualifier())) {
1083    if (Warn) {
1084      S.Diag(MethodImpl->getLocation(),
1085             diag::warn_conflicting_ret_type_modifiers)
1086          << MethodImpl->getDeclName() << IsDeclaration
1087          << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1088        S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1089          << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1090    }
1091    else
1092      return false;
1093  }
1094
1095  if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
1096                                       MethodDecl->getResultType()))
1097    return true;
1098  if (!Warn)
1099    return false;
1100
1101  unsigned DiagID = diag::warn_conflicting_ret_types;
1102
1103  // Mismatches between ObjC pointers go into a different warning
1104  // category, and sometimes they're even completely whitelisted.
1105  if (const ObjCObjectPointerType *ImplPtrTy =
1106        MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
1107    if (const ObjCObjectPointerType *IfacePtrTy =
1108          MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
1109      // Allow non-matching return types as long as they don't violate
1110      // the principle of substitutability.  Specifically, we permit
1111      // return types that are subclasses of the declared return type,
1112      // or that are more-qualified versions of the declared type.
1113      if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1114        return false;
1115
1116      DiagID = diag::warn_non_covariant_ret_types;
1117    }
1118  }
1119
1120  S.Diag(MethodImpl->getLocation(), DiagID)
1121    << MethodImpl->getDeclName()
1122    << MethodDecl->getResultType()
1123    << MethodImpl->getResultType()
1124    << IsDeclaration
1125    << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1126  S.Diag(MethodDecl->getLocation(), diag::note_previous_definition)
1127    << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1128  return false;
1129}
1130
1131static bool CheckMethodOverrideParam(Sema &S,
1132                                     ObjCMethodDecl *MethodImpl,
1133                                     ObjCMethodDecl *MethodDecl,
1134                                     ParmVarDecl *ImplVar,
1135                                     ParmVarDecl *IfaceVar,
1136                                     bool IsProtocolMethodDecl,
1137                                     bool IsDeclaration,
1138                                     bool Warn) {
1139  if (IsProtocolMethodDecl &&
1140      (ImplVar->getObjCDeclQualifier() !=
1141       IfaceVar->getObjCDeclQualifier())) {
1142    if (Warn) {
1143      S.Diag(ImplVar->getLocation(),
1144             diag::warn_conflicting_param_modifiers)
1145          << getTypeRange(ImplVar->getTypeSourceInfo())
1146          << MethodImpl->getDeclName() << IsDeclaration;
1147      S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1148          << getTypeRange(IfaceVar->getTypeSourceInfo());
1149    }
1150    else
1151      return false;
1152  }
1153
1154  QualType ImplTy = ImplVar->getType();
1155  QualType IfaceTy = IfaceVar->getType();
1156
1157  if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1158    return true;
1159
1160  if (!Warn)
1161    return false;
1162  unsigned DiagID = diag::warn_conflicting_param_types;
1163
1164  // Mismatches between ObjC pointers go into a different warning
1165  // category, and sometimes they're even completely whitelisted.
1166  if (const ObjCObjectPointerType *ImplPtrTy =
1167        ImplTy->getAs<ObjCObjectPointerType>()) {
1168    if (const ObjCObjectPointerType *IfacePtrTy =
1169          IfaceTy->getAs<ObjCObjectPointerType>()) {
1170      // Allow non-matching argument types as long as they don't
1171      // violate the principle of substitutability.  Specifically, the
1172      // implementation must accept any objects that the superclass
1173      // accepts, however it may also accept others.
1174      if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1175        return false;
1176
1177      DiagID = diag::warn_non_contravariant_param_types;
1178    }
1179  }
1180
1181  S.Diag(ImplVar->getLocation(), DiagID)
1182    << getTypeRange(ImplVar->getTypeSourceInfo())
1183    << MethodImpl->getDeclName() << IfaceTy << ImplTy
1184    << IsDeclaration;
1185  S.Diag(IfaceVar->getLocation(), diag::note_previous_definition)
1186    << getTypeRange(IfaceVar->getTypeSourceInfo());
1187  return false;
1188}
1189
1190/// In ARC, check whether the conventional meanings of the two methods
1191/// match.  If they don't, it's a hard error.
1192static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1193                                      ObjCMethodDecl *decl) {
1194  ObjCMethodFamily implFamily = impl->getMethodFamily();
1195  ObjCMethodFamily declFamily = decl->getMethodFamily();
1196  if (implFamily == declFamily) return false;
1197
1198  // Since conventions are sorted by selector, the only possibility is
1199  // that the types differ enough to cause one selector or the other
1200  // to fall out of the family.
1201  assert(implFamily == OMF_None || declFamily == OMF_None);
1202
1203  // No further diagnostics required on invalid declarations.
1204  if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1205
1206  const ObjCMethodDecl *unmatched = impl;
1207  ObjCMethodFamily family = declFamily;
1208  unsigned errorID = diag::err_arc_lost_method_convention;
1209  unsigned noteID = diag::note_arc_lost_method_convention;
1210  if (declFamily == OMF_None) {
1211    unmatched = decl;
1212    family = implFamily;
1213    errorID = diag::err_arc_gained_method_convention;
1214    noteID = diag::note_arc_gained_method_convention;
1215  }
1216
1217  // Indexes into a %select clause in the diagnostic.
1218  enum FamilySelector {
1219    F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1220  };
1221  FamilySelector familySelector = FamilySelector();
1222
1223  switch (family) {
1224  case OMF_None: llvm_unreachable("logic error, no method convention");
1225  case OMF_retain:
1226  case OMF_release:
1227  case OMF_autorelease:
1228  case OMF_dealloc:
1229  case OMF_retainCount:
1230  case OMF_self:
1231  case OMF_performSelector:
1232    // Mismatches for these methods don't change ownership
1233    // conventions, so we don't care.
1234    return false;
1235
1236  case OMF_init: familySelector = F_init; break;
1237  case OMF_alloc: familySelector = F_alloc; break;
1238  case OMF_copy: familySelector = F_copy; break;
1239  case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1240  case OMF_new: familySelector = F_new; break;
1241  }
1242
1243  enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1244  ReasonSelector reasonSelector;
1245
1246  // The only reason these methods don't fall within their families is
1247  // due to unusual result types.
1248  if (unmatched->getResultType()->isObjCObjectPointerType()) {
1249    reasonSelector = R_UnrelatedReturn;
1250  } else {
1251    reasonSelector = R_NonObjectReturn;
1252  }
1253
1254  S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
1255  S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
1256
1257  return true;
1258}
1259
1260void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1261                                       ObjCMethodDecl *MethodDecl,
1262                                       bool IsProtocolMethodDecl,
1263                                       bool IsDeclaration) {
1264  if (getLangOptions().ObjCAutoRefCount &&
1265      checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1266    return;
1267
1268  CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1269                            IsProtocolMethodDecl, IsDeclaration, true);
1270
1271  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1272       IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1273       IM != EM; ++IM, ++IF)
1274    CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1275                             IsProtocolMethodDecl, IsDeclaration, true);
1276
1277  if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1278    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic)
1279      << IsDeclaration;
1280    Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1281  }
1282}
1283
1284/// WarnExactTypedMethods - This routine issues a warning if method
1285/// implementation declaration matches exactly that of its declaration.
1286void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1287                                 ObjCMethodDecl *MethodDecl,
1288                                 bool IsProtocolMethodDecl) {
1289  // don't issue warning when protocol method is optional because primary
1290  // class is not required to implement it and it is safe for protocol
1291  // to implement it.
1292  if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1293    return;
1294  // don't issue warning when primary class's method is
1295  // depecated/unavailable.
1296  if (MethodDecl->hasAttr<UnavailableAttr>() ||
1297      MethodDecl->hasAttr<DeprecatedAttr>())
1298    return;
1299
1300  bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1301                                      IsProtocolMethodDecl, false, false);
1302  if (match)
1303    for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1304         IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1305         IM != EM; ++IM, ++IF) {
1306      match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1307                                       *IM, *IF,
1308                                       IsProtocolMethodDecl, false, false);
1309      if (!match)
1310        break;
1311    }
1312  if (match)
1313    match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1314  if (match)
1315    match = !(MethodDecl->isClassMethod() &&
1316              MethodDecl->getSelector() == GetNullarySelector("load", Context));
1317
1318  if (match) {
1319    Diag(ImpMethodDecl->getLocation(),
1320         diag::warn_category_method_impl_match);
1321    Diag(MethodDecl->getLocation(), diag::note_method_declared_at);
1322  }
1323}
1324
1325/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1326/// improve the efficiency of selector lookups and type checking by associating
1327/// with each protocol / interface / category the flattened instance tables. If
1328/// we used an immutable set to keep the table then it wouldn't add significant
1329/// memory cost and it would be handy for lookups.
1330
1331/// CheckProtocolMethodDefs - This routine checks unimplemented methods
1332/// Declared in protocol, and those referenced by it.
1333void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
1334                                   ObjCProtocolDecl *PDecl,
1335                                   bool& IncompleteImpl,
1336                                   const llvm::DenseSet<Selector> &InsMap,
1337                                   const llvm::DenseSet<Selector> &ClsMap,
1338                                   ObjCContainerDecl *CDecl) {
1339  ObjCInterfaceDecl *IDecl;
1340  if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
1341    IDecl = C->getClassInterface();
1342  else
1343    IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1344  assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1345
1346  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1347  ObjCInterfaceDecl *NSIDecl = 0;
1348  if (getLangOptions().NeXTRuntime) {
1349    // check to see if class implements forwardInvocation method and objects
1350    // of this class are derived from 'NSProxy' so that to forward requests
1351    // from one object to another.
1352    // Under such conditions, which means that every method possible is
1353    // implemented in the class, we should not issue "Method definition not
1354    // found" warnings.
1355    // FIXME: Use a general GetUnarySelector method for this.
1356    IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1357    Selector fISelector = Context.Selectors.getSelector(1, &II);
1358    if (InsMap.count(fISelector))
1359      // Is IDecl derived from 'NSProxy'? If so, no instance methods
1360      // need be implemented in the implementation.
1361      NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1362  }
1363
1364  // If a method lookup fails locally we still need to look and see if
1365  // the method was implemented by a base class or an inherited
1366  // protocol. This lookup is slow, but occurs rarely in correct code
1367  // and otherwise would terminate in a warning.
1368
1369  // check unimplemented instance methods.
1370  if (!NSIDecl)
1371    for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1372         E = PDecl->instmeth_end(); I != E; ++I) {
1373      ObjCMethodDecl *method = *I;
1374      if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1375          !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
1376          (!Super ||
1377           !Super->lookupInstanceMethod(method->getSelector()))) {
1378            // Ugly, but necessary. Method declared in protcol might have
1379            // have been synthesized due to a property declared in the class which
1380            // uses the protocol.
1381            ObjCMethodDecl *MethodInClass =
1382            IDecl->lookupInstanceMethod(method->getSelector());
1383            if (!MethodInClass || !MethodInClass->isSynthesized()) {
1384              unsigned DIAG = diag::warn_unimplemented_protocol_method;
1385              if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1386                      != Diagnostic::Ignored) {
1387                WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1388                Diag(method->getLocation(), diag::note_method_declared_at);
1389                Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1390                  << PDecl->getDeclName();
1391              }
1392            }
1393          }
1394    }
1395  // check unimplemented class methods
1396  for (ObjCProtocolDecl::classmeth_iterator
1397         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1398       I != E; ++I) {
1399    ObjCMethodDecl *method = *I;
1400    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1401        !ClsMap.count(method->getSelector()) &&
1402        (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1403      unsigned DIAG = diag::warn_unimplemented_protocol_method;
1404      if (Diags.getDiagnosticLevel(DIAG, ImpLoc) != Diagnostic::Ignored) {
1405        WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1406        Diag(method->getLocation(), diag::note_method_declared_at);
1407        Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1408          PDecl->getDeclName();
1409      }
1410    }
1411  }
1412  // Check on this protocols's referenced protocols, recursively.
1413  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1414       E = PDecl->protocol_end(); PI != E; ++PI)
1415    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
1416}
1417
1418/// MatchAllMethodDeclarations - Check methods declared in interface
1419/// or protocol against those declared in their implementations.
1420///
1421void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1422                                      const llvm::DenseSet<Selector> &ClsMap,
1423                                      llvm::DenseSet<Selector> &InsMapSeen,
1424                                      llvm::DenseSet<Selector> &ClsMapSeen,
1425                                      ObjCImplDecl* IMPDecl,
1426                                      ObjCContainerDecl* CDecl,
1427                                      bool &IncompleteImpl,
1428                                      bool ImmediateClass,
1429                                      bool WarnExactMatch) {
1430  // Check and see if instance methods in class interface have been
1431  // implemented in the implementation class. If so, their types match.
1432  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1433       E = CDecl->instmeth_end(); I != E; ++I) {
1434    if (InsMapSeen.count((*I)->getSelector()))
1435        continue;
1436    InsMapSeen.insert((*I)->getSelector());
1437    if (!(*I)->isSynthesized() &&
1438        !InsMap.count((*I)->getSelector())) {
1439      if (ImmediateClass)
1440        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1441                            diag::note_undef_method_impl);
1442      continue;
1443    } else {
1444      ObjCMethodDecl *ImpMethodDecl =
1445      IMPDecl->getInstanceMethod((*I)->getSelector());
1446      ObjCMethodDecl *MethodDecl =
1447      CDecl->getInstanceMethod((*I)->getSelector());
1448      assert(MethodDecl &&
1449             "MethodDecl is null in ImplMethodsVsClassMethods");
1450      // ImpMethodDecl may be null as in a @dynamic property.
1451      if (ImpMethodDecl) {
1452        if (!WarnExactMatch)
1453          WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1454                                      isa<ObjCProtocolDecl>(CDecl));
1455        else
1456          WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1457                               isa<ObjCProtocolDecl>(CDecl));
1458      }
1459    }
1460  }
1461
1462  // Check and see if class methods in class interface have been
1463  // implemented in the implementation class. If so, their types match.
1464   for (ObjCInterfaceDecl::classmeth_iterator
1465       I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1466     if (ClsMapSeen.count((*I)->getSelector()))
1467       continue;
1468     ClsMapSeen.insert((*I)->getSelector());
1469    if (!ClsMap.count((*I)->getSelector())) {
1470      if (ImmediateClass)
1471        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1472                            diag::note_undef_method_impl);
1473    } else {
1474      ObjCMethodDecl *ImpMethodDecl =
1475        IMPDecl->getClassMethod((*I)->getSelector());
1476      ObjCMethodDecl *MethodDecl =
1477        CDecl->getClassMethod((*I)->getSelector());
1478      if (!WarnExactMatch)
1479        WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1480                                    isa<ObjCProtocolDecl>(CDecl));
1481      else
1482        WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1483                             isa<ObjCProtocolDecl>(CDecl));
1484    }
1485  }
1486
1487  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1488    // Also methods in class extensions need be looked at next.
1489    for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
1490         ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1491      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1492                                 IMPDecl,
1493                                 const_cast<ObjCCategoryDecl *>(ClsExtDecl),
1494                                 IncompleteImpl, false, WarnExactMatch);
1495
1496    // Check for any implementation of a methods declared in protocol.
1497    for (ObjCInterfaceDecl::all_protocol_iterator
1498          PI = I->all_referenced_protocol_begin(),
1499          E = I->all_referenced_protocol_end(); PI != E; ++PI)
1500      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1501                                 IMPDecl,
1502                                 (*PI), IncompleteImpl, false, WarnExactMatch);
1503
1504    // FIXME. For now, we are not checking for extact match of methods
1505    // in category implementation and its primary class's super class.
1506    if (!WarnExactMatch && I->getSuperClass())
1507      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1508                                 IMPDecl,
1509                                 I->getSuperClass(), IncompleteImpl, false);
1510  }
1511}
1512
1513/// MatchMethodsInClassAndProtocols - This routine goes thru list of methods
1514/// declared in the class, and its class extensions. For each method which is
1515/// also declared in one of its qualifying protocols, they must type match or
1516/// it issues a warning.
1517static void MatchMethodsInClassAndProtocols(Sema &S,
1518                                              const ObjCContainerDecl *IDecl,
1519                              Sema::ProtocolsMethodsMap &InstMethodsInProtocols,
1520                              Sema::ProtocolsMethodsMap &ClsMethodsInProtocols) {
1521  for (ObjCInterfaceDecl::instmeth_iterator IM = IDecl->instmeth_begin(),
1522       E = IDecl->instmeth_end(); IM != E; ++IM) {
1523    Selector Sel = (*IM)->getSelector();
1524    if (ObjCMethodDecl *ProtoMethodDecl = InstMethodsInProtocols[Sel]) {
1525      ObjCMethodDecl *ClsMethodDecl = (*IM);
1526      S.WarnConflictingTypedMethods(ClsMethodDecl,
1527                                    ProtoMethodDecl, true, true);
1528    }
1529  }
1530  for (ObjCInterfaceDecl::classmeth_iterator IM = IDecl->classmeth_begin(),
1531       E = IDecl->classmeth_end(); IM != E; ++IM) {
1532    Selector Sel = (*IM)->getSelector();
1533    if (ObjCMethodDecl *ProtoMethodDecl = ClsMethodsInProtocols[Sel]) {
1534      ObjCMethodDecl *ClsMethodDecl = (*IM);
1535      S.WarnConflictingTypedMethods(ClsMethodDecl,
1536                                    ProtoMethodDecl, true, true);
1537    }
1538  }
1539
1540  if (const ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(IDecl)) {
1541    for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
1542         ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1543      MatchMethodsInClassAndProtocols(S, ClsExtDecl, InstMethodsInProtocols,
1544                                        ClsMethodsInProtocols);
1545  }
1546}
1547
1548/// CollectMethodsInOneProtocol - This routine collects all methods declared
1549/// in a given protocol.
1550static void CollectMethodsInOneProtocol(const ObjCProtocolDecl *PDecl,
1551                              Sema::ProtocolsMethodsMap &InstMethodsInProtocols,
1552                              Sema::ProtocolsMethodsMap &ClsMethodsInProtocols) {
1553  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1554       E = PDecl->instmeth_end(); I != E; ++I) {
1555    ObjCMethodDecl *method = *I;
1556    ObjCMethodDecl *&ProtocolEntry =
1557    InstMethodsInProtocols[method->getSelector()];
1558    if (!ProtocolEntry)
1559      ProtocolEntry = method;
1560  }
1561  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
1562       E = PDecl->classmeth_end(); I != E; ++I) {
1563    ObjCMethodDecl *method = *I;
1564    ObjCMethodDecl *&ProtocolEntry =
1565    ClsMethodsInProtocols[method->getSelector()];
1566    if (!ProtocolEntry)
1567      ProtocolEntry = method;
1568  }
1569}
1570
1571/// CollectMethodsInProtocols - This routine collects all methods declared
1572/// in class's list and nested qualified protocols. Instance methods and
1573/// class methods have separate containers as they have identical selectors.
1574static void CollectMethodsInProtocols(const ObjCContainerDecl *ContDecl,
1575                              Sema::ProtocolsMethodsMap &InstMethodsInProtocols,
1576                              Sema::ProtocolsMethodsMap &ClsMethodsInProtocols) {
1577  if (const ObjCInterfaceDecl *CDecl = dyn_cast<ObjCInterfaceDecl>(ContDecl)) {
1578    for (ObjCInterfaceDecl::all_protocol_iterator
1579         PI = CDecl->all_referenced_protocol_begin(),
1580         E = CDecl->all_referenced_protocol_end(); PI != E; ++PI) {
1581      ObjCProtocolDecl *PDecl = (*PI);
1582      CollectMethodsInOneProtocol(PDecl, InstMethodsInProtocols,
1583                                  ClsMethodsInProtocols);
1584
1585      for (ObjCProtocolDecl::protocol_iterator P = PDecl->protocol_begin(),
1586           PE = PDecl->protocol_end(); P != PE; ++P)
1587        CollectMethodsInProtocols((*P), InstMethodsInProtocols,
1588                                  ClsMethodsInProtocols);
1589    }
1590    if (CDecl->getSuperClass())
1591      CollectMethodsInProtocols(CDecl->getSuperClass(), InstMethodsInProtocols,
1592                                ClsMethodsInProtocols);
1593  }
1594
1595  if (const ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(ContDecl))
1596    CollectMethodsInOneProtocol(PDecl, InstMethodsInProtocols,
1597                                ClsMethodsInProtocols);
1598
1599}
1600
1601/// MatchMethodsInClassAndItsProtocol - Check that any redeclaration of
1602/// method in protocol in its qualified class match in their type and
1603/// issue warnings otherwise.
1604void Sema::MatchMethodsInClassAndItsProtocol(const ObjCInterfaceDecl *CDecl) {
1605  ProtocolsMethodsMap InstMethodsInProtocols, ClsMethodsInProtocols;
1606  CollectMethodsInProtocols(CDecl, InstMethodsInProtocols,
1607                            ClsMethodsInProtocols);
1608
1609  if (InstMethodsInProtocols.empty() && ClsMethodsInProtocols.empty())
1610    return;
1611  MatchMethodsInClassAndProtocols(*this, CDecl, InstMethodsInProtocols,
1612                                    ClsMethodsInProtocols);
1613}
1614
1615/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1616/// category matches with those implemented in its primary class and
1617/// warns each time an exact match is found.
1618void Sema::CheckCategoryVsClassMethodMatches(
1619                                  ObjCCategoryImplDecl *CatIMPDecl) {
1620  llvm::DenseSet<Selector> InsMap, ClsMap;
1621
1622  for (ObjCImplementationDecl::instmeth_iterator
1623       I = CatIMPDecl->instmeth_begin(),
1624       E = CatIMPDecl->instmeth_end(); I!=E; ++I)
1625    InsMap.insert((*I)->getSelector());
1626
1627  for (ObjCImplementationDecl::classmeth_iterator
1628       I = CatIMPDecl->classmeth_begin(),
1629       E = CatIMPDecl->classmeth_end(); I != E; ++I)
1630    ClsMap.insert((*I)->getSelector());
1631  if (InsMap.empty() && ClsMap.empty())
1632    return;
1633
1634  // Get category's primary class.
1635  ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1636  if (!CatDecl)
1637    return;
1638  ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1639  if (!IDecl)
1640    return;
1641  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1642  bool IncompleteImpl = false;
1643  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1644                             CatIMPDecl, IDecl,
1645                             IncompleteImpl, false, true /*WarnExactMatch*/);
1646}
1647
1648void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1649                                     ObjCContainerDecl* CDecl,
1650                                     bool IncompleteImpl) {
1651  llvm::DenseSet<Selector> InsMap;
1652  // Check and see if instance methods in class interface have been
1653  // implemented in the implementation class.
1654  for (ObjCImplementationDecl::instmeth_iterator
1655         I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1656    InsMap.insert((*I)->getSelector());
1657
1658  // Check and see if properties declared in the interface have either 1)
1659  // an implementation or 2) there is a @synthesize/@dynamic implementation
1660  // of the property in the @implementation.
1661  if (isa<ObjCInterfaceDecl>(CDecl) &&
1662        !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2))
1663    DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1664
1665  llvm::DenseSet<Selector> ClsMap;
1666  for (ObjCImplementationDecl::classmeth_iterator
1667       I = IMPDecl->classmeth_begin(),
1668       E = IMPDecl->classmeth_end(); I != E; ++I)
1669    ClsMap.insert((*I)->getSelector());
1670
1671  // Check for type conflict of methods declared in a class/protocol and
1672  // its implementation; if any.
1673  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1674  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1675                             IMPDecl, CDecl,
1676                             IncompleteImpl, true);
1677  // Check for any type mismtch of methods declared in class
1678  // and methods declared in protocol. Do this only when the class
1679  // is being implementaed.
1680  if (isa<ObjCImplementationDecl>(IMPDecl))
1681    if (const ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(CDecl))
1682      MatchMethodsInClassAndItsProtocol(I);
1683
1684  // check all methods implemented in category against those declared
1685  // in its primary class.
1686  if (ObjCCategoryImplDecl *CatDecl =
1687        dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1688    CheckCategoryVsClassMethodMatches(CatDecl);
1689
1690  // Check the protocol list for unimplemented methods in the @implementation
1691  // class.
1692  // Check and see if class methods in class interface have been
1693  // implemented in the implementation class.
1694
1695  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1696    for (ObjCInterfaceDecl::all_protocol_iterator
1697          PI = I->all_referenced_protocol_begin(),
1698          E = I->all_referenced_protocol_end(); PI != E; ++PI)
1699      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1700                              InsMap, ClsMap, I);
1701    // Check class extensions (unnamed categories)
1702    for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
1703         Categories; Categories = Categories->getNextClassExtension())
1704      ImplMethodsVsClassMethods(S, IMPDecl,
1705                                const_cast<ObjCCategoryDecl*>(Categories),
1706                                IncompleteImpl);
1707  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1708    // For extended class, unimplemented methods in its protocols will
1709    // be reported in the primary class.
1710    if (!C->IsClassExtension()) {
1711      for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1712           E = C->protocol_end(); PI != E; ++PI)
1713        CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1714                                InsMap, ClsMap, CDecl);
1715      // Report unimplemented properties in the category as well.
1716      // When reporting on missing setter/getters, do not report when
1717      // setter/getter is implemented in category's primary class
1718      // implementation.
1719      if (ObjCInterfaceDecl *ID = C->getClassInterface())
1720        if (ObjCImplDecl *IMP = ID->getImplementation()) {
1721          for (ObjCImplementationDecl::instmeth_iterator
1722               I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1723            InsMap.insert((*I)->getSelector());
1724        }
1725      DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1726    }
1727  } else
1728    assert(false && "invalid ObjCContainerDecl type.");
1729}
1730
1731/// ActOnForwardClassDeclaration -
1732Decl *
1733Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1734                                   IdentifierInfo **IdentList,
1735                                   SourceLocation *IdentLocs,
1736                                   unsigned NumElts) {
1737  SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1738
1739  for (unsigned i = 0; i != NumElts; ++i) {
1740    // Check for another declaration kind with the same name.
1741    NamedDecl *PrevDecl
1742      = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1743                         LookupOrdinaryName, ForRedeclaration);
1744    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1745      // Maybe we will complain about the shadowed template parameter.
1746      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1747      // Just pretend that we didn't see the previous declaration.
1748      PrevDecl = 0;
1749    }
1750
1751    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1752      // GCC apparently allows the following idiom:
1753      //
1754      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1755      // @class XCElementToggler;
1756      //
1757      // FIXME: Make an extension?
1758      TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1759      if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1760        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1761        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1762      } else {
1763        // a forward class declaration matching a typedef name of a class refers
1764        // to the underlying class.
1765        if (const ObjCObjectType *OI =
1766              TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1767          PrevDecl = OI->getInterface();
1768      }
1769    }
1770    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1771    if (!IDecl) {  // Not already seen?  Make a forward decl.
1772      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1773                                        IdentList[i], IdentLocs[i], true);
1774
1775      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1776      // the current DeclContext.  This prevents clients that walk DeclContext
1777      // from seeing the imaginary ObjCInterfaceDecl until it is actually
1778      // declared later (if at all).  We also take care to explicitly make
1779      // sure this declaration is visible for name lookup.
1780      PushOnScopeChains(IDecl, TUScope, false);
1781      CurContext->makeDeclVisibleInContext(IDecl, true);
1782    }
1783
1784    Interfaces.push_back(IDecl);
1785  }
1786
1787  assert(Interfaces.size() == NumElts);
1788  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1789                                               Interfaces.data(), IdentLocs,
1790                                               Interfaces.size());
1791  CurContext->addDecl(CDecl);
1792  CheckObjCDeclScope(CDecl);
1793  return CDecl;
1794}
1795
1796static bool tryMatchRecordTypes(ASTContext &Context,
1797                                Sema::MethodMatchStrategy strategy,
1798                                const Type *left, const Type *right);
1799
1800static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
1801                       QualType leftQT, QualType rightQT) {
1802  const Type *left =
1803    Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
1804  const Type *right =
1805    Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
1806
1807  if (left == right) return true;
1808
1809  // If we're doing a strict match, the types have to match exactly.
1810  if (strategy == Sema::MMS_strict) return false;
1811
1812  if (left->isIncompleteType() || right->isIncompleteType()) return false;
1813
1814  // Otherwise, use this absurdly complicated algorithm to try to
1815  // validate the basic, low-level compatibility of the two types.
1816
1817  // As a minimum, require the sizes and alignments to match.
1818  if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
1819    return false;
1820
1821  // Consider all the kinds of non-dependent canonical types:
1822  // - functions and arrays aren't possible as return and parameter types
1823
1824  // - vector types of equal size can be arbitrarily mixed
1825  if (isa<VectorType>(left)) return isa<VectorType>(right);
1826  if (isa<VectorType>(right)) return false;
1827
1828  // - references should only match references of identical type
1829  // - structs, unions, and Objective-C objects must match more-or-less
1830  //   exactly
1831  // - everything else should be a scalar
1832  if (!left->isScalarType() || !right->isScalarType())
1833    return tryMatchRecordTypes(Context, strategy, left, right);
1834
1835  // Make scalars agree in kind, except count bools as chars.
1836  Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
1837  Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
1838  if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
1839  if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
1840
1841  // Note that data member pointers and function member pointers don't
1842  // intermix because of the size differences.
1843
1844  return (leftSK == rightSK);
1845}
1846
1847static bool tryMatchRecordTypes(ASTContext &Context,
1848                                Sema::MethodMatchStrategy strategy,
1849                                const Type *lt, const Type *rt) {
1850  assert(lt && rt && lt != rt);
1851
1852  if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
1853  RecordDecl *left = cast<RecordType>(lt)->getDecl();
1854  RecordDecl *right = cast<RecordType>(rt)->getDecl();
1855
1856  // Require union-hood to match.
1857  if (left->isUnion() != right->isUnion()) return false;
1858
1859  // Require an exact match if either is non-POD.
1860  if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
1861      (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
1862    return false;
1863
1864  // Require size and alignment to match.
1865  if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
1866
1867  // Require fields to match.
1868  RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
1869  RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
1870  for (; li != le && ri != re; ++li, ++ri) {
1871    if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
1872      return false;
1873  }
1874  return (li == le && ri == re);
1875}
1876
1877/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1878/// returns true, or false, accordingly.
1879/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1880bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
1881                                      const ObjCMethodDecl *right,
1882                                      MethodMatchStrategy strategy) {
1883  if (!matchTypes(Context, strategy,
1884                  left->getResultType(), right->getResultType()))
1885    return false;
1886
1887  if (getLangOptions().ObjCAutoRefCount &&
1888      (left->hasAttr<NSReturnsRetainedAttr>()
1889         != right->hasAttr<NSReturnsRetainedAttr>() ||
1890       left->hasAttr<NSConsumesSelfAttr>()
1891         != right->hasAttr<NSConsumesSelfAttr>()))
1892    return false;
1893
1894  ObjCMethodDecl::param_iterator
1895    li = left->param_begin(), le = left->param_end(), ri = right->param_begin();
1896
1897  for (; li != le; ++li, ++ri) {
1898    assert(ri != right->param_end() && "Param mismatch");
1899    ParmVarDecl *lparm = *li, *rparm = *ri;
1900
1901    if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
1902      return false;
1903
1904    if (getLangOptions().ObjCAutoRefCount &&
1905        lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
1906      return false;
1907  }
1908  return true;
1909}
1910
1911/// \brief Read the contents of the method pool for a given selector from
1912/// external storage.
1913///
1914/// This routine should only be called once, when the method pool has no entry
1915/// for this selector.
1916Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
1917  assert(ExternalSource && "We need an external AST source");
1918  assert(MethodPool.find(Sel) == MethodPool.end() &&
1919         "Selector data already loaded into the method pool");
1920
1921  // Read the method list from the external source.
1922  GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
1923
1924  return MethodPool.insert(std::make_pair(Sel, Methods)).first;
1925}
1926
1927void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
1928                                 bool instance) {
1929  GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
1930  if (Pos == MethodPool.end()) {
1931    if (ExternalSource)
1932      Pos = ReadMethodPool(Method->getSelector());
1933    else
1934      Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
1935                                             GlobalMethods())).first;
1936  }
1937  Method->setDefined(impl);
1938  ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
1939  if (Entry.Method == 0) {
1940    // Haven't seen a method with this selector name yet - add it.
1941    Entry.Method = Method;
1942    Entry.Next = 0;
1943    return;
1944  }
1945
1946  // We've seen a method with this name, see if we have already seen this type
1947  // signature.
1948  for (ObjCMethodList *List = &Entry; List; List = List->Next) {
1949    bool match = MatchTwoMethodDeclarations(Method, List->Method);
1950
1951    if (match) {
1952      ObjCMethodDecl *PrevObjCMethod = List->Method;
1953      PrevObjCMethod->setDefined(impl);
1954      // If a method is deprecated, push it in the global pool.
1955      // This is used for better diagnostics.
1956      if (Method->isDeprecated()) {
1957        if (!PrevObjCMethod->isDeprecated())
1958          List->Method = Method;
1959      }
1960      // If new method is unavailable, push it into global pool
1961      // unless previous one is deprecated.
1962      if (Method->isUnavailable()) {
1963        if (PrevObjCMethod->getAvailability() < AR_Deprecated)
1964          List->Method = Method;
1965      }
1966      return;
1967    }
1968  }
1969
1970  // We have a new signature for an existing method - add it.
1971  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1972  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1973  Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1974}
1975
1976/// Determines if this is an "acceptable" loose mismatch in the global
1977/// method pool.  This exists mostly as a hack to get around certain
1978/// global mismatches which we can't afford to make warnings / errors.
1979/// Really, what we want is a way to take a method out of the global
1980/// method pool.
1981static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
1982                                       ObjCMethodDecl *other) {
1983  if (!chosen->isInstanceMethod())
1984    return false;
1985
1986  Selector sel = chosen->getSelector();
1987  if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
1988    return false;
1989
1990  // Don't complain about mismatches for -length if the method we
1991  // chose has an integral result type.
1992  return (chosen->getResultType()->isIntegerType());
1993}
1994
1995ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1996                                               bool receiverIdOrClass,
1997                                               bool warn, bool instance) {
1998  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1999  if (Pos == MethodPool.end()) {
2000    if (ExternalSource)
2001      Pos = ReadMethodPool(Sel);
2002    else
2003      return 0;
2004  }
2005
2006  ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2007
2008  if (warn && MethList.Method && MethList.Next) {
2009    bool issueDiagnostic = false, issueError = false;
2010
2011    // We support a warning which complains about *any* difference in
2012    // method signature.
2013    bool strictSelectorMatch =
2014      (receiverIdOrClass && warn &&
2015       (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
2016                                 R.getBegin()) !=
2017      Diagnostic::Ignored));
2018    if (strictSelectorMatch)
2019      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2020        if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2021                                        MMS_strict)) {
2022          issueDiagnostic = true;
2023          break;
2024        }
2025      }
2026
2027    // If we didn't see any strict differences, we won't see any loose
2028    // differences.  In ARC, however, we also need to check for loose
2029    // mismatches, because most of them are errors.
2030    if (!strictSelectorMatch ||
2031        (issueDiagnostic && getLangOptions().ObjCAutoRefCount))
2032      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2033        // This checks if the methods differ in type mismatch.
2034        if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2035                                        MMS_loose) &&
2036            !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
2037          issueDiagnostic = true;
2038          if (getLangOptions().ObjCAutoRefCount)
2039            issueError = true;
2040          break;
2041        }
2042      }
2043
2044    if (issueDiagnostic) {
2045      if (issueError)
2046        Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2047      else if (strictSelectorMatch)
2048        Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2049      else
2050        Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2051
2052      Diag(MethList.Method->getLocStart(),
2053           issueError ? diag::note_possibility : diag::note_using)
2054        << MethList.Method->getSourceRange();
2055      for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
2056        Diag(Next->Method->getLocStart(), diag::note_also_found)
2057          << Next->Method->getSourceRange();
2058    }
2059  }
2060  return MethList.Method;
2061}
2062
2063ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2064  GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2065  if (Pos == MethodPool.end())
2066    return 0;
2067
2068  GlobalMethods &Methods = Pos->second;
2069
2070  if (Methods.first.Method && Methods.first.Method->isDefined())
2071    return Methods.first.Method;
2072  if (Methods.second.Method && Methods.second.Method->isDefined())
2073    return Methods.second.Method;
2074  return 0;
2075}
2076
2077/// CompareMethodParamsInBaseAndSuper - This routine compares methods with
2078/// identical selector names in current and its super classes and issues
2079/// a warning if any of their argument types are incompatible.
2080void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
2081                                             ObjCMethodDecl *Method,
2082                                             bool IsInstance)  {
2083  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2084  if (ID == 0) return;
2085
2086  while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
2087    ObjCMethodDecl *SuperMethodDecl =
2088        SD->lookupMethod(Method->getSelector(), IsInstance);
2089    if (SuperMethodDecl == 0) {
2090      ID = SD;
2091      continue;
2092    }
2093    ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
2094      E = Method->param_end();
2095    ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
2096    for (; ParamI != E; ++ParamI, ++PrevI) {
2097      // Number of parameters are the same and is guaranteed by selector match.
2098      assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
2099      QualType T1 = Context.getCanonicalType((*ParamI)->getType());
2100      QualType T2 = Context.getCanonicalType((*PrevI)->getType());
2101      // If type of argument of method in this class does not match its
2102      // respective argument type in the super class method, issue warning;
2103      if (!Context.typesAreCompatible(T1, T2)) {
2104        Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
2105          << T1 << T2;
2106        Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
2107        return;
2108      }
2109    }
2110    ID = SD;
2111  }
2112}
2113
2114/// DiagnoseDuplicateIvars -
2115/// Check for duplicate ivars in the entire class at the start of
2116/// @implementation. This becomes necesssary because class extension can
2117/// add ivars to a class in random order which will not be known until
2118/// class's @implementation is seen.
2119void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2120                                  ObjCInterfaceDecl *SID) {
2121  for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
2122       IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
2123    ObjCIvarDecl* Ivar = (*IVI);
2124    if (Ivar->isInvalidDecl())
2125      continue;
2126    if (IdentifierInfo *II = Ivar->getIdentifier()) {
2127      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2128      if (prevIvar) {
2129        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2130        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2131        Ivar->setInvalidDecl();
2132      }
2133    }
2134  }
2135}
2136
2137// Note: For class/category implemenations, allMethods/allProperties is
2138// always null.
2139void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
2140                      Decl *ClassDecl,
2141                      Decl **allMethods, unsigned allNum,
2142                      Decl **allProperties, unsigned pNum,
2143                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
2144  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
2145  // always passing in a decl. If the decl has an error, isInvalidDecl()
2146  // should be true.
2147  if (!ClassDecl)
2148    return;
2149
2150  bool isInterfaceDeclKind =
2151        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2152         || isa<ObjCProtocolDecl>(ClassDecl);
2153  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2154
2155  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
2156    // FIXME: This is wrong.  We shouldn't be pretending that there is
2157    //  an '@end' in the declaration.
2158    SourceLocation L = ClassDecl->getLocation();
2159    AtEnd.setBegin(L);
2160    AtEnd.setEnd(L);
2161    Diag(L, diag::err_missing_atend);
2162  }
2163
2164  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2165  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2166  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2167
2168  for (unsigned i = 0; i < allNum; i++ ) {
2169    ObjCMethodDecl *Method =
2170      cast_or_null<ObjCMethodDecl>(allMethods[i]);
2171
2172    if (!Method) continue;  // Already issued a diagnostic.
2173    if (Method->isInstanceMethod()) {
2174      /// Check for instance method of the same name with incompatible types
2175      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2176      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2177                              : false;
2178      if ((isInterfaceDeclKind && PrevMethod && !match)
2179          || (checkIdenticalMethods && match)) {
2180          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2181            << Method->getDeclName();
2182          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2183        Method->setInvalidDecl();
2184      } else {
2185        InsMap[Method->getSelector()] = Method;
2186        /// The following allows us to typecheck messages to "id".
2187        AddInstanceMethodToGlobalPool(Method);
2188        // verify that the instance method conforms to the same definition of
2189        // parent methods if it shadows one.
2190        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
2191      }
2192    } else {
2193      /// Check for class method of the same name with incompatible types
2194      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2195      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2196                              : false;
2197      if ((isInterfaceDeclKind && PrevMethod && !match)
2198          || (checkIdenticalMethods && match)) {
2199        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2200          << Method->getDeclName();
2201        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2202        Method->setInvalidDecl();
2203      } else {
2204        ClsMap[Method->getSelector()] = Method;
2205        /// The following allows us to typecheck messages to "Class".
2206        AddFactoryMethodToGlobalPool(Method);
2207        // verify that the class method conforms to the same definition of
2208        // parent methods if it shadows one.
2209        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
2210      }
2211    }
2212  }
2213  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
2214    // Compares properties declared in this class to those of its
2215    // super class.
2216    ComparePropertiesInBaseAndSuper(I);
2217    CompareProperties(I, I);
2218  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2219    // Categories are used to extend the class by declaring new methods.
2220    // By the same token, they are also used to add new properties. No
2221    // need to compare the added property to those in the class.
2222
2223    // Compare protocol properties with those in category
2224    CompareProperties(C, C);
2225    if (C->IsClassExtension()) {
2226      ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2227      DiagnoseClassExtensionDupMethods(C, CCPrimary);
2228    }
2229  }
2230  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2231    if (CDecl->getIdentifier())
2232      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2233      // user-defined setter/getter. It also synthesizes setter/getter methods
2234      // and adds them to the DeclContext and global method pools.
2235      for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
2236                                            E = CDecl->prop_end();
2237           I != E; ++I)
2238        ProcessPropertyDecl(*I, CDecl);
2239    CDecl->setAtEndRange(AtEnd);
2240  }
2241  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2242    IC->setAtEndRange(AtEnd);
2243    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2244      // Any property declared in a class extension might have user
2245      // declared setter or getter in current class extension or one
2246      // of the other class extensions. Mark them as synthesized as
2247      // property will be synthesized when property with same name is
2248      // seen in the @implementation.
2249      for (const ObjCCategoryDecl *ClsExtDecl =
2250           IDecl->getFirstClassExtension();
2251           ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
2252        for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
2253             E = ClsExtDecl->prop_end(); I != E; ++I) {
2254          ObjCPropertyDecl *Property = (*I);
2255          // Skip over properties declared @dynamic
2256          if (const ObjCPropertyImplDecl *PIDecl
2257              = IC->FindPropertyImplDecl(Property->getIdentifier()))
2258            if (PIDecl->getPropertyImplementation()
2259                  == ObjCPropertyImplDecl::Dynamic)
2260              continue;
2261
2262          for (const ObjCCategoryDecl *CExtDecl =
2263               IDecl->getFirstClassExtension();
2264               CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
2265            if (ObjCMethodDecl *GetterMethod =
2266                CExtDecl->getInstanceMethod(Property->getGetterName()))
2267              GetterMethod->setSynthesized(true);
2268            if (!Property->isReadOnly())
2269              if (ObjCMethodDecl *SetterMethod =
2270                  CExtDecl->getInstanceMethod(Property->getSetterName()))
2271                SetterMethod->setSynthesized(true);
2272          }
2273        }
2274      }
2275
2276      if (LangOpts.ObjCDefaultSynthProperties &&
2277          LangOpts.ObjCNonFragileABI2)
2278        DefaultSynthesizeProperties(S, IC, IDecl);
2279      ImplMethodsVsClassMethods(S, IC, IDecl);
2280      AtomicPropertySetterGetterRules(IC, IDecl);
2281      DiagnoseOwningPropertyGetterSynthesis(IC);
2282
2283      if (LangOpts.ObjCNonFragileABI2)
2284        while (IDecl->getSuperClass()) {
2285          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2286          IDecl = IDecl->getSuperClass();
2287        }
2288    }
2289    SetIvarInitializers(IC);
2290  } else if (ObjCCategoryImplDecl* CatImplClass =
2291                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2292    CatImplClass->setAtEndRange(AtEnd);
2293
2294    // Find category interface decl and then check that all methods declared
2295    // in this interface are implemented in the category @implementation.
2296    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2297      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
2298           Categories; Categories = Categories->getNextClassCategory()) {
2299        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
2300          ImplMethodsVsClassMethods(S, CatImplClass, Categories);
2301          break;
2302        }
2303      }
2304    }
2305  }
2306  if (isInterfaceDeclKind) {
2307    // Reject invalid vardecls.
2308    for (unsigned i = 0; i != tuvNum; i++) {
2309      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2310      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2311        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2312          if (!VDecl->hasExternalStorage())
2313            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2314        }
2315    }
2316  }
2317}
2318
2319
2320/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2321/// objective-c's type qualifier from the parser version of the same info.
2322static Decl::ObjCDeclQualifier
2323CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2324  return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2325}
2326
2327static inline
2328bool containsInvalidMethodImplAttribute(const AttrVec &A) {
2329  // The 'ibaction' attribute is allowed on method definitions because of
2330  // how the IBAction macro is used on both method declarations and definitions.
2331  // If the method definitions contains any other attributes, return true.
2332  for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
2333    if ((*i)->getKind() != attr::IBAction)
2334      return true;
2335  return false;
2336}
2337
2338/// \brief Check whether the declared result type of the given Objective-C
2339/// method declaration is compatible with the method's class.
2340///
2341static bool
2342CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2343                                    ObjCInterfaceDecl *CurrentClass) {
2344  QualType ResultType = Method->getResultType();
2345  SourceRange ResultTypeRange;
2346  if (const TypeSourceInfo *ResultTypeInfo = Method->getResultTypeSourceInfo())
2347    ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
2348
2349  // If an Objective-C method inherits its related result type, then its
2350  // declared result type must be compatible with its own class type. The
2351  // declared result type is compatible if:
2352  if (const ObjCObjectPointerType *ResultObjectType
2353                                = ResultType->getAs<ObjCObjectPointerType>()) {
2354    //   - it is id or qualified id, or
2355    if (ResultObjectType->isObjCIdType() ||
2356        ResultObjectType->isObjCQualifiedIdType())
2357      return false;
2358
2359    if (CurrentClass) {
2360      if (ObjCInterfaceDecl *ResultClass
2361                                      = ResultObjectType->getInterfaceDecl()) {
2362        //   - it is the same as the method's class type, or
2363        if (CurrentClass == ResultClass)
2364          return false;
2365
2366        //   - it is a superclass of the method's class type
2367        if (ResultClass->isSuperClassOf(CurrentClass))
2368          return false;
2369      }
2370    }
2371  }
2372
2373  return true;
2374}
2375
2376namespace {
2377/// A helper class for searching for methods which a particular method
2378/// overrides.
2379class OverrideSearch {
2380  Sema &S;
2381  ObjCMethodDecl *Method;
2382  llvm::SmallPtrSet<ObjCContainerDecl*, 8> Searched;
2383  llvm::SmallPtrSet<ObjCMethodDecl*, 8> Overridden;
2384  bool Recursive;
2385
2386public:
2387  OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2388    Selector selector = method->getSelector();
2389
2390    // Bypass this search if we've never seen an instance/class method
2391    // with this selector before.
2392    Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2393    if (it == S.MethodPool.end()) {
2394      if (!S.ExternalSource) return;
2395      it = S.ReadMethodPool(selector);
2396    }
2397    ObjCMethodList &list =
2398      method->isInstanceMethod() ? it->second.first : it->second.second;
2399    if (!list.Method) return;
2400
2401    ObjCContainerDecl *container
2402      = cast<ObjCContainerDecl>(method->getDeclContext());
2403
2404    // Prevent the search from reaching this container again.  This is
2405    // important with categories, which override methods from the
2406    // interface and each other.
2407    Searched.insert(container);
2408    searchFromContainer(container);
2409  }
2410
2411  typedef llvm::SmallPtrSet<ObjCMethodDecl*,8>::iterator iterator;
2412  iterator begin() const { return Overridden.begin(); }
2413  iterator end() const { return Overridden.end(); }
2414
2415private:
2416  void searchFromContainer(ObjCContainerDecl *container) {
2417    if (container->isInvalidDecl()) return;
2418
2419    switch (container->getDeclKind()) {
2420#define OBJCCONTAINER(type, base) \
2421    case Decl::type: \
2422      searchFrom(cast<type##Decl>(container)); \
2423      break;
2424#define ABSTRACT_DECL(expansion)
2425#define DECL(type, base) \
2426    case Decl::type:
2427#include "clang/AST/DeclNodes.inc"
2428      llvm_unreachable("not an ObjC container!");
2429    }
2430  }
2431
2432  void searchFrom(ObjCProtocolDecl *protocol) {
2433    // A method in a protocol declaration overrides declarations from
2434    // referenced ("parent") protocols.
2435    search(protocol->getReferencedProtocols());
2436  }
2437
2438  void searchFrom(ObjCCategoryDecl *category) {
2439    // A method in a category declaration overrides declarations from
2440    // the main class and from protocols the category references.
2441    search(category->getClassInterface());
2442    search(category->getReferencedProtocols());
2443  }
2444
2445  void searchFrom(ObjCCategoryImplDecl *impl) {
2446    // A method in a category definition that has a category
2447    // declaration overrides declarations from the category
2448    // declaration.
2449    if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2450      search(category);
2451
2452    // Otherwise it overrides declarations from the class.
2453    } else {
2454      search(impl->getClassInterface());
2455    }
2456  }
2457
2458  void searchFrom(ObjCInterfaceDecl *iface) {
2459    // A method in a class declaration overrides declarations from
2460
2461    //   - categories,
2462    for (ObjCCategoryDecl *category = iface->getCategoryList();
2463           category; category = category->getNextClassCategory())
2464      search(category);
2465
2466    //   - the super class, and
2467    if (ObjCInterfaceDecl *super = iface->getSuperClass())
2468      search(super);
2469
2470    //   - any referenced protocols.
2471    search(iface->getReferencedProtocols());
2472  }
2473
2474  void searchFrom(ObjCImplementationDecl *impl) {
2475    // A method in a class implementation overrides declarations from
2476    // the class interface.
2477    search(impl->getClassInterface());
2478  }
2479
2480
2481  void search(const ObjCProtocolList &protocols) {
2482    for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2483         i != e; ++i)
2484      search(*i);
2485  }
2486
2487  void search(ObjCContainerDecl *container) {
2488    // Abort if we've already searched this container.
2489    if (!Searched.insert(container)) return;
2490
2491    // Check for a method in this container which matches this selector.
2492    ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2493                                                Method->isInstanceMethod());
2494
2495    // If we find one, record it and bail out.
2496    if (meth) {
2497      Overridden.insert(meth);
2498      return;
2499    }
2500
2501    // Otherwise, search for methods that a hypothetical method here
2502    // would have overridden.
2503
2504    // Note that we're now in a recursive case.
2505    Recursive = true;
2506
2507    searchFromContainer(container);
2508  }
2509};
2510}
2511
2512Decl *Sema::ActOnMethodDeclaration(
2513    Scope *S,
2514    SourceLocation MethodLoc, SourceLocation EndLoc,
2515    tok::TokenKind MethodType, Decl *ClassDecl,
2516    ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
2517    SourceLocation SelectorStartLoc,
2518    Selector Sel,
2519    // optional arguments. The number of types/arguments is obtained
2520    // from the Sel.getNumArgs().
2521    ObjCArgInfo *ArgInfo,
2522    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
2523    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
2524    bool isVariadic, bool MethodDefinition) {
2525  // Make sure we can establish a context for the method.
2526  if (!ClassDecl) {
2527    Diag(MethodLoc, diag::error_missing_method_context);
2528    return 0;
2529  }
2530  QualType resultDeclType;
2531
2532  TypeSourceInfo *ResultTInfo = 0;
2533  if (ReturnType) {
2534    resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
2535
2536    // Methods cannot return interface types. All ObjC objects are
2537    // passed by reference.
2538    if (resultDeclType->isObjCObjectType()) {
2539      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
2540        << 0 << resultDeclType;
2541      return 0;
2542    }
2543  } else { // get the type for "id".
2544    resultDeclType = Context.getObjCIdType();
2545    Diag(MethodLoc, diag::warn_missing_method_return_type)
2546      << FixItHint::CreateInsertion(SelectorStartLoc, "(id)");
2547  }
2548
2549  ObjCMethodDecl* ObjCMethod =
2550    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
2551                           ResultTInfo,
2552                           cast<DeclContext>(ClassDecl),
2553                           MethodType == tok::minus, isVariadic,
2554                           false, false,
2555                           MethodDeclKind == tok::objc_optional
2556                             ? ObjCMethodDecl::Optional
2557                             : ObjCMethodDecl::Required,
2558                           false);
2559
2560  SmallVector<ParmVarDecl*, 16> Params;
2561
2562  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
2563    QualType ArgType;
2564    TypeSourceInfo *DI;
2565
2566    if (ArgInfo[i].Type == 0) {
2567      ArgType = Context.getObjCIdType();
2568      DI = 0;
2569    } else {
2570      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
2571      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2572      ArgType = Context.getAdjustedParameterType(ArgType);
2573    }
2574
2575    LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
2576                   LookupOrdinaryName, ForRedeclaration);
2577    LookupName(R, S);
2578    if (R.isSingleResult()) {
2579      NamedDecl *PrevDecl = R.getFoundDecl();
2580      if (S->isDeclScope(PrevDecl)) {
2581        Diag(ArgInfo[i].NameLoc,
2582             (MethodDefinition ? diag::warn_method_param_redefinition
2583                               : diag::warn_method_param_declaration))
2584          << ArgInfo[i].Name;
2585        Diag(PrevDecl->getLocation(),
2586             diag::note_previous_declaration);
2587      }
2588    }
2589
2590    SourceLocation StartLoc = DI
2591      ? DI->getTypeLoc().getBeginLoc()
2592      : ArgInfo[i].NameLoc;
2593
2594    ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
2595                                        ArgInfo[i].NameLoc, ArgInfo[i].Name,
2596                                        ArgType, DI, SC_None, SC_None);
2597
2598    Param->setObjCMethodScopeInfo(i);
2599
2600    Param->setObjCDeclQualifier(
2601      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
2602
2603    // Apply the attributes to the parameter.
2604    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
2605
2606    S->AddDecl(Param);
2607    IdResolver.AddDecl(Param);
2608
2609    Params.push_back(Param);
2610  }
2611
2612  for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
2613    ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
2614    QualType ArgType = Param->getType();
2615    if (ArgType.isNull())
2616      ArgType = Context.getObjCIdType();
2617    else
2618      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2619      ArgType = Context.getAdjustedParameterType(ArgType);
2620    if (ArgType->isObjCObjectType()) {
2621      Diag(Param->getLocation(),
2622           diag::err_object_cannot_be_passed_returned_by_value)
2623      << 1 << ArgType;
2624      Param->setInvalidDecl();
2625    }
2626    Param->setDeclContext(ObjCMethod);
2627
2628    Params.push_back(Param);
2629  }
2630
2631  ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
2632                              Sel.getNumArgs());
2633  ObjCMethod->setObjCDeclQualifier(
2634    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
2635
2636  if (AttrList)
2637    ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
2638
2639  // Add the method now.
2640  const ObjCMethodDecl *PrevMethod = 0;
2641  if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
2642    if (MethodType == tok::minus) {
2643      PrevMethod = ImpDecl->getInstanceMethod(Sel);
2644      ImpDecl->addInstanceMethod(ObjCMethod);
2645    } else {
2646      PrevMethod = ImpDecl->getClassMethod(Sel);
2647      ImpDecl->addClassMethod(ObjCMethod);
2648    }
2649
2650    if (ObjCMethod->hasAttrs() &&
2651        containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
2652      Diag(EndLoc, diag::warn_attribute_method_def);
2653  } else {
2654    cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
2655  }
2656
2657  if (PrevMethod) {
2658    // You can never have two method definitions with the same name.
2659    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
2660      << ObjCMethod->getDeclName();
2661    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2662  }
2663
2664  // If this Objective-C method does not have a related result type, but we
2665  // are allowed to infer related result types, try to do so based on the
2666  // method family.
2667  ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2668  if (!CurrentClass) {
2669    if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
2670      CurrentClass = Cat->getClassInterface();
2671    else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
2672      CurrentClass = Impl->getClassInterface();
2673    else if (ObjCCategoryImplDecl *CatImpl
2674                                   = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
2675      CurrentClass = CatImpl->getClassInterface();
2676  }
2677
2678  bool isRelatedResultTypeCompatible =
2679    (getLangOptions().ObjCInferRelatedResultType &&
2680     !CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass));
2681
2682  // Search for overridden methods and merge information down from them.
2683  OverrideSearch overrides(*this, ObjCMethod);
2684  for (OverrideSearch::iterator
2685         i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2686    ObjCMethodDecl *overridden = *i;
2687
2688    // Propagate down the 'related result type' bit from overridden methods.
2689    if (isRelatedResultTypeCompatible && overridden->hasRelatedResultType())
2690      ObjCMethod->SetRelatedResultType();
2691
2692    // Then merge the declarations.
2693    mergeObjCMethodDecls(ObjCMethod, overridden);
2694  }
2695
2696  bool ARCError = false;
2697  if (getLangOptions().ObjCAutoRefCount)
2698    ARCError = CheckARCMethodDecl(*this, ObjCMethod);
2699
2700  if (!ARCError && isRelatedResultTypeCompatible &&
2701      !ObjCMethod->hasRelatedResultType()) {
2702    bool InferRelatedResultType = false;
2703    switch (ObjCMethod->getMethodFamily()) {
2704    case OMF_None:
2705    case OMF_copy:
2706    case OMF_dealloc:
2707    case OMF_mutableCopy:
2708    case OMF_release:
2709    case OMF_retainCount:
2710    case OMF_performSelector:
2711      break;
2712
2713    case OMF_alloc:
2714    case OMF_new:
2715      InferRelatedResultType = ObjCMethod->isClassMethod();
2716      break;
2717
2718    case OMF_init:
2719    case OMF_autorelease:
2720    case OMF_retain:
2721    case OMF_self:
2722      InferRelatedResultType = ObjCMethod->isInstanceMethod();
2723      break;
2724    }
2725
2726    if (InferRelatedResultType)
2727      ObjCMethod->SetRelatedResultType();
2728  }
2729
2730  return ObjCMethod;
2731}
2732
2733bool Sema::CheckObjCDeclScope(Decl *D) {
2734  if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
2735    return false;
2736
2737  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
2738  D->setInvalidDecl();
2739
2740  return true;
2741}
2742
2743/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
2744/// instance variables of ClassName into Decls.
2745void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2746                     IdentifierInfo *ClassName,
2747                     SmallVectorImpl<Decl*> &Decls) {
2748  // Check that ClassName is a valid class
2749  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
2750  if (!Class) {
2751    Diag(DeclStart, diag::err_undef_interface) << ClassName;
2752    return;
2753  }
2754  if (LangOpts.ObjCNonFragileABI) {
2755    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
2756    return;
2757  }
2758
2759  // Collect the instance variables
2760  SmallVector<const ObjCIvarDecl*, 32> Ivars;
2761  Context.DeepCollectObjCIvars(Class, true, Ivars);
2762  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2763  for (unsigned i = 0; i < Ivars.size(); i++) {
2764    const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
2765    RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
2766    Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
2767                                           /*FIXME: StartL=*/ID->getLocation(),
2768                                           ID->getLocation(),
2769                                           ID->getIdentifier(), ID->getType(),
2770                                           ID->getBitWidth());
2771    Decls.push_back(FD);
2772  }
2773
2774  // Introduce all of these fields into the appropriate scope.
2775  for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
2776       D != Decls.end(); ++D) {
2777    FieldDecl *FD = cast<FieldDecl>(*D);
2778    if (getLangOptions().CPlusPlus)
2779      PushOnScopeChains(cast<FieldDecl>(FD), S);
2780    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
2781      Record->addDecl(FD);
2782  }
2783}
2784
2785/// \brief Build a type-check a new Objective-C exception variable declaration.
2786VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
2787                                      SourceLocation StartLoc,
2788                                      SourceLocation IdLoc,
2789                                      IdentifierInfo *Id,
2790                                      bool Invalid) {
2791  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
2792  // duration shall not be qualified by an address-space qualifier."
2793  // Since all parameters have automatic store duration, they can not have
2794  // an address space.
2795  if (T.getAddressSpace() != 0) {
2796    Diag(IdLoc, diag::err_arg_with_address_space);
2797    Invalid = true;
2798  }
2799
2800  // An @catch parameter must be an unqualified object pointer type;
2801  // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
2802  if (Invalid) {
2803    // Don't do any further checking.
2804  } else if (T->isDependentType()) {
2805    // Okay: we don't know what this type will instantiate to.
2806  } else if (!T->isObjCObjectPointerType()) {
2807    Invalid = true;
2808    Diag(IdLoc ,diag::err_catch_param_not_objc_type);
2809  } else if (T->isObjCQualifiedIdType()) {
2810    Invalid = true;
2811    Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
2812  }
2813
2814  VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
2815                                 T, TInfo, SC_None, SC_None);
2816  New->setExceptionVariable(true);
2817
2818  if (Invalid)
2819    New->setInvalidDecl();
2820  return New;
2821}
2822
2823Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
2824  const DeclSpec &DS = D.getDeclSpec();
2825
2826  // We allow the "register" storage class on exception variables because
2827  // GCC did, but we drop it completely. Any other storage class is an error.
2828  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2829    Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
2830      << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
2831  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2832    Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
2833      << DS.getStorageClassSpec();
2834  }
2835  if (D.getDeclSpec().isThreadSpecified())
2836    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2837  D.getMutableDeclSpec().ClearStorageClassSpecs();
2838
2839  DiagnoseFunctionSpecifiers(D);
2840
2841  // Check that there are no default arguments inside the type of this
2842  // exception object (C++ only).
2843  if (getLangOptions().CPlusPlus)
2844    CheckExtraCXXDefaultArguments(D);
2845
2846  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2847  QualType ExceptionType = TInfo->getType();
2848
2849  VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
2850                                        D.getSourceRange().getBegin(),
2851                                        D.getIdentifierLoc(),
2852                                        D.getIdentifier(),
2853                                        D.isInvalidType());
2854
2855  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2856  if (D.getCXXScopeSpec().isSet()) {
2857    Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
2858      << D.getCXXScopeSpec().getRange();
2859    New->setInvalidDecl();
2860  }
2861
2862  // Add the parameter declaration into this scope.
2863  S->AddDecl(New);
2864  if (D.getIdentifier())
2865    IdResolver.AddDecl(New);
2866
2867  ProcessDeclAttributes(S, New, D);
2868
2869  if (New->hasAttr<BlocksAttr>())
2870    Diag(New->getLocation(), diag::err_block_on_nonlocal);
2871  return New;
2872}
2873
2874/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2875/// initialization.
2876void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2877                                SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
2878  for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
2879       Iv= Iv->getNextIvar()) {
2880    QualType QT = Context.getBaseElementType(Iv->getType());
2881    if (QT->isRecordType())
2882      Ivars.push_back(Iv);
2883  }
2884}
2885
2886void Sema::DiagnoseUseOfUnimplementedSelectors() {
2887  // Load referenced selectors from the external source.
2888  if (ExternalSource) {
2889    SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
2890    ExternalSource->ReadReferencedSelectors(Sels);
2891    for (unsigned I = 0, N = Sels.size(); I != N; ++I)
2892      ReferencedSelectors[Sels[I].first] = Sels[I].second;
2893  }
2894
2895  // Warning will be issued only when selector table is
2896  // generated (which means there is at lease one implementation
2897  // in the TU). This is to match gcc's behavior.
2898  if (ReferencedSelectors.empty() ||
2899      !Context.AnyObjCImplementation())
2900    return;
2901  for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
2902        ReferencedSelectors.begin(),
2903       E = ReferencedSelectors.end(); S != E; ++S) {
2904    Selector Sel = (*S).first;
2905    if (!LookupImplementedMethodInGlobalPool(Sel))
2906      Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
2907  }
2908  return;
2909}
2910