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