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