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