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