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