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