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