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