xref: /freebsd/contrib/llvm-project/clang/lib/Sema/SemaDeclObjC.cpp (revision f7c32ed617858bcd22f8d1b03199099d50125721)
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 (!dyn_cast_or_null<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, SourceLocation ImpLoc,
2216                                 ObjCMethodDecl *method,
2217                                 bool &IncompleteImpl,
2218                                 unsigned DiagID,
2219                                 NamedDecl *NeededFor = nullptr) {
2220   // No point warning no definition of method which is 'unavailable'.
2221   if (method->getAvailability() == AR_Unavailable)
2222     return;
2223 
2224   // FIXME: For now ignore 'IncompleteImpl'.
2225   // Previously we grouped all unimplemented methods under a single
2226   // warning, but some users strongly voiced that they would prefer
2227   // separate warnings.  We will give that approach a try, as that
2228   // matches what we do with protocols.
2229   {
2230     const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2231     B << method;
2232     if (NeededFor)
2233       B << NeededFor;
2234   }
2235 
2236   // Issue a note to the original declaration.
2237   SourceLocation MethodLoc = method->getBeginLoc();
2238   if (MethodLoc.isValid())
2239     S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2240 }
2241 
2242 /// Determines if type B can be substituted for type A.  Returns true if we can
2243 /// guarantee that anything that the user will do to an object of type A can
2244 /// also be done to an object of type B.  This is trivially true if the two
2245 /// types are the same, or if B is a subclass of A.  It becomes more complex
2246 /// in cases where protocols are involved.
2247 ///
2248 /// Object types in Objective-C describe the minimum requirements for an
2249 /// object, rather than providing a complete description of a type.  For
2250 /// example, if A is a subclass of B, then B* may refer to an instance of A.
2251 /// The principle of substitutability means that we may use an instance of A
2252 /// anywhere that we may use an instance of B - it will implement all of the
2253 /// ivars of B and all of the methods of B.
2254 ///
2255 /// This substitutability is important when type checking methods, because
2256 /// the implementation may have stricter type definitions than the interface.
2257 /// The interface specifies minimum requirements, but the implementation may
2258 /// have more accurate ones.  For example, a method may privately accept
2259 /// instances of B, but only publish that it accepts instances of A.  Any
2260 /// object passed to it will be type checked against B, and so will implicitly
2261 /// by a valid A*.  Similarly, a method may return a subclass of the class that
2262 /// it is declared as returning.
2263 ///
2264 /// This is most important when considering subclassing.  A method in a
2265 /// subclass must accept any object as an argument that its superclass's
2266 /// implementation accepts.  It may, however, accept a more general type
2267 /// without breaking substitutability (i.e. you can still use the subclass
2268 /// anywhere that you can use the superclass, but not vice versa).  The
2269 /// converse requirement applies to return types: the return type for a
2270 /// subclass method must be a valid object of the kind that the superclass
2271 /// advertises, but it may be specified more accurately.  This avoids the need
2272 /// for explicit down-casting by callers.
2273 ///
2274 /// Note: This is a stricter requirement than for assignment.
2275 static bool isObjCTypeSubstitutable(ASTContext &Context,
2276                                     const ObjCObjectPointerType *A,
2277                                     const ObjCObjectPointerType *B,
2278                                     bool rejectId) {
2279   // Reject a protocol-unqualified id.
2280   if (rejectId && B->isObjCIdType()) return false;
2281 
2282   // If B is a qualified id, then A must also be a qualified id and it must
2283   // implement all of the protocols in B.  It may not be a qualified class.
2284   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2285   // stricter definition so it is not substitutable for id<A>.
2286   if (B->isObjCQualifiedIdType()) {
2287     return A->isObjCQualifiedIdType() &&
2288            Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2289   }
2290 
2291   /*
2292   // id is a special type that bypasses type checking completely.  We want a
2293   // warning when it is used in one place but not another.
2294   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2295 
2296 
2297   // If B is a qualified id, then A must also be a qualified id (which it isn't
2298   // if we've got this far)
2299   if (B->isObjCQualifiedIdType()) return false;
2300   */
2301 
2302   // Now we know that A and B are (potentially-qualified) class types.  The
2303   // normal rules for assignment apply.
2304   return Context.canAssignObjCInterfaces(A, B);
2305 }
2306 
2307 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2308   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2309 }
2310 
2311 /// Determine whether two set of Objective-C declaration qualifiers conflict.
2312 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2313                                   Decl::ObjCDeclQualifier y) {
2314   return (x & ~Decl::OBJC_TQ_CSNullability) !=
2315          (y & ~Decl::OBJC_TQ_CSNullability);
2316 }
2317 
2318 static bool CheckMethodOverrideReturn(Sema &S,
2319                                       ObjCMethodDecl *MethodImpl,
2320                                       ObjCMethodDecl *MethodDecl,
2321                                       bool IsProtocolMethodDecl,
2322                                       bool IsOverridingMode,
2323                                       bool Warn) {
2324   if (IsProtocolMethodDecl &&
2325       objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2326                             MethodImpl->getObjCDeclQualifier())) {
2327     if (Warn) {
2328       S.Diag(MethodImpl->getLocation(),
2329              (IsOverridingMode
2330                   ? diag::warn_conflicting_overriding_ret_type_modifiers
2331                   : diag::warn_conflicting_ret_type_modifiers))
2332           << MethodImpl->getDeclName()
2333           << MethodImpl->getReturnTypeSourceRange();
2334       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2335           << MethodDecl->getReturnTypeSourceRange();
2336     }
2337     else
2338       return false;
2339   }
2340   if (Warn && IsOverridingMode &&
2341       !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2342       !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2343                                                  MethodDecl->getReturnType(),
2344                                                  false)) {
2345     auto nullabilityMethodImpl =
2346       *MethodImpl->getReturnType()->getNullability(S.Context);
2347     auto nullabilityMethodDecl =
2348       *MethodDecl->getReturnType()->getNullability(S.Context);
2349       S.Diag(MethodImpl->getLocation(),
2350              diag::warn_conflicting_nullability_attr_overriding_ret_types)
2351         << DiagNullabilityKind(
2352              nullabilityMethodImpl,
2353              ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2354               != 0))
2355         << DiagNullabilityKind(
2356              nullabilityMethodDecl,
2357              ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2358                 != 0));
2359       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2360   }
2361 
2362   if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2363                                        MethodDecl->getReturnType()))
2364     return true;
2365   if (!Warn)
2366     return false;
2367 
2368   unsigned DiagID =
2369     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2370                      : diag::warn_conflicting_ret_types;
2371 
2372   // Mismatches between ObjC pointers go into a different warning
2373   // category, and sometimes they're even completely explicitly allowed.
2374   if (const ObjCObjectPointerType *ImplPtrTy =
2375           MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2376     if (const ObjCObjectPointerType *IfacePtrTy =
2377             MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2378       // Allow non-matching return types as long as they don't violate
2379       // the principle of substitutability.  Specifically, we permit
2380       // return types that are subclasses of the declared return type,
2381       // or that are more-qualified versions of the declared type.
2382       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2383         return false;
2384 
2385       DiagID =
2386         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2387                          : diag::warn_non_covariant_ret_types;
2388     }
2389   }
2390 
2391   S.Diag(MethodImpl->getLocation(), DiagID)
2392       << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2393       << MethodImpl->getReturnType()
2394       << MethodImpl->getReturnTypeSourceRange();
2395   S.Diag(MethodDecl->getLocation(), IsOverridingMode
2396                                         ? diag::note_previous_declaration
2397                                         : diag::note_previous_definition)
2398       << MethodDecl->getReturnTypeSourceRange();
2399   return false;
2400 }
2401 
2402 static bool CheckMethodOverrideParam(Sema &S,
2403                                      ObjCMethodDecl *MethodImpl,
2404                                      ObjCMethodDecl *MethodDecl,
2405                                      ParmVarDecl *ImplVar,
2406                                      ParmVarDecl *IfaceVar,
2407                                      bool IsProtocolMethodDecl,
2408                                      bool IsOverridingMode,
2409                                      bool Warn) {
2410   if (IsProtocolMethodDecl &&
2411       objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2412                             IfaceVar->getObjCDeclQualifier())) {
2413     if (Warn) {
2414       if (IsOverridingMode)
2415         S.Diag(ImplVar->getLocation(),
2416                diag::warn_conflicting_overriding_param_modifiers)
2417             << getTypeRange(ImplVar->getTypeSourceInfo())
2418             << MethodImpl->getDeclName();
2419       else S.Diag(ImplVar->getLocation(),
2420              diag::warn_conflicting_param_modifiers)
2421           << getTypeRange(ImplVar->getTypeSourceInfo())
2422           << MethodImpl->getDeclName();
2423       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2424           << getTypeRange(IfaceVar->getTypeSourceInfo());
2425     }
2426     else
2427       return false;
2428   }
2429 
2430   QualType ImplTy = ImplVar->getType();
2431   QualType IfaceTy = IfaceVar->getType();
2432   if (Warn && IsOverridingMode &&
2433       !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2434       !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2435     S.Diag(ImplVar->getLocation(),
2436            diag::warn_conflicting_nullability_attr_overriding_param_types)
2437       << DiagNullabilityKind(
2438            *ImplTy->getNullability(S.Context),
2439            ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2440             != 0))
2441       << DiagNullabilityKind(
2442            *IfaceTy->getNullability(S.Context),
2443            ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2444             != 0));
2445     S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2446   }
2447   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2448     return true;
2449 
2450   if (!Warn)
2451     return false;
2452   unsigned DiagID =
2453     IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2454                      : diag::warn_conflicting_param_types;
2455 
2456   // Mismatches between ObjC pointers go into a different warning
2457   // category, and sometimes they're even completely explicitly allowed..
2458   if (const ObjCObjectPointerType *ImplPtrTy =
2459         ImplTy->getAs<ObjCObjectPointerType>()) {
2460     if (const ObjCObjectPointerType *IfacePtrTy =
2461           IfaceTy->getAs<ObjCObjectPointerType>()) {
2462       // Allow non-matching argument types as long as they don't
2463       // violate the principle of substitutability.  Specifically, the
2464       // implementation must accept any objects that the superclass
2465       // accepts, however it may also accept others.
2466       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2467         return false;
2468 
2469       DiagID =
2470       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2471                        : diag::warn_non_contravariant_param_types;
2472     }
2473   }
2474 
2475   S.Diag(ImplVar->getLocation(), DiagID)
2476     << getTypeRange(ImplVar->getTypeSourceInfo())
2477     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2478   S.Diag(IfaceVar->getLocation(),
2479          (IsOverridingMode ? diag::note_previous_declaration
2480                            : diag::note_previous_definition))
2481     << getTypeRange(IfaceVar->getTypeSourceInfo());
2482   return false;
2483 }
2484 
2485 /// In ARC, check whether the conventional meanings of the two methods
2486 /// match.  If they don't, it's a hard error.
2487 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2488                                       ObjCMethodDecl *decl) {
2489   ObjCMethodFamily implFamily = impl->getMethodFamily();
2490   ObjCMethodFamily declFamily = decl->getMethodFamily();
2491   if (implFamily == declFamily) return false;
2492 
2493   // Since conventions are sorted by selector, the only possibility is
2494   // that the types differ enough to cause one selector or the other
2495   // to fall out of the family.
2496   assert(implFamily == OMF_None || declFamily == OMF_None);
2497 
2498   // No further diagnostics required on invalid declarations.
2499   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2500 
2501   const ObjCMethodDecl *unmatched = impl;
2502   ObjCMethodFamily family = declFamily;
2503   unsigned errorID = diag::err_arc_lost_method_convention;
2504   unsigned noteID = diag::note_arc_lost_method_convention;
2505   if (declFamily == OMF_None) {
2506     unmatched = decl;
2507     family = implFamily;
2508     errorID = diag::err_arc_gained_method_convention;
2509     noteID = diag::note_arc_gained_method_convention;
2510   }
2511 
2512   // Indexes into a %select clause in the diagnostic.
2513   enum FamilySelector {
2514     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2515   };
2516   FamilySelector familySelector = FamilySelector();
2517 
2518   switch (family) {
2519   case OMF_None: llvm_unreachable("logic error, no method convention");
2520   case OMF_retain:
2521   case OMF_release:
2522   case OMF_autorelease:
2523   case OMF_dealloc:
2524   case OMF_finalize:
2525   case OMF_retainCount:
2526   case OMF_self:
2527   case OMF_initialize:
2528   case OMF_performSelector:
2529     // Mismatches for these methods don't change ownership
2530     // conventions, so we don't care.
2531     return false;
2532 
2533   case OMF_init: familySelector = F_init; break;
2534   case OMF_alloc: familySelector = F_alloc; break;
2535   case OMF_copy: familySelector = F_copy; break;
2536   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2537   case OMF_new: familySelector = F_new; break;
2538   }
2539 
2540   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2541   ReasonSelector reasonSelector;
2542 
2543   // The only reason these methods don't fall within their families is
2544   // due to unusual result types.
2545   if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2546     reasonSelector = R_UnrelatedReturn;
2547   } else {
2548     reasonSelector = R_NonObjectReturn;
2549   }
2550 
2551   S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2552   S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2553 
2554   return true;
2555 }
2556 
2557 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2558                                        ObjCMethodDecl *MethodDecl,
2559                                        bool IsProtocolMethodDecl) {
2560   if (getLangOpts().ObjCAutoRefCount &&
2561       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2562     return;
2563 
2564   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2565                             IsProtocolMethodDecl, false,
2566                             true);
2567 
2568   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2569        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2570        EF = MethodDecl->param_end();
2571        IM != EM && IF != EF; ++IM, ++IF) {
2572     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2573                              IsProtocolMethodDecl, false, true);
2574   }
2575 
2576   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2577     Diag(ImpMethodDecl->getLocation(),
2578          diag::warn_conflicting_variadic);
2579     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2580   }
2581 }
2582 
2583 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2584                                        ObjCMethodDecl *Overridden,
2585                                        bool IsProtocolMethodDecl) {
2586 
2587   CheckMethodOverrideReturn(*this, Method, Overridden,
2588                             IsProtocolMethodDecl, true,
2589                             true);
2590 
2591   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2592        IF = Overridden->param_begin(), EM = Method->param_end(),
2593        EF = Overridden->param_end();
2594        IM != EM && IF != EF; ++IM, ++IF) {
2595     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2596                              IsProtocolMethodDecl, true, true);
2597   }
2598 
2599   if (Method->isVariadic() != Overridden->isVariadic()) {
2600     Diag(Method->getLocation(),
2601          diag::warn_conflicting_overriding_variadic);
2602     Diag(Overridden->getLocation(), diag::note_previous_declaration);
2603   }
2604 }
2605 
2606 /// WarnExactTypedMethods - This routine issues a warning if method
2607 /// implementation declaration matches exactly that of its declaration.
2608 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2609                                  ObjCMethodDecl *MethodDecl,
2610                                  bool IsProtocolMethodDecl) {
2611   // don't issue warning when protocol method is optional because primary
2612   // class is not required to implement it and it is safe for protocol
2613   // to implement it.
2614   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2615     return;
2616   // don't issue warning when primary class's method is
2617   // depecated/unavailable.
2618   if (MethodDecl->hasAttr<UnavailableAttr>() ||
2619       MethodDecl->hasAttr<DeprecatedAttr>())
2620     return;
2621 
2622   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2623                                       IsProtocolMethodDecl, false, false);
2624   if (match)
2625     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2626          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2627          EF = MethodDecl->param_end();
2628          IM != EM && IF != EF; ++IM, ++IF) {
2629       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2630                                        *IM, *IF,
2631                                        IsProtocolMethodDecl, false, false);
2632       if (!match)
2633         break;
2634     }
2635   if (match)
2636     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2637   if (match)
2638     match = !(MethodDecl->isClassMethod() &&
2639               MethodDecl->getSelector() == GetNullarySelector("load", Context));
2640 
2641   if (match) {
2642     Diag(ImpMethodDecl->getLocation(),
2643          diag::warn_category_method_impl_match);
2644     Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2645       << MethodDecl->getDeclName();
2646   }
2647 }
2648 
2649 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2650 /// improve the efficiency of selector lookups and type checking by associating
2651 /// with each protocol / interface / category the flattened instance tables. If
2652 /// we used an immutable set to keep the table then it wouldn't add significant
2653 /// memory cost and it would be handy for lookups.
2654 
2655 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2656 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2657 
2658 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2659                                            ProtocolNameSet &PNS) {
2660   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2661     PNS.insert(PDecl->getIdentifier());
2662   for (const auto *PI : PDecl->protocols())
2663     findProtocolsWithExplicitImpls(PI, PNS);
2664 }
2665 
2666 /// Recursively populates a set with all conformed protocols in a class
2667 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2668 /// attribute.
2669 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2670                                            ProtocolNameSet &PNS) {
2671   if (!Super)
2672     return;
2673 
2674   for (const auto *I : Super->all_referenced_protocols())
2675     findProtocolsWithExplicitImpls(I, PNS);
2676 
2677   findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2678 }
2679 
2680 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
2681 /// Declared in protocol, and those referenced by it.
2682 static void CheckProtocolMethodDefs(Sema &S,
2683                                     SourceLocation ImpLoc,
2684                                     ObjCProtocolDecl *PDecl,
2685                                     bool& IncompleteImpl,
2686                                     const Sema::SelectorSet &InsMap,
2687                                     const Sema::SelectorSet &ClsMap,
2688                                     ObjCContainerDecl *CDecl,
2689                                     LazyProtocolNameSet &ProtocolsExplictImpl) {
2690   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2691   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2692                                : dyn_cast<ObjCInterfaceDecl>(CDecl);
2693   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2694 
2695   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2696   ObjCInterfaceDecl *NSIDecl = nullptr;
2697 
2698   // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2699   // then we should check if any class in the super class hierarchy also
2700   // conforms to this protocol, either directly or via protocol inheritance.
2701   // If so, we can skip checking this protocol completely because we
2702   // know that a parent class already satisfies this protocol.
2703   //
2704   // Note: we could generalize this logic for all protocols, and merely
2705   // add the limit on looking at the super class chain for just
2706   // specially marked protocols.  This may be a good optimization.  This
2707   // change is restricted to 'objc_protocol_requires_explicit_implementation'
2708   // protocols for now for controlled evaluation.
2709   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2710     if (!ProtocolsExplictImpl) {
2711       ProtocolsExplictImpl.reset(new ProtocolNameSet);
2712       findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2713     }
2714     if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2715         ProtocolsExplictImpl->end())
2716       return;
2717 
2718     // If no super class conforms to the protocol, we should not search
2719     // for methods in the super class to implicitly satisfy the protocol.
2720     Super = nullptr;
2721   }
2722 
2723   if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2724     // check to see if class implements forwardInvocation method and objects
2725     // of this class are derived from 'NSProxy' so that to forward requests
2726     // from one object to another.
2727     // Under such conditions, which means that every method possible is
2728     // implemented in the class, we should not issue "Method definition not
2729     // found" warnings.
2730     // FIXME: Use a general GetUnarySelector method for this.
2731     IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2732     Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2733     if (InsMap.count(fISelector))
2734       // Is IDecl derived from 'NSProxy'? If so, no instance methods
2735       // need be implemented in the implementation.
2736       NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2737   }
2738 
2739   // If this is a forward protocol declaration, get its definition.
2740   if (!PDecl->isThisDeclarationADefinition() &&
2741       PDecl->getDefinition())
2742     PDecl = PDecl->getDefinition();
2743 
2744   // If a method lookup fails locally we still need to look and see if
2745   // the method was implemented by a base class or an inherited
2746   // protocol. This lookup is slow, but occurs rarely in correct code
2747   // and otherwise would terminate in a warning.
2748 
2749   // check unimplemented instance methods.
2750   if (!NSIDecl)
2751     for (auto *method : PDecl->instance_methods()) {
2752       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2753           !method->isPropertyAccessor() &&
2754           !InsMap.count(method->getSelector()) &&
2755           (!Super || !Super->lookupMethod(method->getSelector(),
2756                                           true /* instance */,
2757                                           false /* shallowCategory */,
2758                                           true /* followsSuper */,
2759                                           nullptr /* category */))) {
2760             // If a method is not implemented in the category implementation but
2761             // has been declared in its primary class, superclass,
2762             // or in one of their protocols, no need to issue the warning.
2763             // This is because method will be implemented in the primary class
2764             // or one of its super class implementation.
2765 
2766             // Ugly, but necessary. Method declared in protocol might have
2767             // have been synthesized due to a property declared in the class which
2768             // uses the protocol.
2769             if (ObjCMethodDecl *MethodInClass =
2770                   IDecl->lookupMethod(method->getSelector(),
2771                                       true /* instance */,
2772                                       true /* shallowCategoryLookup */,
2773                                       false /* followSuper */))
2774               if (C || MethodInClass->isPropertyAccessor())
2775                 continue;
2776             unsigned DIAG = diag::warn_unimplemented_protocol_method;
2777             if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2778               WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
2779                                   PDecl);
2780             }
2781           }
2782     }
2783   // check unimplemented class methods
2784   for (auto *method : PDecl->class_methods()) {
2785     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2786         !ClsMap.count(method->getSelector()) &&
2787         (!Super || !Super->lookupMethod(method->getSelector(),
2788                                         false /* class method */,
2789                                         false /* shallowCategoryLookup */,
2790                                         true  /* followSuper */,
2791                                         nullptr /* category */))) {
2792       // See above comment for instance method lookups.
2793       if (C && IDecl->lookupMethod(method->getSelector(),
2794                                    false /* class */,
2795                                    true /* shallowCategoryLookup */,
2796                                    false /* followSuper */))
2797         continue;
2798 
2799       unsigned DIAG = diag::warn_unimplemented_protocol_method;
2800       if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2801         WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
2802       }
2803     }
2804   }
2805   // Check on this protocols's referenced protocols, recursively.
2806   for (auto *PI : PDecl->protocols())
2807     CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
2808                             CDecl, ProtocolsExplictImpl);
2809 }
2810 
2811 /// MatchAllMethodDeclarations - Check methods declared in interface
2812 /// or protocol against those declared in their implementations.
2813 ///
2814 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2815                                       const SelectorSet &ClsMap,
2816                                       SelectorSet &InsMapSeen,
2817                                       SelectorSet &ClsMapSeen,
2818                                       ObjCImplDecl* IMPDecl,
2819                                       ObjCContainerDecl* CDecl,
2820                                       bool &IncompleteImpl,
2821                                       bool ImmediateClass,
2822                                       bool WarnCategoryMethodImpl) {
2823   // Check and see if instance methods in class interface have been
2824   // implemented in the implementation class. If so, their types match.
2825   for (auto *I : CDecl->instance_methods()) {
2826     if (!InsMapSeen.insert(I->getSelector()).second)
2827       continue;
2828     if (!I->isPropertyAccessor() &&
2829         !InsMap.count(I->getSelector())) {
2830       if (ImmediateClass)
2831         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2832                             diag::warn_undef_method_impl);
2833       continue;
2834     } else {
2835       ObjCMethodDecl *ImpMethodDecl =
2836         IMPDecl->getInstanceMethod(I->getSelector());
2837       assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2838              "Expected to find the method through lookup as well");
2839       // ImpMethodDecl may be null as in a @dynamic property.
2840       if (ImpMethodDecl) {
2841         // Skip property accessor function stubs.
2842         if (ImpMethodDecl->isSynthesizedAccessorStub())
2843           continue;
2844         if (!WarnCategoryMethodImpl)
2845           WarnConflictingTypedMethods(ImpMethodDecl, I,
2846                                       isa<ObjCProtocolDecl>(CDecl));
2847         else if (!I->isPropertyAccessor())
2848           WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2849       }
2850     }
2851   }
2852 
2853   // Check and see if class methods in class interface have been
2854   // implemented in the implementation class. If so, their types match.
2855   for (auto *I : CDecl->class_methods()) {
2856     if (!ClsMapSeen.insert(I->getSelector()).second)
2857       continue;
2858     if (!I->isPropertyAccessor() &&
2859         !ClsMap.count(I->getSelector())) {
2860       if (ImmediateClass)
2861         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2862                             diag::warn_undef_method_impl);
2863     } else {
2864       ObjCMethodDecl *ImpMethodDecl =
2865         IMPDecl->getClassMethod(I->getSelector());
2866       assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2867              "Expected to find the method through lookup as well");
2868       // ImpMethodDecl may be null as in a @dynamic property.
2869       if (ImpMethodDecl) {
2870         // Skip property accessor function stubs.
2871         if (ImpMethodDecl->isSynthesizedAccessorStub())
2872           continue;
2873         if (!WarnCategoryMethodImpl)
2874           WarnConflictingTypedMethods(ImpMethodDecl, I,
2875                                       isa<ObjCProtocolDecl>(CDecl));
2876         else if (!I->isPropertyAccessor())
2877           WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2878       }
2879     }
2880   }
2881 
2882   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2883     // Also, check for methods declared in protocols inherited by
2884     // this protocol.
2885     for (auto *PI : PD->protocols())
2886       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2887                                  IMPDecl, PI, IncompleteImpl, false,
2888                                  WarnCategoryMethodImpl);
2889   }
2890 
2891   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2892     // when checking that methods in implementation match their declaration,
2893     // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2894     // extension; as well as those in categories.
2895     if (!WarnCategoryMethodImpl) {
2896       for (auto *Cat : I->visible_categories())
2897         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2898                                    IMPDecl, Cat, IncompleteImpl,
2899                                    ImmediateClass && Cat->IsClassExtension(),
2900                                    WarnCategoryMethodImpl);
2901     } else {
2902       // Also methods in class extensions need be looked at next.
2903       for (auto *Ext : I->visible_extensions())
2904         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2905                                    IMPDecl, Ext, IncompleteImpl, false,
2906                                    WarnCategoryMethodImpl);
2907     }
2908 
2909     // Check for any implementation of a methods declared in protocol.
2910     for (auto *PI : I->all_referenced_protocols())
2911       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2912                                  IMPDecl, PI, IncompleteImpl, false,
2913                                  WarnCategoryMethodImpl);
2914 
2915     // FIXME. For now, we are not checking for exact match of methods
2916     // in category implementation and its primary class's super class.
2917     if (!WarnCategoryMethodImpl && I->getSuperClass())
2918       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2919                                  IMPDecl,
2920                                  I->getSuperClass(), IncompleteImpl, false);
2921   }
2922 }
2923 
2924 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2925 /// category matches with those implemented in its primary class and
2926 /// warns each time an exact match is found.
2927 void Sema::CheckCategoryVsClassMethodMatches(
2928                                   ObjCCategoryImplDecl *CatIMPDecl) {
2929   // Get category's primary class.
2930   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2931   if (!CatDecl)
2932     return;
2933   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2934   if (!IDecl)
2935     return;
2936   ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2937   SelectorSet InsMap, ClsMap;
2938 
2939   for (const auto *I : CatIMPDecl->instance_methods()) {
2940     Selector Sel = I->getSelector();
2941     // When checking for methods implemented in the category, skip over
2942     // those declared in category class's super class. This is because
2943     // the super class must implement the method.
2944     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2945       continue;
2946     InsMap.insert(Sel);
2947   }
2948 
2949   for (const auto *I : CatIMPDecl->class_methods()) {
2950     Selector Sel = I->getSelector();
2951     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2952       continue;
2953     ClsMap.insert(Sel);
2954   }
2955   if (InsMap.empty() && ClsMap.empty())
2956     return;
2957 
2958   SelectorSet InsMapSeen, ClsMapSeen;
2959   bool IncompleteImpl = false;
2960   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2961                              CatIMPDecl, IDecl,
2962                              IncompleteImpl, false,
2963                              true /*WarnCategoryMethodImpl*/);
2964 }
2965 
2966 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2967                                      ObjCContainerDecl* CDecl,
2968                                      bool IncompleteImpl) {
2969   SelectorSet InsMap;
2970   // Check and see if instance methods in class interface have been
2971   // implemented in the implementation class.
2972   for (const auto *I : IMPDecl->instance_methods())
2973     InsMap.insert(I->getSelector());
2974 
2975   // Add the selectors for getters/setters of @dynamic properties.
2976   for (const auto *PImpl : IMPDecl->property_impls()) {
2977     // We only care about @dynamic implementations.
2978     if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2979       continue;
2980 
2981     const auto *P = PImpl->getPropertyDecl();
2982     if (!P) continue;
2983 
2984     InsMap.insert(P->getGetterName());
2985     if (!P->getSetterName().isNull())
2986       InsMap.insert(P->getSetterName());
2987   }
2988 
2989   // Check and see if properties declared in the interface have either 1)
2990   // an implementation or 2) there is a @synthesize/@dynamic implementation
2991   // of the property in the @implementation.
2992   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2993     bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2994                                 LangOpts.ObjCRuntime.isNonFragile() &&
2995                                 !IDecl->isObjCRequiresPropertyDefs();
2996     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2997   }
2998 
2999   // Diagnose null-resettable synthesized setters.
3000   diagnoseNullResettableSynthesizedSetters(IMPDecl);
3001 
3002   SelectorSet ClsMap;
3003   for (const auto *I : IMPDecl->class_methods())
3004     ClsMap.insert(I->getSelector());
3005 
3006   // Check for type conflict of methods declared in a class/protocol and
3007   // its implementation; if any.
3008   SelectorSet InsMapSeen, ClsMapSeen;
3009   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3010                              IMPDecl, CDecl,
3011                              IncompleteImpl, true);
3012 
3013   // check all methods implemented in category against those declared
3014   // in its primary class.
3015   if (ObjCCategoryImplDecl *CatDecl =
3016         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3017     CheckCategoryVsClassMethodMatches(CatDecl);
3018 
3019   // Check the protocol list for unimplemented methods in the @implementation
3020   // class.
3021   // Check and see if class methods in class interface have been
3022   // implemented in the implementation class.
3023 
3024   LazyProtocolNameSet ExplicitImplProtocols;
3025 
3026   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3027     for (auto *PI : I->all_referenced_protocols())
3028       CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
3029                               InsMap, ClsMap, I, ExplicitImplProtocols);
3030   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3031     // For extended class, unimplemented methods in its protocols will
3032     // be reported in the primary class.
3033     if (!C->IsClassExtension()) {
3034       for (auto *P : C->protocols())
3035         CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
3036                                 IncompleteImpl, InsMap, ClsMap, CDecl,
3037                                 ExplicitImplProtocols);
3038       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3039                                       /*SynthesizeProperties=*/false);
3040     }
3041   } else
3042     llvm_unreachable("invalid ObjCContainerDecl type.");
3043 }
3044 
3045 Sema::DeclGroupPtrTy
3046 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
3047                                    IdentifierInfo **IdentList,
3048                                    SourceLocation *IdentLocs,
3049                                    ArrayRef<ObjCTypeParamList *> TypeParamLists,
3050                                    unsigned NumElts) {
3051   SmallVector<Decl *, 8> DeclsInGroup;
3052   for (unsigned i = 0; i != NumElts; ++i) {
3053     // Check for another declaration kind with the same name.
3054     NamedDecl *PrevDecl
3055       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
3056                          LookupOrdinaryName, forRedeclarationInCurContext());
3057     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3058       // GCC apparently allows the following idiom:
3059       //
3060       // typedef NSObject < XCElementTogglerP > XCElementToggler;
3061       // @class XCElementToggler;
3062       //
3063       // Here we have chosen to ignore the forward class declaration
3064       // with a warning. Since this is the implied behavior.
3065       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3066       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3067         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3068         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3069       } else {
3070         // a forward class declaration matching a typedef name of a class refers
3071         // to the underlying class. Just ignore the forward class with a warning
3072         // as this will force the intended behavior which is to lookup the
3073         // typedef name.
3074         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3075           Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3076               << IdentList[i];
3077           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3078           continue;
3079         }
3080       }
3081     }
3082 
3083     // Create a declaration to describe this forward declaration.
3084     ObjCInterfaceDecl *PrevIDecl
3085       = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3086 
3087     IdentifierInfo *ClassName = IdentList[i];
3088     if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3089       // A previous decl with a different name is because of
3090       // @compatibility_alias, for example:
3091       // \code
3092       //   @class NewImage;
3093       //   @compatibility_alias OldImage NewImage;
3094       // \endcode
3095       // A lookup for 'OldImage' will return the 'NewImage' decl.
3096       //
3097       // In such a case use the real declaration name, instead of the alias one,
3098       // otherwise we will break IdentifierResolver and redecls-chain invariants.
3099       // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3100       // has been aliased.
3101       ClassName = PrevIDecl->getIdentifier();
3102     }
3103 
3104     // If this forward declaration has type parameters, compare them with the
3105     // type parameters of the previous declaration.
3106     ObjCTypeParamList *TypeParams = TypeParamLists[i];
3107     if (PrevIDecl && TypeParams) {
3108       if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3109         // Check for consistency with the previous declaration.
3110         if (checkTypeParamListConsistency(
3111               *this, PrevTypeParams, TypeParams,
3112               TypeParamListContext::ForwardDeclaration)) {
3113           TypeParams = nullptr;
3114         }
3115       } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3116         // The @interface does not have type parameters. Complain.
3117         Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3118           << ClassName
3119           << TypeParams->getSourceRange();
3120         Diag(Def->getLocation(), diag::note_defined_here)
3121           << ClassName;
3122 
3123         TypeParams = nullptr;
3124       }
3125     }
3126 
3127     ObjCInterfaceDecl *IDecl
3128       = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3129                                   ClassName, TypeParams, PrevIDecl,
3130                                   IdentLocs[i]);
3131     IDecl->setAtEndRange(IdentLocs[i]);
3132 
3133     if (PrevIDecl)
3134       mergeDeclAttributes(IDecl, PrevIDecl);
3135 
3136     PushOnScopeChains(IDecl, TUScope);
3137     CheckObjCDeclScope(IDecl);
3138     DeclsInGroup.push_back(IDecl);
3139   }
3140 
3141   return BuildDeclaratorGroup(DeclsInGroup);
3142 }
3143 
3144 static bool tryMatchRecordTypes(ASTContext &Context,
3145                                 Sema::MethodMatchStrategy strategy,
3146                                 const Type *left, const Type *right);
3147 
3148 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3149                        QualType leftQT, QualType rightQT) {
3150   const Type *left =
3151     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3152   const Type *right =
3153     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3154 
3155   if (left == right) return true;
3156 
3157   // If we're doing a strict match, the types have to match exactly.
3158   if (strategy == Sema::MMS_strict) return false;
3159 
3160   if (left->isIncompleteType() || right->isIncompleteType()) return false;
3161 
3162   // Otherwise, use this absurdly complicated algorithm to try to
3163   // validate the basic, low-level compatibility of the two types.
3164 
3165   // As a minimum, require the sizes and alignments to match.
3166   TypeInfo LeftTI = Context.getTypeInfo(left);
3167   TypeInfo RightTI = Context.getTypeInfo(right);
3168   if (LeftTI.Width != RightTI.Width)
3169     return false;
3170 
3171   if (LeftTI.Align != RightTI.Align)
3172     return false;
3173 
3174   // Consider all the kinds of non-dependent canonical types:
3175   // - functions and arrays aren't possible as return and parameter types
3176 
3177   // - vector types of equal size can be arbitrarily mixed
3178   if (isa<VectorType>(left)) return isa<VectorType>(right);
3179   if (isa<VectorType>(right)) return false;
3180 
3181   // - references should only match references of identical type
3182   // - structs, unions, and Objective-C objects must match more-or-less
3183   //   exactly
3184   // - everything else should be a scalar
3185   if (!left->isScalarType() || !right->isScalarType())
3186     return tryMatchRecordTypes(Context, strategy, left, right);
3187 
3188   // Make scalars agree in kind, except count bools as chars, and group
3189   // all non-member pointers together.
3190   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3191   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3192   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3193   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3194   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3195     leftSK = Type::STK_ObjCObjectPointer;
3196   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3197     rightSK = Type::STK_ObjCObjectPointer;
3198 
3199   // Note that data member pointers and function member pointers don't
3200   // intermix because of the size differences.
3201 
3202   return (leftSK == rightSK);
3203 }
3204 
3205 static bool tryMatchRecordTypes(ASTContext &Context,
3206                                 Sema::MethodMatchStrategy strategy,
3207                                 const Type *lt, const Type *rt) {
3208   assert(lt && rt && lt != rt);
3209 
3210   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3211   RecordDecl *left = cast<RecordType>(lt)->getDecl();
3212   RecordDecl *right = cast<RecordType>(rt)->getDecl();
3213 
3214   // Require union-hood to match.
3215   if (left->isUnion() != right->isUnion()) return false;
3216 
3217   // Require an exact match if either is non-POD.
3218   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3219       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3220     return false;
3221 
3222   // Require size and alignment to match.
3223   TypeInfo LeftTI = Context.getTypeInfo(lt);
3224   TypeInfo RightTI = Context.getTypeInfo(rt);
3225   if (LeftTI.Width != RightTI.Width)
3226     return false;
3227 
3228   if (LeftTI.Align != RightTI.Align)
3229     return false;
3230 
3231   // Require fields to match.
3232   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3233   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3234   for (; li != le && ri != re; ++li, ++ri) {
3235     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3236       return false;
3237   }
3238   return (li == le && ri == re);
3239 }
3240 
3241 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3242 /// returns true, or false, accordingly.
3243 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3244 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3245                                       const ObjCMethodDecl *right,
3246                                       MethodMatchStrategy strategy) {
3247   if (!matchTypes(Context, strategy, left->getReturnType(),
3248                   right->getReturnType()))
3249     return false;
3250 
3251   // If either is hidden, it is not considered to match.
3252   if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible())
3253     return false;
3254 
3255   if (left->isDirectMethod() != right->isDirectMethod())
3256     return false;
3257 
3258   if (getLangOpts().ObjCAutoRefCount &&
3259       (left->hasAttr<NSReturnsRetainedAttr>()
3260          != right->hasAttr<NSReturnsRetainedAttr>() ||
3261        left->hasAttr<NSConsumesSelfAttr>()
3262          != right->hasAttr<NSConsumesSelfAttr>()))
3263     return false;
3264 
3265   ObjCMethodDecl::param_const_iterator
3266     li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3267     re = right->param_end();
3268 
3269   for (; li != le && ri != re; ++li, ++ri) {
3270     assert(ri != right->param_end() && "Param mismatch");
3271     const ParmVarDecl *lparm = *li, *rparm = *ri;
3272 
3273     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3274       return false;
3275 
3276     if (getLangOpts().ObjCAutoRefCount &&
3277         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3278       return false;
3279   }
3280   return true;
3281 }
3282 
3283 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3284                                                ObjCMethodDecl *MethodInList) {
3285   auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3286   auto *MethodInListProtocol =
3287       dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3288   // If this method belongs to a protocol but the method in list does not, or
3289   // vice versa, we say the context is not the same.
3290   if ((MethodProtocol && !MethodInListProtocol) ||
3291       (!MethodProtocol && MethodInListProtocol))
3292     return false;
3293 
3294   if (MethodProtocol && MethodInListProtocol)
3295     return true;
3296 
3297   ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3298   ObjCInterfaceDecl *MethodInListInterface =
3299       MethodInList->getClassInterface();
3300   return MethodInterface == MethodInListInterface;
3301 }
3302 
3303 void Sema::addMethodToGlobalList(ObjCMethodList *List,
3304                                  ObjCMethodDecl *Method) {
3305   // Record at the head of the list whether there were 0, 1, or >= 2 methods
3306   // inside categories.
3307   if (ObjCCategoryDecl *CD =
3308           dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3309     if (!CD->IsClassExtension() && List->getBits() < 2)
3310       List->setBits(List->getBits() + 1);
3311 
3312   // If the list is empty, make it a singleton list.
3313   if (List->getMethod() == nullptr) {
3314     List->setMethod(Method);
3315     List->setNext(nullptr);
3316     return;
3317   }
3318 
3319   // We've seen a method with this name, see if we have already seen this type
3320   // signature.
3321   ObjCMethodList *Previous = List;
3322   ObjCMethodList *ListWithSameDeclaration = nullptr;
3323   for (; List; Previous = List, List = List->getNext()) {
3324     // If we are building a module, keep all of the methods.
3325     if (getLangOpts().isCompilingModule())
3326       continue;
3327 
3328     bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3329                                                       List->getMethod());
3330     // Looking for method with a type bound requires the correct context exists.
3331     // We need to insert a method into the list if the context is different.
3332     // If the method's declaration matches the list
3333     // a> the method belongs to a different context: we need to insert it, in
3334     //    order to emit the availability message, we need to prioritize over
3335     //    availability among the methods with the same declaration.
3336     // b> the method belongs to the same context: there is no need to insert a
3337     //    new entry.
3338     // If the method's declaration does not match the list, we insert it to the
3339     // end.
3340     if (!SameDeclaration ||
3341         !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3342       // Even if two method types do not match, we would like to say
3343       // there is more than one declaration so unavailability/deprecated
3344       // warning is not too noisy.
3345       if (!Method->isDefined())
3346         List->setHasMoreThanOneDecl(true);
3347 
3348       // For methods with the same declaration, the one that is deprecated
3349       // should be put in the front for better diagnostics.
3350       if (Method->isDeprecated() && SameDeclaration &&
3351           !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3352         ListWithSameDeclaration = List;
3353 
3354       if (Method->isUnavailable() && SameDeclaration &&
3355           !ListWithSameDeclaration &&
3356           List->getMethod()->getAvailability() < AR_Deprecated)
3357         ListWithSameDeclaration = List;
3358       continue;
3359     }
3360 
3361     ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3362 
3363     // Propagate the 'defined' bit.
3364     if (Method->isDefined())
3365       PrevObjCMethod->setDefined(true);
3366     else {
3367       // Objective-C doesn't allow an @interface for a class after its
3368       // @implementation. So if Method is not defined and there already is
3369       // an entry for this type signature, Method has to be for a different
3370       // class than PrevObjCMethod.
3371       List->setHasMoreThanOneDecl(true);
3372     }
3373 
3374     // If a method is deprecated, push it in the global pool.
3375     // This is used for better diagnostics.
3376     if (Method->isDeprecated()) {
3377       if (!PrevObjCMethod->isDeprecated())
3378         List->setMethod(Method);
3379     }
3380     // If the new method is unavailable, push it into global pool
3381     // unless previous one is deprecated.
3382     if (Method->isUnavailable()) {
3383       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3384         List->setMethod(Method);
3385     }
3386 
3387     return;
3388   }
3389 
3390   // We have a new signature for an existing method - add it.
3391   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3392   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3393 
3394   // We insert it right before ListWithSameDeclaration.
3395   if (ListWithSameDeclaration) {
3396     auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3397     // FIXME: should we clear the other bits in ListWithSameDeclaration?
3398     ListWithSameDeclaration->setMethod(Method);
3399     ListWithSameDeclaration->setNext(List);
3400     return;
3401   }
3402 
3403   Previous->setNext(new (Mem) ObjCMethodList(Method));
3404 }
3405 
3406 /// Read the contents of the method pool for a given selector from
3407 /// external storage.
3408 void Sema::ReadMethodPool(Selector Sel) {
3409   assert(ExternalSource && "We need an external AST source");
3410   ExternalSource->ReadMethodPool(Sel);
3411 }
3412 
3413 void Sema::updateOutOfDateSelector(Selector Sel) {
3414   if (!ExternalSource)
3415     return;
3416   ExternalSource->updateOutOfDateSelector(Sel);
3417 }
3418 
3419 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3420                                  bool instance) {
3421   // Ignore methods of invalid containers.
3422   if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3423     return;
3424 
3425   if (ExternalSource)
3426     ReadMethodPool(Method->getSelector());
3427 
3428   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3429   if (Pos == MethodPool.end())
3430     Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3431                                            GlobalMethods())).first;
3432 
3433   Method->setDefined(impl);
3434 
3435   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3436   addMethodToGlobalList(&Entry, Method);
3437 }
3438 
3439 /// Determines if this is an "acceptable" loose mismatch in the global
3440 /// method pool.  This exists mostly as a hack to get around certain
3441 /// global mismatches which we can't afford to make warnings / errors.
3442 /// Really, what we want is a way to take a method out of the global
3443 /// method pool.
3444 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3445                                        ObjCMethodDecl *other) {
3446   if (!chosen->isInstanceMethod())
3447     return false;
3448 
3449   if (chosen->isDirectMethod() != other->isDirectMethod())
3450     return false;
3451 
3452   Selector sel = chosen->getSelector();
3453   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3454     return false;
3455 
3456   // Don't complain about mismatches for -length if the method we
3457   // chose has an integral result type.
3458   return (chosen->getReturnType()->isIntegerType());
3459 }
3460 
3461 /// Return true if the given method is wthin the type bound.
3462 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3463                                      const ObjCObjectType *TypeBound) {
3464   if (!TypeBound)
3465     return true;
3466 
3467   if (TypeBound->isObjCId())
3468     // FIXME: should we handle the case of bounding to id<A, B> differently?
3469     return true;
3470 
3471   auto *BoundInterface = TypeBound->getInterface();
3472   assert(BoundInterface && "unexpected object type!");
3473 
3474   // Check if the Method belongs to a protocol. We should allow any method
3475   // defined in any protocol, because any subclass could adopt the protocol.
3476   auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3477   if (MethodProtocol) {
3478     return true;
3479   }
3480 
3481   // If the Method belongs to a class, check if it belongs to the class
3482   // hierarchy of the class bound.
3483   if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3484     // We allow methods declared within classes that are part of the hierarchy
3485     // of the class bound (superclass of, subclass of, or the same as the class
3486     // bound).
3487     return MethodInterface == BoundInterface ||
3488            MethodInterface->isSuperClassOf(BoundInterface) ||
3489            BoundInterface->isSuperClassOf(MethodInterface);
3490   }
3491   llvm_unreachable("unknown method context");
3492 }
3493 
3494 /// We first select the type of the method: Instance or Factory, then collect
3495 /// all methods with that type.
3496 bool Sema::CollectMultipleMethodsInGlobalPool(
3497     Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3498     bool InstanceFirst, bool CheckTheOther,
3499     const ObjCObjectType *TypeBound) {
3500   if (ExternalSource)
3501     ReadMethodPool(Sel);
3502 
3503   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3504   if (Pos == MethodPool.end())
3505     return false;
3506 
3507   // Gather the non-hidden methods.
3508   ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3509                              Pos->second.second;
3510   for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3511     if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3512       if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3513         Methods.push_back(M->getMethod());
3514     }
3515 
3516   // Return if we find any method with the desired kind.
3517   if (!Methods.empty())
3518     return Methods.size() > 1;
3519 
3520   if (!CheckTheOther)
3521     return false;
3522 
3523   // Gather the other kind.
3524   ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3525                               Pos->second.first;
3526   for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3527     if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3528       if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3529         Methods.push_back(M->getMethod());
3530     }
3531 
3532   return Methods.size() > 1;
3533 }
3534 
3535 bool Sema::AreMultipleMethodsInGlobalPool(
3536     Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3537     bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3538   // Diagnose finding more than one method in global pool.
3539   SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3540   FilteredMethods.push_back(BestMethod);
3541 
3542   for (auto *M : Methods)
3543     if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3544       FilteredMethods.push_back(M);
3545 
3546   if (FilteredMethods.size() > 1)
3547     DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3548                                        receiverIdOrClass);
3549 
3550   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3551   // Test for no method in the pool which should not trigger any warning by
3552   // caller.
3553   if (Pos == MethodPool.end())
3554     return true;
3555   ObjCMethodList &MethList =
3556     BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3557   return MethList.hasMoreThanOneDecl();
3558 }
3559 
3560 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3561                                                bool receiverIdOrClass,
3562                                                bool instance) {
3563   if (ExternalSource)
3564     ReadMethodPool(Sel);
3565 
3566   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3567   if (Pos == MethodPool.end())
3568     return nullptr;
3569 
3570   // Gather the non-hidden methods.
3571   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3572   SmallVector<ObjCMethodDecl *, 4> Methods;
3573   for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3574     if (M->getMethod() && M->getMethod()->isUnconditionallyVisible())
3575       return M->getMethod();
3576   }
3577   return nullptr;
3578 }
3579 
3580 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3581                                               Selector Sel, SourceRange R,
3582                                               bool receiverIdOrClass) {
3583   // We found multiple methods, so we may have to complain.
3584   bool issueDiagnostic = false, issueError = false;
3585 
3586   // We support a warning which complains about *any* difference in
3587   // method signature.
3588   bool strictSelectorMatch =
3589   receiverIdOrClass &&
3590   !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3591   if (strictSelectorMatch) {
3592     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3593       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3594         issueDiagnostic = true;
3595         break;
3596       }
3597     }
3598   }
3599 
3600   // If we didn't see any strict differences, we won't see any loose
3601   // differences.  In ARC, however, we also need to check for loose
3602   // mismatches, because most of them are errors.
3603   if (!strictSelectorMatch ||
3604       (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3605     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3606       // This checks if the methods differ in type mismatch.
3607       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3608           !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3609         issueDiagnostic = true;
3610         if (getLangOpts().ObjCAutoRefCount)
3611           issueError = true;
3612         break;
3613       }
3614     }
3615 
3616   if (issueDiagnostic) {
3617     if (issueError)
3618       Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3619     else if (strictSelectorMatch)
3620       Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3621     else
3622       Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3623 
3624     Diag(Methods[0]->getBeginLoc(),
3625          issueError ? diag::note_possibility : diag::note_using)
3626         << Methods[0]->getSourceRange();
3627     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3628       Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3629           << Methods[I]->getSourceRange();
3630     }
3631   }
3632 }
3633 
3634 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3635   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3636   if (Pos == MethodPool.end())
3637     return nullptr;
3638 
3639   GlobalMethods &Methods = Pos->second;
3640   for (const ObjCMethodList *Method = &Methods.first; Method;
3641        Method = Method->getNext())
3642     if (Method->getMethod() &&
3643         (Method->getMethod()->isDefined() ||
3644          Method->getMethod()->isPropertyAccessor()))
3645       return Method->getMethod();
3646 
3647   for (const ObjCMethodList *Method = &Methods.second; Method;
3648        Method = Method->getNext())
3649     if (Method->getMethod() &&
3650         (Method->getMethod()->isDefined() ||
3651          Method->getMethod()->isPropertyAccessor()))
3652       return Method->getMethod();
3653   return nullptr;
3654 }
3655 
3656 static void
3657 HelperSelectorsForTypoCorrection(
3658                       SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3659                       StringRef Typo, const ObjCMethodDecl * Method) {
3660   const unsigned MaxEditDistance = 1;
3661   unsigned BestEditDistance = MaxEditDistance + 1;
3662   std::string MethodName = Method->getSelector().getAsString();
3663 
3664   unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3665   if (MinPossibleEditDistance > 0 &&
3666       Typo.size() / MinPossibleEditDistance < 1)
3667     return;
3668   unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3669   if (EditDistance > MaxEditDistance)
3670     return;
3671   if (EditDistance == BestEditDistance)
3672     BestMethod.push_back(Method);
3673   else if (EditDistance < BestEditDistance) {
3674     BestMethod.clear();
3675     BestMethod.push_back(Method);
3676   }
3677 }
3678 
3679 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3680                                      QualType ObjectType) {
3681   if (ObjectType.isNull())
3682     return true;
3683   if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3684     return true;
3685   return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3686          nullptr;
3687 }
3688 
3689 const ObjCMethodDecl *
3690 Sema::SelectorsForTypoCorrection(Selector Sel,
3691                                  QualType ObjectType) {
3692   unsigned NumArgs = Sel.getNumArgs();
3693   SmallVector<const ObjCMethodDecl *, 8> Methods;
3694   bool ObjectIsId = true, ObjectIsClass = true;
3695   if (ObjectType.isNull())
3696     ObjectIsId = ObjectIsClass = false;
3697   else if (!ObjectType->isObjCObjectPointerType())
3698     return nullptr;
3699   else if (const ObjCObjectPointerType *ObjCPtr =
3700            ObjectType->getAsObjCInterfacePointerType()) {
3701     ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3702     ObjectIsId = ObjectIsClass = false;
3703   }
3704   else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3705     ObjectIsClass = false;
3706   else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3707     ObjectIsId = false;
3708   else
3709     return nullptr;
3710 
3711   for (GlobalMethodPool::iterator b = MethodPool.begin(),
3712        e = MethodPool.end(); b != e; b++) {
3713     // instance methods
3714     for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3715       if (M->getMethod() &&
3716           (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3717           (M->getMethod()->getSelector() != Sel)) {
3718         if (ObjectIsId)
3719           Methods.push_back(M->getMethod());
3720         else if (!ObjectIsClass &&
3721                  HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3722                                           ObjectType))
3723           Methods.push_back(M->getMethod());
3724       }
3725     // class methods
3726     for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3727       if (M->getMethod() &&
3728           (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3729           (M->getMethod()->getSelector() != Sel)) {
3730         if (ObjectIsClass)
3731           Methods.push_back(M->getMethod());
3732         else if (!ObjectIsId &&
3733                  HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3734                                           ObjectType))
3735           Methods.push_back(M->getMethod());
3736       }
3737   }
3738 
3739   SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3740   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3741     HelperSelectorsForTypoCorrection(SelectedMethods,
3742                                      Sel.getAsString(), Methods[i]);
3743   }
3744   return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3745 }
3746 
3747 /// DiagnoseDuplicateIvars -
3748 /// Check for duplicate ivars in the entire class at the start of
3749 /// \@implementation. This becomes necesssary because class extension can
3750 /// add ivars to a class in random order which will not be known until
3751 /// class's \@implementation is seen.
3752 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3753                                   ObjCInterfaceDecl *SID) {
3754   for (auto *Ivar : ID->ivars()) {
3755     if (Ivar->isInvalidDecl())
3756       continue;
3757     if (IdentifierInfo *II = Ivar->getIdentifier()) {
3758       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3759       if (prevIvar) {
3760         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3761         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3762         Ivar->setInvalidDecl();
3763       }
3764     }
3765   }
3766 }
3767 
3768 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3769 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3770   if (S.getLangOpts().ObjCWeak) return;
3771 
3772   for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3773          ivar; ivar = ivar->getNextIvar()) {
3774     if (ivar->isInvalidDecl()) continue;
3775     if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3776       if (S.getLangOpts().ObjCWeakRuntime) {
3777         S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3778       } else {
3779         S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3780       }
3781     }
3782   }
3783 }
3784 
3785 /// Diagnose attempts to use flexible array member with retainable object type.
3786 static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3787                                                   ObjCInterfaceDecl *ID) {
3788   if (!S.getLangOpts().ObjCAutoRefCount)
3789     return;
3790 
3791   for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3792        ivar = ivar->getNextIvar()) {
3793     if (ivar->isInvalidDecl())
3794       continue;
3795     QualType IvarTy = ivar->getType();
3796     if (IvarTy->isIncompleteArrayType() &&
3797         (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3798         IvarTy->isObjCLifetimeType()) {
3799       S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3800       ivar->setInvalidDecl();
3801     }
3802   }
3803 }
3804 
3805 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3806   switch (CurContext->getDeclKind()) {
3807     case Decl::ObjCInterface:
3808       return Sema::OCK_Interface;
3809     case Decl::ObjCProtocol:
3810       return Sema::OCK_Protocol;
3811     case Decl::ObjCCategory:
3812       if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3813         return Sema::OCK_ClassExtension;
3814       return Sema::OCK_Category;
3815     case Decl::ObjCImplementation:
3816       return Sema::OCK_Implementation;
3817     case Decl::ObjCCategoryImpl:
3818       return Sema::OCK_CategoryImplementation;
3819 
3820     default:
3821       return Sema::OCK_None;
3822   }
3823 }
3824 
3825 static bool IsVariableSizedType(QualType T) {
3826   if (T->isIncompleteArrayType())
3827     return true;
3828   const auto *RecordTy = T->getAs<RecordType>();
3829   return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3830 }
3831 
3832 static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3833   ObjCInterfaceDecl *IntfDecl = nullptr;
3834   ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3835       ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3836   if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3837     Ivars = IntfDecl->ivars();
3838   } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3839     IntfDecl = ImplDecl->getClassInterface();
3840     Ivars = ImplDecl->ivars();
3841   } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3842     if (CategoryDecl->IsClassExtension()) {
3843       IntfDecl = CategoryDecl->getClassInterface();
3844       Ivars = CategoryDecl->ivars();
3845     }
3846   }
3847 
3848   // Check if variable sized ivar is in interface and visible to subclasses.
3849   if (!isa<ObjCInterfaceDecl>(OCD)) {
3850     for (auto ivar : Ivars) {
3851       if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3852         S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3853             << ivar->getDeclName() << ivar->getType();
3854       }
3855     }
3856   }
3857 
3858   // Subsequent checks require interface decl.
3859   if (!IntfDecl)
3860     return;
3861 
3862   // Check if variable sized ivar is followed by another ivar.
3863   for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3864        ivar = ivar->getNextIvar()) {
3865     if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3866       continue;
3867     QualType IvarTy = ivar->getType();
3868     bool IsInvalidIvar = false;
3869     if (IvarTy->isIncompleteArrayType()) {
3870       S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3871           << ivar->getDeclName() << IvarTy
3872           << TTK_Class; // Use "class" for Obj-C.
3873       IsInvalidIvar = true;
3874     } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3875       if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3876         S.Diag(ivar->getLocation(),
3877                diag::err_objc_variable_sized_type_not_at_end)
3878             << ivar->getDeclName() << IvarTy;
3879         IsInvalidIvar = true;
3880       }
3881     }
3882     if (IsInvalidIvar) {
3883       S.Diag(ivar->getNextIvar()->getLocation(),
3884              diag::note_next_ivar_declaration)
3885           << ivar->getNextIvar()->getSynthesize();
3886       ivar->setInvalidDecl();
3887     }
3888   }
3889 
3890   // Check if ObjC container adds ivars after variable sized ivar in superclass.
3891   // Perform the check only if OCD is the first container to declare ivars to
3892   // avoid multiple warnings for the same ivar.
3893   ObjCIvarDecl *FirstIvar =
3894       (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3895   if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3896     const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3897     while (SuperClass && SuperClass->ivar_empty())
3898       SuperClass = SuperClass->getSuperClass();
3899     if (SuperClass) {
3900       auto IvarIter = SuperClass->ivar_begin();
3901       std::advance(IvarIter, SuperClass->ivar_size() - 1);
3902       const ObjCIvarDecl *LastIvar = *IvarIter;
3903       if (IsVariableSizedType(LastIvar->getType())) {
3904         S.Diag(FirstIvar->getLocation(),
3905                diag::warn_superclass_variable_sized_type_not_at_end)
3906             << FirstIvar->getDeclName() << LastIvar->getDeclName()
3907             << LastIvar->getType() << SuperClass->getDeclName();
3908         S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3909             << LastIvar->getDeclName();
3910       }
3911     }
3912   }
3913 }
3914 
3915 static void DiagnoseCategoryDirectMembersProtocolConformance(
3916     Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
3917 
3918 static void DiagnoseCategoryDirectMembersProtocolConformance(
3919     Sema &S, ObjCCategoryDecl *CDecl,
3920     const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
3921   for (auto *PI : Protocols)
3922     DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl);
3923 }
3924 
3925 static void DiagnoseCategoryDirectMembersProtocolConformance(
3926     Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
3927   if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
3928     PDecl = PDecl->getDefinition();
3929 
3930   llvm::SmallVector<const Decl *, 4> DirectMembers;
3931   const auto *IDecl = CDecl->getClassInterface();
3932   for (auto *MD : PDecl->methods()) {
3933     if (!MD->isPropertyAccessor()) {
3934       if (const auto *CMD =
3935               IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
3936         if (CMD->isDirectMethod())
3937           DirectMembers.push_back(CMD);
3938       }
3939     }
3940   }
3941   for (auto *PD : PDecl->properties()) {
3942     if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
3943             PD->getIdentifier(),
3944             PD->isClassProperty()
3945                 ? ObjCPropertyQueryKind::OBJC_PR_query_class
3946                 : ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
3947       if (CPD->isDirectProperty())
3948         DirectMembers.push_back(CPD);
3949     }
3950   }
3951   if (!DirectMembers.empty()) {
3952     S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
3953         << CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
3954     for (const auto *MD : DirectMembers)
3955       S.Diag(MD->getLocation(), diag::note_direct_member_here);
3956     return;
3957   }
3958 
3959   // Check on this protocols's referenced protocols, recursively.
3960   DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl,
3961                                                    PDecl->protocols());
3962 }
3963 
3964 // Note: For class/category implementations, allMethods is always null.
3965 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3966                        ArrayRef<DeclGroupPtrTy> allTUVars) {
3967   if (getObjCContainerKind() == Sema::OCK_None)
3968     return nullptr;
3969 
3970   assert(AtEnd.isValid() && "Invalid location for '@end'");
3971 
3972   auto *OCD = cast<ObjCContainerDecl>(CurContext);
3973   Decl *ClassDecl = OCD;
3974 
3975   bool isInterfaceDeclKind =
3976         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3977          || isa<ObjCProtocolDecl>(ClassDecl);
3978   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3979 
3980   // Make synthesized accessor stub functions visible.
3981   // ActOnPropertyImplDecl() creates them as not visible in case
3982   // they are overridden by an explicit method that is encountered
3983   // later.
3984   if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) {
3985     for (auto PropImpl : OID->property_impls()) {
3986       if (auto *Getter = PropImpl->getGetterMethodDecl())
3987         if (Getter->isSynthesizedAccessorStub())
3988           OID->addDecl(Getter);
3989       if (auto *Setter = PropImpl->getSetterMethodDecl())
3990         if (Setter->isSynthesizedAccessorStub())
3991           OID->addDecl(Setter);
3992     }
3993   }
3994 
3995   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3996   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3997   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3998 
3999   for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
4000     ObjCMethodDecl *Method =
4001       cast_or_null<ObjCMethodDecl>(allMethods[i]);
4002 
4003     if (!Method) continue;  // Already issued a diagnostic.
4004     if (Method->isInstanceMethod()) {
4005       /// Check for instance method of the same name with incompatible types
4006       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
4007       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4008                               : false;
4009       if ((isInterfaceDeclKind && PrevMethod && !match)
4010           || (checkIdenticalMethods && match)) {
4011           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4012             << Method->getDeclName();
4013           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4014         Method->setInvalidDecl();
4015       } else {
4016         if (PrevMethod) {
4017           Method->setAsRedeclaration(PrevMethod);
4018           if (!Context.getSourceManager().isInSystemHeader(
4019                  Method->getLocation()))
4020             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4021               << Method->getDeclName();
4022           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4023         }
4024         InsMap[Method->getSelector()] = Method;
4025         /// The following allows us to typecheck messages to "id".
4026         AddInstanceMethodToGlobalPool(Method);
4027       }
4028     } else {
4029       /// Check for class method of the same name with incompatible types
4030       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
4031       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4032                               : false;
4033       if ((isInterfaceDeclKind && PrevMethod && !match)
4034           || (checkIdenticalMethods && match)) {
4035         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4036           << Method->getDeclName();
4037         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4038         Method->setInvalidDecl();
4039       } else {
4040         if (PrevMethod) {
4041           Method->setAsRedeclaration(PrevMethod);
4042           if (!Context.getSourceManager().isInSystemHeader(
4043                  Method->getLocation()))
4044             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4045               << Method->getDeclName();
4046           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4047         }
4048         ClsMap[Method->getSelector()] = Method;
4049         AddFactoryMethodToGlobalPool(Method);
4050       }
4051     }
4052   }
4053   if (isa<ObjCInterfaceDecl>(ClassDecl)) {
4054     // Nothing to do here.
4055   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
4056     // Categories are used to extend the class by declaring new methods.
4057     // By the same token, they are also used to add new properties. No
4058     // need to compare the added property to those in the class.
4059 
4060     if (C->IsClassExtension()) {
4061       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
4062       DiagnoseClassExtensionDupMethods(C, CCPrimary);
4063     }
4064 
4065     DiagnoseCategoryDirectMembersProtocolConformance(*this, C, C->protocols());
4066   }
4067   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
4068     if (CDecl->getIdentifier())
4069       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
4070       // user-defined setter/getter. It also synthesizes setter/getter methods
4071       // and adds them to the DeclContext and global method pools.
4072       for (auto *I : CDecl->properties())
4073         ProcessPropertyDecl(I);
4074     CDecl->setAtEndRange(AtEnd);
4075   }
4076   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
4077     IC->setAtEndRange(AtEnd);
4078     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
4079       // Any property declared in a class extension might have user
4080       // declared setter or getter in current class extension or one
4081       // of the other class extensions. Mark them as synthesized as
4082       // property will be synthesized when property with same name is
4083       // seen in the @implementation.
4084       for (const auto *Ext : IDecl->visible_extensions()) {
4085         for (const auto *Property : Ext->instance_properties()) {
4086           // Skip over properties declared @dynamic
4087           if (const ObjCPropertyImplDecl *PIDecl
4088               = IC->FindPropertyImplDecl(Property->getIdentifier(),
4089                                          Property->getQueryKind()))
4090             if (PIDecl->getPropertyImplementation()
4091                   == ObjCPropertyImplDecl::Dynamic)
4092               continue;
4093 
4094           for (const auto *Ext : IDecl->visible_extensions()) {
4095             if (ObjCMethodDecl *GetterMethod =
4096                     Ext->getInstanceMethod(Property->getGetterName()))
4097               GetterMethod->setPropertyAccessor(true);
4098             if (!Property->isReadOnly())
4099               if (ObjCMethodDecl *SetterMethod
4100                     = Ext->getInstanceMethod(Property->getSetterName()))
4101                 SetterMethod->setPropertyAccessor(true);
4102           }
4103         }
4104       }
4105       ImplMethodsVsClassMethods(S, IC, IDecl);
4106       AtomicPropertySetterGetterRules(IC, IDecl);
4107       DiagnoseOwningPropertyGetterSynthesis(IC);
4108       DiagnoseUnusedBackingIvarInAccessor(S, IC);
4109       if (IDecl->hasDesignatedInitializers())
4110         DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
4111       DiagnoseWeakIvars(*this, IC);
4112       DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
4113 
4114       bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4115       if (IDecl->getSuperClass() == nullptr) {
4116         // This class has no superclass, so check that it has been marked with
4117         // __attribute((objc_root_class)).
4118         if (!HasRootClassAttr) {
4119           SourceLocation DeclLoc(IDecl->getLocation());
4120           SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
4121           Diag(DeclLoc, diag::warn_objc_root_class_missing)
4122             << IDecl->getIdentifier();
4123           // See if NSObject is in the current scope, and if it is, suggest
4124           // adding " : NSObject " to the class declaration.
4125           NamedDecl *IF = LookupSingleName(TUScope,
4126                                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4127                                            DeclLoc, LookupOrdinaryName);
4128           ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4129           if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4130             Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4131               << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4132           } else {
4133             Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4134           }
4135         }
4136       } else if (HasRootClassAttr) {
4137         // Complain that only root classes may have this attribute.
4138         Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4139       }
4140 
4141       if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4142         // An interface can subclass another interface with a
4143         // objc_subclassing_restricted attribute when it has that attribute as
4144         // well (because of interfaces imported from Swift). Therefore we have
4145         // to check if we can subclass in the implementation as well.
4146         if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4147             Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4148           Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4149           Diag(Super->getLocation(), diag::note_class_declared);
4150         }
4151       }
4152 
4153       if (IDecl->hasAttr<ObjCClassStubAttr>())
4154         Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4155 
4156       if (LangOpts.ObjCRuntime.isNonFragile()) {
4157         while (IDecl->getSuperClass()) {
4158           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4159           IDecl = IDecl->getSuperClass();
4160         }
4161       }
4162     }
4163     SetIvarInitializers(IC);
4164   } else if (ObjCCategoryImplDecl* CatImplClass =
4165                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4166     CatImplClass->setAtEndRange(AtEnd);
4167 
4168     // Find category interface decl and then check that all methods declared
4169     // in this interface are implemented in the category @implementation.
4170     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4171       if (ObjCCategoryDecl *Cat
4172             = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4173         ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4174       }
4175     }
4176   } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4177     if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4178       if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4179           Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4180         Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4181         Diag(Super->getLocation(), diag::note_class_declared);
4182       }
4183     }
4184 
4185     if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4186         !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
4187       Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
4188   }
4189   DiagnoseVariableSizedIvars(*this, OCD);
4190   if (isInterfaceDeclKind) {
4191     // Reject invalid vardecls.
4192     for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4193       DeclGroupRef DG = allTUVars[i].get();
4194       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4195         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4196           if (!VDecl->hasExternalStorage())
4197             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4198         }
4199     }
4200   }
4201   ActOnObjCContainerFinishDefinition();
4202 
4203   for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4204     DeclGroupRef DG = allTUVars[i].get();
4205     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4206       (*I)->setTopLevelDeclInObjCContainer();
4207     Consumer.HandleTopLevelDeclInObjCContainer(DG);
4208   }
4209 
4210   ActOnDocumentableDecl(ClassDecl);
4211   return ClassDecl;
4212 }
4213 
4214 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4215 /// objective-c's type qualifier from the parser version of the same info.
4216 static Decl::ObjCDeclQualifier
4217 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
4218   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4219 }
4220 
4221 /// Check whether the declared result type of the given Objective-C
4222 /// method declaration is compatible with the method's class.
4223 ///
4224 static Sema::ResultTypeCompatibilityKind
4225 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4226                                     ObjCInterfaceDecl *CurrentClass) {
4227   QualType ResultType = Method->getReturnType();
4228 
4229   // If an Objective-C method inherits its related result type, then its
4230   // declared result type must be compatible with its own class type. The
4231   // declared result type is compatible if:
4232   if (const ObjCObjectPointerType *ResultObjectType
4233                                 = ResultType->getAs<ObjCObjectPointerType>()) {
4234     //   - it is id or qualified id, or
4235     if (ResultObjectType->isObjCIdType() ||
4236         ResultObjectType->isObjCQualifiedIdType())
4237       return Sema::RTC_Compatible;
4238 
4239     if (CurrentClass) {
4240       if (ObjCInterfaceDecl *ResultClass
4241                                       = ResultObjectType->getInterfaceDecl()) {
4242         //   - it is the same as the method's class type, or
4243         if (declaresSameEntity(CurrentClass, ResultClass))
4244           return Sema::RTC_Compatible;
4245 
4246         //   - it is a superclass of the method's class type
4247         if (ResultClass->isSuperClassOf(CurrentClass))
4248           return Sema::RTC_Compatible;
4249       }
4250     } else {
4251       // Any Objective-C pointer type might be acceptable for a protocol
4252       // method; we just don't know.
4253       return Sema::RTC_Unknown;
4254     }
4255   }
4256 
4257   return Sema::RTC_Incompatible;
4258 }
4259 
4260 namespace {
4261 /// A helper class for searching for methods which a particular method
4262 /// overrides.
4263 class OverrideSearch {
4264 public:
4265   const ObjCMethodDecl *Method;
4266   llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4267   bool Recursive;
4268 
4269 public:
4270   OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4271     Selector selector = method->getSelector();
4272 
4273     // Bypass this search if we've never seen an instance/class method
4274     // with this selector before.
4275     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4276     if (it == S.MethodPool.end()) {
4277       if (!S.getExternalSource()) return;
4278       S.ReadMethodPool(selector);
4279 
4280       it = S.MethodPool.find(selector);
4281       if (it == S.MethodPool.end())
4282         return;
4283     }
4284     const ObjCMethodList &list =
4285       method->isInstanceMethod() ? it->second.first : it->second.second;
4286     if (!list.getMethod()) return;
4287 
4288     const ObjCContainerDecl *container
4289       = cast<ObjCContainerDecl>(method->getDeclContext());
4290 
4291     // Prevent the search from reaching this container again.  This is
4292     // important with categories, which override methods from the
4293     // interface and each other.
4294     if (const ObjCCategoryDecl *Category =
4295             dyn_cast<ObjCCategoryDecl>(container)) {
4296       searchFromContainer(container);
4297       if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4298         searchFromContainer(Interface);
4299     } else {
4300       searchFromContainer(container);
4301     }
4302   }
4303 
4304   typedef decltype(Overridden)::iterator iterator;
4305   iterator begin() const { return Overridden.begin(); }
4306   iterator end() const { return Overridden.end(); }
4307 
4308 private:
4309   void searchFromContainer(const ObjCContainerDecl *container) {
4310     if (container->isInvalidDecl()) return;
4311 
4312     switch (container->getDeclKind()) {
4313 #define OBJCCONTAINER(type, base) \
4314     case Decl::type: \
4315       searchFrom(cast<type##Decl>(container)); \
4316       break;
4317 #define ABSTRACT_DECL(expansion)
4318 #define DECL(type, base) \
4319     case Decl::type:
4320 #include "clang/AST/DeclNodes.inc"
4321       llvm_unreachable("not an ObjC container!");
4322     }
4323   }
4324 
4325   void searchFrom(const ObjCProtocolDecl *protocol) {
4326     if (!protocol->hasDefinition())
4327       return;
4328 
4329     // A method in a protocol declaration overrides declarations from
4330     // referenced ("parent") protocols.
4331     search(protocol->getReferencedProtocols());
4332   }
4333 
4334   void searchFrom(const ObjCCategoryDecl *category) {
4335     // A method in a category declaration overrides declarations from
4336     // the main class and from protocols the category references.
4337     // The main class is handled in the constructor.
4338     search(category->getReferencedProtocols());
4339   }
4340 
4341   void searchFrom(const ObjCCategoryImplDecl *impl) {
4342     // A method in a category definition that has a category
4343     // declaration overrides declarations from the category
4344     // declaration.
4345     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4346       search(category);
4347       if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4348         search(Interface);
4349 
4350     // Otherwise it overrides declarations from the class.
4351     } else if (const auto *Interface = impl->getClassInterface()) {
4352       search(Interface);
4353     }
4354   }
4355 
4356   void searchFrom(const ObjCInterfaceDecl *iface) {
4357     // A method in a class declaration overrides declarations from
4358     if (!iface->hasDefinition())
4359       return;
4360 
4361     //   - categories,
4362     for (auto *Cat : iface->known_categories())
4363       search(Cat);
4364 
4365     //   - the super class, and
4366     if (ObjCInterfaceDecl *super = iface->getSuperClass())
4367       search(super);
4368 
4369     //   - any referenced protocols.
4370     search(iface->getReferencedProtocols());
4371   }
4372 
4373   void searchFrom(const ObjCImplementationDecl *impl) {
4374     // A method in a class implementation overrides declarations from
4375     // the class interface.
4376     if (const auto *Interface = impl->getClassInterface())
4377       search(Interface);
4378   }
4379 
4380   void search(const ObjCProtocolList &protocols) {
4381     for (const auto *Proto : protocols)
4382       search(Proto);
4383   }
4384 
4385   void search(const ObjCContainerDecl *container) {
4386     // Check for a method in this container which matches this selector.
4387     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4388                                                 Method->isInstanceMethod(),
4389                                                 /*AllowHidden=*/true);
4390 
4391     // If we find one, record it and bail out.
4392     if (meth) {
4393       Overridden.insert(meth);
4394       return;
4395     }
4396 
4397     // Otherwise, search for methods that a hypothetical method here
4398     // would have overridden.
4399 
4400     // Note that we're now in a recursive case.
4401     Recursive = true;
4402 
4403     searchFromContainer(container);
4404   }
4405 };
4406 } // end anonymous namespace
4407 
4408 void Sema::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
4409                                           ObjCMethodDecl *overridden) {
4410   if (overridden->isDirectMethod()) {
4411     const auto *attr = overridden->getAttr<ObjCDirectAttr>();
4412     Diag(method->getLocation(), diag::err_objc_override_direct_method);
4413     Diag(attr->getLocation(), diag::note_previous_declaration);
4414   } else if (method->isDirectMethod()) {
4415     const auto *attr = method->getAttr<ObjCDirectAttr>();
4416     Diag(attr->getLocation(), diag::err_objc_direct_on_override)
4417         << isa<ObjCProtocolDecl>(overridden->getDeclContext());
4418     Diag(overridden->getLocation(), diag::note_previous_declaration);
4419   }
4420 }
4421 
4422 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4423                                     ObjCInterfaceDecl *CurrentClass,
4424                                     ResultTypeCompatibilityKind RTC) {
4425   if (!ObjCMethod)
4426     return;
4427   // Search for overridden methods and merge information down from them.
4428   OverrideSearch overrides(*this, ObjCMethod);
4429   // Keep track if the method overrides any method in the class's base classes,
4430   // its protocols, or its categories' protocols; we will keep that info
4431   // in the ObjCMethodDecl.
4432   // For this info, a method in an implementation is not considered as
4433   // overriding the same method in the interface or its categories.
4434   bool hasOverriddenMethodsInBaseOrProtocol = false;
4435   for (ObjCMethodDecl *overridden : overrides) {
4436     if (!hasOverriddenMethodsInBaseOrProtocol) {
4437       if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4438           CurrentClass != overridden->getClassInterface() ||
4439           overridden->isOverriding()) {
4440         CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
4441         hasOverriddenMethodsInBaseOrProtocol = true;
4442       } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4443         // OverrideSearch will return as "overridden" the same method in the
4444         // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4445         // check whether a category of a base class introduced a method with the
4446         // same selector, after the interface method declaration.
4447         // To avoid unnecessary lookups in the majority of cases, we use the
4448         // extra info bits in GlobalMethodPool to check whether there were any
4449         // category methods with this selector.
4450         GlobalMethodPool::iterator It =
4451             MethodPool.find(ObjCMethod->getSelector());
4452         if (It != MethodPool.end()) {
4453           ObjCMethodList &List =
4454             ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4455           unsigned CategCount = List.getBits();
4456           if (CategCount > 0) {
4457             // If the method is in a category we'll do lookup if there were at
4458             // least 2 category methods recorded, otherwise only one will do.
4459             if (CategCount > 1 ||
4460                 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4461               OverrideSearch overrides(*this, overridden);
4462               for (ObjCMethodDecl *SuperOverridden : overrides) {
4463                 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4464                     CurrentClass != SuperOverridden->getClassInterface()) {
4465                   CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
4466                   hasOverriddenMethodsInBaseOrProtocol = true;
4467                   overridden->setOverriding(true);
4468                   break;
4469                 }
4470               }
4471             }
4472           }
4473         }
4474       }
4475     }
4476 
4477     // Propagate down the 'related result type' bit from overridden methods.
4478     if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4479       ObjCMethod->setRelatedResultType();
4480 
4481     // Then merge the declarations.
4482     mergeObjCMethodDecls(ObjCMethod, overridden);
4483 
4484     if (ObjCMethod->isImplicit() && overridden->isImplicit())
4485       continue; // Conflicting properties are detected elsewhere.
4486 
4487     // Check for overriding methods
4488     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4489         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4490       CheckConflictingOverridingMethod(ObjCMethod, overridden,
4491               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4492 
4493     if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4494         isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4495         !overridden->isImplicit() /* not meant for properties */) {
4496       ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4497                                           E = ObjCMethod->param_end();
4498       ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4499                                      PrevE = overridden->param_end();
4500       for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4501         assert(PrevI != overridden->param_end() && "Param mismatch");
4502         QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4503         QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4504         // If type of argument of method in this class does not match its
4505         // respective argument type in the super class method, issue warning;
4506         if (!Context.typesAreCompatible(T1, T2)) {
4507           Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4508             << T1 << T2;
4509           Diag(overridden->getLocation(), diag::note_previous_declaration);
4510           break;
4511         }
4512       }
4513     }
4514   }
4515 
4516   ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4517 }
4518 
4519 /// Merge type nullability from for a redeclaration of the same entity,
4520 /// producing the updated type of the redeclared entity.
4521 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4522                                               QualType type,
4523                                               bool usesCSKeyword,
4524                                               SourceLocation prevLoc,
4525                                               QualType prevType,
4526                                               bool prevUsesCSKeyword) {
4527   // Determine the nullability of both types.
4528   auto nullability = type->getNullability(S.Context);
4529   auto prevNullability = prevType->getNullability(S.Context);
4530 
4531   // Easy case: both have nullability.
4532   if (nullability.hasValue() == prevNullability.hasValue()) {
4533     // Neither has nullability; continue.
4534     if (!nullability)
4535       return type;
4536 
4537     // The nullabilities are equivalent; do nothing.
4538     if (*nullability == *prevNullability)
4539       return type;
4540 
4541     // Complain about mismatched nullability.
4542     S.Diag(loc, diag::err_nullability_conflicting)
4543       << DiagNullabilityKind(*nullability, usesCSKeyword)
4544       << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4545     return type;
4546   }
4547 
4548   // If it's the redeclaration that has nullability, don't change anything.
4549   if (nullability)
4550     return type;
4551 
4552   // Otherwise, provide the result with the same nullability.
4553   return S.Context.getAttributedType(
4554            AttributedType::getNullabilityAttrKind(*prevNullability),
4555            type, type);
4556 }
4557 
4558 /// Merge information from the declaration of a method in the \@interface
4559 /// (or a category/extension) into the corresponding method in the
4560 /// @implementation (for a class or category).
4561 static void mergeInterfaceMethodToImpl(Sema &S,
4562                                        ObjCMethodDecl *method,
4563                                        ObjCMethodDecl *prevMethod) {
4564   // Merge the objc_requires_super attribute.
4565   if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4566       !method->hasAttr<ObjCRequiresSuperAttr>()) {
4567     // merge the attribute into implementation.
4568     method->addAttr(
4569       ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4570                                             method->getLocation()));
4571   }
4572 
4573   // Merge nullability of the result type.
4574   QualType newReturnType
4575     = mergeTypeNullabilityForRedecl(
4576         S, method->getReturnTypeSourceRange().getBegin(),
4577         method->getReturnType(),
4578         method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4579         prevMethod->getReturnTypeSourceRange().getBegin(),
4580         prevMethod->getReturnType(),
4581         prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4582   method->setReturnType(newReturnType);
4583 
4584   // Handle each of the parameters.
4585   unsigned numParams = method->param_size();
4586   unsigned numPrevParams = prevMethod->param_size();
4587   for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4588     ParmVarDecl *param = method->param_begin()[i];
4589     ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4590 
4591     // Merge nullability.
4592     QualType newParamType
4593       = mergeTypeNullabilityForRedecl(
4594           S, param->getLocation(), param->getType(),
4595           param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4596           prevParam->getLocation(), prevParam->getType(),
4597           prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4598     param->setType(newParamType);
4599   }
4600 }
4601 
4602 /// Verify that the method parameters/return value have types that are supported
4603 /// by the x86 target.
4604 static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4605                                           const ObjCMethodDecl *Method) {
4606   assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4607              llvm::Triple::x86 &&
4608          "x86-specific check invoked for a different target");
4609   SourceLocation Loc;
4610   QualType T;
4611   for (const ParmVarDecl *P : Method->parameters()) {
4612     if (P->getType()->isVectorType()) {
4613       Loc = P->getBeginLoc();
4614       T = P->getType();
4615       break;
4616     }
4617   }
4618   if (Loc.isInvalid()) {
4619     if (Method->getReturnType()->isVectorType()) {
4620       Loc = Method->getReturnTypeSourceRange().getBegin();
4621       T = Method->getReturnType();
4622     } else
4623       return;
4624   }
4625 
4626   // Vector parameters/return values are not supported by objc_msgSend on x86 in
4627   // iOS < 9 and macOS < 10.11.
4628   const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4629   VersionTuple AcceptedInVersion;
4630   if (Triple.getOS() == llvm::Triple::IOS)
4631     AcceptedInVersion = VersionTuple(/*Major=*/9);
4632   else if (Triple.isMacOSX())
4633     AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4634   else
4635     return;
4636   if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
4637       AcceptedInVersion)
4638     return;
4639   SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4640       << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4641                                                        : /*parameter*/ 0)
4642       << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4643 }
4644 
4645 static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4646   if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
4647       CD->hasAttr<ObjCDirectMembersAttr>()) {
4648     Method->addAttr(
4649         ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4650   }
4651 }
4652 
4653 static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl,
4654                                          ObjCMethodDecl *Method,
4655                                          ObjCImplDecl *ImpDecl = nullptr) {
4656   auto Sel = Method->getSelector();
4657   bool isInstance = Method->isInstanceMethod();
4658   bool diagnosed = false;
4659 
4660   auto diagClash = [&](const ObjCMethodDecl *IMD) {
4661     if (diagnosed || IMD->isImplicit())
4662       return;
4663     if (Method->isDirectMethod() || IMD->isDirectMethod()) {
4664       S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
4665           << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod()
4666           << Method->getDeclName();
4667       S.Diag(IMD->getLocation(), diag::note_previous_declaration);
4668       diagnosed = true;
4669     }
4670   };
4671 
4672   // Look for any other declaration of this method anywhere we can see in this
4673   // compilation unit.
4674   //
4675   // We do not use IDecl->lookupMethod() because we have specific needs:
4676   //
4677   // - we absolutely do not need to walk protocols, because
4678   //   diag::err_objc_direct_on_protocol has already been emitted
4679   //   during parsing if there's a conflict,
4680   //
4681   // - when we do not find a match in a given @interface container,
4682   //   we need to attempt looking it up in the @implementation block if the
4683   //   translation unit sees it to find more clashes.
4684 
4685   if (auto *IMD = IDecl->getMethod(Sel, isInstance))
4686     diagClash(IMD);
4687   else if (auto *Impl = IDecl->getImplementation())
4688     if (Impl != ImpDecl)
4689       if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
4690         diagClash(IMD);
4691 
4692   for (const auto *Cat : IDecl->visible_categories())
4693     if (auto *IMD = Cat->getMethod(Sel, isInstance))
4694       diagClash(IMD);
4695     else if (auto CatImpl = Cat->getImplementation())
4696       if (CatImpl != ImpDecl)
4697         if (auto *IMD = Cat->getMethod(Sel, isInstance))
4698           diagClash(IMD);
4699 }
4700 
4701 Decl *Sema::ActOnMethodDeclaration(
4702     Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4703     tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4704     ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4705     // optional arguments. The number of types/arguments is obtained
4706     // from the Sel.getNumArgs().
4707     ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4708     unsigned CNumArgs, // c-style args
4709     const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4710     bool isVariadic, bool MethodDefinition) {
4711   // Make sure we can establish a context for the method.
4712   if (!CurContext->isObjCContainer()) {
4713     Diag(MethodLoc, diag::err_missing_method_context);
4714     return nullptr;
4715   }
4716 
4717   Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
4718   QualType resultDeclType;
4719 
4720   bool HasRelatedResultType = false;
4721   TypeSourceInfo *ReturnTInfo = nullptr;
4722   if (ReturnType) {
4723     resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4724 
4725     if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4726       return nullptr;
4727 
4728     QualType bareResultType = resultDeclType;
4729     (void)AttributedType::stripOuterNullability(bareResultType);
4730     HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4731   } else { // get the type for "id".
4732     resultDeclType = Context.getObjCIdType();
4733     Diag(MethodLoc, diag::warn_missing_method_return_type)
4734       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4735   }
4736 
4737   ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4738       Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4739       MethodType == tok::minus, isVariadic,
4740       /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4741       /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4742       MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4743                                            : ObjCMethodDecl::Required,
4744       HasRelatedResultType);
4745 
4746   SmallVector<ParmVarDecl*, 16> Params;
4747 
4748   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4749     QualType ArgType;
4750     TypeSourceInfo *DI;
4751 
4752     if (!ArgInfo[i].Type) {
4753       ArgType = Context.getObjCIdType();
4754       DI = nullptr;
4755     } else {
4756       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4757     }
4758 
4759     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4760                    LookupOrdinaryName, forRedeclarationInCurContext());
4761     LookupName(R, S);
4762     if (R.isSingleResult()) {
4763       NamedDecl *PrevDecl = R.getFoundDecl();
4764       if (S->isDeclScope(PrevDecl)) {
4765         Diag(ArgInfo[i].NameLoc,
4766              (MethodDefinition ? diag::warn_method_param_redefinition
4767                                : diag::warn_method_param_declaration))
4768           << ArgInfo[i].Name;
4769         Diag(PrevDecl->getLocation(),
4770              diag::note_previous_declaration);
4771       }
4772     }
4773 
4774     SourceLocation StartLoc = DI
4775       ? DI->getTypeLoc().getBeginLoc()
4776       : ArgInfo[i].NameLoc;
4777 
4778     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4779                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
4780                                         ArgType, DI, SC_None);
4781 
4782     Param->setObjCMethodScopeInfo(i);
4783 
4784     Param->setObjCDeclQualifier(
4785       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4786 
4787     // Apply the attributes to the parameter.
4788     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4789     AddPragmaAttributes(TUScope, Param);
4790 
4791     if (Param->hasAttr<BlocksAttr>()) {
4792       Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4793       Param->setInvalidDecl();
4794     }
4795     S->AddDecl(Param);
4796     IdResolver.AddDecl(Param);
4797 
4798     Params.push_back(Param);
4799   }
4800 
4801   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4802     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4803     QualType ArgType = Param->getType();
4804     if (ArgType.isNull())
4805       ArgType = Context.getObjCIdType();
4806     else
4807       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4808       ArgType = Context.getAdjustedParameterType(ArgType);
4809 
4810     Param->setDeclContext(ObjCMethod);
4811     Params.push_back(Param);
4812   }
4813 
4814   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4815   ObjCMethod->setObjCDeclQualifier(
4816     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4817 
4818   ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4819   AddPragmaAttributes(TUScope, ObjCMethod);
4820 
4821   // Add the method now.
4822   const ObjCMethodDecl *PrevMethod = nullptr;
4823   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4824     if (MethodType == tok::minus) {
4825       PrevMethod = ImpDecl->getInstanceMethod(Sel);
4826       ImpDecl->addInstanceMethod(ObjCMethod);
4827     } else {
4828       PrevMethod = ImpDecl->getClassMethod(Sel);
4829       ImpDecl->addClassMethod(ObjCMethod);
4830     }
4831 
4832     // If this method overrides a previous @synthesize declaration,
4833     // register it with the property.  Linear search through all
4834     // properties here, because the autosynthesized stub hasn't been
4835     // made visible yet, so it can be overriden by a later
4836     // user-specified implementation.
4837     for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4838       if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4839         if (Setter->getSelector() == Sel &&
4840             Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4841           assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4842           PropertyImpl->setSetterMethodDecl(ObjCMethod);
4843         }
4844       if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4845         if (Getter->getSelector() == Sel &&
4846             Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4847           assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4848           PropertyImpl->setGetterMethodDecl(ObjCMethod);
4849           break;
4850         }
4851     }
4852 
4853     // A method is either tagged direct explicitly, or inherits it from its
4854     // canonical declaration.
4855     //
4856     // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4857     // because IDecl->lookupMethod() returns more possible matches than just
4858     // the canonical declaration.
4859     if (!ObjCMethod->isDirectMethod()) {
4860       const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4861       if (CanonicalMD->isDirectMethod()) {
4862         const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4863         ObjCMethod->addAttr(
4864             ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4865       }
4866     }
4867 
4868     // Merge information from the @interface declaration into the
4869     // @implementation.
4870     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4871       if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4872                                           ObjCMethod->isInstanceMethod())) {
4873         mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4874 
4875         // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4876         // in one of these places:
4877         //
4878         // (1) the canonical declaration in an @interface container paired
4879         //     with the ImplDecl,
4880         // (2) non canonical declarations in @interface not paired with the
4881         //     ImplDecl for the same Class,
4882         // (3) any superclass container.
4883         //
4884         // Direct methods only allow for canonical declarations in the matching
4885         // container (case 1).
4886         //
4887         // Direct methods overriding a superclass declaration (case 3) is
4888         // handled during overrides checks in CheckObjCMethodOverrides().
4889         //
4890         // We deal with same-class container mismatches (Case 2) here.
4891         if (IDecl == IMD->getClassInterface()) {
4892           auto diagContainerMismatch = [&] {
4893             int decl = 0, impl = 0;
4894 
4895             if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4896               decl = Cat->IsClassExtension() ? 1 : 2;
4897 
4898             if (isa<ObjCCategoryImplDecl>(ImpDecl))
4899               impl = 1 + (decl != 0);
4900 
4901             Diag(ObjCMethod->getLocation(),
4902                  diag::err_objc_direct_impl_decl_mismatch)
4903                 << decl << impl;
4904             Diag(IMD->getLocation(), diag::note_previous_declaration);
4905           };
4906 
4907           if (ObjCMethod->isDirectMethod()) {
4908             const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4909             if (ObjCMethod->getCanonicalDecl() != IMD) {
4910               diagContainerMismatch();
4911             } else if (!IMD->isDirectMethod()) {
4912               Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4913               Diag(IMD->getLocation(), diag::note_previous_declaration);
4914             }
4915           } else if (IMD->isDirectMethod()) {
4916             const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4917             if (ObjCMethod->getCanonicalDecl() != IMD) {
4918               diagContainerMismatch();
4919             } else {
4920               ObjCMethod->addAttr(
4921                   ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4922             }
4923           }
4924         }
4925 
4926         // Warn about defining -dealloc in a category.
4927         if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4928             ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4929           Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4930             << ObjCMethod->getDeclName();
4931         }
4932       } else {
4933         mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4934         checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl);
4935       }
4936 
4937       // Warn if a method declared in a protocol to which a category or
4938       // extension conforms is non-escaping and the implementation's method is
4939       // escaping.
4940       for (auto *C : IDecl->visible_categories())
4941         for (auto &P : C->protocols())
4942           if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4943                                           ObjCMethod->isInstanceMethod())) {
4944             assert(ObjCMethod->parameters().size() ==
4945                        IMD->parameters().size() &&
4946                    "Methods have different number of parameters");
4947             auto OI = IMD->param_begin(), OE = IMD->param_end();
4948             auto NI = ObjCMethod->param_begin();
4949             for (; OI != OE; ++OI, ++NI)
4950               diagnoseNoescape(*NI, *OI, C, P, *this);
4951           }
4952     }
4953   } else {
4954     if (!isa<ObjCProtocolDecl>(ClassDecl)) {
4955       mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4956 
4957       ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4958       if (!IDecl)
4959         IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
4960       // For valid code, we should always know the primary interface
4961       // declaration by now, however for invalid code we'll keep parsing
4962       // but we won't find the primary interface and IDecl will be nil.
4963       if (IDecl)
4964         checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod);
4965     }
4966 
4967     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4968   }
4969 
4970   if (PrevMethod) {
4971     // You can never have two method definitions with the same name.
4972     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4973       << ObjCMethod->getDeclName();
4974     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4975     ObjCMethod->setInvalidDecl();
4976     return ObjCMethod;
4977   }
4978 
4979   // If this Objective-C method does not have a related result type, but we
4980   // are allowed to infer related result types, try to do so based on the
4981   // method family.
4982   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4983   if (!CurrentClass) {
4984     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4985       CurrentClass = Cat->getClassInterface();
4986     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4987       CurrentClass = Impl->getClassInterface();
4988     else if (ObjCCategoryImplDecl *CatImpl
4989                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4990       CurrentClass = CatImpl->getClassInterface();
4991   }
4992 
4993   ResultTypeCompatibilityKind RTC
4994     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
4995 
4996   CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
4997 
4998   bool ARCError = false;
4999   if (getLangOpts().ObjCAutoRefCount)
5000     ARCError = CheckARCMethodDecl(ObjCMethod);
5001 
5002   // Infer the related result type when possible.
5003   if (!ARCError && RTC == Sema::RTC_Compatible &&
5004       !ObjCMethod->hasRelatedResultType() &&
5005       LangOpts.ObjCInferRelatedResultType) {
5006     bool InferRelatedResultType = false;
5007     switch (ObjCMethod->getMethodFamily()) {
5008     case OMF_None:
5009     case OMF_copy:
5010     case OMF_dealloc:
5011     case OMF_finalize:
5012     case OMF_mutableCopy:
5013     case OMF_release:
5014     case OMF_retainCount:
5015     case OMF_initialize:
5016     case OMF_performSelector:
5017       break;
5018 
5019     case OMF_alloc:
5020     case OMF_new:
5021         InferRelatedResultType = ObjCMethod->isClassMethod();
5022       break;
5023 
5024     case OMF_init:
5025     case OMF_autorelease:
5026     case OMF_retain:
5027     case OMF_self:
5028       InferRelatedResultType = ObjCMethod->isInstanceMethod();
5029       break;
5030     }
5031 
5032     if (InferRelatedResultType &&
5033         !ObjCMethod->getReturnType()->isObjCIndependentClassType())
5034       ObjCMethod->setRelatedResultType();
5035   }
5036 
5037   if (MethodDefinition &&
5038       Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5039     checkObjCMethodX86VectorTypes(*this, ObjCMethod);
5040 
5041   // + load method cannot have availability attributes. It get called on
5042   // startup, so it has to have the availability of the deployment target.
5043   if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
5044     if (ObjCMethod->isClassMethod() &&
5045         ObjCMethod->getSelector().getAsString() == "load") {
5046       Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
5047           << 0;
5048       ObjCMethod->dropAttr<AvailabilityAttr>();
5049     }
5050   }
5051 
5052   // Insert the invisible arguments, self and _cmd!
5053   ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
5054 
5055   ActOnDocumentableDecl(ObjCMethod);
5056 
5057   return ObjCMethod;
5058 }
5059 
5060 bool Sema::CheckObjCDeclScope(Decl *D) {
5061   // Following is also an error. But it is caused by a missing @end
5062   // and diagnostic is issued elsewhere.
5063   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
5064     return false;
5065 
5066   // If we switched context to translation unit while we are still lexically in
5067   // an objc container, it means the parser missed emitting an error.
5068   if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
5069     return false;
5070 
5071   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
5072   D->setInvalidDecl();
5073 
5074   return true;
5075 }
5076 
5077 /// Called whenever \@defs(ClassName) is encountered in the source.  Inserts the
5078 /// instance variables of ClassName into Decls.
5079 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
5080                      IdentifierInfo *ClassName,
5081                      SmallVectorImpl<Decl*> &Decls) {
5082   // Check that ClassName is a valid class
5083   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
5084   if (!Class) {
5085     Diag(DeclStart, diag::err_undef_interface) << ClassName;
5086     return;
5087   }
5088   if (LangOpts.ObjCRuntime.isNonFragile()) {
5089     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
5090     return;
5091   }
5092 
5093   // Collect the instance variables
5094   SmallVector<const ObjCIvarDecl*, 32> Ivars;
5095   Context.DeepCollectObjCIvars(Class, true, Ivars);
5096   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
5097   for (unsigned i = 0; i < Ivars.size(); i++) {
5098     const FieldDecl* ID = Ivars[i];
5099     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
5100     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
5101                                            /*FIXME: StartL=*/ID->getLocation(),
5102                                            ID->getLocation(),
5103                                            ID->getIdentifier(), ID->getType(),
5104                                            ID->getBitWidth());
5105     Decls.push_back(FD);
5106   }
5107 
5108   // Introduce all of these fields into the appropriate scope.
5109   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
5110        D != Decls.end(); ++D) {
5111     FieldDecl *FD = cast<FieldDecl>(*D);
5112     if (getLangOpts().CPlusPlus)
5113       PushOnScopeChains(FD, S);
5114     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
5115       Record->addDecl(FD);
5116   }
5117 }
5118 
5119 /// Build a type-check a new Objective-C exception variable declaration.
5120 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
5121                                       SourceLocation StartLoc,
5122                                       SourceLocation IdLoc,
5123                                       IdentifierInfo *Id,
5124                                       bool Invalid) {
5125   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5126   // duration shall not be qualified by an address-space qualifier."
5127   // Since all parameters have automatic store duration, they can not have
5128   // an address space.
5129   if (T.getAddressSpace() != LangAS::Default) {
5130     Diag(IdLoc, diag::err_arg_with_address_space);
5131     Invalid = true;
5132   }
5133 
5134   // An @catch parameter must be an unqualified object pointer type;
5135   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
5136   if (Invalid) {
5137     // Don't do any further checking.
5138   } else if (T->isDependentType()) {
5139     // Okay: we don't know what this type will instantiate to.
5140   } else if (T->isObjCQualifiedIdType()) {
5141     Invalid = true;
5142     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
5143   } else if (T->isObjCIdType()) {
5144     // Okay: we don't know what this type will instantiate to.
5145   } else if (!T->isObjCObjectPointerType()) {
5146     Invalid = true;
5147     Diag(IdLoc, diag::err_catch_param_not_objc_type);
5148   } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) {
5149     Invalid = true;
5150     Diag(IdLoc, diag::err_catch_param_not_objc_type);
5151   }
5152 
5153   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
5154                                  T, TInfo, SC_None);
5155   New->setExceptionVariable(true);
5156 
5157   // In ARC, infer 'retaining' for variables of retainable type.
5158   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
5159     Invalid = true;
5160 
5161   if (Invalid)
5162     New->setInvalidDecl();
5163   return New;
5164 }
5165 
5166 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
5167   const DeclSpec &DS = D.getDeclSpec();
5168 
5169   // We allow the "register" storage class on exception variables because
5170   // GCC did, but we drop it completely. Any other storage class is an error.
5171   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
5172     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
5173       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
5174   } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5175     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
5176       << DeclSpec::getSpecifierName(SCS);
5177   }
5178   if (DS.isInlineSpecified())
5179     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5180         << getLangOpts().CPlusPlus17;
5181   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
5182     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5183          diag::err_invalid_thread)
5184      << DeclSpec::getSpecifierName(TSCS);
5185   D.getMutableDeclSpec().ClearStorageClassSpecs();
5186 
5187   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5188 
5189   // Check that there are no default arguments inside the type of this
5190   // exception object (C++ only).
5191   if (getLangOpts().CPlusPlus)
5192     CheckExtraCXXDefaultArguments(D);
5193 
5194   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5195   QualType ExceptionType = TInfo->getType();
5196 
5197   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
5198                                         D.getSourceRange().getBegin(),
5199                                         D.getIdentifierLoc(),
5200                                         D.getIdentifier(),
5201                                         D.isInvalidType());
5202 
5203   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5204   if (D.getCXXScopeSpec().isSet()) {
5205     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
5206       << D.getCXXScopeSpec().getRange();
5207     New->setInvalidDecl();
5208   }
5209 
5210   // Add the parameter declaration into this scope.
5211   S->AddDecl(New);
5212   if (D.getIdentifier())
5213     IdResolver.AddDecl(New);
5214 
5215   ProcessDeclAttributes(S, New, D);
5216 
5217   if (New->hasAttr<BlocksAttr>())
5218     Diag(New->getLocation(), diag::err_block_on_nonlocal);
5219   return New;
5220 }
5221 
5222 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
5223 /// initialization.
5224 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
5225                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
5226   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
5227        Iv= Iv->getNextIvar()) {
5228     QualType QT = Context.getBaseElementType(Iv->getType());
5229     if (QT->isRecordType())
5230       Ivars.push_back(Iv);
5231   }
5232 }
5233 
5234 void Sema::DiagnoseUseOfUnimplementedSelectors() {
5235   // Load referenced selectors from the external source.
5236   if (ExternalSource) {
5237     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
5238     ExternalSource->ReadReferencedSelectors(Sels);
5239     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
5240       ReferencedSelectors[Sels[I].first] = Sels[I].second;
5241   }
5242 
5243   // Warning will be issued only when selector table is
5244   // generated (which means there is at lease one implementation
5245   // in the TU). This is to match gcc's behavior.
5246   if (ReferencedSelectors.empty() ||
5247       !Context.AnyObjCImplementation())
5248     return;
5249   for (auto &SelectorAndLocation : ReferencedSelectors) {
5250     Selector Sel = SelectorAndLocation.first;
5251     SourceLocation Loc = SelectorAndLocation.second;
5252     if (!LookupImplementedMethodInGlobalPool(Sel))
5253       Diag(Loc, diag::warn_unimplemented_selector) << Sel;
5254   }
5255 }
5256 
5257 ObjCIvarDecl *
5258 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
5259                                      const ObjCPropertyDecl *&PDecl) const {
5260   if (Method->isClassMethod())
5261     return nullptr;
5262   const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
5263   if (!IDecl)
5264     return nullptr;
5265   Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
5266                                /*shallowCategoryLookup=*/false,
5267                                /*followSuper=*/false);
5268   if (!Method || !Method->isPropertyAccessor())
5269     return nullptr;
5270   if ((PDecl = Method->findPropertyDecl()))
5271     if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5272       // property backing ivar must belong to property's class
5273       // or be a private ivar in class's implementation.
5274       // FIXME. fix the const-ness issue.
5275       IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5276                                                         IV->getIdentifier());
5277       return IV;
5278     }
5279   return nullptr;
5280 }
5281 
5282 namespace {
5283   /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
5284   /// accessor references the backing ivar.
5285   class UnusedBackingIvarChecker :
5286       public RecursiveASTVisitor<UnusedBackingIvarChecker> {
5287   public:
5288     Sema &S;
5289     const ObjCMethodDecl *Method;
5290     const ObjCIvarDecl *IvarD;
5291     bool AccessedIvar;
5292     bool InvokedSelfMethod;
5293 
5294     UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5295                              const ObjCIvarDecl *IvarD)
5296       : S(S), Method(Method), IvarD(IvarD),
5297         AccessedIvar(false), InvokedSelfMethod(false) {
5298       assert(IvarD);
5299     }
5300 
5301     bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5302       if (E->getDecl() == IvarD) {
5303         AccessedIvar = true;
5304         return false;
5305       }
5306       return true;
5307     }
5308 
5309     bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5310       if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5311           S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5312         InvokedSelfMethod = true;
5313       }
5314       return true;
5315     }
5316   };
5317 } // end anonymous namespace
5318 
5319 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5320                                           const ObjCImplementationDecl *ImplD) {
5321   if (S->hasUnrecoverableErrorOccurred())
5322     return;
5323 
5324   for (const auto *CurMethod : ImplD->instance_methods()) {
5325     unsigned DIAG = diag::warn_unused_property_backing_ivar;
5326     SourceLocation Loc = CurMethod->getLocation();
5327     if (Diags.isIgnored(DIAG, Loc))
5328       continue;
5329 
5330     const ObjCPropertyDecl *PDecl;
5331     const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5332     if (!IV)
5333       continue;
5334 
5335     if (CurMethod->isSynthesizedAccessorStub())
5336       continue;
5337 
5338     UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5339     Checker.TraverseStmt(CurMethod->getBody());
5340     if (Checker.AccessedIvar)
5341       continue;
5342 
5343     // Do not issue this warning if backing ivar is used somewhere and accessor
5344     // implementation makes a self call. This is to prevent false positive in
5345     // cases where the ivar is accessed by another method that the accessor
5346     // delegates to.
5347     if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5348       Diag(Loc, DIAG) << IV;
5349       Diag(PDecl->getLocation(), diag::note_property_declare);
5350     }
5351   }
5352 }
5353