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