xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDeclObjC.cpp (revision 924226fba12cc9a228c73b956e1b7fa24c60b055)
1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements semantic analysis for Objective C declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/RecursiveASTVisitor.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
30 
31 using namespace clang;
32 
33 /// Check whether the given method, which must be in the 'init'
34 /// family, is a valid member of that family.
35 ///
36 /// \param receiverTypeIfCall - if null, check this as if declaring it;
37 ///   if non-null, check this as if making a call to it with the given
38 ///   receiver type
39 ///
40 /// \return true to indicate that there was an error and appropriate
41 ///   actions were taken
42 bool Sema::checkInitMethod(ObjCMethodDecl *method,
43                            QualType receiverTypeIfCall) {
44   if (method->isInvalidDecl()) return true;
45 
46   // This castAs is safe: methods that don't return an object
47   // pointer won't be inferred as inits and will reject an explicit
48   // objc_method_family(init).
49 
50   // We ignore protocols here.  Should we?  What about Class?
51 
52   const ObjCObjectType *result =
53       method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
54 
55   if (result->isObjCId()) {
56     return false;
57   } else if (result->isObjCClass()) {
58     // fall through: always an error
59   } else {
60     ObjCInterfaceDecl *resultClass = result->getInterface();
61     assert(resultClass && "unexpected object type!");
62 
63     // It's okay for the result type to still be a forward declaration
64     // if we're checking an interface declaration.
65     if (!resultClass->hasDefinition()) {
66       if (receiverTypeIfCall.isNull() &&
67           !isa<ObjCImplementationDecl>(method->getDeclContext()))
68         return false;
69 
70     // Otherwise, we try to compare class types.
71     } else {
72       // If this method was declared in a protocol, we can't check
73       // anything unless we have a receiver type that's an interface.
74       const ObjCInterfaceDecl *receiverClass = nullptr;
75       if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76         if (receiverTypeIfCall.isNull())
77           return false;
78 
79         receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
80           ->getInterfaceDecl();
81 
82         // This can be null for calls to e.g. id<Foo>.
83         if (!receiverClass) return false;
84       } else {
85         receiverClass = method->getClassInterface();
86         assert(receiverClass && "method not associated with a class!");
87       }
88 
89       // If either class is a subclass of the other, it's fine.
90       if (receiverClass->isSuperClassOf(resultClass) ||
91           resultClass->isSuperClassOf(receiverClass))
92         return false;
93     }
94   }
95 
96   SourceLocation loc = method->getLocation();
97 
98   // If we're in a system header, and this is not a call, just make
99   // the method unusable.
100   if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
101     method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102                       UnavailableAttr::IR_ARCInitReturnsUnrelated, 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 /// Issue a warning if the parameter of the overridden method is non-escaping
113 /// but the parameter of the overriding method is not.
114 static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
115                              Sema &S) {
116   if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
117     S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
118     S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
119     return false;
120   }
121 
122   return true;
123 }
124 
125 /// Produce additional diagnostics if a category conforms to a protocol that
126 /// defines a method taking a non-escaping parameter.
127 static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
128                              const ObjCCategoryDecl *CD,
129                              const ObjCProtocolDecl *PD, Sema &S) {
130   if (!diagnoseNoescape(NewD, OldD, S))
131     S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
132         << CD->IsClassExtension() << PD
133         << cast<ObjCMethodDecl>(NewD->getDeclContext());
134 }
135 
136 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
137                                    const ObjCMethodDecl *Overridden) {
138   if (Overridden->hasRelatedResultType() &&
139       !NewMethod->hasRelatedResultType()) {
140     // This can only happen when the method follows a naming convention that
141     // implies a related result type, and the original (overridden) method has
142     // a suitable return type, but the new (overriding) method does not have
143     // a suitable return type.
144     QualType ResultType = NewMethod->getReturnType();
145     SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
146 
147     // Figure out which class this method is part of, if any.
148     ObjCInterfaceDecl *CurrentClass
149       = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
150     if (!CurrentClass) {
151       DeclContext *DC = NewMethod->getDeclContext();
152       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
153         CurrentClass = Cat->getClassInterface();
154       else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
155         CurrentClass = Impl->getClassInterface();
156       else if (ObjCCategoryImplDecl *CatImpl
157                = dyn_cast<ObjCCategoryImplDecl>(DC))
158         CurrentClass = CatImpl->getClassInterface();
159     }
160 
161     if (CurrentClass) {
162       Diag(NewMethod->getLocation(),
163            diag::warn_related_result_type_compatibility_class)
164         << Context.getObjCInterfaceType(CurrentClass)
165         << ResultType
166         << ResultTypeRange;
167     } else {
168       Diag(NewMethod->getLocation(),
169            diag::warn_related_result_type_compatibility_protocol)
170         << ResultType
171         << ResultTypeRange;
172     }
173 
174     if (ObjCMethodFamily Family = Overridden->getMethodFamily())
175       Diag(Overridden->getLocation(),
176            diag::note_related_result_type_family)
177         << /*overridden method*/ 0
178         << Family;
179     else
180       Diag(Overridden->getLocation(),
181            diag::note_related_result_type_overridden);
182   }
183 
184   if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
185        Overridden->hasAttr<NSReturnsRetainedAttr>())) {
186     Diag(NewMethod->getLocation(),
187          getLangOpts().ObjCAutoRefCount
188              ? diag::err_nsreturns_retained_attribute_mismatch
189              : diag::warn_nsreturns_retained_attribute_mismatch)
190         << 1;
191     Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
192   }
193   if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
194        Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
195     Diag(NewMethod->getLocation(),
196          getLangOpts().ObjCAutoRefCount
197              ? diag::err_nsreturns_retained_attribute_mismatch
198              : diag::warn_nsreturns_retained_attribute_mismatch)
199         << 0;
200     Diag(Overridden->getLocation(), diag::note_previous_decl)  << "method";
201   }
202 
203   ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
204                                        oe = Overridden->param_end();
205   for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
206                                       ne = NewMethod->param_end();
207        ni != ne && oi != oe; ++ni, ++oi) {
208     const ParmVarDecl *oldDecl = (*oi);
209     ParmVarDecl *newDecl = (*ni);
210     if (newDecl->hasAttr<NSConsumedAttr>() !=
211         oldDecl->hasAttr<NSConsumedAttr>()) {
212       Diag(newDecl->getLocation(),
213            getLangOpts().ObjCAutoRefCount
214                ? diag::err_nsconsumed_attribute_mismatch
215                : diag::warn_nsconsumed_attribute_mismatch);
216       Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
217     }
218 
219     diagnoseNoescape(newDecl, oldDecl, *this);
220   }
221 }
222 
223 /// Check a method declaration for compatibility with the Objective-C
224 /// ARC conventions.
225 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
226   ObjCMethodFamily family = method->getMethodFamily();
227   switch (family) {
228   case OMF_None:
229   case OMF_finalize:
230   case OMF_retain:
231   case OMF_release:
232   case OMF_autorelease:
233   case OMF_retainCount:
234   case OMF_self:
235   case OMF_initialize:
236   case OMF_performSelector:
237     return false;
238 
239   case OMF_dealloc:
240     if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
241       SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
242       if (ResultTypeRange.isInvalid())
243         Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
244             << method->getReturnType()
245             << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
246       else
247         Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
248             << method->getReturnType()
249             << FixItHint::CreateReplacement(ResultTypeRange, "void");
250       return true;
251     }
252     return false;
253 
254   case OMF_init:
255     // If the method doesn't obey the init rules, don't bother annotating it.
256     if (checkInitMethod(method, QualType()))
257       return true;
258 
259     method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
260 
261     // Don't add a second copy of this attribute, but otherwise don't
262     // let it be suppressed.
263     if (method->hasAttr<NSReturnsRetainedAttr>())
264       return false;
265     break;
266 
267   case OMF_alloc:
268   case OMF_copy:
269   case OMF_mutableCopy:
270   case OMF_new:
271     if (method->hasAttr<NSReturnsRetainedAttr>() ||
272         method->hasAttr<NSReturnsNotRetainedAttr>() ||
273         method->hasAttr<NSReturnsAutoreleasedAttr>())
274       return false;
275     break;
276   }
277 
278   method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
279   return false;
280 }
281 
282 static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
283                                                 SourceLocation ImplLoc) {
284   if (!ND)
285     return;
286   bool IsCategory = false;
287   StringRef RealizedPlatform;
288   AvailabilityResult Availability = ND->getAvailability(
289       /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
290       &RealizedPlatform);
291   if (Availability != AR_Deprecated) {
292     if (isa<ObjCMethodDecl>(ND)) {
293       if (Availability != AR_Unavailable)
294         return;
295       if (RealizedPlatform.empty())
296         RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
297       // Warn about implementing unavailable methods, unless the unavailable
298       // is for an app extension.
299       if (RealizedPlatform.endswith("_app_extension"))
300         return;
301       S.Diag(ImplLoc, diag::warn_unavailable_def);
302       S.Diag(ND->getLocation(), diag::note_method_declared_at)
303           << ND->getDeclName();
304       return;
305     }
306     if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
307       if (!CD->getClassInterface()->isDeprecated())
308         return;
309       ND = CD->getClassInterface();
310       IsCategory = true;
311     } else
312       return;
313   }
314   S.Diag(ImplLoc, diag::warn_deprecated_def)
315       << (isa<ObjCMethodDecl>(ND)
316               ? /*Method*/ 0
317               : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
318                                                         : /*Class*/ 1);
319   if (isa<ObjCMethodDecl>(ND))
320     S.Diag(ND->getLocation(), diag::note_method_declared_at)
321         << ND->getDeclName();
322   else
323     S.Diag(ND->getLocation(), diag::note_previous_decl)
324         << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
325 }
326 
327 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
328 /// pool.
329 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
330   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
331 
332   // If we don't have a valid method decl, simply return.
333   if (!MDecl)
334     return;
335   if (MDecl->isInstanceMethod())
336     AddInstanceMethodToGlobalPool(MDecl, true);
337   else
338     AddFactoryMethodToGlobalPool(MDecl, true);
339 }
340 
341 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
342 /// has explicit ownership attribute; false otherwise.
343 static bool
344 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
345   QualType T = Param->getType();
346 
347   if (const PointerType *PT = T->getAs<PointerType>()) {
348     T = PT->getPointeeType();
349   } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
350     T = RT->getPointeeType();
351   } else {
352     return true;
353   }
354 
355   // If we have a lifetime qualifier, but it's local, we must have
356   // inferred it. So, it is implicit.
357   return !T.getLocalQualifiers().hasObjCLifetime();
358 }
359 
360 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
361 /// and user declared, in the method definition's AST.
362 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
363   ImplicitlyRetainedSelfLocs.clear();
364   assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
365   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
366 
367   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
368 
369   // If we don't have a valid method decl, simply return.
370   if (!MDecl)
371     return;
372 
373   QualType ResultType = MDecl->getReturnType();
374   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
375       !MDecl->isInvalidDecl() &&
376       RequireCompleteType(MDecl->getLocation(), ResultType,
377                           diag::err_func_def_incomplete_result))
378     MDecl->setInvalidDecl();
379 
380   // Allow all of Sema to see that we are entering a method definition.
381   PushDeclContext(FnBodyScope, MDecl);
382   PushFunctionScope();
383 
384   // Create Decl objects for each parameter, entrring them in the scope for
385   // binding to their use.
386 
387   // Insert the invisible arguments, self and _cmd!
388   MDecl->createImplicitParams(Context, MDecl->getClassInterface());
389 
390   PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
391   PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
392 
393   // The ObjC parser requires parameter names so there's no need to check.
394   CheckParmsForFunctionDef(MDecl->parameters(),
395                            /*CheckParameterNames=*/false);
396 
397   // Introduce all of the other parameters into this scope.
398   for (auto *Param : MDecl->parameters()) {
399     if (!Param->isInvalidDecl() &&
400         getLangOpts().ObjCAutoRefCount &&
401         !HasExplicitOwnershipAttr(*this, Param))
402       Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
403             Param->getType();
404 
405     if (Param->getIdentifier())
406       PushOnScopeChains(Param, FnBodyScope);
407   }
408 
409   // In ARC, disallow definition of retain/release/autorelease/retainCount
410   if (getLangOpts().ObjCAutoRefCount) {
411     switch (MDecl->getMethodFamily()) {
412     case OMF_retain:
413     case OMF_retainCount:
414     case OMF_release:
415     case OMF_autorelease:
416       Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
417         << 0 << MDecl->getSelector();
418       break;
419 
420     case OMF_None:
421     case OMF_dealloc:
422     case OMF_finalize:
423     case OMF_alloc:
424     case OMF_init:
425     case OMF_mutableCopy:
426     case OMF_copy:
427     case OMF_new:
428     case OMF_self:
429     case OMF_initialize:
430     case OMF_performSelector:
431       break;
432     }
433   }
434 
435   // Warn on deprecated methods under -Wdeprecated-implementations,
436   // and prepare for warning on missing super calls.
437   if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
438     ObjCMethodDecl *IMD =
439       IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
440 
441     if (IMD) {
442       ObjCImplDecl *ImplDeclOfMethodDef =
443         dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
444       ObjCContainerDecl *ContDeclOfMethodDecl =
445         dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
446       ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
447       if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
448         ImplDeclOfMethodDecl = OID->getImplementation();
449       else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
450         if (CD->IsClassExtension()) {
451           if (ObjCInterfaceDecl *OID = CD->getClassInterface())
452             ImplDeclOfMethodDecl = OID->getImplementation();
453         } else
454             ImplDeclOfMethodDecl = CD->getImplementation();
455       }
456       // No need to issue deprecated warning if deprecated mehod in class/category
457       // is being implemented in its own implementation (no overriding is involved).
458       if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
459         DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
460     }
461 
462     if (MDecl->getMethodFamily() == OMF_init) {
463       if (MDecl->isDesignatedInitializerForTheInterface()) {
464         getCurFunction()->ObjCIsDesignatedInit = true;
465         getCurFunction()->ObjCWarnForNoDesignatedInitChain =
466             IC->getSuperClass() != nullptr;
467       } else if (IC->hasDesignatedInitializers()) {
468         getCurFunction()->ObjCIsSecondaryInit = true;
469         getCurFunction()->ObjCWarnForNoInitDelegation = true;
470       }
471     }
472 
473     // If this is "dealloc" or "finalize", set some bit here.
474     // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
475     // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
476     // Only do this if the current class actually has a superclass.
477     if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
478       ObjCMethodFamily Family = MDecl->getMethodFamily();
479       if (Family == OMF_dealloc) {
480         if (!(getLangOpts().ObjCAutoRefCount ||
481               getLangOpts().getGC() == LangOptions::GCOnly))
482           getCurFunction()->ObjCShouldCallSuper = true;
483 
484       } else if (Family == OMF_finalize) {
485         if (Context.getLangOpts().getGC() != LangOptions::NonGC)
486           getCurFunction()->ObjCShouldCallSuper = true;
487 
488       } else {
489         const ObjCMethodDecl *SuperMethod =
490           SuperClass->lookupMethod(MDecl->getSelector(),
491                                    MDecl->isInstanceMethod());
492         getCurFunction()->ObjCShouldCallSuper =
493           (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
494       }
495     }
496   }
497 }
498 
499 namespace {
500 
501 // Callback to only accept typo corrections that are Objective-C classes.
502 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
503 // function will reject corrections to that class.
504 class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
505  public:
506   ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
507   explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
508       : CurrentIDecl(IDecl) {}
509 
510   bool ValidateCandidate(const TypoCorrection &candidate) override {
511     ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
512     return ID && !declaresSameEntity(ID, CurrentIDecl);
513   }
514 
515   std::unique_ptr<CorrectionCandidateCallback> clone() override {
516     return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
517   }
518 
519  private:
520   ObjCInterfaceDecl *CurrentIDecl;
521 };
522 
523 } // end anonymous namespace
524 
525 static void diagnoseUseOfProtocols(Sema &TheSema,
526                                    ObjCContainerDecl *CD,
527                                    ObjCProtocolDecl *const *ProtoRefs,
528                                    unsigned NumProtoRefs,
529                                    const SourceLocation *ProtoLocs) {
530   assert(ProtoRefs);
531   // Diagnose availability in the context of the ObjC container.
532   Sema::ContextRAII SavedContext(TheSema, CD);
533   for (unsigned i = 0; i < NumProtoRefs; ++i) {
534     (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
535                                     /*UnknownObjCClass=*/nullptr,
536                                     /*ObjCPropertyAccess=*/false,
537                                     /*AvoidPartialAvailabilityChecks=*/true);
538   }
539 }
540 
541 void Sema::
542 ActOnSuperClassOfClassInterface(Scope *S,
543                                 SourceLocation AtInterfaceLoc,
544                                 ObjCInterfaceDecl *IDecl,
545                                 IdentifierInfo *ClassName,
546                                 SourceLocation ClassLoc,
547                                 IdentifierInfo *SuperName,
548                                 SourceLocation SuperLoc,
549                                 ArrayRef<ParsedType> SuperTypeArgs,
550                                 SourceRange SuperTypeArgsRange) {
551   // Check if a different kind of symbol declared in this scope.
552   NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
553                                          LookupOrdinaryName);
554 
555   if (!PrevDecl) {
556     // Try to correct for a typo in the superclass name without correcting
557     // to the class we're defining.
558     ObjCInterfaceValidatorCCC CCC(IDecl);
559     if (TypoCorrection Corrected = CorrectTypo(
560             DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
561             TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
562       diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
563                    << SuperName << ClassName);
564       PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
565     }
566   }
567 
568   if (declaresSameEntity(PrevDecl, IDecl)) {
569     Diag(SuperLoc, diag::err_recursive_superclass)
570       << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
571     IDecl->setEndOfDefinitionLoc(ClassLoc);
572   } else {
573     ObjCInterfaceDecl *SuperClassDecl =
574     dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
575     QualType SuperClassType;
576 
577     // Diagnose classes that inherit from deprecated classes.
578     if (SuperClassDecl) {
579       (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
580       SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
581     }
582 
583     if (PrevDecl && !SuperClassDecl) {
584       // The previous declaration was not a class decl. Check if we have a
585       // typedef. If we do, get the underlying class type.
586       if (const TypedefNameDecl *TDecl =
587           dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
588         QualType T = TDecl->getUnderlyingType();
589         if (T->isObjCObjectType()) {
590           if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
591             SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
592             SuperClassType = Context.getTypeDeclType(TDecl);
593 
594             // This handles the following case:
595             // @interface NewI @end
596             // typedef NewI DeprI __attribute__((deprecated("blah")))
597             // @interface SI : DeprI /* warn here */ @end
598             (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
599           }
600         }
601       }
602 
603       // This handles the following case:
604       //
605       // typedef int SuperClass;
606       // @interface MyClass : SuperClass {} @end
607       //
608       if (!SuperClassDecl) {
609         Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
610         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
611       }
612     }
613 
614     if (!isa_and_nonnull<TypedefNameDecl>(PrevDecl)) {
615       if (!SuperClassDecl)
616         Diag(SuperLoc, diag::err_undef_superclass)
617           << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
618       else if (RequireCompleteType(SuperLoc,
619                                    SuperClassType,
620                                    diag::err_forward_superclass,
621                                    SuperClassDecl->getDeclName(),
622                                    ClassName,
623                                    SourceRange(AtInterfaceLoc, ClassLoc))) {
624         SuperClassDecl = nullptr;
625         SuperClassType = QualType();
626       }
627     }
628 
629     if (SuperClassType.isNull()) {
630       assert(!SuperClassDecl && "Failed to set SuperClassType?");
631       return;
632     }
633 
634     // Handle type arguments on the superclass.
635     TypeSourceInfo *SuperClassTInfo = nullptr;
636     if (!SuperTypeArgs.empty()) {
637       TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
638                                         S,
639                                         SuperLoc,
640                                         CreateParsedType(SuperClassType,
641                                                          nullptr),
642                                         SuperTypeArgsRange.getBegin(),
643                                         SuperTypeArgs,
644                                         SuperTypeArgsRange.getEnd(),
645                                         SourceLocation(),
646                                         { },
647                                         { },
648                                         SourceLocation());
649       if (!fullSuperClassType.isUsable())
650         return;
651 
652       SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
653                                          &SuperClassTInfo);
654     }
655 
656     if (!SuperClassTInfo) {
657       SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
658                                                          SuperLoc);
659     }
660 
661     IDecl->setSuperClass(SuperClassTInfo);
662     IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
663   }
664 }
665 
666 DeclResult Sema::actOnObjCTypeParam(Scope *S,
667                                     ObjCTypeParamVariance variance,
668                                     SourceLocation varianceLoc,
669                                     unsigned index,
670                                     IdentifierInfo *paramName,
671                                     SourceLocation paramLoc,
672                                     SourceLocation colonLoc,
673                                     ParsedType parsedTypeBound) {
674   // If there was an explicitly-provided type bound, check it.
675   TypeSourceInfo *typeBoundInfo = nullptr;
676   if (parsedTypeBound) {
677     // The type bound can be any Objective-C pointer type.
678     QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
679     if (typeBound->isObjCObjectPointerType()) {
680       // okay
681     } else if (typeBound->isObjCObjectType()) {
682       // The user forgot the * on an Objective-C pointer type, e.g.,
683       // "T : NSView".
684       SourceLocation starLoc = getLocForEndOfToken(
685                                  typeBoundInfo->getTypeLoc().getEndLoc());
686       Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
687            diag::err_objc_type_param_bound_missing_pointer)
688         << typeBound << paramName
689         << FixItHint::CreateInsertion(starLoc, " *");
690 
691       // Create a new type location builder so we can update the type
692       // location information we have.
693       TypeLocBuilder builder;
694       builder.pushFullCopy(typeBoundInfo->getTypeLoc());
695 
696       // Create the Objective-C pointer type.
697       typeBound = Context.getObjCObjectPointerType(typeBound);
698       ObjCObjectPointerTypeLoc newT
699         = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
700       newT.setStarLoc(starLoc);
701 
702       // Form the new type source information.
703       typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
704     } else {
705       // Not a valid type bound.
706       Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
707            diag::err_objc_type_param_bound_nonobject)
708         << typeBound << paramName;
709 
710       // Forget the bound; we'll default to id later.
711       typeBoundInfo = nullptr;
712     }
713 
714     // Type bounds cannot have qualifiers (even indirectly) or explicit
715     // nullability.
716     if (typeBoundInfo) {
717       QualType typeBound = typeBoundInfo->getType();
718       TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
719       if (qual || typeBound.hasQualifiers()) {
720         bool diagnosed = false;
721         SourceRange rangeToRemove;
722         if (qual) {
723           if (auto attr = qual.getAs<AttributedTypeLoc>()) {
724             rangeToRemove = attr.getLocalSourceRange();
725             if (attr.getTypePtr()->getImmediateNullability()) {
726               Diag(attr.getBeginLoc(),
727                    diag::err_objc_type_param_bound_explicit_nullability)
728                   << paramName << typeBound
729                   << FixItHint::CreateRemoval(rangeToRemove);
730               diagnosed = true;
731             }
732           }
733         }
734 
735         if (!diagnosed) {
736           Diag(qual ? qual.getBeginLoc()
737                     : typeBoundInfo->getTypeLoc().getBeginLoc(),
738                diag::err_objc_type_param_bound_qualified)
739               << paramName << typeBound
740               << typeBound.getQualifiers().getAsString()
741               << FixItHint::CreateRemoval(rangeToRemove);
742         }
743 
744         // If the type bound has qualifiers other than CVR, we need to strip
745         // them or we'll probably assert later when trying to apply new
746         // qualifiers.
747         Qualifiers quals = typeBound.getQualifiers();
748         quals.removeCVRQualifiers();
749         if (!quals.empty()) {
750           typeBoundInfo =
751              Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
752         }
753       }
754     }
755   }
756 
757   // If there was no explicit type bound (or we removed it due to an error),
758   // use 'id' instead.
759   if (!typeBoundInfo) {
760     colonLoc = SourceLocation();
761     typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
762   }
763 
764   // Create the type parameter.
765   return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
766                                    index, paramLoc, paramName, colonLoc,
767                                    typeBoundInfo);
768 }
769 
770 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
771                                                 SourceLocation lAngleLoc,
772                                                 ArrayRef<Decl *> typeParamsIn,
773                                                 SourceLocation rAngleLoc) {
774   // We know that the array only contains Objective-C type parameters.
775   ArrayRef<ObjCTypeParamDecl *>
776     typeParams(
777       reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
778       typeParamsIn.size());
779 
780   // Diagnose redeclarations of type parameters.
781   // We do this now because Objective-C type parameters aren't pushed into
782   // scope until later (after the instance variable block), but we want the
783   // diagnostics to occur right after we parse the type parameter list.
784   llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
785   for (auto typeParam : typeParams) {
786     auto known = knownParams.find(typeParam->getIdentifier());
787     if (known != knownParams.end()) {
788       Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
789         << typeParam->getIdentifier()
790         << SourceRange(known->second->getLocation());
791 
792       typeParam->setInvalidDecl();
793     } else {
794       knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
795 
796       // Push the type parameter into scope.
797       PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
798     }
799   }
800 
801   // Create the parameter list.
802   return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
803 }
804 
805 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
806   for (auto typeParam : *typeParamList) {
807     if (!typeParam->isInvalidDecl()) {
808       S->RemoveDecl(typeParam);
809       IdResolver.RemoveDecl(typeParam);
810     }
811   }
812 }
813 
814 namespace {
815   /// The context in which an Objective-C type parameter list occurs, for use
816   /// in diagnostics.
817   enum class TypeParamListContext {
818     ForwardDeclaration,
819     Definition,
820     Category,
821     Extension
822   };
823 } // end anonymous namespace
824 
825 /// Check consistency between two Objective-C type parameter lists, e.g.,
826 /// between a category/extension and an \@interface or between an \@class and an
827 /// \@interface.
828 static bool checkTypeParamListConsistency(Sema &S,
829                                           ObjCTypeParamList *prevTypeParams,
830                                           ObjCTypeParamList *newTypeParams,
831                                           TypeParamListContext newContext) {
832   // If the sizes don't match, complain about that.
833   if (prevTypeParams->size() != newTypeParams->size()) {
834     SourceLocation diagLoc;
835     if (newTypeParams->size() > prevTypeParams->size()) {
836       diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
837     } else {
838       diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
839     }
840 
841     S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
842       << static_cast<unsigned>(newContext)
843       << (newTypeParams->size() > prevTypeParams->size())
844       << prevTypeParams->size()
845       << newTypeParams->size();
846 
847     return true;
848   }
849 
850   // Match up the type parameters.
851   for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
852     ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
853     ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
854 
855     // Check for consistency of the variance.
856     if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
857       if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
858           newContext != TypeParamListContext::Definition) {
859         // When the new type parameter is invariant and is not part
860         // of the definition, just propagate the variance.
861         newTypeParam->setVariance(prevTypeParam->getVariance());
862       } else if (prevTypeParam->getVariance()
863                    == ObjCTypeParamVariance::Invariant &&
864                  !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
865                    cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
866                      ->getDefinition() == prevTypeParam->getDeclContext())) {
867         // When the old parameter is invariant and was not part of the
868         // definition, just ignore the difference because it doesn't
869         // matter.
870       } else {
871         {
872           // Diagnose the conflict and update the second declaration.
873           SourceLocation diagLoc = newTypeParam->getVarianceLoc();
874           if (diagLoc.isInvalid())
875             diagLoc = newTypeParam->getBeginLoc();
876 
877           auto diag = S.Diag(diagLoc,
878                              diag::err_objc_type_param_variance_conflict)
879                         << static_cast<unsigned>(newTypeParam->getVariance())
880                         << newTypeParam->getDeclName()
881                         << static_cast<unsigned>(prevTypeParam->getVariance())
882                         << prevTypeParam->getDeclName();
883           switch (prevTypeParam->getVariance()) {
884           case ObjCTypeParamVariance::Invariant:
885             diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
886             break;
887 
888           case ObjCTypeParamVariance::Covariant:
889           case ObjCTypeParamVariance::Contravariant: {
890             StringRef newVarianceStr
891                = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
892                    ? "__covariant"
893                    : "__contravariant";
894             if (newTypeParam->getVariance()
895                   == ObjCTypeParamVariance::Invariant) {
896               diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
897                                                  (newVarianceStr + " ").str());
898             } else {
899               diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
900                                                newVarianceStr);
901             }
902           }
903           }
904         }
905 
906         S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
907           << prevTypeParam->getDeclName();
908 
909         // Override the variance.
910         newTypeParam->setVariance(prevTypeParam->getVariance());
911       }
912     }
913 
914     // If the bound types match, there's nothing to do.
915     if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
916                               newTypeParam->getUnderlyingType()))
917       continue;
918 
919     // If the new type parameter's bound was explicit, complain about it being
920     // different from the original.
921     if (newTypeParam->hasExplicitBound()) {
922       SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
923                                     ->getTypeLoc().getSourceRange();
924       S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
925         << newTypeParam->getUnderlyingType()
926         << newTypeParam->getDeclName()
927         << prevTypeParam->hasExplicitBound()
928         << prevTypeParam->getUnderlyingType()
929         << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
930         << prevTypeParam->getDeclName()
931         << FixItHint::CreateReplacement(
932              newBoundRange,
933              prevTypeParam->getUnderlyingType().getAsString(
934                S.Context.getPrintingPolicy()));
935 
936       S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
937         << prevTypeParam->getDeclName();
938 
939       // Override the new type parameter's bound type with the previous type,
940       // so that it's consistent.
941       S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
942       continue;
943     }
944 
945     // The new type parameter got the implicit bound of 'id'. That's okay for
946     // categories and extensions (overwrite it later), but not for forward
947     // declarations and @interfaces, because those must be standalone.
948     if (newContext == TypeParamListContext::ForwardDeclaration ||
949         newContext == TypeParamListContext::Definition) {
950       // Diagnose this problem for forward declarations and definitions.
951       SourceLocation insertionLoc
952         = S.getLocForEndOfToken(newTypeParam->getLocation());
953       std::string newCode
954         = " : " + prevTypeParam->getUnderlyingType().getAsString(
955                     S.Context.getPrintingPolicy());
956       S.Diag(newTypeParam->getLocation(),
957              diag::err_objc_type_param_bound_missing)
958         << prevTypeParam->getUnderlyingType()
959         << newTypeParam->getDeclName()
960         << (newContext == TypeParamListContext::ForwardDeclaration)
961         << FixItHint::CreateInsertion(insertionLoc, newCode);
962 
963       S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
964         << prevTypeParam->getDeclName();
965     }
966 
967     // Update the new type parameter's bound to match the previous one.
968     S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
969   }
970 
971   return false;
972 }
973 
974 Decl *Sema::ActOnStartClassInterface(
975     Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
976     SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
977     IdentifierInfo *SuperName, SourceLocation SuperLoc,
978     ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
979     Decl *const *ProtoRefs, unsigned NumProtoRefs,
980     const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
981     const ParsedAttributesView &AttrList) {
982   assert(ClassName && "Missing class identifier");
983 
984   // Check for another declaration kind with the same name.
985   NamedDecl *PrevDecl =
986       LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
987                        forRedeclarationInCurContext());
988 
989   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
990     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
991     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
992   }
993 
994   // Create a declaration to describe this @interface.
995   ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
996 
997   if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
998     // A previous decl with a different name is because of
999     // @compatibility_alias, for example:
1000     // \code
1001     //   @class NewImage;
1002     //   @compatibility_alias OldImage NewImage;
1003     // \endcode
1004     // A lookup for 'OldImage' will return the 'NewImage' decl.
1005     //
1006     // In such a case use the real declaration name, instead of the alias one,
1007     // otherwise we will break IdentifierResolver and redecls-chain invariants.
1008     // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1009     // has been aliased.
1010     ClassName = PrevIDecl->getIdentifier();
1011   }
1012 
1013   // If there was a forward declaration with type parameters, check
1014   // for consistency.
1015   if (PrevIDecl) {
1016     if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1017       if (typeParamList) {
1018         // Both have type parameter lists; check for consistency.
1019         if (checkTypeParamListConsistency(*this, prevTypeParamList,
1020                                           typeParamList,
1021                                           TypeParamListContext::Definition)) {
1022           typeParamList = nullptr;
1023         }
1024       } else {
1025         Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1026           << ClassName;
1027         Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1028           << ClassName;
1029 
1030         // Clone the type parameter list.
1031         SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1032         for (auto typeParam : *prevTypeParamList) {
1033           clonedTypeParams.push_back(
1034             ObjCTypeParamDecl::Create(
1035               Context,
1036               CurContext,
1037               typeParam->getVariance(),
1038               SourceLocation(),
1039               typeParam->getIndex(),
1040               SourceLocation(),
1041               typeParam->getIdentifier(),
1042               SourceLocation(),
1043               Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1044         }
1045 
1046         typeParamList = ObjCTypeParamList::create(Context,
1047                                                   SourceLocation(),
1048                                                   clonedTypeParams,
1049                                                   SourceLocation());
1050       }
1051     }
1052   }
1053 
1054   ObjCInterfaceDecl *IDecl
1055     = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
1056                                 typeParamList, PrevIDecl, ClassLoc);
1057   if (PrevIDecl) {
1058     // Class already seen. Was it a definition?
1059     if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1060       Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1061         << PrevIDecl->getDeclName();
1062       Diag(Def->getLocation(), diag::note_previous_definition);
1063       IDecl->setInvalidDecl();
1064     }
1065   }
1066 
1067   ProcessDeclAttributeList(TUScope, IDecl, AttrList);
1068   AddPragmaAttributes(TUScope, IDecl);
1069 
1070   // Merge attributes from previous declarations.
1071   if (PrevIDecl)
1072     mergeDeclAttributes(IDecl, PrevIDecl);
1073 
1074   PushOnScopeChains(IDecl, TUScope);
1075 
1076   // Start the definition of this class. If we're in a redefinition case, there
1077   // may already be a definition, so we'll end up adding to it.
1078   if (!IDecl->hasDefinition())
1079     IDecl->startDefinition();
1080 
1081   if (SuperName) {
1082     // Diagnose availability in the context of the @interface.
1083     ContextRAII SavedContext(*this, IDecl);
1084 
1085     ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1086                                     ClassName, ClassLoc,
1087                                     SuperName, SuperLoc, SuperTypeArgs,
1088                                     SuperTypeArgsRange);
1089   } else { // we have a root class.
1090     IDecl->setEndOfDefinitionLoc(ClassLoc);
1091   }
1092 
1093   // Check then save referenced protocols.
1094   if (NumProtoRefs) {
1095     diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1096                            NumProtoRefs, ProtoLocs);
1097     IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1098                            ProtoLocs, Context);
1099     IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1100   }
1101 
1102   CheckObjCDeclScope(IDecl);
1103   return ActOnObjCContainerStartDefinition(IDecl);
1104 }
1105 
1106 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
1107 /// typedef'ed use for a qualified super class and adds them to the list
1108 /// of the protocols.
1109 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1110                                   SmallVectorImpl<SourceLocation> &ProtocolLocs,
1111                                    IdentifierInfo *SuperName,
1112                                    SourceLocation SuperLoc) {
1113   if (!SuperName)
1114     return;
1115   NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1116                                       LookupOrdinaryName);
1117   if (!IDecl)
1118     return;
1119 
1120   if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1121     QualType T = TDecl->getUnderlyingType();
1122     if (T->isObjCObjectType())
1123       if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1124         ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1125         // FIXME: Consider whether this should be an invalid loc since the loc
1126         // is not actually pointing to a protocol name reference but to the
1127         // typedef reference. Note that the base class name loc is also pointing
1128         // at the typedef.
1129         ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1130       }
1131   }
1132 }
1133 
1134 /// ActOnCompatibilityAlias - this action is called after complete parsing of
1135 /// a \@compatibility_alias declaration. It sets up the alias relationships.
1136 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1137                                     IdentifierInfo *AliasName,
1138                                     SourceLocation AliasLocation,
1139                                     IdentifierInfo *ClassName,
1140                                     SourceLocation ClassLocation) {
1141   // Look for previous declaration of alias name
1142   NamedDecl *ADecl =
1143       LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1144                        forRedeclarationInCurContext());
1145   if (ADecl) {
1146     Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1147     Diag(ADecl->getLocation(), diag::note_previous_declaration);
1148     return nullptr;
1149   }
1150   // Check for class declaration
1151   NamedDecl *CDeclU =
1152       LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1153                        forRedeclarationInCurContext());
1154   if (const TypedefNameDecl *TDecl =
1155         dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1156     QualType T = TDecl->getUnderlyingType();
1157     if (T->isObjCObjectType()) {
1158       if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
1159         ClassName = IDecl->getIdentifier();
1160         CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1161                                   LookupOrdinaryName,
1162                                   forRedeclarationInCurContext());
1163       }
1164     }
1165   }
1166   ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1167   if (!CDecl) {
1168     Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1169     if (CDeclU)
1170       Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1171     return nullptr;
1172   }
1173 
1174   // Everything checked out, instantiate a new alias declaration AST.
1175   ObjCCompatibleAliasDecl *AliasDecl =
1176     ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1177 
1178   if (!CheckObjCDeclScope(AliasDecl))
1179     PushOnScopeChains(AliasDecl, TUScope);
1180 
1181   return AliasDecl;
1182 }
1183 
1184 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
1185   IdentifierInfo *PName,
1186   SourceLocation &Ploc, SourceLocation PrevLoc,
1187   const ObjCList<ObjCProtocolDecl> &PList) {
1188 
1189   bool res = false;
1190   for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1191        E = PList.end(); I != E; ++I) {
1192     if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1193                                                  Ploc)) {
1194       if (PDecl->getIdentifier() == PName) {
1195         Diag(Ploc, diag::err_protocol_has_circular_dependency);
1196         Diag(PrevLoc, diag::note_previous_definition);
1197         res = true;
1198       }
1199 
1200       if (!PDecl->hasDefinition())
1201         continue;
1202 
1203       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1204             PDecl->getLocation(), PDecl->getReferencedProtocols()))
1205         res = true;
1206     }
1207   }
1208   return res;
1209 }
1210 
1211 Decl *Sema::ActOnStartProtocolInterface(
1212     SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1213     SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1214     const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1215     const ParsedAttributesView &AttrList) {
1216   bool err = false;
1217   // FIXME: Deal with AttrList.
1218   assert(ProtocolName && "Missing protocol identifier");
1219   ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1220                                               forRedeclarationInCurContext());
1221   ObjCProtocolDecl *PDecl = nullptr;
1222   if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1223     // If we already have a definition, complain.
1224     Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1225     Diag(Def->getLocation(), diag::note_previous_definition);
1226 
1227     // Create a new protocol that is completely distinct from previous
1228     // declarations, and do not make this protocol available for name lookup.
1229     // That way, we'll end up completely ignoring the duplicate.
1230     // FIXME: Can we turn this into an error?
1231     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1232                                      ProtocolLoc, AtProtoInterfaceLoc,
1233                                      /*PrevDecl=*/nullptr);
1234 
1235     // If we are using modules, add the decl to the context in order to
1236     // serialize something meaningful.
1237     if (getLangOpts().Modules)
1238       PushOnScopeChains(PDecl, TUScope);
1239     PDecl->startDefinition();
1240   } else {
1241     if (PrevDecl) {
1242       // Check for circular dependencies among protocol declarations. This can
1243       // only happen if this protocol was forward-declared.
1244       ObjCList<ObjCProtocolDecl> PList;
1245       PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1246       err = CheckForwardProtocolDeclarationForCircularDependency(
1247               ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1248     }
1249 
1250     // Create the new declaration.
1251     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1252                                      ProtocolLoc, AtProtoInterfaceLoc,
1253                                      /*PrevDecl=*/PrevDecl);
1254 
1255     PushOnScopeChains(PDecl, TUScope);
1256     PDecl->startDefinition();
1257   }
1258 
1259   ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1260   AddPragmaAttributes(TUScope, PDecl);
1261 
1262   // Merge attributes from previous declarations.
1263   if (PrevDecl)
1264     mergeDeclAttributes(PDecl, PrevDecl);
1265 
1266   if (!err && NumProtoRefs ) {
1267     /// Check then save referenced protocols.
1268     diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1269                            NumProtoRefs, ProtoLocs);
1270     PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1271                            ProtoLocs, Context);
1272   }
1273 
1274   CheckObjCDeclScope(PDecl);
1275   return ActOnObjCContainerStartDefinition(PDecl);
1276 }
1277 
1278 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1279                                           ObjCProtocolDecl *&UndefinedProtocol) {
1280   if (!PDecl->hasDefinition() ||
1281       !PDecl->getDefinition()->isUnconditionallyVisible()) {
1282     UndefinedProtocol = PDecl;
1283     return true;
1284   }
1285 
1286   for (auto *PI : PDecl->protocols())
1287     if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1288       UndefinedProtocol = PI;
1289       return true;
1290     }
1291   return false;
1292 }
1293 
1294 /// FindProtocolDeclaration - This routine looks up protocols and
1295 /// issues an error if they are not declared. It returns list of
1296 /// protocol declarations in its 'Protocols' argument.
1297 void
1298 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1299                               ArrayRef<IdentifierLocPair> ProtocolId,
1300                               SmallVectorImpl<Decl *> &Protocols) {
1301   for (const IdentifierLocPair &Pair : ProtocolId) {
1302     ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1303     if (!PDecl) {
1304       DeclFilterCCC<ObjCProtocolDecl> CCC{};
1305       TypoCorrection Corrected = CorrectTypo(
1306           DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
1307           TUScope, nullptr, CCC, CTK_ErrorRecovery);
1308       if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1309         diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1310                                     << Pair.first);
1311     }
1312 
1313     if (!PDecl) {
1314       Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1315       continue;
1316     }
1317     // If this is a forward protocol declaration, get its definition.
1318     if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1319       PDecl = PDecl->getDefinition();
1320 
1321     // For an objc container, delay protocol reference checking until after we
1322     // can set the objc decl as the availability context, otherwise check now.
1323     if (!ForObjCContainer) {
1324       (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1325     }
1326 
1327     // If this is a forward declaration and we are supposed to warn in this
1328     // case, do it.
1329     // FIXME: Recover nicely in the hidden case.
1330     ObjCProtocolDecl *UndefinedProtocol;
1331 
1332     if (WarnOnDeclarations &&
1333         NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1334       Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1335       Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1336         << UndefinedProtocol;
1337     }
1338     Protocols.push_back(PDecl);
1339   }
1340 }
1341 
1342 namespace {
1343 // Callback to only accept typo corrections that are either
1344 // Objective-C protocols or valid Objective-C type arguments.
1345 class ObjCTypeArgOrProtocolValidatorCCC final
1346     : public CorrectionCandidateCallback {
1347   ASTContext &Context;
1348   Sema::LookupNameKind LookupKind;
1349  public:
1350   ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1351                                     Sema::LookupNameKind lookupKind)
1352     : Context(context), LookupKind(lookupKind) { }
1353 
1354   bool ValidateCandidate(const TypoCorrection &candidate) override {
1355     // If we're allowed to find protocols and we have a protocol, accept it.
1356     if (LookupKind != Sema::LookupOrdinaryName) {
1357       if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1358         return true;
1359     }
1360 
1361     // If we're allowed to find type names and we have one, accept it.
1362     if (LookupKind != Sema::LookupObjCProtocolName) {
1363       // If we have a type declaration, we might accept this result.
1364       if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1365         // If we found a tag declaration outside of C++, skip it. This
1366         // can happy because we look for any name when there is no
1367         // bias to protocol or type names.
1368         if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1369           return false;
1370 
1371         // Make sure the type is something we would accept as a type
1372         // argument.
1373         auto type = Context.getTypeDeclType(typeDecl);
1374         if (type->isObjCObjectPointerType() ||
1375             type->isBlockPointerType() ||
1376             type->isDependentType() ||
1377             type->isObjCObjectType())
1378           return true;
1379 
1380         return false;
1381       }
1382 
1383       // If we have an Objective-C class type, accept it; there will
1384       // be another fix to add the '*'.
1385       if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1386         return true;
1387 
1388       return false;
1389     }
1390 
1391     return false;
1392   }
1393 
1394   std::unique_ptr<CorrectionCandidateCallback> clone() override {
1395     return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1396   }
1397 };
1398 } // end anonymous namespace
1399 
1400 void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1401                                         SourceLocation ProtocolLoc,
1402                                         IdentifierInfo *TypeArgId,
1403                                         SourceLocation TypeArgLoc,
1404                                         bool SelectProtocolFirst) {
1405   Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1406       << SelectProtocolFirst << TypeArgId << ProtocolId
1407       << SourceRange(ProtocolLoc);
1408 }
1409 
1410 void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1411        Scope *S,
1412        ParsedType baseType,
1413        SourceLocation lAngleLoc,
1414        ArrayRef<IdentifierInfo *> identifiers,
1415        ArrayRef<SourceLocation> identifierLocs,
1416        SourceLocation rAngleLoc,
1417        SourceLocation &typeArgsLAngleLoc,
1418        SmallVectorImpl<ParsedType> &typeArgs,
1419        SourceLocation &typeArgsRAngleLoc,
1420        SourceLocation &protocolLAngleLoc,
1421        SmallVectorImpl<Decl *> &protocols,
1422        SourceLocation &protocolRAngleLoc,
1423        bool warnOnIncompleteProtocols) {
1424   // Local function that updates the declaration specifiers with
1425   // protocol information.
1426   unsigned numProtocolsResolved = 0;
1427   auto resolvedAsProtocols = [&] {
1428     assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1429 
1430     // Determine whether the base type is a parameterized class, in
1431     // which case we want to warn about typos such as
1432     // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1433     ObjCInterfaceDecl *baseClass = nullptr;
1434     QualType base = GetTypeFromParser(baseType, nullptr);
1435     bool allAreTypeNames = false;
1436     SourceLocation firstClassNameLoc;
1437     if (!base.isNull()) {
1438       if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1439         baseClass = objcObjectType->getInterface();
1440         if (baseClass) {
1441           if (auto typeParams = baseClass->getTypeParamList()) {
1442             if (typeParams->size() == numProtocolsResolved) {
1443               // Note that we should be looking for type names, too.
1444               allAreTypeNames = true;
1445             }
1446           }
1447         }
1448       }
1449     }
1450 
1451     for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1452       ObjCProtocolDecl *&proto
1453         = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1454       // For an objc container, delay protocol reference checking until after we
1455       // can set the objc decl as the availability context, otherwise check now.
1456       if (!warnOnIncompleteProtocols) {
1457         (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1458       }
1459 
1460       // If this is a forward protocol declaration, get its definition.
1461       if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1462         proto = proto->getDefinition();
1463 
1464       // If this is a forward declaration and we are supposed to warn in this
1465       // case, do it.
1466       // FIXME: Recover nicely in the hidden case.
1467       ObjCProtocolDecl *forwardDecl = nullptr;
1468       if (warnOnIncompleteProtocols &&
1469           NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1470         Diag(identifierLocs[i], diag::warn_undef_protocolref)
1471           << proto->getDeclName();
1472         Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1473           << forwardDecl;
1474       }
1475 
1476       // If everything this far has been a type name (and we care
1477       // about such things), check whether this name refers to a type
1478       // as well.
1479       if (allAreTypeNames) {
1480         if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1481                                           LookupOrdinaryName)) {
1482           if (isa<ObjCInterfaceDecl>(decl)) {
1483             if (firstClassNameLoc.isInvalid())
1484               firstClassNameLoc = identifierLocs[i];
1485           } else if (!isa<TypeDecl>(decl)) {
1486             // Not a type.
1487             allAreTypeNames = false;
1488           }
1489         } else {
1490           allAreTypeNames = false;
1491         }
1492       }
1493     }
1494 
1495     // All of the protocols listed also have type names, and at least
1496     // one is an Objective-C class name. Check whether all of the
1497     // protocol conformances are declared by the base class itself, in
1498     // which case we warn.
1499     if (allAreTypeNames && firstClassNameLoc.isValid()) {
1500       llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1501       Context.CollectInheritedProtocols(baseClass, knownProtocols);
1502       bool allProtocolsDeclared = true;
1503       for (auto proto : protocols) {
1504         if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1505           allProtocolsDeclared = false;
1506           break;
1507         }
1508       }
1509 
1510       if (allProtocolsDeclared) {
1511         Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1512           << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1513           << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1514                                         " *");
1515       }
1516     }
1517 
1518     protocolLAngleLoc = lAngleLoc;
1519     protocolRAngleLoc = rAngleLoc;
1520     assert(protocols.size() == identifierLocs.size());
1521   };
1522 
1523   // Attempt to resolve all of the identifiers as protocols.
1524   for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1525     ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1526     protocols.push_back(proto);
1527     if (proto)
1528       ++numProtocolsResolved;
1529   }
1530 
1531   // If all of the names were protocols, these were protocol qualifiers.
1532   if (numProtocolsResolved == identifiers.size())
1533     return resolvedAsProtocols();
1534 
1535   // Attempt to resolve all of the identifiers as type names or
1536   // Objective-C class names. The latter is technically ill-formed,
1537   // but is probably something like \c NSArray<NSView *> missing the
1538   // \c*.
1539   typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1540   SmallVector<TypeOrClassDecl, 4> typeDecls;
1541   unsigned numTypeDeclsResolved = 0;
1542   for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1543     NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1544                                        LookupOrdinaryName);
1545     if (!decl) {
1546       typeDecls.push_back(TypeOrClassDecl());
1547       continue;
1548     }
1549 
1550     if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1551       typeDecls.push_back(typeDecl);
1552       ++numTypeDeclsResolved;
1553       continue;
1554     }
1555 
1556     if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1557       typeDecls.push_back(objcClass);
1558       ++numTypeDeclsResolved;
1559       continue;
1560     }
1561 
1562     typeDecls.push_back(TypeOrClassDecl());
1563   }
1564 
1565   AttributeFactory attrFactory;
1566 
1567   // Local function that forms a reference to the given type or
1568   // Objective-C class declaration.
1569   auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1570                                 -> TypeResult {
1571     // Form declaration specifiers. They simply refer to the type.
1572     DeclSpec DS(attrFactory);
1573     const char* prevSpec; // unused
1574     unsigned diagID; // unused
1575     QualType type;
1576     if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1577       type = Context.getTypeDeclType(actualTypeDecl);
1578     else
1579       type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1580     TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1581     ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1582     DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1583                        parsedType, Context.getPrintingPolicy());
1584     // Use the identifier location for the type source range.
1585     DS.SetRangeStart(loc);
1586     DS.SetRangeEnd(loc);
1587 
1588     // Form the declarator.
1589     Declarator D(DS, DeclaratorContext::TypeName);
1590 
1591     // If we have a typedef of an Objective-C class type that is missing a '*',
1592     // add the '*'.
1593     if (type->getAs<ObjCInterfaceType>()) {
1594       SourceLocation starLoc = getLocForEndOfToken(loc);
1595       D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1596                                                 SourceLocation(),
1597                                                 SourceLocation(),
1598                                                 SourceLocation(),
1599                                                 SourceLocation(),
1600                                                 SourceLocation()),
1601                                                 starLoc);
1602 
1603       // Diagnose the missing '*'.
1604       Diag(loc, diag::err_objc_type_arg_missing_star)
1605         << type
1606         << FixItHint::CreateInsertion(starLoc, " *");
1607     }
1608 
1609     // Convert this to a type.
1610     return ActOnTypeName(S, D);
1611   };
1612 
1613   // Local function that updates the declaration specifiers with
1614   // type argument information.
1615   auto resolvedAsTypeDecls = [&] {
1616     // We did not resolve these as protocols.
1617     protocols.clear();
1618 
1619     assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1620     // Map type declarations to type arguments.
1621     for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1622       // Map type reference to a type.
1623       TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1624       if (!type.isUsable()) {
1625         typeArgs.clear();
1626         return;
1627       }
1628 
1629       typeArgs.push_back(type.get());
1630     }
1631 
1632     typeArgsLAngleLoc = lAngleLoc;
1633     typeArgsRAngleLoc = rAngleLoc;
1634   };
1635 
1636   // If all of the identifiers can be resolved as type names or
1637   // Objective-C class names, we have type arguments.
1638   if (numTypeDeclsResolved == identifiers.size())
1639     return resolvedAsTypeDecls();
1640 
1641   // Error recovery: some names weren't found, or we have a mix of
1642   // type and protocol names. Go resolve all of the unresolved names
1643   // and complain if we can't find a consistent answer.
1644   LookupNameKind lookupKind = LookupAnyName;
1645   for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1646     // If we already have a protocol or type. Check whether it is the
1647     // right thing.
1648     if (protocols[i] || typeDecls[i]) {
1649       // If we haven't figured out whether we want types or protocols
1650       // yet, try to figure it out from this name.
1651       if (lookupKind == LookupAnyName) {
1652         // If this name refers to both a protocol and a type (e.g., \c
1653         // NSObject), don't conclude anything yet.
1654         if (protocols[i] && typeDecls[i])
1655           continue;
1656 
1657         // Otherwise, let this name decide whether we'll be correcting
1658         // toward types or protocols.
1659         lookupKind = protocols[i] ? LookupObjCProtocolName
1660                                   : LookupOrdinaryName;
1661         continue;
1662       }
1663 
1664       // If we want protocols and we have a protocol, there's nothing
1665       // more to do.
1666       if (lookupKind == LookupObjCProtocolName && protocols[i])
1667         continue;
1668 
1669       // If we want types and we have a type declaration, there's
1670       // nothing more to do.
1671       if (lookupKind == LookupOrdinaryName && typeDecls[i])
1672         continue;
1673 
1674       // We have a conflict: some names refer to protocols and others
1675       // refer to types.
1676       DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1677                                    identifiers[i], identifierLocs[i],
1678                                    protocols[i] != nullptr);
1679 
1680       protocols.clear();
1681       typeArgs.clear();
1682       return;
1683     }
1684 
1685     // Perform typo correction on the name.
1686     ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1687     TypoCorrection corrected =
1688         CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
1689                     lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
1690     if (corrected) {
1691       // Did we find a protocol?
1692       if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1693         diagnoseTypo(corrected,
1694                      PDiag(diag::err_undeclared_protocol_suggest)
1695                        << identifiers[i]);
1696         lookupKind = LookupObjCProtocolName;
1697         protocols[i] = proto;
1698         ++numProtocolsResolved;
1699         continue;
1700       }
1701 
1702       // Did we find a type?
1703       if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1704         diagnoseTypo(corrected,
1705                      PDiag(diag::err_unknown_typename_suggest)
1706                        << identifiers[i]);
1707         lookupKind = LookupOrdinaryName;
1708         typeDecls[i] = typeDecl;
1709         ++numTypeDeclsResolved;
1710         continue;
1711       }
1712 
1713       // Did we find an Objective-C class?
1714       if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1715         diagnoseTypo(corrected,
1716                      PDiag(diag::err_unknown_type_or_class_name_suggest)
1717                        << identifiers[i] << true);
1718         lookupKind = LookupOrdinaryName;
1719         typeDecls[i] = objcClass;
1720         ++numTypeDeclsResolved;
1721         continue;
1722       }
1723     }
1724 
1725     // We couldn't find anything.
1726     Diag(identifierLocs[i],
1727          (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1728           : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1729           : diag::err_unknown_typename))
1730       << identifiers[i];
1731     protocols.clear();
1732     typeArgs.clear();
1733     return;
1734   }
1735 
1736   // If all of the names were (corrected to) protocols, these were
1737   // protocol qualifiers.
1738   if (numProtocolsResolved == identifiers.size())
1739     return resolvedAsProtocols();
1740 
1741   // Otherwise, all of the names were (corrected to) types.
1742   assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1743   return resolvedAsTypeDecls();
1744 }
1745 
1746 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1747 /// a class method in its extension.
1748 ///
1749 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1750                                             ObjCInterfaceDecl *ID) {
1751   if (!ID)
1752     return;  // Possibly due to previous error
1753 
1754   llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1755   for (auto *MD : ID->methods())
1756     MethodMap[MD->getSelector()] = MD;
1757 
1758   if (MethodMap.empty())
1759     return;
1760   for (const auto *Method : CAT->methods()) {
1761     const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1762     if (PrevMethod &&
1763         (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1764         !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1765       Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1766             << Method->getDeclName();
1767       Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1768     }
1769   }
1770 }
1771 
1772 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1773 Sema::DeclGroupPtrTy
1774 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
1775                                       ArrayRef<IdentifierLocPair> IdentList,
1776                                       const ParsedAttributesView &attrList) {
1777   SmallVector<Decl *, 8> DeclsInGroup;
1778   for (const IdentifierLocPair &IdentPair : IdentList) {
1779     IdentifierInfo *Ident = IdentPair.first;
1780     ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1781                                                 forRedeclarationInCurContext());
1782     ObjCProtocolDecl *PDecl
1783       = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1784                                  IdentPair.second, AtProtocolLoc,
1785                                  PrevDecl);
1786 
1787     PushOnScopeChains(PDecl, TUScope);
1788     CheckObjCDeclScope(PDecl);
1789 
1790     ProcessDeclAttributeList(TUScope, PDecl, attrList);
1791     AddPragmaAttributes(TUScope, PDecl);
1792 
1793     if (PrevDecl)
1794       mergeDeclAttributes(PDecl, PrevDecl);
1795 
1796     DeclsInGroup.push_back(PDecl);
1797   }
1798 
1799   return BuildDeclaratorGroup(DeclsInGroup);
1800 }
1801 
1802 Decl *Sema::ActOnStartCategoryInterface(
1803     SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1804     SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1805     IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1806     Decl *const *ProtoRefs, unsigned NumProtoRefs,
1807     const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1808     const ParsedAttributesView &AttrList) {
1809   ObjCCategoryDecl *CDecl;
1810   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1811 
1812   /// Check that class of this category is already completely declared.
1813 
1814   if (!IDecl
1815       || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1816                              diag::err_category_forward_interface,
1817                              CategoryName == nullptr)) {
1818     // Create an invalid ObjCCategoryDecl to serve as context for
1819     // the enclosing method declarations.  We mark the decl invalid
1820     // to make it clear that this isn't a valid AST.
1821     CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1822                                      ClassLoc, CategoryLoc, CategoryName,
1823                                      IDecl, typeParamList);
1824     CDecl->setInvalidDecl();
1825     CurContext->addDecl(CDecl);
1826 
1827     if (!IDecl)
1828       Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1829     return ActOnObjCContainerStartDefinition(CDecl);
1830   }
1831 
1832   if (!CategoryName && IDecl->getImplementation()) {
1833     Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1834     Diag(IDecl->getImplementation()->getLocation(),
1835           diag::note_implementation_declared);
1836   }
1837 
1838   if (CategoryName) {
1839     /// Check for duplicate interface declaration for this category
1840     if (ObjCCategoryDecl *Previous
1841           = IDecl->FindCategoryDeclaration(CategoryName)) {
1842       // Class extensions can be declared multiple times, categories cannot.
1843       Diag(CategoryLoc, diag::warn_dup_category_def)
1844         << ClassName << CategoryName;
1845       Diag(Previous->getLocation(), diag::note_previous_definition);
1846     }
1847   }
1848 
1849   // If we have a type parameter list, check it.
1850   if (typeParamList) {
1851     if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1852       if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1853                                         CategoryName
1854                                           ? TypeParamListContext::Category
1855                                           : TypeParamListContext::Extension))
1856         typeParamList = nullptr;
1857     } else {
1858       Diag(typeParamList->getLAngleLoc(),
1859            diag::err_objc_parameterized_category_nonclass)
1860         << (CategoryName != nullptr)
1861         << ClassName
1862         << typeParamList->getSourceRange();
1863 
1864       typeParamList = nullptr;
1865     }
1866   }
1867 
1868   CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1869                                    ClassLoc, CategoryLoc, CategoryName, IDecl,
1870                                    typeParamList);
1871   // FIXME: PushOnScopeChains?
1872   CurContext->addDecl(CDecl);
1873 
1874   // Process the attributes before looking at protocols to ensure that the
1875   // availability attribute is attached to the category to provide availability
1876   // checking for protocol uses.
1877   ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1878   AddPragmaAttributes(TUScope, CDecl);
1879 
1880   if (NumProtoRefs) {
1881     diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1882                            NumProtoRefs, ProtoLocs);
1883     CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1884                            ProtoLocs, Context);
1885     // Protocols in the class extension belong to the class.
1886     if (CDecl->IsClassExtension())
1887      IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1888                                             NumProtoRefs, Context);
1889   }
1890 
1891   CheckObjCDeclScope(CDecl);
1892   return ActOnObjCContainerStartDefinition(CDecl);
1893 }
1894 
1895 /// ActOnStartCategoryImplementation - Perform semantic checks on the
1896 /// category implementation declaration and build an ObjCCategoryImplDecl
1897 /// object.
1898 Decl *Sema::ActOnStartCategoryImplementation(
1899                       SourceLocation AtCatImplLoc,
1900                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
1901                       IdentifierInfo *CatName, SourceLocation CatLoc,
1902                       const ParsedAttributesView &Attrs) {
1903   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1904   ObjCCategoryDecl *CatIDecl = nullptr;
1905   if (IDecl && IDecl->hasDefinition()) {
1906     CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1907     if (!CatIDecl) {
1908       // Category @implementation with no corresponding @interface.
1909       // Create and install one.
1910       CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1911                                           ClassLoc, CatLoc,
1912                                           CatName, IDecl,
1913                                           /*typeParamList=*/nullptr);
1914       CatIDecl->setImplicit();
1915     }
1916   }
1917 
1918   ObjCCategoryImplDecl *CDecl =
1919     ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
1920                                  ClassLoc, AtCatImplLoc, CatLoc);
1921   /// Check that class of this category is already completely declared.
1922   if (!IDecl) {
1923     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1924     CDecl->setInvalidDecl();
1925   } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1926                                  diag::err_undef_interface)) {
1927     CDecl->setInvalidDecl();
1928   }
1929 
1930   ProcessDeclAttributeList(TUScope, CDecl, Attrs);
1931   AddPragmaAttributes(TUScope, CDecl);
1932 
1933   // FIXME: PushOnScopeChains?
1934   CurContext->addDecl(CDecl);
1935 
1936   // If the interface has the objc_runtime_visible attribute, we
1937   // cannot implement a category for it.
1938   if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1939     Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1940       << IDecl->getDeclName();
1941   }
1942 
1943   /// Check that CatName, category name, is not used in another implementation.
1944   if (CatIDecl) {
1945     if (CatIDecl->getImplementation()) {
1946       Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1947         << CatName;
1948       Diag(CatIDecl->getImplementation()->getLocation(),
1949            diag::note_previous_definition);
1950       CDecl->setInvalidDecl();
1951     } else {
1952       CatIDecl->setImplementation(CDecl);
1953       // Warn on implementating category of deprecated class under
1954       // -Wdeprecated-implementations flag.
1955       DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1956                                           CDecl->getLocation());
1957     }
1958   }
1959 
1960   CheckObjCDeclScope(CDecl);
1961   return ActOnObjCContainerStartDefinition(CDecl);
1962 }
1963 
1964 Decl *Sema::ActOnStartClassImplementation(
1965                       SourceLocation AtClassImplLoc,
1966                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
1967                       IdentifierInfo *SuperClassname,
1968                       SourceLocation SuperClassLoc,
1969                       const ParsedAttributesView &Attrs) {
1970   ObjCInterfaceDecl *IDecl = nullptr;
1971   // Check for another declaration kind with the same name.
1972   NamedDecl *PrevDecl
1973     = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1974                        forRedeclarationInCurContext());
1975   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1976     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1977     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1978   } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1979     // FIXME: This will produce an error if the definition of the interface has
1980     // been imported from a module but is not visible.
1981     RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1982                         diag::warn_undef_interface);
1983   } else {
1984     // We did not find anything with the name ClassName; try to correct for
1985     // typos in the class name.
1986     ObjCInterfaceValidatorCCC CCC{};
1987     TypoCorrection Corrected =
1988         CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
1989                     LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
1990     if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1991       // Suggest the (potentially) correct interface name. Don't provide a
1992       // code-modification hint or use the typo name for recovery, because
1993       // this is just a warning. The program may actually be correct.
1994       diagnoseTypo(Corrected,
1995                    PDiag(diag::warn_undef_interface_suggest) << ClassName,
1996                    /*ErrorRecovery*/false);
1997     } else {
1998       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1999     }
2000   }
2001 
2002   // Check that super class name is valid class name
2003   ObjCInterfaceDecl *SDecl = nullptr;
2004   if (SuperClassname) {
2005     // Check if a different kind of symbol declared in this scope.
2006     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
2007                                 LookupOrdinaryName);
2008     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2009       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2010         << SuperClassname;
2011       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2012     } else {
2013       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2014       if (SDecl && !SDecl->hasDefinition())
2015         SDecl = nullptr;
2016       if (!SDecl)
2017         Diag(SuperClassLoc, diag::err_undef_superclass)
2018           << SuperClassname << ClassName;
2019       else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2020         // This implementation and its interface do not have the same
2021         // super class.
2022         Diag(SuperClassLoc, diag::err_conflicting_super_class)
2023           << SDecl->getDeclName();
2024         Diag(SDecl->getLocation(), diag::note_previous_definition);
2025       }
2026     }
2027   }
2028 
2029   if (!IDecl) {
2030     // Legacy case of @implementation with no corresponding @interface.
2031     // Build, chain & install the interface decl into the identifier.
2032 
2033     // FIXME: Do we support attributes on the @implementation? If so we should
2034     // copy them over.
2035     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
2036                                       ClassName, /*typeParamList=*/nullptr,
2037                                       /*PrevDecl=*/nullptr, ClassLoc,
2038                                       true);
2039     AddPragmaAttributes(TUScope, IDecl);
2040     IDecl->startDefinition();
2041     if (SDecl) {
2042       IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2043                              Context.getObjCInterfaceType(SDecl),
2044                              SuperClassLoc));
2045       IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2046     } else {
2047       IDecl->setEndOfDefinitionLoc(ClassLoc);
2048     }
2049 
2050     PushOnScopeChains(IDecl, TUScope);
2051   } else {
2052     // Mark the interface as being completed, even if it was just as
2053     //   @class ....;
2054     // declaration; the user cannot reopen it.
2055     if (!IDecl->hasDefinition())
2056       IDecl->startDefinition();
2057   }
2058 
2059   ObjCImplementationDecl* IMPDecl =
2060     ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
2061                                    ClassLoc, AtClassImplLoc, SuperClassLoc);
2062 
2063   ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
2064   AddPragmaAttributes(TUScope, IMPDecl);
2065 
2066   if (CheckObjCDeclScope(IMPDecl))
2067     return ActOnObjCContainerStartDefinition(IMPDecl);
2068 
2069   // Check that there is no duplicate implementation of this class.
2070   if (IDecl->getImplementation()) {
2071     // FIXME: Don't leak everything!
2072     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2073     Diag(IDecl->getImplementation()->getLocation(),
2074          diag::note_previous_definition);
2075     IMPDecl->setInvalidDecl();
2076   } else { // add it to the list.
2077     IDecl->setImplementation(IMPDecl);
2078     PushOnScopeChains(IMPDecl, TUScope);
2079     // Warn on implementating deprecated class under
2080     // -Wdeprecated-implementations flag.
2081     DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
2082   }
2083 
2084   // If the superclass has the objc_runtime_visible attribute, we
2085   // cannot implement a subclass of it.
2086   if (IDecl->getSuperClass() &&
2087       IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2088     Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2089       << IDecl->getDeclName()
2090       << IDecl->getSuperClass()->getDeclName();
2091   }
2092 
2093   return ActOnObjCContainerStartDefinition(IMPDecl);
2094 }
2095 
2096 Sema::DeclGroupPtrTy
2097 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2098   SmallVector<Decl *, 64> DeclsInGroup;
2099   DeclsInGroup.reserve(Decls.size() + 1);
2100 
2101   for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2102     Decl *Dcl = Decls[i];
2103     if (!Dcl)
2104       continue;
2105     if (Dcl->getDeclContext()->isFileContext())
2106       Dcl->setTopLevelDeclInObjCContainer();
2107     DeclsInGroup.push_back(Dcl);
2108   }
2109 
2110   DeclsInGroup.push_back(ObjCImpDecl);
2111 
2112   return BuildDeclaratorGroup(DeclsInGroup);
2113 }
2114 
2115 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2116                                     ObjCIvarDecl **ivars, unsigned numIvars,
2117                                     SourceLocation RBrace) {
2118   assert(ImpDecl && "missing implementation decl");
2119   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2120   if (!IDecl)
2121     return;
2122   /// Check case of non-existing \@interface decl.
2123   /// (legacy objective-c \@implementation decl without an \@interface decl).
2124   /// Add implementations's ivar to the synthesize class's ivar list.
2125   if (IDecl->isImplicitInterfaceDecl()) {
2126     IDecl->setEndOfDefinitionLoc(RBrace);
2127     // Add ivar's to class's DeclContext.
2128     for (unsigned i = 0, e = numIvars; i != e; ++i) {
2129       ivars[i]->setLexicalDeclContext(ImpDecl);
2130       // In a 'fragile' runtime the ivar was added to the implicit
2131       // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is
2132       // only in the ObjCImplementationDecl. In the non-fragile case the ivar
2133       // therefore also needs to be propagated to the ObjCInterfaceDecl.
2134       if (!LangOpts.ObjCRuntime.isFragile())
2135         IDecl->makeDeclVisibleInContext(ivars[i]);
2136       ImpDecl->addDecl(ivars[i]);
2137     }
2138 
2139     return;
2140   }
2141   // If implementation has empty ivar list, just return.
2142   if (numIvars == 0)
2143     return;
2144 
2145   assert(ivars && "missing @implementation ivars");
2146   if (LangOpts.ObjCRuntime.isNonFragile()) {
2147     if (ImpDecl->getSuperClass())
2148       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2149     for (unsigned i = 0; i < numIvars; i++) {
2150       ObjCIvarDecl* ImplIvar = ivars[i];
2151       if (const ObjCIvarDecl *ClsIvar =
2152             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2153         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2154         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2155         continue;
2156       }
2157       // Check class extensions (unnamed categories) for duplicate ivars.
2158       for (const auto *CDecl : IDecl->visible_extensions()) {
2159         if (const ObjCIvarDecl *ClsExtIvar =
2160             CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2161           Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2162           Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2163           continue;
2164         }
2165       }
2166       // Instance ivar to Implementation's DeclContext.
2167       ImplIvar->setLexicalDeclContext(ImpDecl);
2168       IDecl->makeDeclVisibleInContext(ImplIvar);
2169       ImpDecl->addDecl(ImplIvar);
2170     }
2171     return;
2172   }
2173   // Check interface's Ivar list against those in the implementation.
2174   // names and types must match.
2175   //
2176   unsigned j = 0;
2177   ObjCInterfaceDecl::ivar_iterator
2178     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2179   for (; numIvars > 0 && IVI != IVE; ++IVI) {
2180     ObjCIvarDecl* ImplIvar = ivars[j++];
2181     ObjCIvarDecl* ClsIvar = *IVI;
2182     assert (ImplIvar && "missing implementation ivar");
2183     assert (ClsIvar && "missing class ivar");
2184 
2185     // First, make sure the types match.
2186     if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2187       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2188         << ImplIvar->getIdentifier()
2189         << ImplIvar->getType() << ClsIvar->getType();
2190       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2191     } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2192                ImplIvar->getBitWidthValue(Context) !=
2193                ClsIvar->getBitWidthValue(Context)) {
2194       Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2195            diag::err_conflicting_ivar_bitwidth)
2196           << ImplIvar->getIdentifier();
2197       Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2198            diag::note_previous_definition);
2199     }
2200     // Make sure the names are identical.
2201     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2202       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2203         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2204       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2205     }
2206     --numIvars;
2207   }
2208 
2209   if (numIvars > 0)
2210     Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2211   else if (IVI != IVE)
2212     Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2213 }
2214 
2215 static void WarnUndefinedMethod(Sema &S, ObjCImplDecl *Impl,
2216                                 ObjCMethodDecl *method, bool &IncompleteImpl,
2217                                 unsigned DiagID,
2218                                 NamedDecl *NeededFor = nullptr) {
2219   // No point warning no definition of method which is 'unavailable'.
2220   if (method->getAvailability() == AR_Unavailable)
2221     return;
2222 
2223   // FIXME: For now ignore 'IncompleteImpl'.
2224   // Previously we grouped all unimplemented methods under a single
2225   // warning, but some users strongly voiced that they would prefer
2226   // separate warnings.  We will give that approach a try, as that
2227   // matches what we do with protocols.
2228   {
2229     const Sema::SemaDiagnosticBuilder &B = S.Diag(Impl->getLocation(), DiagID);
2230     B << method;
2231     if (NeededFor)
2232       B << NeededFor;
2233 
2234     // Add an empty definition at the end of the @implementation.
2235     std::string FixItStr;
2236     llvm::raw_string_ostream Out(FixItStr);
2237     method->print(Out, Impl->getASTContext().getPrintingPolicy());
2238     Out << " {\n}\n\n";
2239 
2240     SourceLocation Loc = Impl->getAtEndRange().getBegin();
2241     B << FixItHint::CreateInsertion(Loc, FixItStr);
2242   }
2243 
2244   // Issue a note to the original declaration.
2245   SourceLocation MethodLoc = method->getBeginLoc();
2246   if (MethodLoc.isValid())
2247     S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2248 }
2249 
2250 /// Determines if type B can be substituted for type A.  Returns true if we can
2251 /// guarantee that anything that the user will do to an object of type A can
2252 /// also be done to an object of type B.  This is trivially true if the two
2253 /// types are the same, or if B is a subclass of A.  It becomes more complex
2254 /// in cases where protocols are involved.
2255 ///
2256 /// Object types in Objective-C describe the minimum requirements for an
2257 /// object, rather than providing a complete description of a type.  For
2258 /// example, if A is a subclass of B, then B* may refer to an instance of A.
2259 /// The principle of substitutability means that we may use an instance of A
2260 /// anywhere that we may use an instance of B - it will implement all of the
2261 /// ivars of B and all of the methods of B.
2262 ///
2263 /// This substitutability is important when type checking methods, because
2264 /// the implementation may have stricter type definitions than the interface.
2265 /// The interface specifies minimum requirements, but the implementation may
2266 /// have more accurate ones.  For example, a method may privately accept
2267 /// instances of B, but only publish that it accepts instances of A.  Any
2268 /// object passed to it will be type checked against B, and so will implicitly
2269 /// by a valid A*.  Similarly, a method may return a subclass of the class that
2270 /// it is declared as returning.
2271 ///
2272 /// This is most important when considering subclassing.  A method in a
2273 /// subclass must accept any object as an argument that its superclass's
2274 /// implementation accepts.  It may, however, accept a more general type
2275 /// without breaking substitutability (i.e. you can still use the subclass
2276 /// anywhere that you can use the superclass, but not vice versa).  The
2277 /// converse requirement applies to return types: the return type for a
2278 /// subclass method must be a valid object of the kind that the superclass
2279 /// advertises, but it may be specified more accurately.  This avoids the need
2280 /// for explicit down-casting by callers.
2281 ///
2282 /// Note: This is a stricter requirement than for assignment.
2283 static bool isObjCTypeSubstitutable(ASTContext &Context,
2284                                     const ObjCObjectPointerType *A,
2285                                     const ObjCObjectPointerType *B,
2286                                     bool rejectId) {
2287   // Reject a protocol-unqualified id.
2288   if (rejectId && B->isObjCIdType()) return false;
2289 
2290   // If B is a qualified id, then A must also be a qualified id and it must
2291   // implement all of the protocols in B.  It may not be a qualified class.
2292   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2293   // stricter definition so it is not substitutable for id<A>.
2294   if (B->isObjCQualifiedIdType()) {
2295     return A->isObjCQualifiedIdType() &&
2296            Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2297   }
2298 
2299   /*
2300   // id is a special type that bypasses type checking completely.  We want a
2301   // warning when it is used in one place but not another.
2302   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2303 
2304 
2305   // If B is a qualified id, then A must also be a qualified id (which it isn't
2306   // if we've got this far)
2307   if (B->isObjCQualifiedIdType()) return false;
2308   */
2309 
2310   // Now we know that A and B are (potentially-qualified) class types.  The
2311   // normal rules for assignment apply.
2312   return Context.canAssignObjCInterfaces(A, B);
2313 }
2314 
2315 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2316   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2317 }
2318 
2319 /// Determine whether two set of Objective-C declaration qualifiers conflict.
2320 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2321                                   Decl::ObjCDeclQualifier y) {
2322   return (x & ~Decl::OBJC_TQ_CSNullability) !=
2323          (y & ~Decl::OBJC_TQ_CSNullability);
2324 }
2325 
2326 static bool CheckMethodOverrideReturn(Sema &S,
2327                                       ObjCMethodDecl *MethodImpl,
2328                                       ObjCMethodDecl *MethodDecl,
2329                                       bool IsProtocolMethodDecl,
2330                                       bool IsOverridingMode,
2331                                       bool Warn) {
2332   if (IsProtocolMethodDecl &&
2333       objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2334                             MethodImpl->getObjCDeclQualifier())) {
2335     if (Warn) {
2336       S.Diag(MethodImpl->getLocation(),
2337              (IsOverridingMode
2338                   ? diag::warn_conflicting_overriding_ret_type_modifiers
2339                   : diag::warn_conflicting_ret_type_modifiers))
2340           << MethodImpl->getDeclName()
2341           << MethodImpl->getReturnTypeSourceRange();
2342       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2343           << MethodDecl->getReturnTypeSourceRange();
2344     }
2345     else
2346       return false;
2347   }
2348   if (Warn && IsOverridingMode &&
2349       !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2350       !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2351                                                  MethodDecl->getReturnType(),
2352                                                  false)) {
2353     auto nullabilityMethodImpl =
2354       *MethodImpl->getReturnType()->getNullability(S.Context);
2355     auto nullabilityMethodDecl =
2356       *MethodDecl->getReturnType()->getNullability(S.Context);
2357       S.Diag(MethodImpl->getLocation(),
2358              diag::warn_conflicting_nullability_attr_overriding_ret_types)
2359         << DiagNullabilityKind(
2360              nullabilityMethodImpl,
2361              ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2362               != 0))
2363         << DiagNullabilityKind(
2364              nullabilityMethodDecl,
2365              ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2366                 != 0));
2367       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2368   }
2369 
2370   if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2371                                        MethodDecl->getReturnType()))
2372     return true;
2373   if (!Warn)
2374     return false;
2375 
2376   unsigned DiagID =
2377     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2378                      : diag::warn_conflicting_ret_types;
2379 
2380   // Mismatches between ObjC pointers go into a different warning
2381   // category, and sometimes they're even completely explicitly allowed.
2382   if (const ObjCObjectPointerType *ImplPtrTy =
2383           MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2384     if (const ObjCObjectPointerType *IfacePtrTy =
2385             MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2386       // Allow non-matching return types as long as they don't violate
2387       // the principle of substitutability.  Specifically, we permit
2388       // return types that are subclasses of the declared return type,
2389       // or that are more-qualified versions of the declared type.
2390       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2391         return false;
2392 
2393       DiagID =
2394         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2395                          : diag::warn_non_covariant_ret_types;
2396     }
2397   }
2398 
2399   S.Diag(MethodImpl->getLocation(), DiagID)
2400       << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2401       << MethodImpl->getReturnType()
2402       << MethodImpl->getReturnTypeSourceRange();
2403   S.Diag(MethodDecl->getLocation(), IsOverridingMode
2404                                         ? diag::note_previous_declaration
2405                                         : diag::note_previous_definition)
2406       << MethodDecl->getReturnTypeSourceRange();
2407   return false;
2408 }
2409 
2410 static bool CheckMethodOverrideParam(Sema &S,
2411                                      ObjCMethodDecl *MethodImpl,
2412                                      ObjCMethodDecl *MethodDecl,
2413                                      ParmVarDecl *ImplVar,
2414                                      ParmVarDecl *IfaceVar,
2415                                      bool IsProtocolMethodDecl,
2416                                      bool IsOverridingMode,
2417                                      bool Warn) {
2418   if (IsProtocolMethodDecl &&
2419       objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2420                             IfaceVar->getObjCDeclQualifier())) {
2421     if (Warn) {
2422       if (IsOverridingMode)
2423         S.Diag(ImplVar->getLocation(),
2424                diag::warn_conflicting_overriding_param_modifiers)
2425             << getTypeRange(ImplVar->getTypeSourceInfo())
2426             << MethodImpl->getDeclName();
2427       else S.Diag(ImplVar->getLocation(),
2428              diag::warn_conflicting_param_modifiers)
2429           << getTypeRange(ImplVar->getTypeSourceInfo())
2430           << MethodImpl->getDeclName();
2431       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2432           << getTypeRange(IfaceVar->getTypeSourceInfo());
2433     }
2434     else
2435       return false;
2436   }
2437 
2438   QualType ImplTy = ImplVar->getType();
2439   QualType IfaceTy = IfaceVar->getType();
2440   if (Warn && IsOverridingMode &&
2441       !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2442       !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2443     S.Diag(ImplVar->getLocation(),
2444            diag::warn_conflicting_nullability_attr_overriding_param_types)
2445       << DiagNullabilityKind(
2446            *ImplTy->getNullability(S.Context),
2447            ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2448             != 0))
2449       << DiagNullabilityKind(
2450            *IfaceTy->getNullability(S.Context),
2451            ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2452             != 0));
2453     S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2454   }
2455   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2456     return true;
2457 
2458   if (!Warn)
2459     return false;
2460   unsigned DiagID =
2461     IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2462                      : diag::warn_conflicting_param_types;
2463 
2464   // Mismatches between ObjC pointers go into a different warning
2465   // category, and sometimes they're even completely explicitly allowed..
2466   if (const ObjCObjectPointerType *ImplPtrTy =
2467         ImplTy->getAs<ObjCObjectPointerType>()) {
2468     if (const ObjCObjectPointerType *IfacePtrTy =
2469           IfaceTy->getAs<ObjCObjectPointerType>()) {
2470       // Allow non-matching argument types as long as they don't
2471       // violate the principle of substitutability.  Specifically, the
2472       // implementation must accept any objects that the superclass
2473       // accepts, however it may also accept others.
2474       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2475         return false;
2476 
2477       DiagID =
2478       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2479                        : diag::warn_non_contravariant_param_types;
2480     }
2481   }
2482 
2483   S.Diag(ImplVar->getLocation(), DiagID)
2484     << getTypeRange(ImplVar->getTypeSourceInfo())
2485     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2486   S.Diag(IfaceVar->getLocation(),
2487          (IsOverridingMode ? diag::note_previous_declaration
2488                            : diag::note_previous_definition))
2489     << getTypeRange(IfaceVar->getTypeSourceInfo());
2490   return false;
2491 }
2492 
2493 /// In ARC, check whether the conventional meanings of the two methods
2494 /// match.  If they don't, it's a hard error.
2495 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2496                                       ObjCMethodDecl *decl) {
2497   ObjCMethodFamily implFamily = impl->getMethodFamily();
2498   ObjCMethodFamily declFamily = decl->getMethodFamily();
2499   if (implFamily == declFamily) return false;
2500 
2501   // Since conventions are sorted by selector, the only possibility is
2502   // that the types differ enough to cause one selector or the other
2503   // to fall out of the family.
2504   assert(implFamily == OMF_None || declFamily == OMF_None);
2505 
2506   // No further diagnostics required on invalid declarations.
2507   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2508 
2509   const ObjCMethodDecl *unmatched = impl;
2510   ObjCMethodFamily family = declFamily;
2511   unsigned errorID = diag::err_arc_lost_method_convention;
2512   unsigned noteID = diag::note_arc_lost_method_convention;
2513   if (declFamily == OMF_None) {
2514     unmatched = decl;
2515     family = implFamily;
2516     errorID = diag::err_arc_gained_method_convention;
2517     noteID = diag::note_arc_gained_method_convention;
2518   }
2519 
2520   // Indexes into a %select clause in the diagnostic.
2521   enum FamilySelector {
2522     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2523   };
2524   FamilySelector familySelector = FamilySelector();
2525 
2526   switch (family) {
2527   case OMF_None: llvm_unreachable("logic error, no method convention");
2528   case OMF_retain:
2529   case OMF_release:
2530   case OMF_autorelease:
2531   case OMF_dealloc:
2532   case OMF_finalize:
2533   case OMF_retainCount:
2534   case OMF_self:
2535   case OMF_initialize:
2536   case OMF_performSelector:
2537     // Mismatches for these methods don't change ownership
2538     // conventions, so we don't care.
2539     return false;
2540 
2541   case OMF_init: familySelector = F_init; break;
2542   case OMF_alloc: familySelector = F_alloc; break;
2543   case OMF_copy: familySelector = F_copy; break;
2544   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2545   case OMF_new: familySelector = F_new; break;
2546   }
2547 
2548   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2549   ReasonSelector reasonSelector;
2550 
2551   // The only reason these methods don't fall within their families is
2552   // due to unusual result types.
2553   if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2554     reasonSelector = R_UnrelatedReturn;
2555   } else {
2556     reasonSelector = R_NonObjectReturn;
2557   }
2558 
2559   S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2560   S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2561 
2562   return true;
2563 }
2564 
2565 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2566                                        ObjCMethodDecl *MethodDecl,
2567                                        bool IsProtocolMethodDecl) {
2568   if (getLangOpts().ObjCAutoRefCount &&
2569       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2570     return;
2571 
2572   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2573                             IsProtocolMethodDecl, false,
2574                             true);
2575 
2576   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2577        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2578        EF = MethodDecl->param_end();
2579        IM != EM && IF != EF; ++IM, ++IF) {
2580     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2581                              IsProtocolMethodDecl, false, true);
2582   }
2583 
2584   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2585     Diag(ImpMethodDecl->getLocation(),
2586          diag::warn_conflicting_variadic);
2587     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2588   }
2589 }
2590 
2591 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2592                                        ObjCMethodDecl *Overridden,
2593                                        bool IsProtocolMethodDecl) {
2594 
2595   CheckMethodOverrideReturn(*this, Method, Overridden,
2596                             IsProtocolMethodDecl, true,
2597                             true);
2598 
2599   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2600        IF = Overridden->param_begin(), EM = Method->param_end(),
2601        EF = Overridden->param_end();
2602        IM != EM && IF != EF; ++IM, ++IF) {
2603     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2604                              IsProtocolMethodDecl, true, true);
2605   }
2606 
2607   if (Method->isVariadic() != Overridden->isVariadic()) {
2608     Diag(Method->getLocation(),
2609          diag::warn_conflicting_overriding_variadic);
2610     Diag(Overridden->getLocation(), diag::note_previous_declaration);
2611   }
2612 }
2613 
2614 /// WarnExactTypedMethods - This routine issues a warning if method
2615 /// implementation declaration matches exactly that of its declaration.
2616 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2617                                  ObjCMethodDecl *MethodDecl,
2618                                  bool IsProtocolMethodDecl) {
2619   // don't issue warning when protocol method is optional because primary
2620   // class is not required to implement it and it is safe for protocol
2621   // to implement it.
2622   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2623     return;
2624   // don't issue warning when primary class's method is
2625   // deprecated/unavailable.
2626   if (MethodDecl->hasAttr<UnavailableAttr>() ||
2627       MethodDecl->hasAttr<DeprecatedAttr>())
2628     return;
2629 
2630   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2631                                       IsProtocolMethodDecl, false, false);
2632   if (match)
2633     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2634          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2635          EF = MethodDecl->param_end();
2636          IM != EM && IF != EF; ++IM, ++IF) {
2637       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2638                                        *IM, *IF,
2639                                        IsProtocolMethodDecl, false, false);
2640       if (!match)
2641         break;
2642     }
2643   if (match)
2644     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2645   if (match)
2646     match = !(MethodDecl->isClassMethod() &&
2647               MethodDecl->getSelector() == GetNullarySelector("load", Context));
2648 
2649   if (match) {
2650     Diag(ImpMethodDecl->getLocation(),
2651          diag::warn_category_method_impl_match);
2652     Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2653       << MethodDecl->getDeclName();
2654   }
2655 }
2656 
2657 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2658 /// improve the efficiency of selector lookups and type checking by associating
2659 /// with each protocol / interface / category the flattened instance tables. If
2660 /// we used an immutable set to keep the table then it wouldn't add significant
2661 /// memory cost and it would be handy for lookups.
2662 
2663 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2664 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2665 
2666 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2667                                            ProtocolNameSet &PNS) {
2668   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2669     PNS.insert(PDecl->getIdentifier());
2670   for (const auto *PI : PDecl->protocols())
2671     findProtocolsWithExplicitImpls(PI, PNS);
2672 }
2673 
2674 /// Recursively populates a set with all conformed protocols in a class
2675 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2676 /// attribute.
2677 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2678                                            ProtocolNameSet &PNS) {
2679   if (!Super)
2680     return;
2681 
2682   for (const auto *I : Super->all_referenced_protocols())
2683     findProtocolsWithExplicitImpls(I, PNS);
2684 
2685   findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2686 }
2687 
2688 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
2689 /// Declared in protocol, and those referenced by it.
2690 static void CheckProtocolMethodDefs(
2691     Sema &S, ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool &IncompleteImpl,
2692     const Sema::SelectorSet &InsMap, const Sema::SelectorSet &ClsMap,
2693     ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) {
2694   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2695   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2696                                : dyn_cast<ObjCInterfaceDecl>(CDecl);
2697   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2698 
2699   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2700   ObjCInterfaceDecl *NSIDecl = nullptr;
2701 
2702   // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2703   // then we should check if any class in the super class hierarchy also
2704   // conforms to this protocol, either directly or via protocol inheritance.
2705   // If so, we can skip checking this protocol completely because we
2706   // know that a parent class already satisfies this protocol.
2707   //
2708   // Note: we could generalize this logic for all protocols, and merely
2709   // add the limit on looking at the super class chain for just
2710   // specially marked protocols.  This may be a good optimization.  This
2711   // change is restricted to 'objc_protocol_requires_explicit_implementation'
2712   // protocols for now for controlled evaluation.
2713   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2714     if (!ProtocolsExplictImpl) {
2715       ProtocolsExplictImpl.reset(new ProtocolNameSet);
2716       findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2717     }
2718     if (ProtocolsExplictImpl->contains(PDecl->getIdentifier()))
2719       return;
2720 
2721     // If no super class conforms to the protocol, we should not search
2722     // for methods in the super class to implicitly satisfy the protocol.
2723     Super = nullptr;
2724   }
2725 
2726   if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2727     // check to see if class implements forwardInvocation method and objects
2728     // of this class are derived from 'NSProxy' so that to forward requests
2729     // from one object to another.
2730     // Under such conditions, which means that every method possible is
2731     // implemented in the class, we should not issue "Method definition not
2732     // found" warnings.
2733     // FIXME: Use a general GetUnarySelector method for this.
2734     IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2735     Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2736     if (InsMap.count(fISelector))
2737       // Is IDecl derived from 'NSProxy'? If so, no instance methods
2738       // need be implemented in the implementation.
2739       NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2740   }
2741 
2742   // If this is a forward protocol declaration, get its definition.
2743   if (!PDecl->isThisDeclarationADefinition() &&
2744       PDecl->getDefinition())
2745     PDecl = PDecl->getDefinition();
2746 
2747   // If a method lookup fails locally we still need to look and see if
2748   // the method was implemented by a base class or an inherited
2749   // protocol. This lookup is slow, but occurs rarely in correct code
2750   // and otherwise would terminate in a warning.
2751 
2752   // check unimplemented instance methods.
2753   if (!NSIDecl)
2754     for (auto *method : PDecl->instance_methods()) {
2755       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2756           !method->isPropertyAccessor() &&
2757           !InsMap.count(method->getSelector()) &&
2758           (!Super || !Super->lookupMethod(method->getSelector(),
2759                                           true /* instance */,
2760                                           false /* shallowCategory */,
2761                                           true /* followsSuper */,
2762                                           nullptr /* category */))) {
2763             // If a method is not implemented in the category implementation but
2764             // has been declared in its primary class, superclass,
2765             // or in one of their protocols, no need to issue the warning.
2766             // This is because method will be implemented in the primary class
2767             // or one of its super class implementation.
2768 
2769             // Ugly, but necessary. Method declared in protocol might have
2770             // have been synthesized due to a property declared in the class which
2771             // uses the protocol.
2772             if (ObjCMethodDecl *MethodInClass =
2773                   IDecl->lookupMethod(method->getSelector(),
2774                                       true /* instance */,
2775                                       true /* shallowCategoryLookup */,
2776                                       false /* followSuper */))
2777               if (C || MethodInClass->isPropertyAccessor())
2778                 continue;
2779             unsigned DIAG = diag::warn_unimplemented_protocol_method;
2780             if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2781               WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2782             }
2783           }
2784     }
2785   // check unimplemented class methods
2786   for (auto *method : PDecl->class_methods()) {
2787     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2788         !ClsMap.count(method->getSelector()) &&
2789         (!Super || !Super->lookupMethod(method->getSelector(),
2790                                         false /* class method */,
2791                                         false /* shallowCategoryLookup */,
2792                                         true  /* followSuper */,
2793                                         nullptr /* category */))) {
2794       // See above comment for instance method lookups.
2795       if (C && IDecl->lookupMethod(method->getSelector(),
2796                                    false /* class */,
2797                                    true /* shallowCategoryLookup */,
2798                                    false /* followSuper */))
2799         continue;
2800 
2801       unsigned DIAG = diag::warn_unimplemented_protocol_method;
2802       if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2803         WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2804       }
2805     }
2806   }
2807   // Check on this protocols's referenced protocols, recursively.
2808   for (auto *PI : PDecl->protocols())
2809     CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
2810                             ProtocolsExplictImpl);
2811 }
2812 
2813 /// MatchAllMethodDeclarations - Check methods declared in interface
2814 /// or protocol against those declared in their implementations.
2815 ///
2816 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2817                                       const SelectorSet &ClsMap,
2818                                       SelectorSet &InsMapSeen,
2819                                       SelectorSet &ClsMapSeen,
2820                                       ObjCImplDecl* IMPDecl,
2821                                       ObjCContainerDecl* CDecl,
2822                                       bool &IncompleteImpl,
2823                                       bool ImmediateClass,
2824                                       bool WarnCategoryMethodImpl) {
2825   // Check and see if instance methods in class interface have been
2826   // implemented in the implementation class. If so, their types match.
2827   for (auto *I : CDecl->instance_methods()) {
2828     if (!InsMapSeen.insert(I->getSelector()).second)
2829       continue;
2830     if (!I->isPropertyAccessor() &&
2831         !InsMap.count(I->getSelector())) {
2832       if (ImmediateClass)
2833         WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
2834                             diag::warn_undef_method_impl);
2835       continue;
2836     } else {
2837       ObjCMethodDecl *ImpMethodDecl =
2838         IMPDecl->getInstanceMethod(I->getSelector());
2839       assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2840              "Expected to find the method through lookup as well");
2841       // ImpMethodDecl may be null as in a @dynamic property.
2842       if (ImpMethodDecl) {
2843         // Skip property accessor function stubs.
2844         if (ImpMethodDecl->isSynthesizedAccessorStub())
2845           continue;
2846         if (!WarnCategoryMethodImpl)
2847           WarnConflictingTypedMethods(ImpMethodDecl, I,
2848                                       isa<ObjCProtocolDecl>(CDecl));
2849         else if (!I->isPropertyAccessor())
2850           WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2851       }
2852     }
2853   }
2854 
2855   // Check and see if class methods in class interface have been
2856   // implemented in the implementation class. If so, their types match.
2857   for (auto *I : CDecl->class_methods()) {
2858     if (!ClsMapSeen.insert(I->getSelector()).second)
2859       continue;
2860     if (!I->isPropertyAccessor() &&
2861         !ClsMap.count(I->getSelector())) {
2862       if (ImmediateClass)
2863         WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
2864                             diag::warn_undef_method_impl);
2865     } else {
2866       ObjCMethodDecl *ImpMethodDecl =
2867         IMPDecl->getClassMethod(I->getSelector());
2868       assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2869              "Expected to find the method through lookup as well");
2870       // ImpMethodDecl may be null as in a @dynamic property.
2871       if (ImpMethodDecl) {
2872         // Skip property accessor function stubs.
2873         if (ImpMethodDecl->isSynthesizedAccessorStub())
2874           continue;
2875         if (!WarnCategoryMethodImpl)
2876           WarnConflictingTypedMethods(ImpMethodDecl, I,
2877                                       isa<ObjCProtocolDecl>(CDecl));
2878         else if (!I->isPropertyAccessor())
2879           WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2880       }
2881     }
2882   }
2883 
2884   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2885     // Also, check for methods declared in protocols inherited by
2886     // this protocol.
2887     for (auto *PI : PD->protocols())
2888       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2889                                  IMPDecl, PI, IncompleteImpl, false,
2890                                  WarnCategoryMethodImpl);
2891   }
2892 
2893   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2894     // when checking that methods in implementation match their declaration,
2895     // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2896     // extension; as well as those in categories.
2897     if (!WarnCategoryMethodImpl) {
2898       for (auto *Cat : I->visible_categories())
2899         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2900                                    IMPDecl, Cat, IncompleteImpl,
2901                                    ImmediateClass && Cat->IsClassExtension(),
2902                                    WarnCategoryMethodImpl);
2903     } else {
2904       // Also methods in class extensions need be looked at next.
2905       for (auto *Ext : I->visible_extensions())
2906         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2907                                    IMPDecl, Ext, IncompleteImpl, false,
2908                                    WarnCategoryMethodImpl);
2909     }
2910 
2911     // Check for any implementation of a methods declared in protocol.
2912     for (auto *PI : I->all_referenced_protocols())
2913       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2914                                  IMPDecl, PI, IncompleteImpl, false,
2915                                  WarnCategoryMethodImpl);
2916 
2917     // FIXME. For now, we are not checking for exact match of methods
2918     // in category implementation and its primary class's super class.
2919     if (!WarnCategoryMethodImpl && I->getSuperClass())
2920       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2921                                  IMPDecl,
2922                                  I->getSuperClass(), IncompleteImpl, false);
2923   }
2924 }
2925 
2926 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2927 /// category matches with those implemented in its primary class and
2928 /// warns each time an exact match is found.
2929 void Sema::CheckCategoryVsClassMethodMatches(
2930                                   ObjCCategoryImplDecl *CatIMPDecl) {
2931   // Get category's primary class.
2932   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2933   if (!CatDecl)
2934     return;
2935   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2936   if (!IDecl)
2937     return;
2938   ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2939   SelectorSet InsMap, ClsMap;
2940 
2941   for (const auto *I : CatIMPDecl->instance_methods()) {
2942     Selector Sel = I->getSelector();
2943     // When checking for methods implemented in the category, skip over
2944     // those declared in category class's super class. This is because
2945     // the super class must implement the method.
2946     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2947       continue;
2948     InsMap.insert(Sel);
2949   }
2950 
2951   for (const auto *I : CatIMPDecl->class_methods()) {
2952     Selector Sel = I->getSelector();
2953     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2954       continue;
2955     ClsMap.insert(Sel);
2956   }
2957   if (InsMap.empty() && ClsMap.empty())
2958     return;
2959 
2960   SelectorSet InsMapSeen, ClsMapSeen;
2961   bool IncompleteImpl = false;
2962   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2963                              CatIMPDecl, IDecl,
2964                              IncompleteImpl, false,
2965                              true /*WarnCategoryMethodImpl*/);
2966 }
2967 
2968 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2969                                      ObjCContainerDecl* CDecl,
2970                                      bool IncompleteImpl) {
2971   SelectorSet InsMap;
2972   // Check and see if instance methods in class interface have been
2973   // implemented in the implementation class.
2974   for (const auto *I : IMPDecl->instance_methods())
2975     InsMap.insert(I->getSelector());
2976 
2977   // Add the selectors for getters/setters of @dynamic properties.
2978   for (const auto *PImpl : IMPDecl->property_impls()) {
2979     // We only care about @dynamic implementations.
2980     if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2981       continue;
2982 
2983     const auto *P = PImpl->getPropertyDecl();
2984     if (!P) continue;
2985 
2986     InsMap.insert(P->getGetterName());
2987     if (!P->getSetterName().isNull())
2988       InsMap.insert(P->getSetterName());
2989   }
2990 
2991   // Check and see if properties declared in the interface have either 1)
2992   // an implementation or 2) there is a @synthesize/@dynamic implementation
2993   // of the property in the @implementation.
2994   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2995     bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2996                                 LangOpts.ObjCRuntime.isNonFragile() &&
2997                                 !IDecl->isObjCRequiresPropertyDefs();
2998     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2999   }
3000 
3001   // Diagnose null-resettable synthesized setters.
3002   diagnoseNullResettableSynthesizedSetters(IMPDecl);
3003 
3004   SelectorSet ClsMap;
3005   for (const auto *I : IMPDecl->class_methods())
3006     ClsMap.insert(I->getSelector());
3007 
3008   // Check for type conflict of methods declared in a class/protocol and
3009   // its implementation; if any.
3010   SelectorSet InsMapSeen, ClsMapSeen;
3011   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3012                              IMPDecl, CDecl,
3013                              IncompleteImpl, true);
3014 
3015   // check all methods implemented in category against those declared
3016   // in its primary class.
3017   if (ObjCCategoryImplDecl *CatDecl =
3018         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3019     CheckCategoryVsClassMethodMatches(CatDecl);
3020 
3021   // Check the protocol list for unimplemented methods in the @implementation
3022   // class.
3023   // Check and see if class methods in class interface have been
3024   // implemented in the implementation class.
3025 
3026   LazyProtocolNameSet ExplicitImplProtocols;
3027 
3028   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3029     for (auto *PI : I->all_referenced_protocols())
3030       CheckProtocolMethodDefs(*this, IMPDecl, PI, IncompleteImpl, InsMap,
3031                               ClsMap, I, ExplicitImplProtocols);
3032   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3033     // For extended class, unimplemented methods in its protocols will
3034     // be reported in the primary class.
3035     if (!C->IsClassExtension()) {
3036       for (auto *P : C->protocols())
3037         CheckProtocolMethodDefs(*this, IMPDecl, P, IncompleteImpl, InsMap,
3038                                 ClsMap, CDecl, ExplicitImplProtocols);
3039       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3040                                       /*SynthesizeProperties=*/false);
3041     }
3042   } else
3043     llvm_unreachable("invalid ObjCContainerDecl type.");
3044 }
3045 
3046 Sema::DeclGroupPtrTy
3047 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
3048                                    IdentifierInfo **IdentList,
3049                                    SourceLocation *IdentLocs,
3050                                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
3051                                    unsigned NumElts) {
3052   SmallVector<Decl *, 8> DeclsInGroup;
3053   for (unsigned i = 0; i != NumElts; ++i) {
3054     // Check for another declaration kind with the same name.
3055     NamedDecl *PrevDecl
3056       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
3057                          LookupOrdinaryName, forRedeclarationInCurContext());
3058     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3059       // GCC apparently allows the following idiom:
3060       //
3061       // typedef NSObject < XCElementTogglerP > XCElementToggler;
3062       // @class XCElementToggler;
3063       //
3064       // Here we have chosen to ignore the forward class declaration
3065       // with a warning. Since this is the implied behavior.
3066       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3067       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3068         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3069         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3070       } else {
3071         // a forward class declaration matching a typedef name of a class refers
3072         // to the underlying class. Just ignore the forward class with a warning
3073         // as this will force the intended behavior which is to lookup the
3074         // typedef name.
3075         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3076           Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3077               << IdentList[i];
3078           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3079           continue;
3080         }
3081       }
3082     }
3083 
3084     // Create a declaration to describe this forward declaration.
3085     ObjCInterfaceDecl *PrevIDecl
3086       = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3087 
3088     IdentifierInfo *ClassName = IdentList[i];
3089     if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3090       // A previous decl with a different name is because of
3091       // @compatibility_alias, for example:
3092       // \code
3093       //   @class NewImage;
3094       //   @compatibility_alias OldImage NewImage;
3095       // \endcode
3096       // A lookup for 'OldImage' will return the 'NewImage' decl.
3097       //
3098       // In such a case use the real declaration name, instead of the alias one,
3099       // otherwise we will break IdentifierResolver and redecls-chain invariants.
3100       // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3101       // has been aliased.
3102       ClassName = PrevIDecl->getIdentifier();
3103     }
3104 
3105     // If this forward declaration has type parameters, compare them with the
3106     // type parameters of the previous declaration.
3107     ObjCTypeParamList *TypeParams = TypeParamLists[i];
3108     if (PrevIDecl && TypeParams) {
3109       if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3110         // Check for consistency with the previous declaration.
3111         if (checkTypeParamListConsistency(
3112               *this, PrevTypeParams, TypeParams,
3113               TypeParamListContext::ForwardDeclaration)) {
3114           TypeParams = nullptr;
3115         }
3116       } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3117         // The @interface does not have type parameters. Complain.
3118         Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3119           << ClassName
3120           << TypeParams->getSourceRange();
3121         Diag(Def->getLocation(), diag::note_defined_here)
3122           << ClassName;
3123 
3124         TypeParams = nullptr;
3125       }
3126     }
3127 
3128     ObjCInterfaceDecl *IDecl
3129       = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3130                                   ClassName, TypeParams, PrevIDecl,
3131                                   IdentLocs[i]);
3132     IDecl->setAtEndRange(IdentLocs[i]);
3133 
3134     if (PrevIDecl)
3135       mergeDeclAttributes(IDecl, PrevIDecl);
3136 
3137     PushOnScopeChains(IDecl, TUScope);
3138     CheckObjCDeclScope(IDecl);
3139     DeclsInGroup.push_back(IDecl);
3140   }
3141 
3142   return BuildDeclaratorGroup(DeclsInGroup);
3143 }
3144 
3145 static bool tryMatchRecordTypes(ASTContext &Context,
3146                                 Sema::MethodMatchStrategy strategy,
3147                                 const Type *left, const Type *right);
3148 
3149 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3150                        QualType leftQT, QualType rightQT) {
3151   const Type *left =
3152     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3153   const Type *right =
3154     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3155 
3156   if (left == right) return true;
3157 
3158   // If we're doing a strict match, the types have to match exactly.
3159   if (strategy == Sema::MMS_strict) return false;
3160 
3161   if (left->isIncompleteType() || right->isIncompleteType()) return false;
3162 
3163   // Otherwise, use this absurdly complicated algorithm to try to
3164   // validate the basic, low-level compatibility of the two types.
3165 
3166   // As a minimum, require the sizes and alignments to match.
3167   TypeInfo LeftTI = Context.getTypeInfo(left);
3168   TypeInfo RightTI = Context.getTypeInfo(right);
3169   if (LeftTI.Width != RightTI.Width)
3170     return false;
3171 
3172   if (LeftTI.Align != RightTI.Align)
3173     return false;
3174 
3175   // Consider all the kinds of non-dependent canonical types:
3176   // - functions and arrays aren't possible as return and parameter types
3177 
3178   // - vector types of equal size can be arbitrarily mixed
3179   if (isa<VectorType>(left)) return isa<VectorType>(right);
3180   if (isa<VectorType>(right)) return false;
3181 
3182   // - references should only match references of identical type
3183   // - structs, unions, and Objective-C objects must match more-or-less
3184   //   exactly
3185   // - everything else should be a scalar
3186   if (!left->isScalarType() || !right->isScalarType())
3187     return tryMatchRecordTypes(Context, strategy, left, right);
3188 
3189   // Make scalars agree in kind, except count bools as chars, and group
3190   // all non-member pointers together.
3191   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3192   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3193   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3194   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3195   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3196     leftSK = Type::STK_ObjCObjectPointer;
3197   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3198     rightSK = Type::STK_ObjCObjectPointer;
3199 
3200   // Note that data member pointers and function member pointers don't
3201   // intermix because of the size differences.
3202 
3203   return (leftSK == rightSK);
3204 }
3205 
3206 static bool tryMatchRecordTypes(ASTContext &Context,
3207                                 Sema::MethodMatchStrategy strategy,
3208                                 const Type *lt, const Type *rt) {
3209   assert(lt && rt && lt != rt);
3210 
3211   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3212   RecordDecl *left = cast<RecordType>(lt)->getDecl();
3213   RecordDecl *right = cast<RecordType>(rt)->getDecl();
3214 
3215   // Require union-hood to match.
3216   if (left->isUnion() != right->isUnion()) return false;
3217 
3218   // Require an exact match if either is non-POD.
3219   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3220       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3221     return false;
3222 
3223   // Require size and alignment to match.
3224   TypeInfo LeftTI = Context.getTypeInfo(lt);
3225   TypeInfo RightTI = Context.getTypeInfo(rt);
3226   if (LeftTI.Width != RightTI.Width)
3227     return false;
3228 
3229   if (LeftTI.Align != RightTI.Align)
3230     return false;
3231 
3232   // Require fields to match.
3233   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3234   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3235   for (; li != le && ri != re; ++li, ++ri) {
3236     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3237       return false;
3238   }
3239   return (li == le && ri == re);
3240 }
3241 
3242 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3243 /// returns true, or false, accordingly.
3244 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3245 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3246                                       const ObjCMethodDecl *right,
3247                                       MethodMatchStrategy strategy) {
3248   if (!matchTypes(Context, strategy, left->getReturnType(),
3249                   right->getReturnType()))
3250     return false;
3251 
3252   // If either is hidden, it is not considered to match.
3253   if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible())
3254     return false;
3255 
3256   if (left->isDirectMethod() != right->isDirectMethod())
3257     return false;
3258 
3259   if (getLangOpts().ObjCAutoRefCount &&
3260       (left->hasAttr<NSReturnsRetainedAttr>()
3261          != right->hasAttr<NSReturnsRetainedAttr>() ||
3262        left->hasAttr<NSConsumesSelfAttr>()
3263          != right->hasAttr<NSConsumesSelfAttr>()))
3264     return false;
3265 
3266   ObjCMethodDecl::param_const_iterator
3267     li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3268     re = right->param_end();
3269 
3270   for (; li != le && ri != re; ++li, ++ri) {
3271     assert(ri != right->param_end() && "Param mismatch");
3272     const ParmVarDecl *lparm = *li, *rparm = *ri;
3273 
3274     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3275       return false;
3276 
3277     if (getLangOpts().ObjCAutoRefCount &&
3278         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3279       return false;
3280   }
3281   return true;
3282 }
3283 
3284 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3285                                                ObjCMethodDecl *MethodInList) {
3286   auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3287   auto *MethodInListProtocol =
3288       dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3289   // If this method belongs to a protocol but the method in list does not, or
3290   // vice versa, we say the context is not the same.
3291   if ((MethodProtocol && !MethodInListProtocol) ||
3292       (!MethodProtocol && MethodInListProtocol))
3293     return false;
3294 
3295   if (MethodProtocol && MethodInListProtocol)
3296     return true;
3297 
3298   ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3299   ObjCInterfaceDecl *MethodInListInterface =
3300       MethodInList->getClassInterface();
3301   return MethodInterface == MethodInListInterface;
3302 }
3303 
3304 void Sema::addMethodToGlobalList(ObjCMethodList *List,
3305                                  ObjCMethodDecl *Method) {
3306   // Record at the head of the list whether there were 0, 1, or >= 2 methods
3307   // inside categories.
3308   if (ObjCCategoryDecl *CD =
3309           dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3310     if (!CD->IsClassExtension() && List->getBits() < 2)
3311       List->setBits(List->getBits() + 1);
3312 
3313   // If the list is empty, make it a singleton list.
3314   if (List->getMethod() == nullptr) {
3315     List->setMethod(Method);
3316     List->setNext(nullptr);
3317     return;
3318   }
3319 
3320   // We've seen a method with this name, see if we have already seen this type
3321   // signature.
3322   ObjCMethodList *Previous = List;
3323   ObjCMethodList *ListWithSameDeclaration = nullptr;
3324   for (; List; Previous = List, List = List->getNext()) {
3325     // If we are building a module, keep all of the methods.
3326     if (getLangOpts().isCompilingModule())
3327       continue;
3328 
3329     bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3330                                                       List->getMethod());
3331     // Looking for method with a type bound requires the correct context exists.
3332     // We need to insert a method into the list if the context is different.
3333     // If the method's declaration matches the list
3334     // a> the method belongs to a different context: we need to insert it, in
3335     //    order to emit the availability message, we need to prioritize over
3336     //    availability among the methods with the same declaration.
3337     // b> the method belongs to the same context: there is no need to insert a
3338     //    new entry.
3339     // If the method's declaration does not match the list, we insert it to the
3340     // end.
3341     if (!SameDeclaration ||
3342         !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3343       // Even if two method types do not match, we would like to say
3344       // there is more than one declaration so unavailability/deprecated
3345       // warning is not too noisy.
3346       if (!Method->isDefined())
3347         List->setHasMoreThanOneDecl(true);
3348 
3349       // For methods with the same declaration, the one that is deprecated
3350       // should be put in the front for better diagnostics.
3351       if (Method->isDeprecated() && SameDeclaration &&
3352           !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3353         ListWithSameDeclaration = List;
3354 
3355       if (Method->isUnavailable() && SameDeclaration &&
3356           !ListWithSameDeclaration &&
3357           List->getMethod()->getAvailability() < AR_Deprecated)
3358         ListWithSameDeclaration = List;
3359       continue;
3360     }
3361 
3362     ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3363 
3364     // Propagate the 'defined' bit.
3365     if (Method->isDefined())
3366       PrevObjCMethod->setDefined(true);
3367     else {
3368       // Objective-C doesn't allow an @interface for a class after its
3369       // @implementation. So if Method is not defined and there already is
3370       // an entry for this type signature, Method has to be for a different
3371       // class than PrevObjCMethod.
3372       List->setHasMoreThanOneDecl(true);
3373     }
3374 
3375     // If a method is deprecated, push it in the global pool.
3376     // This is used for better diagnostics.
3377     if (Method->isDeprecated()) {
3378       if (!PrevObjCMethod->isDeprecated())
3379         List->setMethod(Method);
3380     }
3381     // If the new method is unavailable, push it into global pool
3382     // unless previous one is deprecated.
3383     if (Method->isUnavailable()) {
3384       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3385         List->setMethod(Method);
3386     }
3387 
3388     return;
3389   }
3390 
3391   // We have a new signature for an existing method - add it.
3392   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3393   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3394 
3395   // We insert it right before ListWithSameDeclaration.
3396   if (ListWithSameDeclaration) {
3397     auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3398     // FIXME: should we clear the other bits in ListWithSameDeclaration?
3399     ListWithSameDeclaration->setMethod(Method);
3400     ListWithSameDeclaration->setNext(List);
3401     return;
3402   }
3403 
3404   Previous->setNext(new (Mem) ObjCMethodList(Method));
3405 }
3406 
3407 /// Read the contents of the method pool for a given selector from
3408 /// external storage.
3409 void Sema::ReadMethodPool(Selector Sel) {
3410   assert(ExternalSource && "We need an external AST source");
3411   ExternalSource->ReadMethodPool(Sel);
3412 }
3413 
3414 void Sema::updateOutOfDateSelector(Selector Sel) {
3415   if (!ExternalSource)
3416     return;
3417   ExternalSource->updateOutOfDateSelector(Sel);
3418 }
3419 
3420 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3421                                  bool instance) {
3422   // Ignore methods of invalid containers.
3423   if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3424     return;
3425 
3426   if (ExternalSource)
3427     ReadMethodPool(Method->getSelector());
3428 
3429   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3430   if (Pos == MethodPool.end())
3431     Pos = MethodPool
3432               .insert(std::make_pair(Method->getSelector(),
3433                                      GlobalMethodPool::Lists()))
3434               .first;
3435 
3436   Method->setDefined(impl);
3437 
3438   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3439   addMethodToGlobalList(&Entry, Method);
3440 }
3441 
3442 /// Determines if this is an "acceptable" loose mismatch in the global
3443 /// method pool.  This exists mostly as a hack to get around certain
3444 /// global mismatches which we can't afford to make warnings / errors.
3445 /// Really, what we want is a way to take a method out of the global
3446 /// method pool.
3447 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3448                                        ObjCMethodDecl *other) {
3449   if (!chosen->isInstanceMethod())
3450     return false;
3451 
3452   if (chosen->isDirectMethod() != other->isDirectMethod())
3453     return false;
3454 
3455   Selector sel = chosen->getSelector();
3456   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3457     return false;
3458 
3459   // Don't complain about mismatches for -length if the method we
3460   // chose has an integral result type.
3461   return (chosen->getReturnType()->isIntegerType());
3462 }
3463 
3464 /// Return true if the given method is wthin the type bound.
3465 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3466                                      const ObjCObjectType *TypeBound) {
3467   if (!TypeBound)
3468     return true;
3469 
3470   if (TypeBound->isObjCId())
3471     // FIXME: should we handle the case of bounding to id<A, B> differently?
3472     return true;
3473 
3474   auto *BoundInterface = TypeBound->getInterface();
3475   assert(BoundInterface && "unexpected object type!");
3476 
3477   // Check if the Method belongs to a protocol. We should allow any method
3478   // defined in any protocol, because any subclass could adopt the protocol.
3479   auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3480   if (MethodProtocol) {
3481     return true;
3482   }
3483 
3484   // If the Method belongs to a class, check if it belongs to the class
3485   // hierarchy of the class bound.
3486   if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3487     // We allow methods declared within classes that are part of the hierarchy
3488     // of the class bound (superclass of, subclass of, or the same as the class
3489     // bound).
3490     return MethodInterface == BoundInterface ||
3491            MethodInterface->isSuperClassOf(BoundInterface) ||
3492            BoundInterface->isSuperClassOf(MethodInterface);
3493   }
3494   llvm_unreachable("unknown method context");
3495 }
3496 
3497 /// We first select the type of the method: Instance or Factory, then collect
3498 /// all methods with that type.
3499 bool Sema::CollectMultipleMethodsInGlobalPool(
3500     Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3501     bool InstanceFirst, bool CheckTheOther,
3502     const ObjCObjectType *TypeBound) {
3503   if (ExternalSource)
3504     ReadMethodPool(Sel);
3505 
3506   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3507   if (Pos == MethodPool.end())
3508     return false;
3509 
3510   // Gather the non-hidden methods.
3511   ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3512                              Pos->second.second;
3513   for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3514     if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3515       if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3516         Methods.push_back(M->getMethod());
3517     }
3518 
3519   // Return if we find any method with the desired kind.
3520   if (!Methods.empty())
3521     return Methods.size() > 1;
3522 
3523   if (!CheckTheOther)
3524     return false;
3525 
3526   // Gather the other kind.
3527   ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3528                               Pos->second.first;
3529   for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3530     if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3531       if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3532         Methods.push_back(M->getMethod());
3533     }
3534 
3535   return Methods.size() > 1;
3536 }
3537 
3538 bool Sema::AreMultipleMethodsInGlobalPool(
3539     Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3540     bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3541   // Diagnose finding more than one method in global pool.
3542   SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3543   FilteredMethods.push_back(BestMethod);
3544 
3545   for (auto *M : Methods)
3546     if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3547       FilteredMethods.push_back(M);
3548 
3549   if (FilteredMethods.size() > 1)
3550     DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3551                                        receiverIdOrClass);
3552 
3553   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3554   // Test for no method in the pool which should not trigger any warning by
3555   // caller.
3556   if (Pos == MethodPool.end())
3557     return true;
3558   ObjCMethodList &MethList =
3559     BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3560   return MethList.hasMoreThanOneDecl();
3561 }
3562 
3563 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3564                                                bool receiverIdOrClass,
3565                                                bool instance) {
3566   if (ExternalSource)
3567     ReadMethodPool(Sel);
3568 
3569   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3570   if (Pos == MethodPool.end())
3571     return nullptr;
3572 
3573   // Gather the non-hidden methods.
3574   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3575   SmallVector<ObjCMethodDecl *, 4> Methods;
3576   for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3577     if (M->getMethod() && M->getMethod()->isUnconditionallyVisible())
3578       return M->getMethod();
3579   }
3580   return nullptr;
3581 }
3582 
3583 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3584                                               Selector Sel, SourceRange R,
3585                                               bool receiverIdOrClass) {
3586   // We found multiple methods, so we may have to complain.
3587   bool issueDiagnostic = false, issueError = false;
3588 
3589   // We support a warning which complains about *any* difference in
3590   // method signature.
3591   bool strictSelectorMatch =
3592   receiverIdOrClass &&
3593   !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3594   if (strictSelectorMatch) {
3595     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3596       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3597         issueDiagnostic = true;
3598         break;
3599       }
3600     }
3601   }
3602 
3603   // If we didn't see any strict differences, we won't see any loose
3604   // differences.  In ARC, however, we also need to check for loose
3605   // mismatches, because most of them are errors.
3606   if (!strictSelectorMatch ||
3607       (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3608     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3609       // This checks if the methods differ in type mismatch.
3610       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3611           !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3612         issueDiagnostic = true;
3613         if (getLangOpts().ObjCAutoRefCount)
3614           issueError = true;
3615         break;
3616       }
3617     }
3618 
3619   if (issueDiagnostic) {
3620     if (issueError)
3621       Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3622     else if (strictSelectorMatch)
3623       Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3624     else
3625       Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3626 
3627     Diag(Methods[0]->getBeginLoc(),
3628          issueError ? diag::note_possibility : diag::note_using)
3629         << Methods[0]->getSourceRange();
3630     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3631       Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3632           << Methods[I]->getSourceRange();
3633     }
3634   }
3635 }
3636 
3637 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3638   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3639   if (Pos == MethodPool.end())
3640     return nullptr;
3641 
3642   GlobalMethodPool::Lists &Methods = Pos->second;
3643   for (const ObjCMethodList *Method = &Methods.first; Method;
3644        Method = Method->getNext())
3645     if (Method->getMethod() &&
3646         (Method->getMethod()->isDefined() ||
3647          Method->getMethod()->isPropertyAccessor()))
3648       return Method->getMethod();
3649 
3650   for (const ObjCMethodList *Method = &Methods.second; Method;
3651        Method = Method->getNext())
3652     if (Method->getMethod() &&
3653         (Method->getMethod()->isDefined() ||
3654          Method->getMethod()->isPropertyAccessor()))
3655       return Method->getMethod();
3656   return nullptr;
3657 }
3658 
3659 static void
3660 HelperSelectorsForTypoCorrection(
3661                       SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3662                       StringRef Typo, const ObjCMethodDecl * Method) {
3663   const unsigned MaxEditDistance = 1;
3664   unsigned BestEditDistance = MaxEditDistance + 1;
3665   std::string MethodName = Method->getSelector().getAsString();
3666 
3667   unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3668   if (MinPossibleEditDistance > 0 &&
3669       Typo.size() / MinPossibleEditDistance < 1)
3670     return;
3671   unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3672   if (EditDistance > MaxEditDistance)
3673     return;
3674   if (EditDistance == BestEditDistance)
3675     BestMethod.push_back(Method);
3676   else if (EditDistance < BestEditDistance) {
3677     BestMethod.clear();
3678     BestMethod.push_back(Method);
3679   }
3680 }
3681 
3682 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3683                                      QualType ObjectType) {
3684   if (ObjectType.isNull())
3685     return true;
3686   if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3687     return true;
3688   return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3689          nullptr;
3690 }
3691 
3692 const ObjCMethodDecl *
3693 Sema::SelectorsForTypoCorrection(Selector Sel,
3694                                  QualType ObjectType) {
3695   unsigned NumArgs = Sel.getNumArgs();
3696   SmallVector<const ObjCMethodDecl *, 8> Methods;
3697   bool ObjectIsId = true, ObjectIsClass = true;
3698   if (ObjectType.isNull())
3699     ObjectIsId = ObjectIsClass = false;
3700   else if (!ObjectType->isObjCObjectPointerType())
3701     return nullptr;
3702   else if (const ObjCObjectPointerType *ObjCPtr =
3703            ObjectType->getAsObjCInterfacePointerType()) {
3704     ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3705     ObjectIsId = ObjectIsClass = false;
3706   }
3707   else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3708     ObjectIsClass = false;
3709   else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3710     ObjectIsId = false;
3711   else
3712     return nullptr;
3713 
3714   for (GlobalMethodPool::iterator b = MethodPool.begin(),
3715        e = MethodPool.end(); b != e; b++) {
3716     // instance methods
3717     for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3718       if (M->getMethod() &&
3719           (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3720           (M->getMethod()->getSelector() != Sel)) {
3721         if (ObjectIsId)
3722           Methods.push_back(M->getMethod());
3723         else if (!ObjectIsClass &&
3724                  HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3725                                           ObjectType))
3726           Methods.push_back(M->getMethod());
3727       }
3728     // class methods
3729     for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3730       if (M->getMethod() &&
3731           (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3732           (M->getMethod()->getSelector() != Sel)) {
3733         if (ObjectIsClass)
3734           Methods.push_back(M->getMethod());
3735         else if (!ObjectIsId &&
3736                  HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3737                                           ObjectType))
3738           Methods.push_back(M->getMethod());
3739       }
3740   }
3741 
3742   SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3743   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3744     HelperSelectorsForTypoCorrection(SelectedMethods,
3745                                      Sel.getAsString(), Methods[i]);
3746   }
3747   return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3748 }
3749 
3750 /// DiagnoseDuplicateIvars -
3751 /// Check for duplicate ivars in the entire class at the start of
3752 /// \@implementation. This becomes necesssary because class extension can
3753 /// add ivars to a class in random order which will not be known until
3754 /// class's \@implementation is seen.
3755 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3756                                   ObjCInterfaceDecl *SID) {
3757   for (auto *Ivar : ID->ivars()) {
3758     if (Ivar->isInvalidDecl())
3759       continue;
3760     if (IdentifierInfo *II = Ivar->getIdentifier()) {
3761       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3762       if (prevIvar) {
3763         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3764         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3765         Ivar->setInvalidDecl();
3766       }
3767     }
3768   }
3769 }
3770 
3771 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3772 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3773   if (S.getLangOpts().ObjCWeak) return;
3774 
3775   for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3776          ivar; ivar = ivar->getNextIvar()) {
3777     if (ivar->isInvalidDecl()) continue;
3778     if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3779       if (S.getLangOpts().ObjCWeakRuntime) {
3780         S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3781       } else {
3782         S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3783       }
3784     }
3785   }
3786 }
3787 
3788 /// Diagnose attempts to use flexible array member with retainable object type.
3789 static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3790                                                   ObjCInterfaceDecl *ID) {
3791   if (!S.getLangOpts().ObjCAutoRefCount)
3792     return;
3793 
3794   for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3795        ivar = ivar->getNextIvar()) {
3796     if (ivar->isInvalidDecl())
3797       continue;
3798     QualType IvarTy = ivar->getType();
3799     if (IvarTy->isIncompleteArrayType() &&
3800         (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3801         IvarTy->isObjCLifetimeType()) {
3802       S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3803       ivar->setInvalidDecl();
3804     }
3805   }
3806 }
3807 
3808 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3809   switch (CurContext->getDeclKind()) {
3810     case Decl::ObjCInterface:
3811       return Sema::OCK_Interface;
3812     case Decl::ObjCProtocol:
3813       return Sema::OCK_Protocol;
3814     case Decl::ObjCCategory:
3815       if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3816         return Sema::OCK_ClassExtension;
3817       return Sema::OCK_Category;
3818     case Decl::ObjCImplementation:
3819       return Sema::OCK_Implementation;
3820     case Decl::ObjCCategoryImpl:
3821       return Sema::OCK_CategoryImplementation;
3822 
3823     default:
3824       return Sema::OCK_None;
3825   }
3826 }
3827 
3828 static bool IsVariableSizedType(QualType T) {
3829   if (T->isIncompleteArrayType())
3830     return true;
3831   const auto *RecordTy = T->getAs<RecordType>();
3832   return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3833 }
3834 
3835 static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3836   ObjCInterfaceDecl *IntfDecl = nullptr;
3837   ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3838       ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3839   if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3840     Ivars = IntfDecl->ivars();
3841   } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3842     IntfDecl = ImplDecl->getClassInterface();
3843     Ivars = ImplDecl->ivars();
3844   } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3845     if (CategoryDecl->IsClassExtension()) {
3846       IntfDecl = CategoryDecl->getClassInterface();
3847       Ivars = CategoryDecl->ivars();
3848     }
3849   }
3850 
3851   // Check if variable sized ivar is in interface and visible to subclasses.
3852   if (!isa<ObjCInterfaceDecl>(OCD)) {
3853     for (auto ivar : Ivars) {
3854       if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3855         S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3856             << ivar->getDeclName() << ivar->getType();
3857       }
3858     }
3859   }
3860 
3861   // Subsequent checks require interface decl.
3862   if (!IntfDecl)
3863     return;
3864 
3865   // Check if variable sized ivar is followed by another ivar.
3866   for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3867        ivar = ivar->getNextIvar()) {
3868     if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3869       continue;
3870     QualType IvarTy = ivar->getType();
3871     bool IsInvalidIvar = false;
3872     if (IvarTy->isIncompleteArrayType()) {
3873       S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3874           << ivar->getDeclName() << IvarTy
3875           << TTK_Class; // Use "class" for Obj-C.
3876       IsInvalidIvar = true;
3877     } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3878       if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3879         S.Diag(ivar->getLocation(),
3880                diag::err_objc_variable_sized_type_not_at_end)
3881             << ivar->getDeclName() << IvarTy;
3882         IsInvalidIvar = true;
3883       }
3884     }
3885     if (IsInvalidIvar) {
3886       S.Diag(ivar->getNextIvar()->getLocation(),
3887              diag::note_next_ivar_declaration)
3888           << ivar->getNextIvar()->getSynthesize();
3889       ivar->setInvalidDecl();
3890     }
3891   }
3892 
3893   // Check if ObjC container adds ivars after variable sized ivar in superclass.
3894   // Perform the check only if OCD is the first container to declare ivars to
3895   // avoid multiple warnings for the same ivar.
3896   ObjCIvarDecl *FirstIvar =
3897       (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3898   if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3899     const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3900     while (SuperClass && SuperClass->ivar_empty())
3901       SuperClass = SuperClass->getSuperClass();
3902     if (SuperClass) {
3903       auto IvarIter = SuperClass->ivar_begin();
3904       std::advance(IvarIter, SuperClass->ivar_size() - 1);
3905       const ObjCIvarDecl *LastIvar = *IvarIter;
3906       if (IsVariableSizedType(LastIvar->getType())) {
3907         S.Diag(FirstIvar->getLocation(),
3908                diag::warn_superclass_variable_sized_type_not_at_end)
3909             << FirstIvar->getDeclName() << LastIvar->getDeclName()
3910             << LastIvar->getType() << SuperClass->getDeclName();
3911         S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3912             << LastIvar->getDeclName();
3913       }
3914     }
3915   }
3916 }
3917 
3918 static void DiagnoseCategoryDirectMembersProtocolConformance(
3919     Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
3920 
3921 static void DiagnoseCategoryDirectMembersProtocolConformance(
3922     Sema &S, ObjCCategoryDecl *CDecl,
3923     const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
3924   for (auto *PI : Protocols)
3925     DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl);
3926 }
3927 
3928 static void DiagnoseCategoryDirectMembersProtocolConformance(
3929     Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
3930   if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
3931     PDecl = PDecl->getDefinition();
3932 
3933   llvm::SmallVector<const Decl *, 4> DirectMembers;
3934   const auto *IDecl = CDecl->getClassInterface();
3935   for (auto *MD : PDecl->methods()) {
3936     if (!MD->isPropertyAccessor()) {
3937       if (const auto *CMD =
3938               IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
3939         if (CMD->isDirectMethod())
3940           DirectMembers.push_back(CMD);
3941       }
3942     }
3943   }
3944   for (auto *PD : PDecl->properties()) {
3945     if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
3946             PD->getIdentifier(),
3947             PD->isClassProperty()
3948                 ? ObjCPropertyQueryKind::OBJC_PR_query_class
3949                 : ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
3950       if (CPD->isDirectProperty())
3951         DirectMembers.push_back(CPD);
3952     }
3953   }
3954   if (!DirectMembers.empty()) {
3955     S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
3956         << CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
3957     for (const auto *MD : DirectMembers)
3958       S.Diag(MD->getLocation(), diag::note_direct_member_here);
3959     return;
3960   }
3961 
3962   // Check on this protocols's referenced protocols, recursively.
3963   DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl,
3964                                                    PDecl->protocols());
3965 }
3966 
3967 // Note: For class/category implementations, allMethods is always null.
3968 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3969                        ArrayRef<DeclGroupPtrTy> allTUVars) {
3970   if (getObjCContainerKind() == Sema::OCK_None)
3971     return nullptr;
3972 
3973   assert(AtEnd.isValid() && "Invalid location for '@end'");
3974 
3975   auto *OCD = cast<ObjCContainerDecl>(CurContext);
3976   Decl *ClassDecl = OCD;
3977 
3978   bool isInterfaceDeclKind =
3979         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3980          || isa<ObjCProtocolDecl>(ClassDecl);
3981   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3982 
3983   // Make synthesized accessor stub functions visible.
3984   // ActOnPropertyImplDecl() creates them as not visible in case
3985   // they are overridden by an explicit method that is encountered
3986   // later.
3987   if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) {
3988     for (auto PropImpl : OID->property_impls()) {
3989       if (auto *Getter = PropImpl->getGetterMethodDecl())
3990         if (Getter->isSynthesizedAccessorStub())
3991           OID->addDecl(Getter);
3992       if (auto *Setter = PropImpl->getSetterMethodDecl())
3993         if (Setter->isSynthesizedAccessorStub())
3994           OID->addDecl(Setter);
3995     }
3996   }
3997 
3998   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3999   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
4000   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
4001 
4002   for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
4003     ObjCMethodDecl *Method =
4004       cast_or_null<ObjCMethodDecl>(allMethods[i]);
4005 
4006     if (!Method) continue;  // Already issued a diagnostic.
4007     if (Method->isInstanceMethod()) {
4008       /// Check for instance method of the same name with incompatible types
4009       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
4010       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4011                               : false;
4012       if ((isInterfaceDeclKind && PrevMethod && !match)
4013           || (checkIdenticalMethods && match)) {
4014           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4015             << Method->getDeclName();
4016           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4017         Method->setInvalidDecl();
4018       } else {
4019         if (PrevMethod) {
4020           Method->setAsRedeclaration(PrevMethod);
4021           if (!Context.getSourceManager().isInSystemHeader(
4022                  Method->getLocation()))
4023             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4024               << Method->getDeclName();
4025           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4026         }
4027         InsMap[Method->getSelector()] = Method;
4028         /// The following allows us to typecheck messages to "id".
4029         AddInstanceMethodToGlobalPool(Method);
4030       }
4031     } else {
4032       /// Check for class method of the same name with incompatible types
4033       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
4034       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4035                               : false;
4036       if ((isInterfaceDeclKind && PrevMethod && !match)
4037           || (checkIdenticalMethods && match)) {
4038         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4039           << Method->getDeclName();
4040         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4041         Method->setInvalidDecl();
4042       } else {
4043         if (PrevMethod) {
4044           Method->setAsRedeclaration(PrevMethod);
4045           if (!Context.getSourceManager().isInSystemHeader(
4046                  Method->getLocation()))
4047             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4048               << Method->getDeclName();
4049           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4050         }
4051         ClsMap[Method->getSelector()] = Method;
4052         AddFactoryMethodToGlobalPool(Method);
4053       }
4054     }
4055   }
4056   if (isa<ObjCInterfaceDecl>(ClassDecl)) {
4057     // Nothing to do here.
4058   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
4059     // Categories are used to extend the class by declaring new methods.
4060     // By the same token, they are also used to add new properties. No
4061     // need to compare the added property to those in the class.
4062 
4063     if (C->IsClassExtension()) {
4064       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
4065       DiagnoseClassExtensionDupMethods(C, CCPrimary);
4066     }
4067 
4068     DiagnoseCategoryDirectMembersProtocolConformance(*this, C, C->protocols());
4069   }
4070   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
4071     if (CDecl->getIdentifier())
4072       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
4073       // user-defined setter/getter. It also synthesizes setter/getter methods
4074       // and adds them to the DeclContext and global method pools.
4075       for (auto *I : CDecl->properties())
4076         ProcessPropertyDecl(I);
4077     CDecl->setAtEndRange(AtEnd);
4078   }
4079   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
4080     IC->setAtEndRange(AtEnd);
4081     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
4082       // Any property declared in a class extension might have user
4083       // declared setter or getter in current class extension or one
4084       // of the other class extensions. Mark them as synthesized as
4085       // property will be synthesized when property with same name is
4086       // seen in the @implementation.
4087       for (const auto *Ext : IDecl->visible_extensions()) {
4088         for (const auto *Property : Ext->instance_properties()) {
4089           // Skip over properties declared @dynamic
4090           if (const ObjCPropertyImplDecl *PIDecl
4091               = IC->FindPropertyImplDecl(Property->getIdentifier(),
4092                                          Property->getQueryKind()))
4093             if (PIDecl->getPropertyImplementation()
4094                   == ObjCPropertyImplDecl::Dynamic)
4095               continue;
4096 
4097           for (const auto *Ext : IDecl->visible_extensions()) {
4098             if (ObjCMethodDecl *GetterMethod =
4099                     Ext->getInstanceMethod(Property->getGetterName()))
4100               GetterMethod->setPropertyAccessor(true);
4101             if (!Property->isReadOnly())
4102               if (ObjCMethodDecl *SetterMethod
4103                     = Ext->getInstanceMethod(Property->getSetterName()))
4104                 SetterMethod->setPropertyAccessor(true);
4105           }
4106         }
4107       }
4108       ImplMethodsVsClassMethods(S, IC, IDecl);
4109       AtomicPropertySetterGetterRules(IC, IDecl);
4110       DiagnoseOwningPropertyGetterSynthesis(IC);
4111       DiagnoseUnusedBackingIvarInAccessor(S, IC);
4112       if (IDecl->hasDesignatedInitializers())
4113         DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
4114       DiagnoseWeakIvars(*this, IC);
4115       DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
4116 
4117       bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4118       if (IDecl->getSuperClass() == nullptr) {
4119         // This class has no superclass, so check that it has been marked with
4120         // __attribute((objc_root_class)).
4121         if (!HasRootClassAttr) {
4122           SourceLocation DeclLoc(IDecl->getLocation());
4123           SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
4124           Diag(DeclLoc, diag::warn_objc_root_class_missing)
4125             << IDecl->getIdentifier();
4126           // See if NSObject is in the current scope, and if it is, suggest
4127           // adding " : NSObject " to the class declaration.
4128           NamedDecl *IF = LookupSingleName(TUScope,
4129                                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4130                                            DeclLoc, LookupOrdinaryName);
4131           ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4132           if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4133             Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4134               << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4135           } else {
4136             Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4137           }
4138         }
4139       } else if (HasRootClassAttr) {
4140         // Complain that only root classes may have this attribute.
4141         Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4142       }
4143 
4144       if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4145         // An interface can subclass another interface with a
4146         // objc_subclassing_restricted attribute when it has that attribute as
4147         // well (because of interfaces imported from Swift). Therefore we have
4148         // to check if we can subclass in the implementation as well.
4149         if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4150             Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4151           Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4152           Diag(Super->getLocation(), diag::note_class_declared);
4153         }
4154       }
4155 
4156       if (IDecl->hasAttr<ObjCClassStubAttr>())
4157         Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4158 
4159       if (LangOpts.ObjCRuntime.isNonFragile()) {
4160         while (IDecl->getSuperClass()) {
4161           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4162           IDecl = IDecl->getSuperClass();
4163         }
4164       }
4165     }
4166     SetIvarInitializers(IC);
4167   } else if (ObjCCategoryImplDecl* CatImplClass =
4168                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4169     CatImplClass->setAtEndRange(AtEnd);
4170 
4171     // Find category interface decl and then check that all methods declared
4172     // in this interface are implemented in the category @implementation.
4173     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4174       if (ObjCCategoryDecl *Cat
4175             = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4176         ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4177       }
4178     }
4179   } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4180     if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4181       if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4182           Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4183         Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4184         Diag(Super->getLocation(), diag::note_class_declared);
4185       }
4186     }
4187 
4188     if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4189         !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
4190       Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
4191   }
4192   DiagnoseVariableSizedIvars(*this, OCD);
4193   if (isInterfaceDeclKind) {
4194     // Reject invalid vardecls.
4195     for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4196       DeclGroupRef DG = allTUVars[i].get();
4197       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4198         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4199           if (!VDecl->hasExternalStorage())
4200             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4201         }
4202     }
4203   }
4204   ActOnObjCContainerFinishDefinition();
4205 
4206   for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4207     DeclGroupRef DG = allTUVars[i].get();
4208     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4209       (*I)->setTopLevelDeclInObjCContainer();
4210     Consumer.HandleTopLevelDeclInObjCContainer(DG);
4211   }
4212 
4213   ActOnDocumentableDecl(ClassDecl);
4214   return ClassDecl;
4215 }
4216 
4217 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4218 /// objective-c's type qualifier from the parser version of the same info.
4219 static Decl::ObjCDeclQualifier
4220 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
4221   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4222 }
4223 
4224 /// Check whether the declared result type of the given Objective-C
4225 /// method declaration is compatible with the method's class.
4226 ///
4227 static Sema::ResultTypeCompatibilityKind
4228 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4229                                     ObjCInterfaceDecl *CurrentClass) {
4230   QualType ResultType = Method->getReturnType();
4231 
4232   // If an Objective-C method inherits its related result type, then its
4233   // declared result type must be compatible with its own class type. The
4234   // declared result type is compatible if:
4235   if (const ObjCObjectPointerType *ResultObjectType
4236                                 = ResultType->getAs<ObjCObjectPointerType>()) {
4237     //   - it is id or qualified id, or
4238     if (ResultObjectType->isObjCIdType() ||
4239         ResultObjectType->isObjCQualifiedIdType())
4240       return Sema::RTC_Compatible;
4241 
4242     if (CurrentClass) {
4243       if (ObjCInterfaceDecl *ResultClass
4244                                       = ResultObjectType->getInterfaceDecl()) {
4245         //   - it is the same as the method's class type, or
4246         if (declaresSameEntity(CurrentClass, ResultClass))
4247           return Sema::RTC_Compatible;
4248 
4249         //   - it is a superclass of the method's class type
4250         if (ResultClass->isSuperClassOf(CurrentClass))
4251           return Sema::RTC_Compatible;
4252       }
4253     } else {
4254       // Any Objective-C pointer type might be acceptable for a protocol
4255       // method; we just don't know.
4256       return Sema::RTC_Unknown;
4257     }
4258   }
4259 
4260   return Sema::RTC_Incompatible;
4261 }
4262 
4263 namespace {
4264 /// A helper class for searching for methods which a particular method
4265 /// overrides.
4266 class OverrideSearch {
4267 public:
4268   const ObjCMethodDecl *Method;
4269   llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4270   bool Recursive;
4271 
4272 public:
4273   OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4274     Selector selector = method->getSelector();
4275 
4276     // Bypass this search if we've never seen an instance/class method
4277     // with this selector before.
4278     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4279     if (it == S.MethodPool.end()) {
4280       if (!S.getExternalSource()) return;
4281       S.ReadMethodPool(selector);
4282 
4283       it = S.MethodPool.find(selector);
4284       if (it == S.MethodPool.end())
4285         return;
4286     }
4287     const ObjCMethodList &list =
4288       method->isInstanceMethod() ? it->second.first : it->second.second;
4289     if (!list.getMethod()) return;
4290 
4291     const ObjCContainerDecl *container
4292       = cast<ObjCContainerDecl>(method->getDeclContext());
4293 
4294     // Prevent the search from reaching this container again.  This is
4295     // important with categories, which override methods from the
4296     // interface and each other.
4297     if (const ObjCCategoryDecl *Category =
4298             dyn_cast<ObjCCategoryDecl>(container)) {
4299       searchFromContainer(container);
4300       if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4301         searchFromContainer(Interface);
4302     } else {
4303       searchFromContainer(container);
4304     }
4305   }
4306 
4307   typedef decltype(Overridden)::iterator iterator;
4308   iterator begin() const { return Overridden.begin(); }
4309   iterator end() const { return Overridden.end(); }
4310 
4311 private:
4312   void searchFromContainer(const ObjCContainerDecl *container) {
4313     if (container->isInvalidDecl()) return;
4314 
4315     switch (container->getDeclKind()) {
4316 #define OBJCCONTAINER(type, base) \
4317     case Decl::type: \
4318       searchFrom(cast<type##Decl>(container)); \
4319       break;
4320 #define ABSTRACT_DECL(expansion)
4321 #define DECL(type, base) \
4322     case Decl::type:
4323 #include "clang/AST/DeclNodes.inc"
4324       llvm_unreachable("not an ObjC container!");
4325     }
4326   }
4327 
4328   void searchFrom(const ObjCProtocolDecl *protocol) {
4329     if (!protocol->hasDefinition())
4330       return;
4331 
4332     // A method in a protocol declaration overrides declarations from
4333     // referenced ("parent") protocols.
4334     search(protocol->getReferencedProtocols());
4335   }
4336 
4337   void searchFrom(const ObjCCategoryDecl *category) {
4338     // A method in a category declaration overrides declarations from
4339     // the main class and from protocols the category references.
4340     // The main class is handled in the constructor.
4341     search(category->getReferencedProtocols());
4342   }
4343 
4344   void searchFrom(const ObjCCategoryImplDecl *impl) {
4345     // A method in a category definition that has a category
4346     // declaration overrides declarations from the category
4347     // declaration.
4348     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4349       search(category);
4350       if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4351         search(Interface);
4352 
4353     // Otherwise it overrides declarations from the class.
4354     } else if (const auto *Interface = impl->getClassInterface()) {
4355       search(Interface);
4356     }
4357   }
4358 
4359   void searchFrom(const ObjCInterfaceDecl *iface) {
4360     // A method in a class declaration overrides declarations from
4361     if (!iface->hasDefinition())
4362       return;
4363 
4364     //   - categories,
4365     for (auto *Cat : iface->known_categories())
4366       search(Cat);
4367 
4368     //   - the super class, and
4369     if (ObjCInterfaceDecl *super = iface->getSuperClass())
4370       search(super);
4371 
4372     //   - any referenced protocols.
4373     search(iface->getReferencedProtocols());
4374   }
4375 
4376   void searchFrom(const ObjCImplementationDecl *impl) {
4377     // A method in a class implementation overrides declarations from
4378     // the class interface.
4379     if (const auto *Interface = impl->getClassInterface())
4380       search(Interface);
4381   }
4382 
4383   void search(const ObjCProtocolList &protocols) {
4384     for (const auto *Proto : protocols)
4385       search(Proto);
4386   }
4387 
4388   void search(const ObjCContainerDecl *container) {
4389     // Check for a method in this container which matches this selector.
4390     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4391                                                 Method->isInstanceMethod(),
4392                                                 /*AllowHidden=*/true);
4393 
4394     // If we find one, record it and bail out.
4395     if (meth) {
4396       Overridden.insert(meth);
4397       return;
4398     }
4399 
4400     // Otherwise, search for methods that a hypothetical method here
4401     // would have overridden.
4402 
4403     // Note that we're now in a recursive case.
4404     Recursive = true;
4405 
4406     searchFromContainer(container);
4407   }
4408 };
4409 } // end anonymous namespace
4410 
4411 void Sema::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
4412                                           ObjCMethodDecl *overridden) {
4413   if (overridden->isDirectMethod()) {
4414     const auto *attr = overridden->getAttr<ObjCDirectAttr>();
4415     Diag(method->getLocation(), diag::err_objc_override_direct_method);
4416     Diag(attr->getLocation(), diag::note_previous_declaration);
4417   } else if (method->isDirectMethod()) {
4418     const auto *attr = method->getAttr<ObjCDirectAttr>();
4419     Diag(attr->getLocation(), diag::err_objc_direct_on_override)
4420         << isa<ObjCProtocolDecl>(overridden->getDeclContext());
4421     Diag(overridden->getLocation(), diag::note_previous_declaration);
4422   }
4423 }
4424 
4425 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4426                                     ObjCInterfaceDecl *CurrentClass,
4427                                     ResultTypeCompatibilityKind RTC) {
4428   if (!ObjCMethod)
4429     return;
4430   // Search for overridden methods and merge information down from them.
4431   OverrideSearch overrides(*this, ObjCMethod);
4432   // Keep track if the method overrides any method in the class's base classes,
4433   // its protocols, or its categories' protocols; we will keep that info
4434   // in the ObjCMethodDecl.
4435   // For this info, a method in an implementation is not considered as
4436   // overriding the same method in the interface or its categories.
4437   bool hasOverriddenMethodsInBaseOrProtocol = false;
4438   for (ObjCMethodDecl *overridden : overrides) {
4439     if (!hasOverriddenMethodsInBaseOrProtocol) {
4440       if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4441           CurrentClass != overridden->getClassInterface() ||
4442           overridden->isOverriding()) {
4443         CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
4444         hasOverriddenMethodsInBaseOrProtocol = true;
4445       } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4446         // OverrideSearch will return as "overridden" the same method in the
4447         // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4448         // check whether a category of a base class introduced a method with the
4449         // same selector, after the interface method declaration.
4450         // To avoid unnecessary lookups in the majority of cases, we use the
4451         // extra info bits in GlobalMethodPool to check whether there were any
4452         // category methods with this selector.
4453         GlobalMethodPool::iterator It =
4454             MethodPool.find(ObjCMethod->getSelector());
4455         if (It != MethodPool.end()) {
4456           ObjCMethodList &List =
4457             ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4458           unsigned CategCount = List.getBits();
4459           if (CategCount > 0) {
4460             // If the method is in a category we'll do lookup if there were at
4461             // least 2 category methods recorded, otherwise only one will do.
4462             if (CategCount > 1 ||
4463                 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4464               OverrideSearch overrides(*this, overridden);
4465               for (ObjCMethodDecl *SuperOverridden : overrides) {
4466                 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4467                     CurrentClass != SuperOverridden->getClassInterface()) {
4468                   CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
4469                   hasOverriddenMethodsInBaseOrProtocol = true;
4470                   overridden->setOverriding(true);
4471                   break;
4472                 }
4473               }
4474             }
4475           }
4476         }
4477       }
4478     }
4479 
4480     // Propagate down the 'related result type' bit from overridden methods.
4481     if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4482       ObjCMethod->setRelatedResultType();
4483 
4484     // Then merge the declarations.
4485     mergeObjCMethodDecls(ObjCMethod, overridden);
4486 
4487     if (ObjCMethod->isImplicit() && overridden->isImplicit())
4488       continue; // Conflicting properties are detected elsewhere.
4489 
4490     // Check for overriding methods
4491     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4492         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4493       CheckConflictingOverridingMethod(ObjCMethod, overridden,
4494               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4495 
4496     if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4497         isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4498         !overridden->isImplicit() /* not meant for properties */) {
4499       ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4500                                           E = ObjCMethod->param_end();
4501       ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4502                                      PrevE = overridden->param_end();
4503       for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4504         assert(PrevI != overridden->param_end() && "Param mismatch");
4505         QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4506         QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4507         // If type of argument of method in this class does not match its
4508         // respective argument type in the super class method, issue warning;
4509         if (!Context.typesAreCompatible(T1, T2)) {
4510           Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4511             << T1 << T2;
4512           Diag(overridden->getLocation(), diag::note_previous_declaration);
4513           break;
4514         }
4515       }
4516     }
4517   }
4518 
4519   ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4520 }
4521 
4522 /// Merge type nullability from for a redeclaration of the same entity,
4523 /// producing the updated type of the redeclared entity.
4524 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4525                                               QualType type,
4526                                               bool usesCSKeyword,
4527                                               SourceLocation prevLoc,
4528                                               QualType prevType,
4529                                               bool prevUsesCSKeyword) {
4530   // Determine the nullability of both types.
4531   auto nullability = type->getNullability(S.Context);
4532   auto prevNullability = prevType->getNullability(S.Context);
4533 
4534   // Easy case: both have nullability.
4535   if (nullability.hasValue() == prevNullability.hasValue()) {
4536     // Neither has nullability; continue.
4537     if (!nullability)
4538       return type;
4539 
4540     // The nullabilities are equivalent; do nothing.
4541     if (*nullability == *prevNullability)
4542       return type;
4543 
4544     // Complain about mismatched nullability.
4545     S.Diag(loc, diag::err_nullability_conflicting)
4546       << DiagNullabilityKind(*nullability, usesCSKeyword)
4547       << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4548     return type;
4549   }
4550 
4551   // If it's the redeclaration that has nullability, don't change anything.
4552   if (nullability)
4553     return type;
4554 
4555   // Otherwise, provide the result with the same nullability.
4556   return S.Context.getAttributedType(
4557            AttributedType::getNullabilityAttrKind(*prevNullability),
4558            type, type);
4559 }
4560 
4561 /// Merge information from the declaration of a method in the \@interface
4562 /// (or a category/extension) into the corresponding method in the
4563 /// @implementation (for a class or category).
4564 static void mergeInterfaceMethodToImpl(Sema &S,
4565                                        ObjCMethodDecl *method,
4566                                        ObjCMethodDecl *prevMethod) {
4567   // Merge the objc_requires_super attribute.
4568   if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4569       !method->hasAttr<ObjCRequiresSuperAttr>()) {
4570     // merge the attribute into implementation.
4571     method->addAttr(
4572       ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4573                                             method->getLocation()));
4574   }
4575 
4576   // Merge nullability of the result type.
4577   QualType newReturnType
4578     = mergeTypeNullabilityForRedecl(
4579         S, method->getReturnTypeSourceRange().getBegin(),
4580         method->getReturnType(),
4581         method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4582         prevMethod->getReturnTypeSourceRange().getBegin(),
4583         prevMethod->getReturnType(),
4584         prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4585   method->setReturnType(newReturnType);
4586 
4587   // Handle each of the parameters.
4588   unsigned numParams = method->param_size();
4589   unsigned numPrevParams = prevMethod->param_size();
4590   for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4591     ParmVarDecl *param = method->param_begin()[i];
4592     ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4593 
4594     // Merge nullability.
4595     QualType newParamType
4596       = mergeTypeNullabilityForRedecl(
4597           S, param->getLocation(), param->getType(),
4598           param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4599           prevParam->getLocation(), prevParam->getType(),
4600           prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4601     param->setType(newParamType);
4602   }
4603 }
4604 
4605 /// Verify that the method parameters/return value have types that are supported
4606 /// by the x86 target.
4607 static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4608                                           const ObjCMethodDecl *Method) {
4609   assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4610              llvm::Triple::x86 &&
4611          "x86-specific check invoked for a different target");
4612   SourceLocation Loc;
4613   QualType T;
4614   for (const ParmVarDecl *P : Method->parameters()) {
4615     if (P->getType()->isVectorType()) {
4616       Loc = P->getBeginLoc();
4617       T = P->getType();
4618       break;
4619     }
4620   }
4621   if (Loc.isInvalid()) {
4622     if (Method->getReturnType()->isVectorType()) {
4623       Loc = Method->getReturnTypeSourceRange().getBegin();
4624       T = Method->getReturnType();
4625     } else
4626       return;
4627   }
4628 
4629   // Vector parameters/return values are not supported by objc_msgSend on x86 in
4630   // iOS < 9 and macOS < 10.11.
4631   const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4632   VersionTuple AcceptedInVersion;
4633   if (Triple.getOS() == llvm::Triple::IOS)
4634     AcceptedInVersion = VersionTuple(/*Major=*/9);
4635   else if (Triple.isMacOSX())
4636     AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4637   else
4638     return;
4639   if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
4640       AcceptedInVersion)
4641     return;
4642   SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4643       << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4644                                                        : /*parameter*/ 0)
4645       << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4646 }
4647 
4648 static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4649   if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
4650       CD->hasAttr<ObjCDirectMembersAttr>()) {
4651     Method->addAttr(
4652         ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4653   }
4654 }
4655 
4656 static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl,
4657                                          ObjCMethodDecl *Method,
4658                                          ObjCImplDecl *ImpDecl = nullptr) {
4659   auto Sel = Method->getSelector();
4660   bool isInstance = Method->isInstanceMethod();
4661   bool diagnosed = false;
4662 
4663   auto diagClash = [&](const ObjCMethodDecl *IMD) {
4664     if (diagnosed || IMD->isImplicit())
4665       return;
4666     if (Method->isDirectMethod() || IMD->isDirectMethod()) {
4667       S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
4668           << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod()
4669           << Method->getDeclName();
4670       S.Diag(IMD->getLocation(), diag::note_previous_declaration);
4671       diagnosed = true;
4672     }
4673   };
4674 
4675   // Look for any other declaration of this method anywhere we can see in this
4676   // compilation unit.
4677   //
4678   // We do not use IDecl->lookupMethod() because we have specific needs:
4679   //
4680   // - we absolutely do not need to walk protocols, because
4681   //   diag::err_objc_direct_on_protocol has already been emitted
4682   //   during parsing if there's a conflict,
4683   //
4684   // - when we do not find a match in a given @interface container,
4685   //   we need to attempt looking it up in the @implementation block if the
4686   //   translation unit sees it to find more clashes.
4687 
4688   if (auto *IMD = IDecl->getMethod(Sel, isInstance))
4689     diagClash(IMD);
4690   else if (auto *Impl = IDecl->getImplementation())
4691     if (Impl != ImpDecl)
4692       if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
4693         diagClash(IMD);
4694 
4695   for (const auto *Cat : IDecl->visible_categories())
4696     if (auto *IMD = Cat->getMethod(Sel, isInstance))
4697       diagClash(IMD);
4698     else if (auto CatImpl = Cat->getImplementation())
4699       if (CatImpl != ImpDecl)
4700         if (auto *IMD = Cat->getMethod(Sel, isInstance))
4701           diagClash(IMD);
4702 }
4703 
4704 Decl *Sema::ActOnMethodDeclaration(
4705     Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4706     tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4707     ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4708     // optional arguments. The number of types/arguments is obtained
4709     // from the Sel.getNumArgs().
4710     ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4711     unsigned CNumArgs, // c-style args
4712     const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4713     bool isVariadic, bool MethodDefinition) {
4714   // Make sure we can establish a context for the method.
4715   if (!CurContext->isObjCContainer()) {
4716     Diag(MethodLoc, diag::err_missing_method_context);
4717     return nullptr;
4718   }
4719 
4720   Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
4721   QualType resultDeclType;
4722 
4723   bool HasRelatedResultType = false;
4724   TypeSourceInfo *ReturnTInfo = nullptr;
4725   if (ReturnType) {
4726     resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4727 
4728     if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4729       return nullptr;
4730 
4731     QualType bareResultType = resultDeclType;
4732     (void)AttributedType::stripOuterNullability(bareResultType);
4733     HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4734   } else { // get the type for "id".
4735     resultDeclType = Context.getObjCIdType();
4736     Diag(MethodLoc, diag::warn_missing_method_return_type)
4737       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4738   }
4739 
4740   ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4741       Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4742       MethodType == tok::minus, isVariadic,
4743       /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4744       /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4745       MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4746                                            : ObjCMethodDecl::Required,
4747       HasRelatedResultType);
4748 
4749   SmallVector<ParmVarDecl*, 16> Params;
4750 
4751   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4752     QualType ArgType;
4753     TypeSourceInfo *DI;
4754 
4755     if (!ArgInfo[i].Type) {
4756       ArgType = Context.getObjCIdType();
4757       DI = nullptr;
4758     } else {
4759       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4760     }
4761 
4762     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4763                    LookupOrdinaryName, forRedeclarationInCurContext());
4764     LookupName(R, S);
4765     if (R.isSingleResult()) {
4766       NamedDecl *PrevDecl = R.getFoundDecl();
4767       if (S->isDeclScope(PrevDecl)) {
4768         Diag(ArgInfo[i].NameLoc,
4769              (MethodDefinition ? diag::warn_method_param_redefinition
4770                                : diag::warn_method_param_declaration))
4771           << ArgInfo[i].Name;
4772         Diag(PrevDecl->getLocation(),
4773              diag::note_previous_declaration);
4774       }
4775     }
4776 
4777     SourceLocation StartLoc = DI
4778       ? DI->getTypeLoc().getBeginLoc()
4779       : ArgInfo[i].NameLoc;
4780 
4781     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4782                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
4783                                         ArgType, DI, SC_None);
4784 
4785     Param->setObjCMethodScopeInfo(i);
4786 
4787     Param->setObjCDeclQualifier(
4788       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4789 
4790     // Apply the attributes to the parameter.
4791     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4792     AddPragmaAttributes(TUScope, Param);
4793 
4794     if (Param->hasAttr<BlocksAttr>()) {
4795       Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4796       Param->setInvalidDecl();
4797     }
4798     S->AddDecl(Param);
4799     IdResolver.AddDecl(Param);
4800 
4801     Params.push_back(Param);
4802   }
4803 
4804   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4805     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4806     QualType ArgType = Param->getType();
4807     if (ArgType.isNull())
4808       ArgType = Context.getObjCIdType();
4809     else
4810       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4811       ArgType = Context.getAdjustedParameterType(ArgType);
4812 
4813     Param->setDeclContext(ObjCMethod);
4814     Params.push_back(Param);
4815   }
4816 
4817   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4818   ObjCMethod->setObjCDeclQualifier(
4819     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4820 
4821   ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4822   AddPragmaAttributes(TUScope, ObjCMethod);
4823 
4824   // Add the method now.
4825   const ObjCMethodDecl *PrevMethod = nullptr;
4826   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4827     if (MethodType == tok::minus) {
4828       PrevMethod = ImpDecl->getInstanceMethod(Sel);
4829       ImpDecl->addInstanceMethod(ObjCMethod);
4830     } else {
4831       PrevMethod = ImpDecl->getClassMethod(Sel);
4832       ImpDecl->addClassMethod(ObjCMethod);
4833     }
4834 
4835     // If this method overrides a previous @synthesize declaration,
4836     // register it with the property.  Linear search through all
4837     // properties here, because the autosynthesized stub hasn't been
4838     // made visible yet, so it can be overridden by a later
4839     // user-specified implementation.
4840     for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4841       if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4842         if (Setter->getSelector() == Sel &&
4843             Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4844           assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4845           PropertyImpl->setSetterMethodDecl(ObjCMethod);
4846         }
4847       if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4848         if (Getter->getSelector() == Sel &&
4849             Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4850           assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4851           PropertyImpl->setGetterMethodDecl(ObjCMethod);
4852           break;
4853         }
4854     }
4855 
4856     // A method is either tagged direct explicitly, or inherits it from its
4857     // canonical declaration.
4858     //
4859     // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4860     // because IDecl->lookupMethod() returns more possible matches than just
4861     // the canonical declaration.
4862     if (!ObjCMethod->isDirectMethod()) {
4863       const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4864       if (CanonicalMD->isDirectMethod()) {
4865         const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4866         ObjCMethod->addAttr(
4867             ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4868       }
4869     }
4870 
4871     // Merge information from the @interface declaration into the
4872     // @implementation.
4873     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4874       if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4875                                           ObjCMethod->isInstanceMethod())) {
4876         mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4877 
4878         // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4879         // in one of these places:
4880         //
4881         // (1) the canonical declaration in an @interface container paired
4882         //     with the ImplDecl,
4883         // (2) non canonical declarations in @interface not paired with the
4884         //     ImplDecl for the same Class,
4885         // (3) any superclass container.
4886         //
4887         // Direct methods only allow for canonical declarations in the matching
4888         // container (case 1).
4889         //
4890         // Direct methods overriding a superclass declaration (case 3) is
4891         // handled during overrides checks in CheckObjCMethodOverrides().
4892         //
4893         // We deal with same-class container mismatches (Case 2) here.
4894         if (IDecl == IMD->getClassInterface()) {
4895           auto diagContainerMismatch = [&] {
4896             int decl = 0, impl = 0;
4897 
4898             if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4899               decl = Cat->IsClassExtension() ? 1 : 2;
4900 
4901             if (isa<ObjCCategoryImplDecl>(ImpDecl))
4902               impl = 1 + (decl != 0);
4903 
4904             Diag(ObjCMethod->getLocation(),
4905                  diag::err_objc_direct_impl_decl_mismatch)
4906                 << decl << impl;
4907             Diag(IMD->getLocation(), diag::note_previous_declaration);
4908           };
4909 
4910           if (ObjCMethod->isDirectMethod()) {
4911             const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4912             if (ObjCMethod->getCanonicalDecl() != IMD) {
4913               diagContainerMismatch();
4914             } else if (!IMD->isDirectMethod()) {
4915               Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4916               Diag(IMD->getLocation(), diag::note_previous_declaration);
4917             }
4918           } else if (IMD->isDirectMethod()) {
4919             const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4920             if (ObjCMethod->getCanonicalDecl() != IMD) {
4921               diagContainerMismatch();
4922             } else {
4923               ObjCMethod->addAttr(
4924                   ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4925             }
4926           }
4927         }
4928 
4929         // Warn about defining -dealloc in a category.
4930         if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4931             ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4932           Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4933             << ObjCMethod->getDeclName();
4934         }
4935       } else {
4936         mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4937         checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl);
4938       }
4939 
4940       // Warn if a method declared in a protocol to which a category or
4941       // extension conforms is non-escaping and the implementation's method is
4942       // escaping.
4943       for (auto *C : IDecl->visible_categories())
4944         for (auto &P : C->protocols())
4945           if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4946                                           ObjCMethod->isInstanceMethod())) {
4947             assert(ObjCMethod->parameters().size() ==
4948                        IMD->parameters().size() &&
4949                    "Methods have different number of parameters");
4950             auto OI = IMD->param_begin(), OE = IMD->param_end();
4951             auto NI = ObjCMethod->param_begin();
4952             for (; OI != OE; ++OI, ++NI)
4953               diagnoseNoescape(*NI, *OI, C, P, *this);
4954           }
4955     }
4956   } else {
4957     if (!isa<ObjCProtocolDecl>(ClassDecl)) {
4958       mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4959 
4960       ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4961       if (!IDecl)
4962         IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
4963       // For valid code, we should always know the primary interface
4964       // declaration by now, however for invalid code we'll keep parsing
4965       // but we won't find the primary interface and IDecl will be nil.
4966       if (IDecl)
4967         checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod);
4968     }
4969 
4970     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4971   }
4972 
4973   if (PrevMethod) {
4974     // You can never have two method definitions with the same name.
4975     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4976       << ObjCMethod->getDeclName();
4977     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4978     ObjCMethod->setInvalidDecl();
4979     return ObjCMethod;
4980   }
4981 
4982   // If this Objective-C method does not have a related result type, but we
4983   // are allowed to infer related result types, try to do so based on the
4984   // method family.
4985   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4986   if (!CurrentClass) {
4987     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4988       CurrentClass = Cat->getClassInterface();
4989     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4990       CurrentClass = Impl->getClassInterface();
4991     else if (ObjCCategoryImplDecl *CatImpl
4992                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4993       CurrentClass = CatImpl->getClassInterface();
4994   }
4995 
4996   ResultTypeCompatibilityKind RTC
4997     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
4998 
4999   CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
5000 
5001   bool ARCError = false;
5002   if (getLangOpts().ObjCAutoRefCount)
5003     ARCError = CheckARCMethodDecl(ObjCMethod);
5004 
5005   // Infer the related result type when possible.
5006   if (!ARCError && RTC == Sema::RTC_Compatible &&
5007       !ObjCMethod->hasRelatedResultType() &&
5008       LangOpts.ObjCInferRelatedResultType) {
5009     bool InferRelatedResultType = false;
5010     switch (ObjCMethod->getMethodFamily()) {
5011     case OMF_None:
5012     case OMF_copy:
5013     case OMF_dealloc:
5014     case OMF_finalize:
5015     case OMF_mutableCopy:
5016     case OMF_release:
5017     case OMF_retainCount:
5018     case OMF_initialize:
5019     case OMF_performSelector:
5020       break;
5021 
5022     case OMF_alloc:
5023     case OMF_new:
5024         InferRelatedResultType = ObjCMethod->isClassMethod();
5025       break;
5026 
5027     case OMF_init:
5028     case OMF_autorelease:
5029     case OMF_retain:
5030     case OMF_self:
5031       InferRelatedResultType = ObjCMethod->isInstanceMethod();
5032       break;
5033     }
5034 
5035     if (InferRelatedResultType &&
5036         !ObjCMethod->getReturnType()->isObjCIndependentClassType())
5037       ObjCMethod->setRelatedResultType();
5038   }
5039 
5040   if (MethodDefinition &&
5041       Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5042     checkObjCMethodX86VectorTypes(*this, ObjCMethod);
5043 
5044   // + load method cannot have availability attributes. It get called on
5045   // startup, so it has to have the availability of the deployment target.
5046   if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
5047     if (ObjCMethod->isClassMethod() &&
5048         ObjCMethod->getSelector().getAsString() == "load") {
5049       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
5050           << 0;
5051       ObjCMethod->dropAttr<AvailabilityAttr>();
5052     }
5053   }
5054 
5055   // Insert the invisible arguments, self and _cmd!
5056   ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
5057 
5058   ActOnDocumentableDecl(ObjCMethod);
5059 
5060   return ObjCMethod;
5061 }
5062 
5063 bool Sema::CheckObjCDeclScope(Decl *D) {
5064   // Following is also an error. But it is caused by a missing @end
5065   // and diagnostic is issued elsewhere.
5066   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
5067     return false;
5068 
5069   // If we switched context to translation unit while we are still lexically in
5070   // an objc container, it means the parser missed emitting an error.
5071   if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
5072     return false;
5073 
5074   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
5075   D->setInvalidDecl();
5076 
5077   return true;
5078 }
5079 
5080 /// Called whenever \@defs(ClassName) is encountered in the source.  Inserts the
5081 /// instance variables of ClassName into Decls.
5082 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
5083                      IdentifierInfo *ClassName,
5084                      SmallVectorImpl<Decl*> &Decls) {
5085   // Check that ClassName is a valid class
5086   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
5087   if (!Class) {
5088     Diag(DeclStart, diag::err_undef_interface) << ClassName;
5089     return;
5090   }
5091   if (LangOpts.ObjCRuntime.isNonFragile()) {
5092     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
5093     return;
5094   }
5095 
5096   // Collect the instance variables
5097   SmallVector<const ObjCIvarDecl*, 32> Ivars;
5098   Context.DeepCollectObjCIvars(Class, true, Ivars);
5099   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
5100   for (unsigned i = 0; i < Ivars.size(); i++) {
5101     const FieldDecl* ID = Ivars[i];
5102     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
5103     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
5104                                            /*FIXME: StartL=*/ID->getLocation(),
5105                                            ID->getLocation(),
5106                                            ID->getIdentifier(), ID->getType(),
5107                                            ID->getBitWidth());
5108     Decls.push_back(FD);
5109   }
5110 
5111   // Introduce all of these fields into the appropriate scope.
5112   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
5113        D != Decls.end(); ++D) {
5114     FieldDecl *FD = cast<FieldDecl>(*D);
5115     if (getLangOpts().CPlusPlus)
5116       PushOnScopeChains(FD, S);
5117     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
5118       Record->addDecl(FD);
5119   }
5120 }
5121 
5122 /// Build a type-check a new Objective-C exception variable declaration.
5123 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
5124                                       SourceLocation StartLoc,
5125                                       SourceLocation IdLoc,
5126                                       IdentifierInfo *Id,
5127                                       bool Invalid) {
5128   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5129   // duration shall not be qualified by an address-space qualifier."
5130   // Since all parameters have automatic store duration, they can not have
5131   // an address space.
5132   if (T.getAddressSpace() != LangAS::Default) {
5133     Diag(IdLoc, diag::err_arg_with_address_space);
5134     Invalid = true;
5135   }
5136 
5137   // An @catch parameter must be an unqualified object pointer type;
5138   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
5139   if (Invalid) {
5140     // Don't do any further checking.
5141   } else if (T->isDependentType()) {
5142     // Okay: we don't know what this type will instantiate to.
5143   } else if (T->isObjCQualifiedIdType()) {
5144     Invalid = true;
5145     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
5146   } else if (T->isObjCIdType()) {
5147     // Okay: we don't know what this type will instantiate to.
5148   } else if (!T->isObjCObjectPointerType()) {
5149     Invalid = true;
5150     Diag(IdLoc, diag::err_catch_param_not_objc_type);
5151   } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) {
5152     Invalid = true;
5153     Diag(IdLoc, diag::err_catch_param_not_objc_type);
5154   }
5155 
5156   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
5157                                  T, TInfo, SC_None);
5158   New->setExceptionVariable(true);
5159 
5160   // In ARC, infer 'retaining' for variables of retainable type.
5161   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
5162     Invalid = true;
5163 
5164   if (Invalid)
5165     New->setInvalidDecl();
5166   return New;
5167 }
5168 
5169 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
5170   const DeclSpec &DS = D.getDeclSpec();
5171 
5172   // We allow the "register" storage class on exception variables because
5173   // GCC did, but we drop it completely. Any other storage class is an error.
5174   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
5175     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
5176       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
5177   } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5178     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
5179       << DeclSpec::getSpecifierName(SCS);
5180   }
5181   if (DS.isInlineSpecified())
5182     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5183         << getLangOpts().CPlusPlus17;
5184   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
5185     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5186          diag::err_invalid_thread)
5187      << DeclSpec::getSpecifierName(TSCS);
5188   D.getMutableDeclSpec().ClearStorageClassSpecs();
5189 
5190   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5191 
5192   // Check that there are no default arguments inside the type of this
5193   // exception object (C++ only).
5194   if (getLangOpts().CPlusPlus)
5195     CheckExtraCXXDefaultArguments(D);
5196 
5197   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5198   QualType ExceptionType = TInfo->getType();
5199 
5200   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
5201                                         D.getSourceRange().getBegin(),
5202                                         D.getIdentifierLoc(),
5203                                         D.getIdentifier(),
5204                                         D.isInvalidType());
5205 
5206   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5207   if (D.getCXXScopeSpec().isSet()) {
5208     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
5209       << D.getCXXScopeSpec().getRange();
5210     New->setInvalidDecl();
5211   }
5212 
5213   // Add the parameter declaration into this scope.
5214   S->AddDecl(New);
5215   if (D.getIdentifier())
5216     IdResolver.AddDecl(New);
5217 
5218   ProcessDeclAttributes(S, New, D);
5219 
5220   if (New->hasAttr<BlocksAttr>())
5221     Diag(New->getLocation(), diag::err_block_on_nonlocal);
5222   return New;
5223 }
5224 
5225 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
5226 /// initialization.
5227 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
5228                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
5229   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
5230        Iv= Iv->getNextIvar()) {
5231     QualType QT = Context.getBaseElementType(Iv->getType());
5232     if (QT->isRecordType())
5233       Ivars.push_back(Iv);
5234   }
5235 }
5236 
5237 void Sema::DiagnoseUseOfUnimplementedSelectors() {
5238   // Load referenced selectors from the external source.
5239   if (ExternalSource) {
5240     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
5241     ExternalSource->ReadReferencedSelectors(Sels);
5242     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
5243       ReferencedSelectors[Sels[I].first] = Sels[I].second;
5244   }
5245 
5246   // Warning will be issued only when selector table is
5247   // generated (which means there is at lease one implementation
5248   // in the TU). This is to match gcc's behavior.
5249   if (ReferencedSelectors.empty() ||
5250       !Context.AnyObjCImplementation())
5251     return;
5252   for (auto &SelectorAndLocation : ReferencedSelectors) {
5253     Selector Sel = SelectorAndLocation.first;
5254     SourceLocation Loc = SelectorAndLocation.second;
5255     if (!LookupImplementedMethodInGlobalPool(Sel))
5256       Diag(Loc, diag::warn_unimplemented_selector) << Sel;
5257   }
5258 }
5259 
5260 ObjCIvarDecl *
5261 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
5262                                      const ObjCPropertyDecl *&PDecl) const {
5263   if (Method->isClassMethod())
5264     return nullptr;
5265   const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
5266   if (!IDecl)
5267     return nullptr;
5268   Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
5269                                /*shallowCategoryLookup=*/false,
5270                                /*followSuper=*/false);
5271   if (!Method || !Method->isPropertyAccessor())
5272     return nullptr;
5273   if ((PDecl = Method->findPropertyDecl()))
5274     if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5275       // property backing ivar must belong to property's class
5276       // or be a private ivar in class's implementation.
5277       // FIXME. fix the const-ness issue.
5278       IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5279                                                         IV->getIdentifier());
5280       return IV;
5281     }
5282   return nullptr;
5283 }
5284 
5285 namespace {
5286   /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
5287   /// accessor references the backing ivar.
5288   class UnusedBackingIvarChecker :
5289       public RecursiveASTVisitor<UnusedBackingIvarChecker> {
5290   public:
5291     Sema &S;
5292     const ObjCMethodDecl *Method;
5293     const ObjCIvarDecl *IvarD;
5294     bool AccessedIvar;
5295     bool InvokedSelfMethod;
5296 
5297     UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5298                              const ObjCIvarDecl *IvarD)
5299       : S(S), Method(Method), IvarD(IvarD),
5300         AccessedIvar(false), InvokedSelfMethod(false) {
5301       assert(IvarD);
5302     }
5303 
5304     bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5305       if (E->getDecl() == IvarD) {
5306         AccessedIvar = true;
5307         return false;
5308       }
5309       return true;
5310     }
5311 
5312     bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5313       if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5314           S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5315         InvokedSelfMethod = true;
5316       }
5317       return true;
5318     }
5319   };
5320 } // end anonymous namespace
5321 
5322 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5323                                           const ObjCImplementationDecl *ImplD) {
5324   if (S->hasUnrecoverableErrorOccurred())
5325     return;
5326 
5327   for (const auto *CurMethod : ImplD->instance_methods()) {
5328     unsigned DIAG = diag::warn_unused_property_backing_ivar;
5329     SourceLocation Loc = CurMethod->getLocation();
5330     if (Diags.isIgnored(DIAG, Loc))
5331       continue;
5332 
5333     const ObjCPropertyDecl *PDecl;
5334     const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5335     if (!IV)
5336       continue;
5337 
5338     if (CurMethod->isSynthesizedAccessorStub())
5339       continue;
5340 
5341     UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5342     Checker.TraverseStmt(CurMethod->getBody());
5343     if (Checker.AccessedIvar)
5344       continue;
5345 
5346     // Do not issue this warning if backing ivar is used somewhere and accessor
5347     // implementation makes a self call. This is to prevent false positive in
5348     // cases where the ivar is accessed by another method that the accessor
5349     // delegates to.
5350     if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5351       Diag(Loc, DIAG) << IV;
5352       Diag(PDecl->getLocation(), diag::note_property_declare);
5353     }
5354   }
5355 }
5356