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