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