Revert "[InstCombine] Support gep nuw in icmp folds" (#118698)
[llvm-project.git] / clang / lib / Sema / SemaDeclObjC.cpp
blob6e6174ba17c5575da7267ea1b96eda46a3adfc04
1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for Objective C declarations.
11 //===----------------------------------------------------------------------===//
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DynamicRecursiveASTVisitor.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/DelayedDiagnostic.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "clang/Sema/SemaObjC.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/DenseSet.h"
33 using namespace clang;
35 /// Check whether the given method, which must be in the 'init'
36 /// family, is a valid member of that family.
37 ///
38 /// \param receiverTypeIfCall - if null, check this as if declaring it;
39 /// if non-null, check this as if making a call to it with the given
40 /// receiver type
41 ///
42 /// \return true to indicate that there was an error and appropriate
43 /// actions were taken
44 bool SemaObjC::checkInitMethod(ObjCMethodDecl *method,
45 QualType receiverTypeIfCall) {
46 ASTContext &Context = getASTContext();
47 if (method->isInvalidDecl()) return true;
49 // This castAs is safe: methods that don't return an object
50 // pointer won't be inferred as inits and will reject an explicit
51 // objc_method_family(init).
53 // We ignore protocols here. Should we? What about Class?
55 const ObjCObjectType *result =
56 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
58 if (result->isObjCId()) {
59 return false;
60 } else if (result->isObjCClass()) {
61 // fall through: always an error
62 } else {
63 ObjCInterfaceDecl *resultClass = result->getInterface();
64 assert(resultClass && "unexpected object type!");
66 // It's okay for the result type to still be a forward declaration
67 // if we're checking an interface declaration.
68 if (!resultClass->hasDefinition()) {
69 if (receiverTypeIfCall.isNull() &&
70 !isa<ObjCImplementationDecl>(method->getDeclContext()))
71 return false;
73 // Otherwise, we try to compare class types.
74 } else {
75 // If this method was declared in a protocol, we can't check
76 // anything unless we have a receiver type that's an interface.
77 const ObjCInterfaceDecl *receiverClass = nullptr;
78 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
79 if (receiverTypeIfCall.isNull())
80 return false;
82 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
83 ->getInterfaceDecl();
85 // This can be null for calls to e.g. id<Foo>.
86 if (!receiverClass) return false;
87 } else {
88 receiverClass = method->getClassInterface();
89 assert(receiverClass && "method not associated with a class!");
92 // If either class is a subclass of the other, it's fine.
93 if (receiverClass->isSuperClassOf(resultClass) ||
94 resultClass->isSuperClassOf(receiverClass))
95 return false;
99 SourceLocation loc = method->getLocation();
101 // If we're in a system header, and this is not a call, just make
102 // the method unusable.
103 if (receiverTypeIfCall.isNull() &&
104 SemaRef.getSourceManager().isInSystemHeader(loc)) {
105 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
106 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
107 return true;
110 // Otherwise, it's an error.
111 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
112 method->setInvalidDecl();
113 return true;
116 /// Issue a warning if the parameter of the overridden method is non-escaping
117 /// but the parameter of the overriding method is not.
118 static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
119 Sema &S) {
120 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
121 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
122 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
123 return false;
126 return true;
129 /// Produce additional diagnostics if a category conforms to a protocol that
130 /// defines a method taking a non-escaping parameter.
131 static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
132 const ObjCCategoryDecl *CD,
133 const ObjCProtocolDecl *PD, Sema &S) {
134 if (!diagnoseNoescape(NewD, OldD, S))
135 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
136 << CD->IsClassExtension() << PD
137 << cast<ObjCMethodDecl>(NewD->getDeclContext());
140 void SemaObjC::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
141 const ObjCMethodDecl *Overridden) {
142 ASTContext &Context = getASTContext();
143 if (Overridden->hasRelatedResultType() &&
144 !NewMethod->hasRelatedResultType()) {
145 // This can only happen when the method follows a naming convention that
146 // implies a related result type, and the original (overridden) method has
147 // a suitable return type, but the new (overriding) method does not have
148 // a suitable return type.
149 QualType ResultType = NewMethod->getReturnType();
150 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
152 // Figure out which class this method is part of, if any.
153 ObjCInterfaceDecl *CurrentClass
154 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
155 if (!CurrentClass) {
156 DeclContext *DC = NewMethod->getDeclContext();
157 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
158 CurrentClass = Cat->getClassInterface();
159 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
160 CurrentClass = Impl->getClassInterface();
161 else if (ObjCCategoryImplDecl *CatImpl
162 = dyn_cast<ObjCCategoryImplDecl>(DC))
163 CurrentClass = CatImpl->getClassInterface();
166 if (CurrentClass) {
167 Diag(NewMethod->getLocation(),
168 diag::warn_related_result_type_compatibility_class)
169 << Context.getObjCInterfaceType(CurrentClass)
170 << ResultType
171 << ResultTypeRange;
172 } else {
173 Diag(NewMethod->getLocation(),
174 diag::warn_related_result_type_compatibility_protocol)
175 << ResultType
176 << ResultTypeRange;
179 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
180 Diag(Overridden->getLocation(),
181 diag::note_related_result_type_family)
182 << /*overridden method*/ 0
183 << Family;
184 else
185 Diag(Overridden->getLocation(),
186 diag::note_related_result_type_overridden);
189 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
190 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
191 Diag(NewMethod->getLocation(),
192 getLangOpts().ObjCAutoRefCount
193 ? diag::err_nsreturns_retained_attribute_mismatch
194 : diag::warn_nsreturns_retained_attribute_mismatch)
195 << 1;
196 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
198 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
199 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
200 Diag(NewMethod->getLocation(),
201 getLangOpts().ObjCAutoRefCount
202 ? diag::err_nsreturns_retained_attribute_mismatch
203 : diag::warn_nsreturns_retained_attribute_mismatch)
204 << 0;
205 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
208 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
209 oe = Overridden->param_end();
210 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
211 ne = NewMethod->param_end();
212 ni != ne && oi != oe; ++ni, ++oi) {
213 const ParmVarDecl *oldDecl = (*oi);
214 ParmVarDecl *newDecl = (*ni);
215 if (newDecl->hasAttr<NSConsumedAttr>() !=
216 oldDecl->hasAttr<NSConsumedAttr>()) {
217 Diag(newDecl->getLocation(),
218 getLangOpts().ObjCAutoRefCount
219 ? diag::err_nsconsumed_attribute_mismatch
220 : diag::warn_nsconsumed_attribute_mismatch);
221 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
224 diagnoseNoescape(newDecl, oldDecl, SemaRef);
228 /// Check a method declaration for compatibility with the Objective-C
229 /// ARC conventions.
230 bool SemaObjC::CheckARCMethodDecl(ObjCMethodDecl *method) {
231 ASTContext &Context = getASTContext();
232 ObjCMethodFamily family = method->getMethodFamily();
233 switch (family) {
234 case OMF_None:
235 case OMF_finalize:
236 case OMF_retain:
237 case OMF_release:
238 case OMF_autorelease:
239 case OMF_retainCount:
240 case OMF_self:
241 case OMF_initialize:
242 case OMF_performSelector:
243 return false;
245 case OMF_dealloc:
246 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
247 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
248 if (ResultTypeRange.isInvalid())
249 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
250 << method->getReturnType()
251 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
252 else
253 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
254 << method->getReturnType()
255 << FixItHint::CreateReplacement(ResultTypeRange, "void");
256 return true;
258 return false;
260 case OMF_init:
261 // If the method doesn't obey the init rules, don't bother annotating it.
262 if (checkInitMethod(method, QualType()))
263 return true;
265 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
267 // Don't add a second copy of this attribute, but otherwise don't
268 // let it be suppressed.
269 if (method->hasAttr<NSReturnsRetainedAttr>())
270 return false;
271 break;
273 case OMF_alloc:
274 case OMF_copy:
275 case OMF_mutableCopy:
276 case OMF_new:
277 if (method->hasAttr<NSReturnsRetainedAttr>() ||
278 method->hasAttr<NSReturnsNotRetainedAttr>() ||
279 method->hasAttr<NSReturnsAutoreleasedAttr>())
280 return false;
281 break;
284 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
285 return false;
288 static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
289 SourceLocation ImplLoc) {
290 if (!ND)
291 return;
292 bool IsCategory = false;
293 StringRef RealizedPlatform;
294 AvailabilityResult Availability = ND->getAvailability(
295 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
296 &RealizedPlatform);
297 if (Availability != AR_Deprecated) {
298 if (isa<ObjCMethodDecl>(ND)) {
299 if (Availability != AR_Unavailable)
300 return;
301 if (RealizedPlatform.empty())
302 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
303 // Warn about implementing unavailable methods, unless the unavailable
304 // is for an app extension.
305 if (RealizedPlatform.ends_with("_app_extension"))
306 return;
307 S.Diag(ImplLoc, diag::warn_unavailable_def);
308 S.Diag(ND->getLocation(), diag::note_method_declared_at)
309 << ND->getDeclName();
310 return;
312 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
313 if (!CD->getClassInterface()->isDeprecated())
314 return;
315 ND = CD->getClassInterface();
316 IsCategory = true;
317 } else
318 return;
320 S.Diag(ImplLoc, diag::warn_deprecated_def)
321 << (isa<ObjCMethodDecl>(ND)
322 ? /*Method*/ 0
323 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
324 : /*Class*/ 1);
325 if (isa<ObjCMethodDecl>(ND))
326 S.Diag(ND->getLocation(), diag::note_method_declared_at)
327 << ND->getDeclName();
328 else
329 S.Diag(ND->getLocation(), diag::note_previous_decl)
330 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
333 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
334 /// pool.
335 void SemaObjC::AddAnyMethodToGlobalPool(Decl *D) {
336 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
338 // If we don't have a valid method decl, simply return.
339 if (!MDecl)
340 return;
341 if (MDecl->isInstanceMethod())
342 AddInstanceMethodToGlobalPool(MDecl, true);
343 else
344 AddFactoryMethodToGlobalPool(MDecl, true);
347 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
348 /// has explicit ownership attribute; false otherwise.
349 static bool
350 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
351 QualType T = Param->getType();
353 if (const PointerType *PT = T->getAs<PointerType>()) {
354 T = PT->getPointeeType();
355 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
356 T = RT->getPointeeType();
357 } else {
358 return true;
361 // If we have a lifetime qualifier, but it's local, we must have
362 // inferred it. So, it is implicit.
363 return !T.getLocalQualifiers().hasObjCLifetime();
366 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
367 /// and user declared, in the method definition's AST.
368 void SemaObjC::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
369 ASTContext &Context = getASTContext();
370 SemaRef.ImplicitlyRetainedSelfLocs.clear();
371 assert((SemaRef.getCurMethodDecl() == nullptr) && "Methodparsing confused");
372 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
374 SemaRef.PushExpressionEvaluationContext(
375 SemaRef.ExprEvalContexts.back().Context);
377 // If we don't have a valid method decl, simply return.
378 if (!MDecl)
379 return;
381 QualType ResultType = MDecl->getReturnType();
382 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
383 !MDecl->isInvalidDecl() &&
384 SemaRef.RequireCompleteType(MDecl->getLocation(), ResultType,
385 diag::err_func_def_incomplete_result))
386 MDecl->setInvalidDecl();
388 // Allow all of Sema to see that we are entering a method definition.
389 SemaRef.PushDeclContext(FnBodyScope, MDecl);
390 SemaRef.PushFunctionScope();
392 // Create Decl objects for each parameter, entrring them in the scope for
393 // binding to their use.
395 // Insert the invisible arguments, self and _cmd!
396 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
398 SemaRef.PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
399 SemaRef.PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
401 // The ObjC parser requires parameter names so there's no need to check.
402 SemaRef.CheckParmsForFunctionDef(MDecl->parameters(),
403 /*CheckParameterNames=*/false);
405 // Introduce all of the other parameters into this scope.
406 for (auto *Param : MDecl->parameters()) {
407 if (!Param->isInvalidDecl() && getLangOpts().ObjCAutoRefCount &&
408 !HasExplicitOwnershipAttr(SemaRef, Param))
409 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
410 Param->getType();
412 if (Param->getIdentifier())
413 SemaRef.PushOnScopeChains(Param, FnBodyScope);
416 // In ARC, disallow definition of retain/release/autorelease/retainCount
417 if (getLangOpts().ObjCAutoRefCount) {
418 switch (MDecl->getMethodFamily()) {
419 case OMF_retain:
420 case OMF_retainCount:
421 case OMF_release:
422 case OMF_autorelease:
423 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
424 << 0 << MDecl->getSelector();
425 break;
427 case OMF_None:
428 case OMF_dealloc:
429 case OMF_finalize:
430 case OMF_alloc:
431 case OMF_init:
432 case OMF_mutableCopy:
433 case OMF_copy:
434 case OMF_new:
435 case OMF_self:
436 case OMF_initialize:
437 case OMF_performSelector:
438 break;
442 // Warn on deprecated methods under -Wdeprecated-implementations,
443 // and prepare for warning on missing super calls.
444 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
445 ObjCMethodDecl *IMD =
446 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
448 if (IMD) {
449 ObjCImplDecl *ImplDeclOfMethodDef =
450 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
451 ObjCContainerDecl *ContDeclOfMethodDecl =
452 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
453 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
454 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
455 ImplDeclOfMethodDecl = OID->getImplementation();
456 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
457 if (CD->IsClassExtension()) {
458 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
459 ImplDeclOfMethodDecl = OID->getImplementation();
460 } else
461 ImplDeclOfMethodDecl = CD->getImplementation();
463 // No need to issue deprecated warning if deprecated mehod in class/category
464 // is being implemented in its own implementation (no overriding is involved).
465 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
466 DiagnoseObjCImplementedDeprecations(SemaRef, IMD, MDecl->getLocation());
469 if (MDecl->getMethodFamily() == OMF_init) {
470 if (MDecl->isDesignatedInitializerForTheInterface()) {
471 SemaRef.getCurFunction()->ObjCIsDesignatedInit = true;
472 SemaRef.getCurFunction()->ObjCWarnForNoDesignatedInitChain =
473 IC->getSuperClass() != nullptr;
474 } else if (IC->hasDesignatedInitializers()) {
475 SemaRef.getCurFunction()->ObjCIsSecondaryInit = true;
476 SemaRef.getCurFunction()->ObjCWarnForNoInitDelegation = true;
480 // If this is "dealloc" or "finalize", set some bit here.
481 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
482 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
483 // Only do this if the current class actually has a superclass.
484 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
485 ObjCMethodFamily Family = MDecl->getMethodFamily();
486 if (Family == OMF_dealloc) {
487 if (!(getLangOpts().ObjCAutoRefCount ||
488 getLangOpts().getGC() == LangOptions::GCOnly))
489 SemaRef.getCurFunction()->ObjCShouldCallSuper = true;
491 } else if (Family == OMF_finalize) {
492 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
493 SemaRef.getCurFunction()->ObjCShouldCallSuper = true;
495 } else {
496 const ObjCMethodDecl *SuperMethod =
497 SuperClass->lookupMethod(MDecl->getSelector(),
498 MDecl->isInstanceMethod());
499 SemaRef.getCurFunction()->ObjCShouldCallSuper =
500 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
505 // Some function attributes (like OptimizeNoneAttr) need actions before
506 // parsing body started.
507 SemaRef.applyFunctionAttributesBeforeParsingBody(D);
510 namespace {
512 // Callback to only accept typo corrections that are Objective-C classes.
513 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
514 // function will reject corrections to that class.
515 class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
516 public:
517 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
518 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
519 : CurrentIDecl(IDecl) {}
521 bool ValidateCandidate(const TypoCorrection &candidate) override {
522 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
523 return ID && !declaresSameEntity(ID, CurrentIDecl);
526 std::unique_ptr<CorrectionCandidateCallback> clone() override {
527 return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
530 private:
531 ObjCInterfaceDecl *CurrentIDecl;
534 } // end anonymous namespace
536 static void diagnoseUseOfProtocols(Sema &TheSema,
537 ObjCContainerDecl *CD,
538 ObjCProtocolDecl *const *ProtoRefs,
539 unsigned NumProtoRefs,
540 const SourceLocation *ProtoLocs) {
541 assert(ProtoRefs);
542 // Diagnose availability in the context of the ObjC container.
543 Sema::ContextRAII SavedContext(TheSema, CD);
544 for (unsigned i = 0; i < NumProtoRefs; ++i) {
545 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
546 /*UnknownObjCClass=*/nullptr,
547 /*ObjCPropertyAccess=*/false,
548 /*AvoidPartialAvailabilityChecks=*/true);
552 void SemaObjC::ActOnSuperClassOfClassInterface(
553 Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl,
554 IdentifierInfo *ClassName, SourceLocation ClassLoc,
555 IdentifierInfo *SuperName, SourceLocation SuperLoc,
556 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange) {
557 ASTContext &Context = getASTContext();
558 // Check if a different kind of symbol declared in this scope.
559 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
560 SemaRef.TUScope, SuperName, SuperLoc, Sema::LookupOrdinaryName);
562 if (!PrevDecl) {
563 // Try to correct for a typo in the superclass name without correcting
564 // to the class we're defining.
565 ObjCInterfaceValidatorCCC CCC(IDecl);
566 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
567 DeclarationNameInfo(SuperName, SuperLoc), Sema::LookupOrdinaryName,
568 SemaRef.TUScope, nullptr, CCC, Sema::CTK_ErrorRecovery)) {
569 SemaRef.diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
570 << SuperName << ClassName);
571 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
575 if (declaresSameEntity(PrevDecl, IDecl)) {
576 Diag(SuperLoc, diag::err_recursive_superclass)
577 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
578 IDecl->setEndOfDefinitionLoc(ClassLoc);
579 } else {
580 ObjCInterfaceDecl *SuperClassDecl =
581 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
582 QualType SuperClassType;
584 // Diagnose classes that inherit from deprecated classes.
585 if (SuperClassDecl) {
586 (void)SemaRef.DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
587 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
590 if (PrevDecl && !SuperClassDecl) {
591 // The previous declaration was not a class decl. Check if we have a
592 // typedef. If we do, get the underlying class type.
593 if (const TypedefNameDecl *TDecl =
594 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
595 QualType T = TDecl->getUnderlyingType();
596 if (T->isObjCObjectType()) {
597 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
598 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
599 SuperClassType = Context.getTypeDeclType(TDecl);
601 // This handles the following case:
602 // @interface NewI @end
603 // typedef NewI DeprI __attribute__((deprecated("blah")))
604 // @interface SI : DeprI /* warn here */ @end
605 (void)SemaRef.DiagnoseUseOfDecl(
606 const_cast<TypedefNameDecl *>(TDecl), SuperLoc);
611 // This handles the following case:
613 // typedef int SuperClass;
614 // @interface MyClass : SuperClass {} @end
616 if (!SuperClassDecl) {
617 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
618 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
622 if (!isa_and_nonnull<TypedefNameDecl>(PrevDecl)) {
623 if (!SuperClassDecl)
624 Diag(SuperLoc, diag::err_undef_superclass)
625 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
626 else if (SemaRef.RequireCompleteType(
627 SuperLoc, SuperClassType, diag::err_forward_superclass,
628 SuperClassDecl->getDeclName(), ClassName,
629 SourceRange(AtInterfaceLoc, ClassLoc))) {
630 SuperClassDecl = nullptr;
631 SuperClassType = QualType();
635 if (SuperClassType.isNull()) {
636 assert(!SuperClassDecl && "Failed to set SuperClassType?");
637 return;
640 // Handle type arguments on the superclass.
641 TypeSourceInfo *SuperClassTInfo = nullptr;
642 if (!SuperTypeArgs.empty()) {
643 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
644 S, SuperLoc, SemaRef.CreateParsedType(SuperClassType, nullptr),
645 SuperTypeArgsRange.getBegin(), SuperTypeArgs,
646 SuperTypeArgsRange.getEnd(), SourceLocation(), {}, {},
647 SourceLocation());
648 if (!fullSuperClassType.isUsable())
649 return;
651 SuperClassType =
652 SemaRef.GetTypeFromParser(fullSuperClassType.get(), &SuperClassTInfo);
655 if (!SuperClassTInfo) {
656 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
657 SuperLoc);
660 IDecl->setSuperClass(SuperClassTInfo);
661 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
665 DeclResult SemaObjC::actOnObjCTypeParam(
666 Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc,
667 unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc,
668 SourceLocation colonLoc, ParsedType parsedTypeBound) {
669 ASTContext &Context = getASTContext();
670 // If there was an explicitly-provided type bound, check it.
671 TypeSourceInfo *typeBoundInfo = nullptr;
672 if (parsedTypeBound) {
673 // The type bound can be any Objective-C pointer type.
674 QualType typeBound =
675 SemaRef.GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
676 if (typeBound->isObjCObjectPointerType()) {
677 // okay
678 } else if (typeBound->isObjCObjectType()) {
679 // The user forgot the * on an Objective-C pointer type, e.g.,
680 // "T : NSView".
681 SourceLocation starLoc =
682 SemaRef.getLocForEndOfToken(typeBoundInfo->getTypeLoc().getEndLoc());
683 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
684 diag::err_objc_type_param_bound_missing_pointer)
685 << typeBound << paramName
686 << FixItHint::CreateInsertion(starLoc, " *");
688 // Create a new type location builder so we can update the type
689 // location information we have.
690 TypeLocBuilder builder;
691 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
693 // Create the Objective-C pointer type.
694 typeBound = Context.getObjCObjectPointerType(typeBound);
695 ObjCObjectPointerTypeLoc newT
696 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
697 newT.setStarLoc(starLoc);
699 // Form the new type source information.
700 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
701 } else {
702 // Not a valid type bound.
703 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
704 diag::err_objc_type_param_bound_nonobject)
705 << typeBound << paramName;
707 // Forget the bound; we'll default to id later.
708 typeBoundInfo = nullptr;
711 // Type bounds cannot have qualifiers (even indirectly) or explicit
712 // nullability.
713 if (typeBoundInfo) {
714 QualType typeBound = typeBoundInfo->getType();
715 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
716 if (qual || typeBound.hasQualifiers()) {
717 bool diagnosed = false;
718 SourceRange rangeToRemove;
719 if (qual) {
720 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
721 rangeToRemove = attr.getLocalSourceRange();
722 if (attr.getTypePtr()->getImmediateNullability()) {
723 Diag(attr.getBeginLoc(),
724 diag::err_objc_type_param_bound_explicit_nullability)
725 << paramName << typeBound
726 << FixItHint::CreateRemoval(rangeToRemove);
727 diagnosed = true;
732 if (!diagnosed) {
733 Diag(qual ? qual.getBeginLoc()
734 : typeBoundInfo->getTypeLoc().getBeginLoc(),
735 diag::err_objc_type_param_bound_qualified)
736 << paramName << typeBound
737 << typeBound.getQualifiers().getAsString()
738 << FixItHint::CreateRemoval(rangeToRemove);
741 // If the type bound has qualifiers other than CVR, we need to strip
742 // them or we'll probably assert later when trying to apply new
743 // qualifiers.
744 Qualifiers quals = typeBound.getQualifiers();
745 quals.removeCVRQualifiers();
746 if (!quals.empty()) {
747 typeBoundInfo =
748 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
754 // If there was no explicit type bound (or we removed it due to an error),
755 // use 'id' instead.
756 if (!typeBoundInfo) {
757 colonLoc = SourceLocation();
758 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
761 // Create the type parameter.
762 return ObjCTypeParamDecl::Create(Context, SemaRef.CurContext, variance,
763 varianceLoc, index, paramLoc, paramName,
764 colonLoc, typeBoundInfo);
767 ObjCTypeParamList *
768 SemaObjC::actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc,
769 ArrayRef<Decl *> typeParamsIn,
770 SourceLocation rAngleLoc) {
771 ASTContext &Context = getASTContext();
772 // We know that the array only contains Objective-C type parameters.
773 ArrayRef<ObjCTypeParamDecl *>
774 typeParams(
775 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
776 typeParamsIn.size());
778 // Diagnose redeclarations of type parameters.
779 // We do this now because Objective-C type parameters aren't pushed into
780 // scope until later (after the instance variable block), but we want the
781 // diagnostics to occur right after we parse the type parameter list.
782 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
783 for (auto *typeParam : typeParams) {
784 auto known = knownParams.find(typeParam->getIdentifier());
785 if (known != knownParams.end()) {
786 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
787 << typeParam->getIdentifier()
788 << SourceRange(known->second->getLocation());
790 typeParam->setInvalidDecl();
791 } else {
792 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
794 // Push the type parameter into scope.
795 SemaRef.PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
799 // Create the parameter list.
800 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
803 void SemaObjC::popObjCTypeParamList(Scope *S,
804 ObjCTypeParamList *typeParamList) {
805 for (auto *typeParam : *typeParamList) {
806 if (!typeParam->isInvalidDecl()) {
807 S->RemoveDecl(typeParam);
808 SemaRef.IdResolver.RemoveDecl(typeParam);
813 namespace {
814 /// The context in which an Objective-C type parameter list occurs, for use
815 /// in diagnostics.
816 enum class TypeParamListContext {
817 ForwardDeclaration,
818 Definition,
819 Category,
820 Extension
822 } // end anonymous namespace
824 /// Check consistency between two Objective-C type parameter lists, e.g.,
825 /// between a category/extension and an \@interface or between an \@class and an
826 /// \@interface.
827 static bool checkTypeParamListConsistency(Sema &S,
828 ObjCTypeParamList *prevTypeParams,
829 ObjCTypeParamList *newTypeParams,
830 TypeParamListContext newContext) {
831 // If the sizes don't match, complain about that.
832 if (prevTypeParams->size() != newTypeParams->size()) {
833 SourceLocation diagLoc;
834 if (newTypeParams->size() > prevTypeParams->size()) {
835 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
836 } else {
837 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
840 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
841 << static_cast<unsigned>(newContext)
842 << (newTypeParams->size() > prevTypeParams->size())
843 << prevTypeParams->size()
844 << newTypeParams->size();
846 return true;
849 // Match up the type parameters.
850 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
851 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
852 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
854 // Check for consistency of the variance.
855 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
856 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
857 newContext != TypeParamListContext::Definition) {
858 // When the new type parameter is invariant and is not part
859 // of the definition, just propagate the variance.
860 newTypeParam->setVariance(prevTypeParam->getVariance());
861 } else if (prevTypeParam->getVariance()
862 == ObjCTypeParamVariance::Invariant &&
863 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
864 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
865 ->getDefinition() == prevTypeParam->getDeclContext())) {
866 // When the old parameter is invariant and was not part of the
867 // definition, just ignore the difference because it doesn't
868 // matter.
869 } else {
871 // Diagnose the conflict and update the second declaration.
872 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
873 if (diagLoc.isInvalid())
874 diagLoc = newTypeParam->getBeginLoc();
876 auto diag = S.Diag(diagLoc,
877 diag::err_objc_type_param_variance_conflict)
878 << static_cast<unsigned>(newTypeParam->getVariance())
879 << newTypeParam->getDeclName()
880 << static_cast<unsigned>(prevTypeParam->getVariance())
881 << prevTypeParam->getDeclName();
882 switch (prevTypeParam->getVariance()) {
883 case ObjCTypeParamVariance::Invariant:
884 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
885 break;
887 case ObjCTypeParamVariance::Covariant:
888 case ObjCTypeParamVariance::Contravariant: {
889 StringRef newVarianceStr
890 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
891 ? "__covariant"
892 : "__contravariant";
893 if (newTypeParam->getVariance()
894 == ObjCTypeParamVariance::Invariant) {
895 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
896 (newVarianceStr + " ").str());
897 } else {
898 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
899 newVarianceStr);
905 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
906 << prevTypeParam->getDeclName();
908 // Override the variance.
909 newTypeParam->setVariance(prevTypeParam->getVariance());
913 // If the bound types match, there's nothing to do.
914 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
915 newTypeParam->getUnderlyingType()))
916 continue;
918 // If the new type parameter's bound was explicit, complain about it being
919 // different from the original.
920 if (newTypeParam->hasExplicitBound()) {
921 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
922 ->getTypeLoc().getSourceRange();
923 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
924 << newTypeParam->getUnderlyingType()
925 << newTypeParam->getDeclName()
926 << prevTypeParam->hasExplicitBound()
927 << prevTypeParam->getUnderlyingType()
928 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
929 << prevTypeParam->getDeclName()
930 << FixItHint::CreateReplacement(
931 newBoundRange,
932 prevTypeParam->getUnderlyingType().getAsString(
933 S.Context.getPrintingPolicy()));
935 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
936 << prevTypeParam->getDeclName();
938 // Override the new type parameter's bound type with the previous type,
939 // so that it's consistent.
940 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
941 continue;
944 // The new type parameter got the implicit bound of 'id'. That's okay for
945 // categories and extensions (overwrite it later), but not for forward
946 // declarations and @interfaces, because those must be standalone.
947 if (newContext == TypeParamListContext::ForwardDeclaration ||
948 newContext == TypeParamListContext::Definition) {
949 // Diagnose this problem for forward declarations and definitions.
950 SourceLocation insertionLoc
951 = S.getLocForEndOfToken(newTypeParam->getLocation());
952 std::string newCode
953 = " : " + prevTypeParam->getUnderlyingType().getAsString(
954 S.Context.getPrintingPolicy());
955 S.Diag(newTypeParam->getLocation(),
956 diag::err_objc_type_param_bound_missing)
957 << prevTypeParam->getUnderlyingType()
958 << newTypeParam->getDeclName()
959 << (newContext == TypeParamListContext::ForwardDeclaration)
960 << FixItHint::CreateInsertion(insertionLoc, newCode);
962 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
963 << prevTypeParam->getDeclName();
966 // Update the new type parameter's bound to match the previous one.
967 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
970 return false;
973 ObjCInterfaceDecl *SemaObjC::ActOnStartClassInterface(
974 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
975 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
976 IdentifierInfo *SuperName, SourceLocation SuperLoc,
977 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
978 Decl *const *ProtoRefs, unsigned NumProtoRefs,
979 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
980 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
981 assert(ClassName && "Missing class identifier");
983 ASTContext &Context = getASTContext();
984 // Check for another declaration kind with the same name.
985 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
986 SemaRef.TUScope, ClassName, ClassLoc, Sema::LookupOrdinaryName,
987 SemaRef.forRedeclarationInCurContext());
989 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
990 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
991 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
994 // Create a declaration to describe this @interface.
995 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
997 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
998 // A previous decl with a different name is because of
999 // @compatibility_alias, for example:
1000 // \code
1001 // @class NewImage;
1002 // @compatibility_alias OldImage NewImage;
1003 // \endcode
1004 // A lookup for 'OldImage' will return the 'NewImage' decl.
1006 // In such a case use the real declaration name, instead of the alias one,
1007 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1008 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1009 // has been aliased.
1010 ClassName = PrevIDecl->getIdentifier();
1013 // If there was a forward declaration with type parameters, check
1014 // for consistency.
1015 if (PrevIDecl) {
1016 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1017 if (typeParamList) {
1018 // Both have type parameter lists; check for consistency.
1019 if (checkTypeParamListConsistency(SemaRef, prevTypeParamList,
1020 typeParamList,
1021 TypeParamListContext::Definition)) {
1022 typeParamList = nullptr;
1024 } else {
1025 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1026 << ClassName;
1027 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1028 << ClassName;
1030 // Clone the type parameter list.
1031 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1032 for (auto *typeParam : *prevTypeParamList) {
1033 clonedTypeParams.push_back(ObjCTypeParamDecl::Create(
1034 Context, SemaRef.CurContext, typeParam->getVariance(),
1035 SourceLocation(), typeParam->getIndex(), SourceLocation(),
1036 typeParam->getIdentifier(), SourceLocation(),
1037 Context.getTrivialTypeSourceInfo(
1038 typeParam->getUnderlyingType())));
1041 typeParamList = ObjCTypeParamList::create(Context,
1042 SourceLocation(),
1043 clonedTypeParams,
1044 SourceLocation());
1049 ObjCInterfaceDecl *IDecl =
1050 ObjCInterfaceDecl::Create(Context, SemaRef.CurContext, AtInterfaceLoc,
1051 ClassName, typeParamList, PrevIDecl, ClassLoc);
1052 if (PrevIDecl) {
1053 // Class already seen. Was it a definition?
1054 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1055 if (SkipBody && !SemaRef.hasVisibleDefinition(Def)) {
1056 SkipBody->CheckSameAsPrevious = true;
1057 SkipBody->New = IDecl;
1058 SkipBody->Previous = Def;
1059 } else {
1060 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1061 << PrevIDecl->getDeclName();
1062 Diag(Def->getLocation(), diag::note_previous_definition);
1063 IDecl->setInvalidDecl();
1068 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, IDecl, AttrList);
1069 SemaRef.AddPragmaAttributes(SemaRef.TUScope, IDecl);
1070 SemaRef.ProcessAPINotes(IDecl);
1072 // Merge attributes from previous declarations.
1073 if (PrevIDecl)
1074 SemaRef.mergeDeclAttributes(IDecl, PrevIDecl);
1076 SemaRef.PushOnScopeChains(IDecl, SemaRef.TUScope);
1078 // Start the definition of this class. If we're in a redefinition case, there
1079 // may already be a definition, so we'll end up adding to it.
1080 if (SkipBody && SkipBody->CheckSameAsPrevious)
1081 IDecl->startDuplicateDefinitionForComparison();
1082 else if (!IDecl->hasDefinition())
1083 IDecl->startDefinition();
1085 if (SuperName) {
1086 // Diagnose availability in the context of the @interface.
1087 Sema::ContextRAII SavedContext(SemaRef, IDecl);
1089 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1090 ClassName, ClassLoc,
1091 SuperName, SuperLoc, SuperTypeArgs,
1092 SuperTypeArgsRange);
1093 } else { // we have a root class.
1094 IDecl->setEndOfDefinitionLoc(ClassLoc);
1097 // Check then save referenced protocols.
1098 if (NumProtoRefs) {
1099 diagnoseUseOfProtocols(SemaRef, IDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1100 NumProtoRefs, ProtoLocs);
1101 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1102 ProtoLocs, Context);
1103 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1106 CheckObjCDeclScope(IDecl);
1107 ActOnObjCContainerStartDefinition(IDecl);
1108 return IDecl;
1111 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
1112 /// typedef'ed use for a qualified super class and adds them to the list
1113 /// of the protocols.
1114 void SemaObjC::ActOnTypedefedProtocols(
1115 SmallVectorImpl<Decl *> &ProtocolRefs,
1116 SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName,
1117 SourceLocation SuperLoc) {
1118 if (!SuperName)
1119 return;
1120 NamedDecl *IDecl = SemaRef.LookupSingleName(
1121 SemaRef.TUScope, SuperName, SuperLoc, Sema::LookupOrdinaryName);
1122 if (!IDecl)
1123 return;
1125 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1126 QualType T = TDecl->getUnderlyingType();
1127 if (T->isObjCObjectType())
1128 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1129 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1130 // FIXME: Consider whether this should be an invalid loc since the loc
1131 // is not actually pointing to a protocol name reference but to the
1132 // typedef reference. Note that the base class name loc is also pointing
1133 // at the typedef.
1134 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1139 /// ActOnCompatibilityAlias - this action is called after complete parsing of
1140 /// a \@compatibility_alias declaration. It sets up the alias relationships.
1141 Decl *SemaObjC::ActOnCompatibilityAlias(SourceLocation AtLoc,
1142 IdentifierInfo *AliasName,
1143 SourceLocation AliasLocation,
1144 IdentifierInfo *ClassName,
1145 SourceLocation ClassLocation) {
1146 ASTContext &Context = getASTContext();
1147 // Look for previous declaration of alias name
1148 NamedDecl *ADecl = SemaRef.LookupSingleName(
1149 SemaRef.TUScope, AliasName, AliasLocation, Sema::LookupOrdinaryName,
1150 SemaRef.forRedeclarationInCurContext());
1151 if (ADecl) {
1152 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1153 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1154 return nullptr;
1156 // Check for class declaration
1157 NamedDecl *CDeclU = SemaRef.LookupSingleName(
1158 SemaRef.TUScope, ClassName, ClassLocation, Sema::LookupOrdinaryName,
1159 SemaRef.forRedeclarationInCurContext());
1160 if (const TypedefNameDecl *TDecl =
1161 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1162 QualType T = TDecl->getUnderlyingType();
1163 if (T->isObjCObjectType()) {
1164 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
1165 ClassName = IDecl->getIdentifier();
1166 CDeclU = SemaRef.LookupSingleName(
1167 SemaRef.TUScope, ClassName, ClassLocation, Sema::LookupOrdinaryName,
1168 SemaRef.forRedeclarationInCurContext());
1172 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1173 if (!CDecl) {
1174 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1175 if (CDeclU)
1176 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1177 return nullptr;
1180 // Everything checked out, instantiate a new alias declaration AST.
1181 ObjCCompatibleAliasDecl *AliasDecl = ObjCCompatibleAliasDecl::Create(
1182 Context, SemaRef.CurContext, AtLoc, AliasName, CDecl);
1184 if (!CheckObjCDeclScope(AliasDecl))
1185 SemaRef.PushOnScopeChains(AliasDecl, SemaRef.TUScope);
1187 return AliasDecl;
1190 bool SemaObjC::CheckForwardProtocolDeclarationForCircularDependency(
1191 IdentifierInfo *PName, SourceLocation &Ploc, SourceLocation PrevLoc,
1192 const ObjCList<ObjCProtocolDecl> &PList) {
1194 bool res = false;
1195 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1196 E = PList.end(); I != E; ++I) {
1197 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), Ploc)) {
1198 if (PDecl->getIdentifier() == PName) {
1199 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1200 Diag(PrevLoc, diag::note_previous_definition);
1201 res = true;
1204 if (!PDecl->hasDefinition())
1205 continue;
1207 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1208 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1209 res = true;
1212 return res;
1215 ObjCProtocolDecl *SemaObjC::ActOnStartProtocolInterface(
1216 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1217 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1218 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1219 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
1220 ASTContext &Context = getASTContext();
1221 bool err = false;
1222 // FIXME: Deal with AttrList.
1223 assert(ProtocolName && "Missing protocol identifier");
1224 ObjCProtocolDecl *PrevDecl = LookupProtocol(
1225 ProtocolName, ProtocolLoc, SemaRef.forRedeclarationInCurContext());
1226 ObjCProtocolDecl *PDecl = nullptr;
1227 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1228 // Create a new protocol that is completely distinct from previous
1229 // declarations, and do not make this protocol available for name lookup.
1230 // That way, we'll end up completely ignoring the duplicate.
1231 // FIXME: Can we turn this into an error?
1232 PDecl = ObjCProtocolDecl::Create(Context, SemaRef.CurContext, ProtocolName,
1233 ProtocolLoc, AtProtoInterfaceLoc,
1234 /*PrevDecl=*/Def);
1236 if (SkipBody && !SemaRef.hasVisibleDefinition(Def)) {
1237 SkipBody->CheckSameAsPrevious = true;
1238 SkipBody->New = PDecl;
1239 SkipBody->Previous = Def;
1240 } else {
1241 // If we already have a definition, complain.
1242 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1243 Diag(Def->getLocation(), diag::note_previous_definition);
1246 // If we are using modules, add the decl to the context in order to
1247 // serialize something meaningful.
1248 if (getLangOpts().Modules)
1249 SemaRef.PushOnScopeChains(PDecl, SemaRef.TUScope);
1250 PDecl->startDuplicateDefinitionForComparison();
1251 } else {
1252 if (PrevDecl) {
1253 // Check for circular dependencies among protocol declarations. This can
1254 // only happen if this protocol was forward-declared.
1255 ObjCList<ObjCProtocolDecl> PList;
1256 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1257 err = CheckForwardProtocolDeclarationForCircularDependency(
1258 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1261 // Create the new declaration.
1262 PDecl = ObjCProtocolDecl::Create(Context, SemaRef.CurContext, ProtocolName,
1263 ProtocolLoc, AtProtoInterfaceLoc,
1264 /*PrevDecl=*/PrevDecl);
1266 SemaRef.PushOnScopeChains(PDecl, SemaRef.TUScope);
1267 PDecl->startDefinition();
1270 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, PDecl, AttrList);
1271 SemaRef.AddPragmaAttributes(SemaRef.TUScope, PDecl);
1272 SemaRef.ProcessAPINotes(PDecl);
1274 // Merge attributes from previous declarations.
1275 if (PrevDecl)
1276 SemaRef.mergeDeclAttributes(PDecl, PrevDecl);
1278 if (!err && NumProtoRefs ) {
1279 /// Check then save referenced protocols.
1280 diagnoseUseOfProtocols(SemaRef, PDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1281 NumProtoRefs, ProtoLocs);
1282 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1283 ProtoLocs, Context);
1286 CheckObjCDeclScope(PDecl);
1287 ActOnObjCContainerStartDefinition(PDecl);
1288 return PDecl;
1291 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1292 ObjCProtocolDecl *&UndefinedProtocol) {
1293 if (!PDecl->hasDefinition() ||
1294 !PDecl->getDefinition()->isUnconditionallyVisible()) {
1295 UndefinedProtocol = PDecl;
1296 return true;
1299 for (auto *PI : PDecl->protocols())
1300 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1301 UndefinedProtocol = PI;
1302 return true;
1304 return false;
1307 /// FindProtocolDeclaration - This routine looks up protocols and
1308 /// issues an error if they are not declared. It returns list of
1309 /// protocol declarations in its 'Protocols' argument.
1310 void SemaObjC::FindProtocolDeclaration(bool WarnOnDeclarations,
1311 bool ForObjCContainer,
1312 ArrayRef<IdentifierLocPair> ProtocolId,
1313 SmallVectorImpl<Decl *> &Protocols) {
1314 for (const IdentifierLocPair &Pair : ProtocolId) {
1315 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1316 if (!PDecl) {
1317 DeclFilterCCC<ObjCProtocolDecl> CCC{};
1318 TypoCorrection Corrected =
1319 SemaRef.CorrectTypo(DeclarationNameInfo(Pair.first, Pair.second),
1320 Sema::LookupObjCProtocolName, SemaRef.TUScope,
1321 nullptr, CCC, Sema::CTK_ErrorRecovery);
1322 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1323 SemaRef.diagnoseTypo(Corrected,
1324 PDiag(diag::err_undeclared_protocol_suggest)
1325 << Pair.first);
1328 if (!PDecl) {
1329 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1330 continue;
1332 // If this is a forward protocol declaration, get its definition.
1333 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1334 PDecl = PDecl->getDefinition();
1336 // For an objc container, delay protocol reference checking until after we
1337 // can set the objc decl as the availability context, otherwise check now.
1338 if (!ForObjCContainer) {
1339 (void)SemaRef.DiagnoseUseOfDecl(PDecl, Pair.second);
1342 // If this is a forward declaration and we are supposed to warn in this
1343 // case, do it.
1344 // FIXME: Recover nicely in the hidden case.
1345 ObjCProtocolDecl *UndefinedProtocol;
1347 if (WarnOnDeclarations &&
1348 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1349 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1350 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1351 << UndefinedProtocol;
1353 Protocols.push_back(PDecl);
1357 namespace {
1358 // Callback to only accept typo corrections that are either
1359 // Objective-C protocols or valid Objective-C type arguments.
1360 class ObjCTypeArgOrProtocolValidatorCCC final
1361 : public CorrectionCandidateCallback {
1362 ASTContext &Context;
1363 Sema::LookupNameKind LookupKind;
1364 public:
1365 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1366 Sema::LookupNameKind lookupKind)
1367 : Context(context), LookupKind(lookupKind) { }
1369 bool ValidateCandidate(const TypoCorrection &candidate) override {
1370 // If we're allowed to find protocols and we have a protocol, accept it.
1371 if (LookupKind != Sema::LookupOrdinaryName) {
1372 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1373 return true;
1376 // If we're allowed to find type names and we have one, accept it.
1377 if (LookupKind != Sema::LookupObjCProtocolName) {
1378 // If we have a type declaration, we might accept this result.
1379 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1380 // If we found a tag declaration outside of C++, skip it. This
1381 // can happy because we look for any name when there is no
1382 // bias to protocol or type names.
1383 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1384 return false;
1386 // Make sure the type is something we would accept as a type
1387 // argument.
1388 auto type = Context.getTypeDeclType(typeDecl);
1389 if (type->isObjCObjectPointerType() ||
1390 type->isBlockPointerType() ||
1391 type->isDependentType() ||
1392 type->isObjCObjectType())
1393 return true;
1395 return false;
1398 // If we have an Objective-C class type, accept it; there will
1399 // be another fix to add the '*'.
1400 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1401 return true;
1403 return false;
1406 return false;
1409 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1410 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1413 } // end anonymous namespace
1415 void SemaObjC::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1416 SourceLocation ProtocolLoc,
1417 IdentifierInfo *TypeArgId,
1418 SourceLocation TypeArgLoc,
1419 bool SelectProtocolFirst) {
1420 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1421 << SelectProtocolFirst << TypeArgId << ProtocolId
1422 << SourceRange(ProtocolLoc);
1425 void SemaObjC::actOnObjCTypeArgsOrProtocolQualifiers(
1426 Scope *S, ParsedType baseType, SourceLocation lAngleLoc,
1427 ArrayRef<IdentifierInfo *> identifiers,
1428 ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc,
1429 SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs,
1430 SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc,
1431 SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc,
1432 bool warnOnIncompleteProtocols) {
1433 ASTContext &Context = getASTContext();
1434 // Local function that updates the declaration specifiers with
1435 // protocol information.
1436 unsigned numProtocolsResolved = 0;
1437 auto resolvedAsProtocols = [&] {
1438 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1440 // Determine whether the base type is a parameterized class, in
1441 // which case we want to warn about typos such as
1442 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1443 ObjCInterfaceDecl *baseClass = nullptr;
1444 QualType base = SemaRef.GetTypeFromParser(baseType, nullptr);
1445 bool allAreTypeNames = false;
1446 SourceLocation firstClassNameLoc;
1447 if (!base.isNull()) {
1448 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1449 baseClass = objcObjectType->getInterface();
1450 if (baseClass) {
1451 if (auto typeParams = baseClass->getTypeParamList()) {
1452 if (typeParams->size() == numProtocolsResolved) {
1453 // Note that we should be looking for type names, too.
1454 allAreTypeNames = true;
1461 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1462 ObjCProtocolDecl *&proto
1463 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1464 // For an objc container, delay protocol reference checking until after we
1465 // can set the objc decl as the availability context, otherwise check now.
1466 if (!warnOnIncompleteProtocols) {
1467 (void)SemaRef.DiagnoseUseOfDecl(proto, identifierLocs[i]);
1470 // If this is a forward protocol declaration, get its definition.
1471 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1472 proto = proto->getDefinition();
1474 // If this is a forward declaration and we are supposed to warn in this
1475 // case, do it.
1476 // FIXME: Recover nicely in the hidden case.
1477 ObjCProtocolDecl *forwardDecl = nullptr;
1478 if (warnOnIncompleteProtocols &&
1479 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1480 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1481 << proto->getDeclName();
1482 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1483 << forwardDecl;
1486 // If everything this far has been a type name (and we care
1487 // about such things), check whether this name refers to a type
1488 // as well.
1489 if (allAreTypeNames) {
1490 if (auto *decl =
1491 SemaRef.LookupSingleName(S, identifiers[i], identifierLocs[i],
1492 Sema::LookupOrdinaryName)) {
1493 if (isa<ObjCInterfaceDecl>(decl)) {
1494 if (firstClassNameLoc.isInvalid())
1495 firstClassNameLoc = identifierLocs[i];
1496 } else if (!isa<TypeDecl>(decl)) {
1497 // Not a type.
1498 allAreTypeNames = false;
1500 } else {
1501 allAreTypeNames = false;
1506 // All of the protocols listed also have type names, and at least
1507 // one is an Objective-C class name. Check whether all of the
1508 // protocol conformances are declared by the base class itself, in
1509 // which case we warn.
1510 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1511 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1512 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1513 bool allProtocolsDeclared = true;
1514 for (auto *proto : protocols) {
1515 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1516 allProtocolsDeclared = false;
1517 break;
1521 if (allProtocolsDeclared) {
1522 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1523 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1524 << FixItHint::CreateInsertion(
1525 SemaRef.getLocForEndOfToken(firstClassNameLoc), " *");
1529 protocolLAngleLoc = lAngleLoc;
1530 protocolRAngleLoc = rAngleLoc;
1531 assert(protocols.size() == identifierLocs.size());
1534 // Attempt to resolve all of the identifiers as protocols.
1535 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1536 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1537 protocols.push_back(proto);
1538 if (proto)
1539 ++numProtocolsResolved;
1542 // If all of the names were protocols, these were protocol qualifiers.
1543 if (numProtocolsResolved == identifiers.size())
1544 return resolvedAsProtocols();
1546 // Attempt to resolve all of the identifiers as type names or
1547 // Objective-C class names. The latter is technically ill-formed,
1548 // but is probably something like \c NSArray<NSView *> missing the
1549 // \c*.
1550 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1551 SmallVector<TypeOrClassDecl, 4> typeDecls;
1552 unsigned numTypeDeclsResolved = 0;
1553 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1554 NamedDecl *decl = SemaRef.LookupSingleName(
1555 S, identifiers[i], identifierLocs[i], Sema::LookupOrdinaryName);
1556 if (!decl) {
1557 typeDecls.push_back(TypeOrClassDecl());
1558 continue;
1561 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1562 typeDecls.push_back(typeDecl);
1563 ++numTypeDeclsResolved;
1564 continue;
1567 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1568 typeDecls.push_back(objcClass);
1569 ++numTypeDeclsResolved;
1570 continue;
1573 typeDecls.push_back(TypeOrClassDecl());
1576 AttributeFactory attrFactory;
1578 // Local function that forms a reference to the given type or
1579 // Objective-C class declaration.
1580 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1581 -> TypeResult {
1582 // Form declaration specifiers. They simply refer to the type.
1583 DeclSpec DS(attrFactory);
1584 const char* prevSpec; // unused
1585 unsigned diagID; // unused
1586 QualType type;
1587 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1588 type = Context.getTypeDeclType(actualTypeDecl);
1589 else
1590 type = Context.getObjCInterfaceType(cast<ObjCInterfaceDecl *>(typeDecl));
1591 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1592 ParsedType parsedType = SemaRef.CreateParsedType(type, parsedTSInfo);
1593 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1594 parsedType, Context.getPrintingPolicy());
1595 // Use the identifier location for the type source range.
1596 DS.SetRangeStart(loc);
1597 DS.SetRangeEnd(loc);
1599 // Form the declarator.
1600 Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
1602 // If we have a typedef of an Objective-C class type that is missing a '*',
1603 // add the '*'.
1604 if (type->getAs<ObjCInterfaceType>()) {
1605 SourceLocation starLoc = SemaRef.getLocForEndOfToken(loc);
1606 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1607 SourceLocation(),
1608 SourceLocation(),
1609 SourceLocation(),
1610 SourceLocation(),
1611 SourceLocation()),
1612 starLoc);
1614 // Diagnose the missing '*'.
1615 Diag(loc, diag::err_objc_type_arg_missing_star)
1616 << type
1617 << FixItHint::CreateInsertion(starLoc, " *");
1620 // Convert this to a type.
1621 return SemaRef.ActOnTypeName(D);
1624 // Local function that updates the declaration specifiers with
1625 // type argument information.
1626 auto resolvedAsTypeDecls = [&] {
1627 // We did not resolve these as protocols.
1628 protocols.clear();
1630 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1631 // Map type declarations to type arguments.
1632 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1633 // Map type reference to a type.
1634 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1635 if (!type.isUsable()) {
1636 typeArgs.clear();
1637 return;
1640 typeArgs.push_back(type.get());
1643 typeArgsLAngleLoc = lAngleLoc;
1644 typeArgsRAngleLoc = rAngleLoc;
1647 // If all of the identifiers can be resolved as type names or
1648 // Objective-C class names, we have type arguments.
1649 if (numTypeDeclsResolved == identifiers.size())
1650 return resolvedAsTypeDecls();
1652 // Error recovery: some names weren't found, or we have a mix of
1653 // type and protocol names. Go resolve all of the unresolved names
1654 // and complain if we can't find a consistent answer.
1655 Sema::LookupNameKind lookupKind = Sema::LookupAnyName;
1656 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1657 // If we already have a protocol or type. Check whether it is the
1658 // right thing.
1659 if (protocols[i] || typeDecls[i]) {
1660 // If we haven't figured out whether we want types or protocols
1661 // yet, try to figure it out from this name.
1662 if (lookupKind == Sema::LookupAnyName) {
1663 // If this name refers to both a protocol and a type (e.g., \c
1664 // NSObject), don't conclude anything yet.
1665 if (protocols[i] && typeDecls[i])
1666 continue;
1668 // Otherwise, let this name decide whether we'll be correcting
1669 // toward types or protocols.
1670 lookupKind = protocols[i] ? Sema::LookupObjCProtocolName
1671 : Sema::LookupOrdinaryName;
1672 continue;
1675 // If we want protocols and we have a protocol, there's nothing
1676 // more to do.
1677 if (lookupKind == Sema::LookupObjCProtocolName && protocols[i])
1678 continue;
1680 // If we want types and we have a type declaration, there's
1681 // nothing more to do.
1682 if (lookupKind == Sema::LookupOrdinaryName && typeDecls[i])
1683 continue;
1685 // We have a conflict: some names refer to protocols and others
1686 // refer to types.
1687 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1688 identifiers[i], identifierLocs[i],
1689 protocols[i] != nullptr);
1691 protocols.clear();
1692 typeArgs.clear();
1693 return;
1696 // Perform typo correction on the name.
1697 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1698 TypoCorrection corrected = SemaRef.CorrectTypo(
1699 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1700 nullptr, CCC, Sema::CTK_ErrorRecovery);
1701 if (corrected) {
1702 // Did we find a protocol?
1703 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1704 SemaRef.diagnoseTypo(corrected,
1705 PDiag(diag::err_undeclared_protocol_suggest)
1706 << identifiers[i]);
1707 lookupKind = Sema::LookupObjCProtocolName;
1708 protocols[i] = proto;
1709 ++numProtocolsResolved;
1710 continue;
1713 // Did we find a type?
1714 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1715 SemaRef.diagnoseTypo(corrected,
1716 PDiag(diag::err_unknown_typename_suggest)
1717 << identifiers[i]);
1718 lookupKind = Sema::LookupOrdinaryName;
1719 typeDecls[i] = typeDecl;
1720 ++numTypeDeclsResolved;
1721 continue;
1724 // Did we find an Objective-C class?
1725 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1726 SemaRef.diagnoseTypo(corrected,
1727 PDiag(diag::err_unknown_type_or_class_name_suggest)
1728 << identifiers[i] << true);
1729 lookupKind = Sema::LookupOrdinaryName;
1730 typeDecls[i] = objcClass;
1731 ++numTypeDeclsResolved;
1732 continue;
1736 // We couldn't find anything.
1737 Diag(identifierLocs[i],
1738 (lookupKind == Sema::LookupAnyName ? diag::err_objc_type_arg_missing
1739 : lookupKind == Sema::LookupObjCProtocolName
1740 ? diag::err_undeclared_protocol
1741 : diag::err_unknown_typename))
1742 << identifiers[i];
1743 protocols.clear();
1744 typeArgs.clear();
1745 return;
1748 // If all of the names were (corrected to) protocols, these were
1749 // protocol qualifiers.
1750 if (numProtocolsResolved == identifiers.size())
1751 return resolvedAsProtocols();
1753 // Otherwise, all of the names were (corrected to) types.
1754 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1755 return resolvedAsTypeDecls();
1758 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1759 /// a class method in its extension.
1761 void SemaObjC::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1762 ObjCInterfaceDecl *ID) {
1763 if (!ID)
1764 return; // Possibly due to previous error
1766 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1767 for (auto *MD : ID->methods())
1768 MethodMap[MD->getSelector()] = MD;
1770 if (MethodMap.empty())
1771 return;
1772 for (const auto *Method : CAT->methods()) {
1773 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1774 if (PrevMethod &&
1775 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1776 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1777 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1778 << Method->getDeclName();
1779 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1784 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1785 SemaObjC::DeclGroupPtrTy SemaObjC::ActOnForwardProtocolDeclaration(
1786 SourceLocation AtProtocolLoc, ArrayRef<IdentifierLocPair> IdentList,
1787 const ParsedAttributesView &attrList) {
1788 ASTContext &Context = getASTContext();
1789 SmallVector<Decl *, 8> DeclsInGroup;
1790 for (const IdentifierLocPair &IdentPair : IdentList) {
1791 IdentifierInfo *Ident = IdentPair.first;
1792 ObjCProtocolDecl *PrevDecl = LookupProtocol(
1793 Ident, IdentPair.second, SemaRef.forRedeclarationInCurContext());
1794 ObjCProtocolDecl *PDecl =
1795 ObjCProtocolDecl::Create(Context, SemaRef.CurContext, Ident,
1796 IdentPair.second, AtProtocolLoc, PrevDecl);
1798 SemaRef.PushOnScopeChains(PDecl, SemaRef.TUScope);
1799 CheckObjCDeclScope(PDecl);
1801 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, PDecl, attrList);
1802 SemaRef.AddPragmaAttributes(SemaRef.TUScope, PDecl);
1804 if (PrevDecl)
1805 SemaRef.mergeDeclAttributes(PDecl, PrevDecl);
1807 DeclsInGroup.push_back(PDecl);
1810 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
1813 ObjCCategoryDecl *SemaObjC::ActOnStartCategoryInterface(
1814 SourceLocation AtInterfaceLoc, const IdentifierInfo *ClassName,
1815 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1816 const IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1817 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1818 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1819 const ParsedAttributesView &AttrList) {
1820 ASTContext &Context = getASTContext();
1821 ObjCCategoryDecl *CDecl;
1822 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1824 /// Check that class of this category is already completely declared.
1826 if (!IDecl ||
1827 SemaRef.RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1828 diag::err_category_forward_interface,
1829 CategoryName == nullptr)) {
1830 // Create an invalid ObjCCategoryDecl to serve as context for
1831 // the enclosing method declarations. We mark the decl invalid
1832 // to make it clear that this isn't a valid AST.
1833 CDecl = ObjCCategoryDecl::Create(Context, SemaRef.CurContext,
1834 AtInterfaceLoc, ClassLoc, CategoryLoc,
1835 CategoryName, IDecl, typeParamList);
1836 CDecl->setInvalidDecl();
1837 SemaRef.CurContext->addDecl(CDecl);
1839 if (!IDecl)
1840 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1841 ActOnObjCContainerStartDefinition(CDecl);
1842 return CDecl;
1845 if (!CategoryName && IDecl->getImplementation()) {
1846 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1847 Diag(IDecl->getImplementation()->getLocation(),
1848 diag::note_implementation_declared);
1851 if (CategoryName) {
1852 /// Check for duplicate interface declaration for this category
1853 if (ObjCCategoryDecl *Previous
1854 = IDecl->FindCategoryDeclaration(CategoryName)) {
1855 // Class extensions can be declared multiple times, categories cannot.
1856 Diag(CategoryLoc, diag::warn_dup_category_def)
1857 << ClassName << CategoryName;
1858 Diag(Previous->getLocation(), diag::note_previous_definition);
1862 // If we have a type parameter list, check it.
1863 if (typeParamList) {
1864 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1865 if (checkTypeParamListConsistency(
1866 SemaRef, prevTypeParamList, typeParamList,
1867 CategoryName ? TypeParamListContext::Category
1868 : TypeParamListContext::Extension))
1869 typeParamList = nullptr;
1870 } else {
1871 Diag(typeParamList->getLAngleLoc(),
1872 diag::err_objc_parameterized_category_nonclass)
1873 << (CategoryName != nullptr)
1874 << ClassName
1875 << typeParamList->getSourceRange();
1877 typeParamList = nullptr;
1881 CDecl = ObjCCategoryDecl::Create(Context, SemaRef.CurContext, AtInterfaceLoc,
1882 ClassLoc, CategoryLoc, CategoryName, IDecl,
1883 typeParamList);
1884 // FIXME: PushOnScopeChains?
1885 SemaRef.CurContext->addDecl(CDecl);
1887 // Process the attributes before looking at protocols to ensure that the
1888 // availability attribute is attached to the category to provide availability
1889 // checking for protocol uses.
1890 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, CDecl, AttrList);
1891 SemaRef.AddPragmaAttributes(SemaRef.TUScope, CDecl);
1893 if (NumProtoRefs) {
1894 diagnoseUseOfProtocols(SemaRef, CDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1895 NumProtoRefs, ProtoLocs);
1896 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1897 ProtoLocs, Context);
1898 // Protocols in the class extension belong to the class.
1899 if (CDecl->IsClassExtension())
1900 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1901 NumProtoRefs, Context);
1904 CheckObjCDeclScope(CDecl);
1905 ActOnObjCContainerStartDefinition(CDecl);
1906 return CDecl;
1909 /// ActOnStartCategoryImplementation - Perform semantic checks on the
1910 /// category implementation declaration and build an ObjCCategoryImplDecl
1911 /// object.
1912 ObjCCategoryImplDecl *SemaObjC::ActOnStartCategoryImplementation(
1913 SourceLocation AtCatImplLoc, const IdentifierInfo *ClassName,
1914 SourceLocation ClassLoc, const IdentifierInfo *CatName,
1915 SourceLocation CatLoc, const ParsedAttributesView &Attrs) {
1916 ASTContext &Context = getASTContext();
1917 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1918 ObjCCategoryDecl *CatIDecl = nullptr;
1919 if (IDecl && IDecl->hasDefinition()) {
1920 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1921 if (!CatIDecl) {
1922 // Category @implementation with no corresponding @interface.
1923 // Create and install one.
1924 CatIDecl =
1925 ObjCCategoryDecl::Create(Context, SemaRef.CurContext, AtCatImplLoc,
1926 ClassLoc, CatLoc, CatName, IDecl,
1927 /*typeParamList=*/nullptr);
1928 CatIDecl->setImplicit();
1932 ObjCCategoryImplDecl *CDecl =
1933 ObjCCategoryImplDecl::Create(Context, SemaRef.CurContext, CatName, IDecl,
1934 ClassLoc, AtCatImplLoc, CatLoc);
1935 /// Check that class of this category is already completely declared.
1936 if (!IDecl) {
1937 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1938 CDecl->setInvalidDecl();
1939 } else if (SemaRef.RequireCompleteType(ClassLoc,
1940 Context.getObjCInterfaceType(IDecl),
1941 diag::err_undef_interface)) {
1942 CDecl->setInvalidDecl();
1945 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, CDecl, Attrs);
1946 SemaRef.AddPragmaAttributes(SemaRef.TUScope, CDecl);
1948 // FIXME: PushOnScopeChains?
1949 SemaRef.CurContext->addDecl(CDecl);
1951 // If the interface has the objc_runtime_visible attribute, we
1952 // cannot implement a category for it.
1953 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1954 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1955 << IDecl->getDeclName();
1958 /// Check that CatName, category name, is not used in another implementation.
1959 if (CatIDecl) {
1960 if (CatIDecl->getImplementation()) {
1961 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1962 << CatName;
1963 Diag(CatIDecl->getImplementation()->getLocation(),
1964 diag::note_previous_definition);
1965 CDecl->setInvalidDecl();
1966 } else {
1967 CatIDecl->setImplementation(CDecl);
1968 // Warn on implementating category of deprecated class under
1969 // -Wdeprecated-implementations flag.
1970 DiagnoseObjCImplementedDeprecations(SemaRef, CatIDecl,
1971 CDecl->getLocation());
1975 CheckObjCDeclScope(CDecl);
1976 ActOnObjCContainerStartDefinition(CDecl);
1977 return CDecl;
1980 ObjCImplementationDecl *SemaObjC::ActOnStartClassImplementation(
1981 SourceLocation AtClassImplLoc, const IdentifierInfo *ClassName,
1982 SourceLocation ClassLoc, const IdentifierInfo *SuperClassname,
1983 SourceLocation SuperClassLoc, const ParsedAttributesView &Attrs) {
1984 ASTContext &Context = getASTContext();
1985 ObjCInterfaceDecl *IDecl = nullptr;
1986 // Check for another declaration kind with the same name.
1987 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
1988 SemaRef.TUScope, ClassName, ClassLoc, Sema::LookupOrdinaryName,
1989 SemaRef.forRedeclarationInCurContext());
1990 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1991 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1992 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1993 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1994 // FIXME: This will produce an error if the definition of the interface has
1995 // been imported from a module but is not visible.
1996 SemaRef.RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1997 diag::warn_undef_interface);
1998 } else {
1999 // We did not find anything with the name ClassName; try to correct for
2000 // typos in the class name.
2001 ObjCInterfaceValidatorCCC CCC{};
2002 TypoCorrection Corrected = SemaRef.CorrectTypo(
2003 DeclarationNameInfo(ClassName, ClassLoc), Sema::LookupOrdinaryName,
2004 SemaRef.TUScope, nullptr, CCC, Sema::CTK_NonError);
2005 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2006 // Suggest the (potentially) correct interface name. Don't provide a
2007 // code-modification hint or use the typo name for recovery, because
2008 // this is just a warning. The program may actually be correct.
2009 SemaRef.diagnoseTypo(
2010 Corrected, PDiag(diag::warn_undef_interface_suggest) << ClassName,
2011 /*ErrorRecovery*/ false);
2012 } else {
2013 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
2017 // Check that super class name is valid class name
2018 ObjCInterfaceDecl *SDecl = nullptr;
2019 if (SuperClassname) {
2020 // Check if a different kind of symbol declared in this scope.
2021 PrevDecl =
2022 SemaRef.LookupSingleName(SemaRef.TUScope, SuperClassname, SuperClassLoc,
2023 Sema::LookupOrdinaryName);
2024 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2025 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2026 << SuperClassname;
2027 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2028 } else {
2029 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2030 if (SDecl && !SDecl->hasDefinition())
2031 SDecl = nullptr;
2032 if (!SDecl)
2033 Diag(SuperClassLoc, diag::err_undef_superclass)
2034 << SuperClassname << ClassName;
2035 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2036 // This implementation and its interface do not have the same
2037 // super class.
2038 Diag(SuperClassLoc, diag::err_conflicting_super_class)
2039 << SDecl->getDeclName();
2040 Diag(SDecl->getLocation(), diag::note_previous_definition);
2045 if (!IDecl) {
2046 // Legacy case of @implementation with no corresponding @interface.
2047 // Build, chain & install the interface decl into the identifier.
2049 // FIXME: Do we support attributes on the @implementation? If so we should
2050 // copy them over.
2051 IDecl =
2052 ObjCInterfaceDecl::Create(Context, SemaRef.CurContext, AtClassImplLoc,
2053 ClassName, /*typeParamList=*/nullptr,
2054 /*PrevDecl=*/nullptr, ClassLoc, true);
2055 SemaRef.AddPragmaAttributes(SemaRef.TUScope, IDecl);
2056 IDecl->startDefinition();
2057 if (SDecl) {
2058 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2059 Context.getObjCInterfaceType(SDecl),
2060 SuperClassLoc));
2061 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2062 } else {
2063 IDecl->setEndOfDefinitionLoc(ClassLoc);
2066 SemaRef.PushOnScopeChains(IDecl, SemaRef.TUScope);
2067 } else {
2068 // Mark the interface as being completed, even if it was just as
2069 // @class ....;
2070 // declaration; the user cannot reopen it.
2071 if (!IDecl->hasDefinition())
2072 IDecl->startDefinition();
2075 ObjCImplementationDecl *IMPDecl =
2076 ObjCImplementationDecl::Create(Context, SemaRef.CurContext, IDecl, SDecl,
2077 ClassLoc, AtClassImplLoc, SuperClassLoc);
2079 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, IMPDecl, Attrs);
2080 SemaRef.AddPragmaAttributes(SemaRef.TUScope, IMPDecl);
2082 if (CheckObjCDeclScope(IMPDecl)) {
2083 ActOnObjCContainerStartDefinition(IMPDecl);
2084 return IMPDecl;
2087 // Check that there is no duplicate implementation of this class.
2088 if (IDecl->getImplementation()) {
2089 // FIXME: Don't leak everything!
2090 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2091 Diag(IDecl->getImplementation()->getLocation(),
2092 diag::note_previous_definition);
2093 IMPDecl->setInvalidDecl();
2094 } else { // add it to the list.
2095 IDecl->setImplementation(IMPDecl);
2096 SemaRef.PushOnScopeChains(IMPDecl, SemaRef.TUScope);
2097 // Warn on implementating deprecated class under
2098 // -Wdeprecated-implementations flag.
2099 DiagnoseObjCImplementedDeprecations(SemaRef, IDecl, IMPDecl->getLocation());
2102 // If the superclass has the objc_runtime_visible attribute, we
2103 // cannot implement a subclass of it.
2104 if (IDecl->getSuperClass() &&
2105 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2106 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2107 << IDecl->getDeclName()
2108 << IDecl->getSuperClass()->getDeclName();
2111 ActOnObjCContainerStartDefinition(IMPDecl);
2112 return IMPDecl;
2115 SemaObjC::DeclGroupPtrTy
2116 SemaObjC::ActOnFinishObjCImplementation(Decl *ObjCImpDecl,
2117 ArrayRef<Decl *> Decls) {
2118 SmallVector<Decl *, 64> DeclsInGroup;
2119 DeclsInGroup.reserve(Decls.size() + 1);
2121 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2122 Decl *Dcl = Decls[i];
2123 if (!Dcl)
2124 continue;
2125 if (Dcl->getDeclContext()->isFileContext())
2126 Dcl->setTopLevelDeclInObjCContainer();
2127 DeclsInGroup.push_back(Dcl);
2130 DeclsInGroup.push_back(ObjCImpDecl);
2132 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
2135 void SemaObjC::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2136 ObjCIvarDecl **ivars, unsigned numIvars,
2137 SourceLocation RBrace) {
2138 assert(ImpDecl && "missing implementation decl");
2139 ASTContext &Context = getASTContext();
2140 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2141 if (!IDecl)
2142 return;
2143 /// Check case of non-existing \@interface decl.
2144 /// (legacy objective-c \@implementation decl without an \@interface decl).
2145 /// Add implementations's ivar to the synthesize class's ivar list.
2146 if (IDecl->isImplicitInterfaceDecl()) {
2147 IDecl->setEndOfDefinitionLoc(RBrace);
2148 // Add ivar's to class's DeclContext.
2149 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2150 ivars[i]->setLexicalDeclContext(ImpDecl);
2151 // In a 'fragile' runtime the ivar was added to the implicit
2152 // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is
2153 // only in the ObjCImplementationDecl. In the non-fragile case the ivar
2154 // therefore also needs to be propagated to the ObjCInterfaceDecl.
2155 if (!getLangOpts().ObjCRuntime.isFragile())
2156 IDecl->makeDeclVisibleInContext(ivars[i]);
2157 ImpDecl->addDecl(ivars[i]);
2160 return;
2162 // If implementation has empty ivar list, just return.
2163 if (numIvars == 0)
2164 return;
2166 assert(ivars && "missing @implementation ivars");
2167 if (getLangOpts().ObjCRuntime.isNonFragile()) {
2168 if (ImpDecl->getSuperClass())
2169 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2170 for (unsigned i = 0; i < numIvars; i++) {
2171 ObjCIvarDecl* ImplIvar = ivars[i];
2172 if (const ObjCIvarDecl *ClsIvar =
2173 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2174 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2175 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2176 continue;
2178 // Check class extensions (unnamed categories) for duplicate ivars.
2179 for (const auto *CDecl : IDecl->visible_extensions()) {
2180 if (const ObjCIvarDecl *ClsExtIvar =
2181 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2182 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2183 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2184 continue;
2187 // Instance ivar to Implementation's DeclContext.
2188 ImplIvar->setLexicalDeclContext(ImpDecl);
2189 IDecl->makeDeclVisibleInContext(ImplIvar);
2190 ImpDecl->addDecl(ImplIvar);
2192 return;
2194 // Check interface's Ivar list against those in the implementation.
2195 // names and types must match.
2197 unsigned j = 0;
2198 ObjCInterfaceDecl::ivar_iterator
2199 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2200 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2201 ObjCIvarDecl* ImplIvar = ivars[j++];
2202 ObjCIvarDecl* ClsIvar = *IVI;
2203 assert (ImplIvar && "missing implementation ivar");
2204 assert (ClsIvar && "missing class ivar");
2206 // First, make sure the types match.
2207 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2208 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2209 << ImplIvar->getIdentifier()
2210 << ImplIvar->getType() << ClsIvar->getType();
2211 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2212 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2213 ImplIvar->getBitWidthValue(Context) !=
2214 ClsIvar->getBitWidthValue(Context)) {
2215 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2216 diag::err_conflicting_ivar_bitwidth)
2217 << ImplIvar->getIdentifier();
2218 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2219 diag::note_previous_definition);
2221 // Make sure the names are identical.
2222 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2223 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2224 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2225 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2227 --numIvars;
2230 if (numIvars > 0)
2231 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2232 else if (IVI != IVE)
2233 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2236 static bool shouldWarnUndefinedMethod(const ObjCMethodDecl *M) {
2237 // No point warning no definition of method which is 'unavailable'.
2238 return M->getAvailability() != AR_Unavailable;
2241 static void WarnUndefinedMethod(Sema &S, ObjCImplDecl *Impl,
2242 ObjCMethodDecl *method, bool &IncompleteImpl,
2243 unsigned DiagID,
2244 NamedDecl *NeededFor = nullptr) {
2245 if (!shouldWarnUndefinedMethod(method))
2246 return;
2248 // FIXME: For now ignore 'IncompleteImpl'.
2249 // Previously we grouped all unimplemented methods under a single
2250 // warning, but some users strongly voiced that they would prefer
2251 // separate warnings. We will give that approach a try, as that
2252 // matches what we do with protocols.
2254 const SemaBase::SemaDiagnosticBuilder &B =
2255 S.Diag(Impl->getLocation(), DiagID);
2256 B << method;
2257 if (NeededFor)
2258 B << NeededFor;
2260 // Add an empty definition at the end of the @implementation.
2261 std::string FixItStr;
2262 llvm::raw_string_ostream Out(FixItStr);
2263 method->print(Out, Impl->getASTContext().getPrintingPolicy());
2264 Out << " {\n}\n\n";
2266 SourceLocation Loc = Impl->getAtEndRange().getBegin();
2267 B << FixItHint::CreateInsertion(Loc, FixItStr);
2270 // Issue a note to the original declaration.
2271 SourceLocation MethodLoc = method->getBeginLoc();
2272 if (MethodLoc.isValid())
2273 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2276 /// Determines if type B can be substituted for type A. Returns true if we can
2277 /// guarantee that anything that the user will do to an object of type A can
2278 /// also be done to an object of type B. This is trivially true if the two
2279 /// types are the same, or if B is a subclass of A. It becomes more complex
2280 /// in cases where protocols are involved.
2282 /// Object types in Objective-C describe the minimum requirements for an
2283 /// object, rather than providing a complete description of a type. For
2284 /// example, if A is a subclass of B, then B* may refer to an instance of A.
2285 /// The principle of substitutability means that we may use an instance of A
2286 /// anywhere that we may use an instance of B - it will implement all of the
2287 /// ivars of B and all of the methods of B.
2289 /// This substitutability is important when type checking methods, because
2290 /// the implementation may have stricter type definitions than the interface.
2291 /// The interface specifies minimum requirements, but the implementation may
2292 /// have more accurate ones. For example, a method may privately accept
2293 /// instances of B, but only publish that it accepts instances of A. Any
2294 /// object passed to it will be type checked against B, and so will implicitly
2295 /// by a valid A*. Similarly, a method may return a subclass of the class that
2296 /// it is declared as returning.
2298 /// This is most important when considering subclassing. A method in a
2299 /// subclass must accept any object as an argument that its superclass's
2300 /// implementation accepts. It may, however, accept a more general type
2301 /// without breaking substitutability (i.e. you can still use the subclass
2302 /// anywhere that you can use the superclass, but not vice versa). The
2303 /// converse requirement applies to return types: the return type for a
2304 /// subclass method must be a valid object of the kind that the superclass
2305 /// advertises, but it may be specified more accurately. This avoids the need
2306 /// for explicit down-casting by callers.
2308 /// Note: This is a stricter requirement than for assignment.
2309 static bool isObjCTypeSubstitutable(ASTContext &Context,
2310 const ObjCObjectPointerType *A,
2311 const ObjCObjectPointerType *B,
2312 bool rejectId) {
2313 // Reject a protocol-unqualified id.
2314 if (rejectId && B->isObjCIdType()) return false;
2316 // If B is a qualified id, then A must also be a qualified id and it must
2317 // implement all of the protocols in B. It may not be a qualified class.
2318 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2319 // stricter definition so it is not substitutable for id<A>.
2320 if (B->isObjCQualifiedIdType()) {
2321 return A->isObjCQualifiedIdType() &&
2322 Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2326 // id is a special type that bypasses type checking completely. We want a
2327 // warning when it is used in one place but not another.
2328 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2331 // If B is a qualified id, then A must also be a qualified id (which it isn't
2332 // if we've got this far)
2333 if (B->isObjCQualifiedIdType()) return false;
2336 // Now we know that A and B are (potentially-qualified) class types. The
2337 // normal rules for assignment apply.
2338 return Context.canAssignObjCInterfaces(A, B);
2341 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2342 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2345 /// Determine whether two set of Objective-C declaration qualifiers conflict.
2346 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2347 Decl::ObjCDeclQualifier y) {
2348 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2349 (y & ~Decl::OBJC_TQ_CSNullability);
2352 static bool CheckMethodOverrideReturn(Sema &S,
2353 ObjCMethodDecl *MethodImpl,
2354 ObjCMethodDecl *MethodDecl,
2355 bool IsProtocolMethodDecl,
2356 bool IsOverridingMode,
2357 bool Warn) {
2358 if (IsProtocolMethodDecl &&
2359 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2360 MethodImpl->getObjCDeclQualifier())) {
2361 if (Warn) {
2362 S.Diag(MethodImpl->getLocation(),
2363 (IsOverridingMode
2364 ? diag::warn_conflicting_overriding_ret_type_modifiers
2365 : diag::warn_conflicting_ret_type_modifiers))
2366 << MethodImpl->getDeclName()
2367 << MethodImpl->getReturnTypeSourceRange();
2368 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2369 << MethodDecl->getReturnTypeSourceRange();
2371 else
2372 return false;
2374 if (Warn && IsOverridingMode &&
2375 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2376 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2377 MethodDecl->getReturnType(),
2378 false)) {
2379 auto nullabilityMethodImpl = *MethodImpl->getReturnType()->getNullability();
2380 auto nullabilityMethodDecl = *MethodDecl->getReturnType()->getNullability();
2381 S.Diag(MethodImpl->getLocation(),
2382 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2383 << DiagNullabilityKind(nullabilityMethodImpl,
2384 ((MethodImpl->getObjCDeclQualifier() &
2385 Decl::OBJC_TQ_CSNullability) != 0))
2386 << DiagNullabilityKind(nullabilityMethodDecl,
2387 ((MethodDecl->getObjCDeclQualifier() &
2388 Decl::OBJC_TQ_CSNullability) != 0));
2389 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2392 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2393 MethodDecl->getReturnType()))
2394 return true;
2395 if (!Warn)
2396 return false;
2398 unsigned DiagID =
2399 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2400 : diag::warn_conflicting_ret_types;
2402 // Mismatches between ObjC pointers go into a different warning
2403 // category, and sometimes they're even completely explicitly allowed.
2404 if (const ObjCObjectPointerType *ImplPtrTy =
2405 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2406 if (const ObjCObjectPointerType *IfacePtrTy =
2407 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2408 // Allow non-matching return types as long as they don't violate
2409 // the principle of substitutability. Specifically, we permit
2410 // return types that are subclasses of the declared return type,
2411 // or that are more-qualified versions of the declared type.
2412 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2413 return false;
2415 DiagID =
2416 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2417 : diag::warn_non_covariant_ret_types;
2421 S.Diag(MethodImpl->getLocation(), DiagID)
2422 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2423 << MethodImpl->getReturnType()
2424 << MethodImpl->getReturnTypeSourceRange();
2425 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2426 ? diag::note_previous_declaration
2427 : diag::note_previous_definition)
2428 << MethodDecl->getReturnTypeSourceRange();
2429 return false;
2432 static bool CheckMethodOverrideParam(Sema &S,
2433 ObjCMethodDecl *MethodImpl,
2434 ObjCMethodDecl *MethodDecl,
2435 ParmVarDecl *ImplVar,
2436 ParmVarDecl *IfaceVar,
2437 bool IsProtocolMethodDecl,
2438 bool IsOverridingMode,
2439 bool Warn) {
2440 if (IsProtocolMethodDecl &&
2441 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2442 IfaceVar->getObjCDeclQualifier())) {
2443 if (Warn) {
2444 if (IsOverridingMode)
2445 S.Diag(ImplVar->getLocation(),
2446 diag::warn_conflicting_overriding_param_modifiers)
2447 << getTypeRange(ImplVar->getTypeSourceInfo())
2448 << MethodImpl->getDeclName();
2449 else S.Diag(ImplVar->getLocation(),
2450 diag::warn_conflicting_param_modifiers)
2451 << getTypeRange(ImplVar->getTypeSourceInfo())
2452 << MethodImpl->getDeclName();
2453 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2454 << getTypeRange(IfaceVar->getTypeSourceInfo());
2456 else
2457 return false;
2460 QualType ImplTy = ImplVar->getType();
2461 QualType IfaceTy = IfaceVar->getType();
2462 if (Warn && IsOverridingMode &&
2463 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2464 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2465 S.Diag(ImplVar->getLocation(),
2466 diag::warn_conflicting_nullability_attr_overriding_param_types)
2467 << DiagNullabilityKind(*ImplTy->getNullability(),
2468 ((ImplVar->getObjCDeclQualifier() &
2469 Decl::OBJC_TQ_CSNullability) != 0))
2470 << DiagNullabilityKind(*IfaceTy->getNullability(),
2471 ((IfaceVar->getObjCDeclQualifier() &
2472 Decl::OBJC_TQ_CSNullability) != 0));
2473 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2475 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2476 return true;
2478 if (!Warn)
2479 return false;
2480 unsigned DiagID =
2481 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2482 : diag::warn_conflicting_param_types;
2484 // Mismatches between ObjC pointers go into a different warning
2485 // category, and sometimes they're even completely explicitly allowed..
2486 if (const ObjCObjectPointerType *ImplPtrTy =
2487 ImplTy->getAs<ObjCObjectPointerType>()) {
2488 if (const ObjCObjectPointerType *IfacePtrTy =
2489 IfaceTy->getAs<ObjCObjectPointerType>()) {
2490 // Allow non-matching argument types as long as they don't
2491 // violate the principle of substitutability. Specifically, the
2492 // implementation must accept any objects that the superclass
2493 // accepts, however it may also accept others.
2494 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2495 return false;
2497 DiagID =
2498 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2499 : diag::warn_non_contravariant_param_types;
2503 S.Diag(ImplVar->getLocation(), DiagID)
2504 << getTypeRange(ImplVar->getTypeSourceInfo())
2505 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2506 S.Diag(IfaceVar->getLocation(),
2507 (IsOverridingMode ? diag::note_previous_declaration
2508 : diag::note_previous_definition))
2509 << getTypeRange(IfaceVar->getTypeSourceInfo());
2510 return false;
2513 /// In ARC, check whether the conventional meanings of the two methods
2514 /// match. If they don't, it's a hard error.
2515 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2516 ObjCMethodDecl *decl) {
2517 ObjCMethodFamily implFamily = impl->getMethodFamily();
2518 ObjCMethodFamily declFamily = decl->getMethodFamily();
2519 if (implFamily == declFamily) return false;
2521 // Since conventions are sorted by selector, the only possibility is
2522 // that the types differ enough to cause one selector or the other
2523 // to fall out of the family.
2524 assert(implFamily == OMF_None || declFamily == OMF_None);
2526 // No further diagnostics required on invalid declarations.
2527 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2529 const ObjCMethodDecl *unmatched = impl;
2530 ObjCMethodFamily family = declFamily;
2531 unsigned errorID = diag::err_arc_lost_method_convention;
2532 unsigned noteID = diag::note_arc_lost_method_convention;
2533 if (declFamily == OMF_None) {
2534 unmatched = decl;
2535 family = implFamily;
2536 errorID = diag::err_arc_gained_method_convention;
2537 noteID = diag::note_arc_gained_method_convention;
2540 // Indexes into a %select clause in the diagnostic.
2541 enum FamilySelector {
2542 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2544 FamilySelector familySelector = FamilySelector();
2546 switch (family) {
2547 case OMF_None: llvm_unreachable("logic error, no method convention");
2548 case OMF_retain:
2549 case OMF_release:
2550 case OMF_autorelease:
2551 case OMF_dealloc:
2552 case OMF_finalize:
2553 case OMF_retainCount:
2554 case OMF_self:
2555 case OMF_initialize:
2556 case OMF_performSelector:
2557 // Mismatches for these methods don't change ownership
2558 // conventions, so we don't care.
2559 return false;
2561 case OMF_init: familySelector = F_init; break;
2562 case OMF_alloc: familySelector = F_alloc; break;
2563 case OMF_copy: familySelector = F_copy; break;
2564 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2565 case OMF_new: familySelector = F_new; break;
2568 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2569 ReasonSelector reasonSelector;
2571 // The only reason these methods don't fall within their families is
2572 // due to unusual result types.
2573 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2574 reasonSelector = R_UnrelatedReturn;
2575 } else {
2576 reasonSelector = R_NonObjectReturn;
2579 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2580 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2582 return true;
2585 void SemaObjC::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2586 ObjCMethodDecl *MethodDecl,
2587 bool IsProtocolMethodDecl) {
2588 if (getLangOpts().ObjCAutoRefCount &&
2589 checkMethodFamilyMismatch(SemaRef, ImpMethodDecl, MethodDecl))
2590 return;
2592 CheckMethodOverrideReturn(SemaRef, ImpMethodDecl, MethodDecl,
2593 IsProtocolMethodDecl, false, true);
2595 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2596 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2597 EF = MethodDecl->param_end();
2598 IM != EM && IF != EF; ++IM, ++IF) {
2599 CheckMethodOverrideParam(SemaRef, ImpMethodDecl, MethodDecl, *IM, *IF,
2600 IsProtocolMethodDecl, false, true);
2603 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2604 Diag(ImpMethodDecl->getLocation(),
2605 diag::warn_conflicting_variadic);
2606 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2610 void SemaObjC::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2611 ObjCMethodDecl *Overridden,
2612 bool IsProtocolMethodDecl) {
2614 CheckMethodOverrideReturn(SemaRef, Method, Overridden, IsProtocolMethodDecl,
2615 true, true);
2617 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2618 IF = Overridden->param_begin(), EM = Method->param_end(),
2619 EF = Overridden->param_end();
2620 IM != EM && IF != EF; ++IM, ++IF) {
2621 CheckMethodOverrideParam(SemaRef, Method, Overridden, *IM, *IF,
2622 IsProtocolMethodDecl, true, true);
2625 if (Method->isVariadic() != Overridden->isVariadic()) {
2626 Diag(Method->getLocation(),
2627 diag::warn_conflicting_overriding_variadic);
2628 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2632 /// WarnExactTypedMethods - This routine issues a warning if method
2633 /// implementation declaration matches exactly that of its declaration.
2634 void SemaObjC::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2635 ObjCMethodDecl *MethodDecl,
2636 bool IsProtocolMethodDecl) {
2637 ASTContext &Context = getASTContext();
2638 // don't issue warning when protocol method is optional because primary
2639 // class is not required to implement it and it is safe for protocol
2640 // to implement it.
2641 if (MethodDecl->getImplementationControl() ==
2642 ObjCImplementationControl::Optional)
2643 return;
2644 // don't issue warning when primary class's method is
2645 // deprecated/unavailable.
2646 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2647 MethodDecl->hasAttr<DeprecatedAttr>())
2648 return;
2650 bool match = CheckMethodOverrideReturn(SemaRef, ImpMethodDecl, MethodDecl,
2651 IsProtocolMethodDecl, false, false);
2652 if (match)
2653 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2654 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2655 EF = MethodDecl->param_end();
2656 IM != EM && IF != EF; ++IM, ++IF) {
2657 match = CheckMethodOverrideParam(SemaRef, ImpMethodDecl, MethodDecl, *IM,
2658 *IF, IsProtocolMethodDecl, false, false);
2659 if (!match)
2660 break;
2662 if (match)
2663 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2664 if (match)
2665 match = !(MethodDecl->isClassMethod() &&
2666 MethodDecl->getSelector() == GetNullarySelector("load", Context));
2668 if (match) {
2669 Diag(ImpMethodDecl->getLocation(),
2670 diag::warn_category_method_impl_match);
2671 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2672 << MethodDecl->getDeclName();
2676 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2677 /// improve the efficiency of selector lookups and type checking by associating
2678 /// with each protocol / interface / category the flattened instance tables. If
2679 /// we used an immutable set to keep the table then it wouldn't add significant
2680 /// memory cost and it would be handy for lookups.
2682 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2683 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2685 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2686 ProtocolNameSet &PNS) {
2687 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2688 PNS.insert(PDecl->getIdentifier());
2689 for (const auto *PI : PDecl->protocols())
2690 findProtocolsWithExplicitImpls(PI, PNS);
2693 /// Recursively populates a set with all conformed protocols in a class
2694 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2695 /// attribute.
2696 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2697 ProtocolNameSet &PNS) {
2698 if (!Super)
2699 return;
2701 for (const auto *I : Super->all_referenced_protocols())
2702 findProtocolsWithExplicitImpls(I, PNS);
2704 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2707 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
2708 /// Declared in protocol, and those referenced by it.
2709 static void CheckProtocolMethodDefs(
2710 Sema &S, ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool &IncompleteImpl,
2711 const SemaObjC::SelectorSet &InsMap, const SemaObjC::SelectorSet &ClsMap,
2712 ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) {
2713 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2714 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2715 : dyn_cast<ObjCInterfaceDecl>(CDecl);
2716 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2718 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2719 ObjCInterfaceDecl *NSIDecl = nullptr;
2721 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2722 // then we should check if any class in the super class hierarchy also
2723 // conforms to this protocol, either directly or via protocol inheritance.
2724 // If so, we can skip checking this protocol completely because we
2725 // know that a parent class already satisfies this protocol.
2727 // Note: we could generalize this logic for all protocols, and merely
2728 // add the limit on looking at the super class chain for just
2729 // specially marked protocols. This may be a good optimization. This
2730 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2731 // protocols for now for controlled evaluation.
2732 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2733 if (!ProtocolsExplictImpl) {
2734 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2735 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2737 if (ProtocolsExplictImpl->contains(PDecl->getIdentifier()))
2738 return;
2740 // If no super class conforms to the protocol, we should not search
2741 // for methods in the super class to implicitly satisfy the protocol.
2742 Super = nullptr;
2745 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2746 // check to see if class implements forwardInvocation method and objects
2747 // of this class are derived from 'NSProxy' so that to forward requests
2748 // from one object to another.
2749 // Under such conditions, which means that every method possible is
2750 // implemented in the class, we should not issue "Method definition not
2751 // found" warnings.
2752 // FIXME: Use a general GetUnarySelector method for this.
2753 const IdentifierInfo *II = &S.Context.Idents.get("forwardInvocation");
2754 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2755 if (InsMap.count(fISelector))
2756 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2757 // need be implemented in the implementation.
2758 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2761 // If this is a forward protocol declaration, get its definition.
2762 if (!PDecl->isThisDeclarationADefinition() &&
2763 PDecl->getDefinition())
2764 PDecl = PDecl->getDefinition();
2766 // If a method lookup fails locally we still need to look and see if
2767 // the method was implemented by a base class or an inherited
2768 // protocol. This lookup is slow, but occurs rarely in correct code
2769 // and otherwise would terminate in a warning.
2771 // check unimplemented instance methods.
2772 if (!NSIDecl)
2773 for (auto *method : PDecl->instance_methods()) {
2774 if (method->getImplementationControl() !=
2775 ObjCImplementationControl::Optional &&
2776 !method->isPropertyAccessor() &&
2777 !InsMap.count(method->getSelector()) &&
2778 (!Super || !Super->lookupMethod(
2779 method->getSelector(), true /* instance */,
2780 false /* shallowCategory */, true /* followsSuper */,
2781 nullptr /* category */))) {
2782 // If a method is not implemented in the category implementation but
2783 // has been declared in its primary class, superclass,
2784 // or in one of their protocols, no need to issue the warning.
2785 // This is because method will be implemented in the primary class
2786 // or one of its super class implementation.
2788 // Ugly, but necessary. Method declared in protocol might have
2789 // have been synthesized due to a property declared in the class which
2790 // uses the protocol.
2791 if (ObjCMethodDecl *MethodInClass = IDecl->lookupMethod(
2792 method->getSelector(), true /* instance */,
2793 true /* shallowCategoryLookup */, false /* followSuper */))
2794 if (C || MethodInClass->isPropertyAccessor())
2795 continue;
2796 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2797 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2798 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2802 // check unimplemented class methods
2803 for (auto *method : PDecl->class_methods()) {
2804 if (method->getImplementationControl() !=
2805 ObjCImplementationControl::Optional &&
2806 !ClsMap.count(method->getSelector()) &&
2807 (!Super || !Super->lookupMethod(
2808 method->getSelector(), false /* class method */,
2809 false /* shallowCategoryLookup */,
2810 true /* followSuper */, nullptr /* category */))) {
2811 // See above comment for instance method lookups.
2812 if (C && IDecl->lookupMethod(method->getSelector(),
2813 false /* class */,
2814 true /* shallowCategoryLookup */,
2815 false /* followSuper */))
2816 continue;
2818 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2819 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2820 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2824 // Check on this protocols's referenced protocols, recursively.
2825 for (auto *PI : PDecl->protocols())
2826 CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
2827 ProtocolsExplictImpl);
2830 /// MatchAllMethodDeclarations - Check methods declared in interface
2831 /// or protocol against those declared in their implementations.
2833 void SemaObjC::MatchAllMethodDeclarations(
2834 const SelectorSet &InsMap, const SelectorSet &ClsMap,
2835 SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl *IMPDecl,
2836 ObjCContainerDecl *CDecl, bool &IncompleteImpl, bool ImmediateClass,
2837 bool WarnCategoryMethodImpl) {
2838 // Check and see if instance methods in class interface have been
2839 // implemented in the implementation class. If so, their types match.
2840 for (auto *I : CDecl->instance_methods()) {
2841 if (!InsMapSeen.insert(I->getSelector()).second)
2842 continue;
2843 if (!I->isPropertyAccessor() &&
2844 !InsMap.count(I->getSelector())) {
2845 if (ImmediateClass)
2846 WarnUndefinedMethod(SemaRef, IMPDecl, I, IncompleteImpl,
2847 diag::warn_undef_method_impl);
2848 continue;
2849 } else {
2850 ObjCMethodDecl *ImpMethodDecl =
2851 IMPDecl->getInstanceMethod(I->getSelector());
2852 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2853 "Expected to find the method through lookup as well");
2854 // ImpMethodDecl may be null as in a @dynamic property.
2855 if (ImpMethodDecl) {
2856 // Skip property accessor function stubs.
2857 if (ImpMethodDecl->isSynthesizedAccessorStub())
2858 continue;
2859 if (!WarnCategoryMethodImpl)
2860 WarnConflictingTypedMethods(ImpMethodDecl, I,
2861 isa<ObjCProtocolDecl>(CDecl));
2862 else if (!I->isPropertyAccessor())
2863 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2868 // Check and see if class methods in class interface have been
2869 // implemented in the implementation class. If so, their types match.
2870 for (auto *I : CDecl->class_methods()) {
2871 if (!ClsMapSeen.insert(I->getSelector()).second)
2872 continue;
2873 if (!I->isPropertyAccessor() &&
2874 !ClsMap.count(I->getSelector())) {
2875 if (ImmediateClass)
2876 WarnUndefinedMethod(SemaRef, IMPDecl, I, IncompleteImpl,
2877 diag::warn_undef_method_impl);
2878 } else {
2879 ObjCMethodDecl *ImpMethodDecl =
2880 IMPDecl->getClassMethod(I->getSelector());
2881 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2882 "Expected to find the method through lookup as well");
2883 // ImpMethodDecl may be null as in a @dynamic property.
2884 if (ImpMethodDecl) {
2885 // Skip property accessor function stubs.
2886 if (ImpMethodDecl->isSynthesizedAccessorStub())
2887 continue;
2888 if (!WarnCategoryMethodImpl)
2889 WarnConflictingTypedMethods(ImpMethodDecl, I,
2890 isa<ObjCProtocolDecl>(CDecl));
2891 else if (!I->isPropertyAccessor())
2892 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2897 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2898 // Also, check for methods declared in protocols inherited by
2899 // this protocol.
2900 for (auto *PI : PD->protocols())
2901 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2902 IMPDecl, PI, IncompleteImpl, false,
2903 WarnCategoryMethodImpl);
2906 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2907 // when checking that methods in implementation match their declaration,
2908 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2909 // extension; as well as those in categories.
2910 if (!WarnCategoryMethodImpl) {
2911 for (auto *Cat : I->visible_categories())
2912 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2913 IMPDecl, Cat, IncompleteImpl,
2914 ImmediateClass && Cat->IsClassExtension(),
2915 WarnCategoryMethodImpl);
2916 } else {
2917 // Also methods in class extensions need be looked at next.
2918 for (auto *Ext : I->visible_extensions())
2919 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2920 IMPDecl, Ext, IncompleteImpl, false,
2921 WarnCategoryMethodImpl);
2924 // Check for any implementation of a methods declared in protocol.
2925 for (auto *PI : I->all_referenced_protocols())
2926 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2927 IMPDecl, PI, IncompleteImpl, false,
2928 WarnCategoryMethodImpl);
2930 // FIXME. For now, we are not checking for exact match of methods
2931 // in category implementation and its primary class's super class.
2932 if (!WarnCategoryMethodImpl && I->getSuperClass())
2933 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2934 IMPDecl,
2935 I->getSuperClass(), IncompleteImpl, false);
2939 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2940 /// category matches with those implemented in its primary class and
2941 /// warns each time an exact match is found.
2942 void SemaObjC::CheckCategoryVsClassMethodMatches(
2943 ObjCCategoryImplDecl *CatIMPDecl) {
2944 // Get category's primary class.
2945 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2946 if (!CatDecl)
2947 return;
2948 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2949 if (!IDecl)
2950 return;
2951 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2952 SelectorSet InsMap, ClsMap;
2954 for (const auto *I : CatIMPDecl->instance_methods()) {
2955 Selector Sel = I->getSelector();
2956 // When checking for methods implemented in the category, skip over
2957 // those declared in category class's super class. This is because
2958 // the super class must implement the method.
2959 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2960 continue;
2961 InsMap.insert(Sel);
2964 for (const auto *I : CatIMPDecl->class_methods()) {
2965 Selector Sel = I->getSelector();
2966 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2967 continue;
2968 ClsMap.insert(Sel);
2970 if (InsMap.empty() && ClsMap.empty())
2971 return;
2973 SelectorSet InsMapSeen, ClsMapSeen;
2974 bool IncompleteImpl = false;
2975 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2976 CatIMPDecl, IDecl,
2977 IncompleteImpl, false,
2978 true /*WarnCategoryMethodImpl*/);
2981 void SemaObjC::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl *IMPDecl,
2982 ObjCContainerDecl *CDecl,
2983 bool IncompleteImpl) {
2984 SelectorSet InsMap;
2985 // Check and see if instance methods in class interface have been
2986 // implemented in the implementation class.
2987 for (const auto *I : IMPDecl->instance_methods())
2988 InsMap.insert(I->getSelector());
2990 // Add the selectors for getters/setters of @dynamic properties.
2991 for (const auto *PImpl : IMPDecl->property_impls()) {
2992 // We only care about @dynamic implementations.
2993 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2994 continue;
2996 const auto *P = PImpl->getPropertyDecl();
2997 if (!P) continue;
2999 InsMap.insert(P->getGetterName());
3000 if (!P->getSetterName().isNull())
3001 InsMap.insert(P->getSetterName());
3004 // Check and see if properties declared in the interface have either 1)
3005 // an implementation or 2) there is a @synthesize/@dynamic implementation
3006 // of the property in the @implementation.
3007 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
3008 bool SynthesizeProperties = getLangOpts().ObjCDefaultSynthProperties &&
3009 getLangOpts().ObjCRuntime.isNonFragile() &&
3010 !IDecl->isObjCRequiresPropertyDefs();
3011 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
3014 // Diagnose null-resettable synthesized setters.
3015 diagnoseNullResettableSynthesizedSetters(IMPDecl);
3017 SelectorSet ClsMap;
3018 for (const auto *I : IMPDecl->class_methods())
3019 ClsMap.insert(I->getSelector());
3021 // Check for type conflict of methods declared in a class/protocol and
3022 // its implementation; if any.
3023 SelectorSet InsMapSeen, ClsMapSeen;
3024 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3025 IMPDecl, CDecl,
3026 IncompleteImpl, true);
3028 // check all methods implemented in category against those declared
3029 // in its primary class.
3030 if (ObjCCategoryImplDecl *CatDecl =
3031 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3032 CheckCategoryVsClassMethodMatches(CatDecl);
3034 // Check the protocol list for unimplemented methods in the @implementation
3035 // class.
3036 // Check and see if class methods in class interface have been
3037 // implemented in the implementation class.
3039 LazyProtocolNameSet ExplicitImplProtocols;
3041 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3042 for (auto *PI : I->all_referenced_protocols())
3043 CheckProtocolMethodDefs(SemaRef, IMPDecl, PI, IncompleteImpl, InsMap,
3044 ClsMap, I, ExplicitImplProtocols);
3045 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3046 // For extended class, unimplemented methods in its protocols will
3047 // be reported in the primary class.
3048 if (!C->IsClassExtension()) {
3049 for (auto *P : C->protocols())
3050 CheckProtocolMethodDefs(SemaRef, IMPDecl, P, IncompleteImpl, InsMap,
3051 ClsMap, CDecl, ExplicitImplProtocols);
3052 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3053 /*SynthesizeProperties=*/false);
3055 } else
3056 llvm_unreachable("invalid ObjCContainerDecl type.");
3059 SemaObjC::DeclGroupPtrTy SemaObjC::ActOnForwardClassDeclaration(
3060 SourceLocation AtClassLoc, IdentifierInfo **IdentList,
3061 SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists,
3062 unsigned NumElts) {
3063 ASTContext &Context = getASTContext();
3064 SmallVector<Decl *, 8> DeclsInGroup;
3065 for (unsigned i = 0; i != NumElts; ++i) {
3066 // Check for another declaration kind with the same name.
3067 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
3068 SemaRef.TUScope, IdentList[i], IdentLocs[i], Sema::LookupOrdinaryName,
3069 SemaRef.forRedeclarationInCurContext());
3070 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3071 // GCC apparently allows the following idiom:
3073 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3074 // @class XCElementToggler;
3076 // Here we have chosen to ignore the forward class declaration
3077 // with a warning. Since this is the implied behavior.
3078 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3079 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3080 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3081 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3082 } else {
3083 // a forward class declaration matching a typedef name of a class refers
3084 // to the underlying class. Just ignore the forward class with a warning
3085 // as this will force the intended behavior which is to lookup the
3086 // typedef name.
3087 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3088 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3089 << IdentList[i];
3090 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3091 continue;
3096 // Create a declaration to describe this forward declaration.
3097 ObjCInterfaceDecl *PrevIDecl
3098 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3100 IdentifierInfo *ClassName = IdentList[i];
3101 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3102 // A previous decl with a different name is because of
3103 // @compatibility_alias, for example:
3104 // \code
3105 // @class NewImage;
3106 // @compatibility_alias OldImage NewImage;
3107 // \endcode
3108 // A lookup for 'OldImage' will return the 'NewImage' decl.
3110 // In such a case use the real declaration name, instead of the alias one,
3111 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3112 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3113 // has been aliased.
3114 ClassName = PrevIDecl->getIdentifier();
3117 // If this forward declaration has type parameters, compare them with the
3118 // type parameters of the previous declaration.
3119 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3120 if (PrevIDecl && TypeParams) {
3121 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3122 // Check for consistency with the previous declaration.
3123 if (checkTypeParamListConsistency(
3124 SemaRef, PrevTypeParams, TypeParams,
3125 TypeParamListContext::ForwardDeclaration)) {
3126 TypeParams = nullptr;
3128 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3129 // The @interface does not have type parameters. Complain.
3130 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3131 << ClassName
3132 << TypeParams->getSourceRange();
3133 Diag(Def->getLocation(), diag::note_defined_here)
3134 << ClassName;
3136 TypeParams = nullptr;
3140 ObjCInterfaceDecl *IDecl = ObjCInterfaceDecl::Create(
3141 Context, SemaRef.CurContext, AtClassLoc, ClassName, TypeParams,
3142 PrevIDecl, IdentLocs[i]);
3143 IDecl->setAtEndRange(IdentLocs[i]);
3145 if (PrevIDecl)
3146 SemaRef.mergeDeclAttributes(IDecl, PrevIDecl);
3148 SemaRef.PushOnScopeChains(IDecl, SemaRef.TUScope);
3149 CheckObjCDeclScope(IDecl);
3150 DeclsInGroup.push_back(IDecl);
3153 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
3156 static bool tryMatchRecordTypes(ASTContext &Context,
3157 SemaObjC::MethodMatchStrategy strategy,
3158 const Type *left, const Type *right);
3160 static bool matchTypes(ASTContext &Context,
3161 SemaObjC::MethodMatchStrategy strategy, QualType leftQT,
3162 QualType rightQT) {
3163 const Type *left =
3164 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3165 const Type *right =
3166 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3168 if (left == right) return true;
3170 // If we're doing a strict match, the types have to match exactly.
3171 if (strategy == SemaObjC::MMS_strict)
3172 return false;
3174 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3176 // Otherwise, use this absurdly complicated algorithm to try to
3177 // validate the basic, low-level compatibility of the two types.
3179 // As a minimum, require the sizes and alignments to match.
3180 TypeInfo LeftTI = Context.getTypeInfo(left);
3181 TypeInfo RightTI = Context.getTypeInfo(right);
3182 if (LeftTI.Width != RightTI.Width)
3183 return false;
3185 if (LeftTI.Align != RightTI.Align)
3186 return false;
3188 // Consider all the kinds of non-dependent canonical types:
3189 // - functions and arrays aren't possible as return and parameter types
3191 // - vector types of equal size can be arbitrarily mixed
3192 if (isa<VectorType>(left)) return isa<VectorType>(right);
3193 if (isa<VectorType>(right)) return false;
3195 // - references should only match references of identical type
3196 // - structs, unions, and Objective-C objects must match more-or-less
3197 // exactly
3198 // - everything else should be a scalar
3199 if (!left->isScalarType() || !right->isScalarType())
3200 return tryMatchRecordTypes(Context, strategy, left, right);
3202 // Make scalars agree in kind, except count bools as chars, and group
3203 // all non-member pointers together.
3204 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3205 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3206 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3207 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3208 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3209 leftSK = Type::STK_ObjCObjectPointer;
3210 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3211 rightSK = Type::STK_ObjCObjectPointer;
3213 // Note that data member pointers and function member pointers don't
3214 // intermix because of the size differences.
3216 return (leftSK == rightSK);
3219 static bool tryMatchRecordTypes(ASTContext &Context,
3220 SemaObjC::MethodMatchStrategy strategy,
3221 const Type *lt, const Type *rt) {
3222 assert(lt && rt && lt != rt);
3224 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3225 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3226 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3228 // Require union-hood to match.
3229 if (left->isUnion() != right->isUnion()) return false;
3231 // Require an exact match if either is non-POD.
3232 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3233 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3234 return false;
3236 // Require size and alignment to match.
3237 TypeInfo LeftTI = Context.getTypeInfo(lt);
3238 TypeInfo RightTI = Context.getTypeInfo(rt);
3239 if (LeftTI.Width != RightTI.Width)
3240 return false;
3242 if (LeftTI.Align != RightTI.Align)
3243 return false;
3245 // Require fields to match.
3246 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3247 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3248 for (; li != le && ri != re; ++li, ++ri) {
3249 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3250 return false;
3252 return (li == le && ri == re);
3255 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3256 /// returns true, or false, accordingly.
3257 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3258 bool SemaObjC::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3259 const ObjCMethodDecl *right,
3260 MethodMatchStrategy strategy) {
3261 ASTContext &Context = getASTContext();
3262 if (!matchTypes(Context, strategy, left->getReturnType(),
3263 right->getReturnType()))
3264 return false;
3266 // If either is hidden, it is not considered to match.
3267 if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible())
3268 return false;
3270 if (left->isDirectMethod() != right->isDirectMethod())
3271 return false;
3273 if (getLangOpts().ObjCAutoRefCount &&
3274 (left->hasAttr<NSReturnsRetainedAttr>()
3275 != right->hasAttr<NSReturnsRetainedAttr>() ||
3276 left->hasAttr<NSConsumesSelfAttr>()
3277 != right->hasAttr<NSConsumesSelfAttr>()))
3278 return false;
3280 ObjCMethodDecl::param_const_iterator
3281 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3282 re = right->param_end();
3284 for (; li != le && ri != re; ++li, ++ri) {
3285 assert(ri != right->param_end() && "Param mismatch");
3286 const ParmVarDecl *lparm = *li, *rparm = *ri;
3288 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3289 return false;
3291 if (getLangOpts().ObjCAutoRefCount &&
3292 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3293 return false;
3295 return true;
3298 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3299 ObjCMethodDecl *MethodInList) {
3300 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3301 auto *MethodInListProtocol =
3302 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3303 // If this method belongs to a protocol but the method in list does not, or
3304 // vice versa, we say the context is not the same.
3305 if ((MethodProtocol && !MethodInListProtocol) ||
3306 (!MethodProtocol && MethodInListProtocol))
3307 return false;
3309 if (MethodProtocol && MethodInListProtocol)
3310 return true;
3312 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3313 ObjCInterfaceDecl *MethodInListInterface =
3314 MethodInList->getClassInterface();
3315 return MethodInterface == MethodInListInterface;
3318 void SemaObjC::addMethodToGlobalList(ObjCMethodList *List,
3319 ObjCMethodDecl *Method) {
3320 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3321 // inside categories.
3322 if (ObjCCategoryDecl *CD =
3323 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3324 if (!CD->IsClassExtension() && List->getBits() < 2)
3325 List->setBits(List->getBits() + 1);
3327 // If the list is empty, make it a singleton list.
3328 if (List->getMethod() == nullptr) {
3329 List->setMethod(Method);
3330 List->setNext(nullptr);
3331 return;
3334 // We've seen a method with this name, see if we have already seen this type
3335 // signature.
3336 ObjCMethodList *Previous = List;
3337 ObjCMethodList *ListWithSameDeclaration = nullptr;
3338 for (; List; Previous = List, List = List->getNext()) {
3339 // If we are building a module, keep all of the methods.
3340 if (getLangOpts().isCompilingModule())
3341 continue;
3343 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3344 List->getMethod());
3345 // Looking for method with a type bound requires the correct context exists.
3346 // We need to insert a method into the list if the context is different.
3347 // If the method's declaration matches the list
3348 // a> the method belongs to a different context: we need to insert it, in
3349 // order to emit the availability message, we need to prioritize over
3350 // availability among the methods with the same declaration.
3351 // b> the method belongs to the same context: there is no need to insert a
3352 // new entry.
3353 // If the method's declaration does not match the list, we insert it to the
3354 // end.
3355 if (!SameDeclaration ||
3356 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3357 // Even if two method types do not match, we would like to say
3358 // there is more than one declaration so unavailability/deprecated
3359 // warning is not too noisy.
3360 if (!Method->isDefined())
3361 List->setHasMoreThanOneDecl(true);
3363 // For methods with the same declaration, the one that is deprecated
3364 // should be put in the front for better diagnostics.
3365 if (Method->isDeprecated() && SameDeclaration &&
3366 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3367 ListWithSameDeclaration = List;
3369 if (Method->isUnavailable() && SameDeclaration &&
3370 !ListWithSameDeclaration &&
3371 List->getMethod()->getAvailability() < AR_Deprecated)
3372 ListWithSameDeclaration = List;
3373 continue;
3376 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3378 // Propagate the 'defined' bit.
3379 if (Method->isDefined())
3380 PrevObjCMethod->setDefined(true);
3381 else {
3382 // Objective-C doesn't allow an @interface for a class after its
3383 // @implementation. So if Method is not defined and there already is
3384 // an entry for this type signature, Method has to be for a different
3385 // class than PrevObjCMethod.
3386 List->setHasMoreThanOneDecl(true);
3389 // If a method is deprecated, push it in the global pool.
3390 // This is used for better diagnostics.
3391 if (Method->isDeprecated()) {
3392 if (!PrevObjCMethod->isDeprecated())
3393 List->setMethod(Method);
3395 // If the new method is unavailable, push it into global pool
3396 // unless previous one is deprecated.
3397 if (Method->isUnavailable()) {
3398 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3399 List->setMethod(Method);
3402 return;
3405 // We have a new signature for an existing method - add it.
3406 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3407 ObjCMethodList *Mem = SemaRef.BumpAlloc.Allocate<ObjCMethodList>();
3409 // We insert it right before ListWithSameDeclaration.
3410 if (ListWithSameDeclaration) {
3411 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3412 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3413 ListWithSameDeclaration->setMethod(Method);
3414 ListWithSameDeclaration->setNext(List);
3415 return;
3418 Previous->setNext(new (Mem) ObjCMethodList(Method));
3421 /// Read the contents of the method pool for a given selector from
3422 /// external storage.
3423 void SemaObjC::ReadMethodPool(Selector Sel) {
3424 assert(SemaRef.ExternalSource && "We need an external AST source");
3425 SemaRef.ExternalSource->ReadMethodPool(Sel);
3428 void SemaObjC::updateOutOfDateSelector(Selector Sel) {
3429 if (!SemaRef.ExternalSource)
3430 return;
3431 SemaRef.ExternalSource->updateOutOfDateSelector(Sel);
3434 void SemaObjC::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3435 bool instance) {
3436 // Ignore methods of invalid containers.
3437 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3438 return;
3440 if (SemaRef.ExternalSource)
3441 ReadMethodPool(Method->getSelector());
3443 auto &Lists = MethodPool[Method->getSelector()];
3445 Method->setDefined(impl);
3447 ObjCMethodList &Entry = instance ? Lists.first : Lists.second;
3448 addMethodToGlobalList(&Entry, Method);
3451 /// Determines if this is an "acceptable" loose mismatch in the global
3452 /// method pool. This exists mostly as a hack to get around certain
3453 /// global mismatches which we can't afford to make warnings / errors.
3454 /// Really, what we want is a way to take a method out of the global
3455 /// method pool.
3456 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3457 ObjCMethodDecl *other) {
3458 if (!chosen->isInstanceMethod())
3459 return false;
3461 if (chosen->isDirectMethod() != other->isDirectMethod())
3462 return false;
3464 Selector sel = chosen->getSelector();
3465 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3466 return false;
3468 // Don't complain about mismatches for -length if the method we
3469 // chose has an integral result type.
3470 return (chosen->getReturnType()->isIntegerType());
3473 /// Return true if the given method is wthin the type bound.
3474 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3475 const ObjCObjectType *TypeBound) {
3476 if (!TypeBound)
3477 return true;
3479 if (TypeBound->isObjCId())
3480 // FIXME: should we handle the case of bounding to id<A, B> differently?
3481 return true;
3483 auto *BoundInterface = TypeBound->getInterface();
3484 assert(BoundInterface && "unexpected object type!");
3486 // Check if the Method belongs to a protocol. We should allow any method
3487 // defined in any protocol, because any subclass could adopt the protocol.
3488 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3489 if (MethodProtocol) {
3490 return true;
3493 // If the Method belongs to a class, check if it belongs to the class
3494 // hierarchy of the class bound.
3495 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3496 // We allow methods declared within classes that are part of the hierarchy
3497 // of the class bound (superclass of, subclass of, or the same as the class
3498 // bound).
3499 return MethodInterface == BoundInterface ||
3500 MethodInterface->isSuperClassOf(BoundInterface) ||
3501 BoundInterface->isSuperClassOf(MethodInterface);
3503 llvm_unreachable("unknown method context");
3506 /// We first select the type of the method: Instance or Factory, then collect
3507 /// all methods with that type.
3508 bool SemaObjC::CollectMultipleMethodsInGlobalPool(
3509 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3510 bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound) {
3511 if (SemaRef.ExternalSource)
3512 ReadMethodPool(Sel);
3514 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3515 if (Pos == MethodPool.end())
3516 return false;
3518 // Gather the non-hidden methods.
3519 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3520 Pos->second.second;
3521 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3522 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3523 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3524 Methods.push_back(M->getMethod());
3527 // Return if we find any method with the desired kind.
3528 if (!Methods.empty())
3529 return Methods.size() > 1;
3531 if (!CheckTheOther)
3532 return false;
3534 // Gather the other kind.
3535 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3536 Pos->second.first;
3537 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3538 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3539 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3540 Methods.push_back(M->getMethod());
3543 return Methods.size() > 1;
3546 bool SemaObjC::AreMultipleMethodsInGlobalPool(
3547 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3548 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3549 // Diagnose finding more than one method in global pool.
3550 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3551 FilteredMethods.push_back(BestMethod);
3553 for (auto *M : Methods)
3554 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3555 FilteredMethods.push_back(M);
3557 if (FilteredMethods.size() > 1)
3558 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3559 receiverIdOrClass);
3561 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3562 // Test for no method in the pool which should not trigger any warning by
3563 // caller.
3564 if (Pos == MethodPool.end())
3565 return true;
3566 ObjCMethodList &MethList =
3567 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3568 return MethList.hasMoreThanOneDecl();
3571 ObjCMethodDecl *SemaObjC::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3572 bool receiverIdOrClass,
3573 bool instance) {
3574 if (SemaRef.ExternalSource)
3575 ReadMethodPool(Sel);
3577 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3578 if (Pos == MethodPool.end())
3579 return nullptr;
3581 // Gather the non-hidden methods.
3582 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3583 SmallVector<ObjCMethodDecl *, 4> Methods;
3584 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3585 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible())
3586 return M->getMethod();
3588 return nullptr;
3591 void SemaObjC::DiagnoseMultipleMethodInGlobalPool(
3592 SmallVectorImpl<ObjCMethodDecl *> &Methods, Selector Sel, SourceRange R,
3593 bool receiverIdOrClass) {
3594 // We found multiple methods, so we may have to complain.
3595 bool issueDiagnostic = false, issueError = false;
3597 // We support a warning which complains about *any* difference in
3598 // method signature.
3599 bool strictSelectorMatch =
3600 receiverIdOrClass &&
3601 !getDiagnostics().isIgnored(diag::warn_strict_multiple_method_decl,
3602 R.getBegin());
3603 if (strictSelectorMatch) {
3604 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3605 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3606 issueDiagnostic = true;
3607 break;
3612 // If we didn't see any strict differences, we won't see any loose
3613 // differences. In ARC, however, we also need to check for loose
3614 // mismatches, because most of them are errors.
3615 if (!strictSelectorMatch ||
3616 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3617 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3618 // This checks if the methods differ in type mismatch.
3619 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3620 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3621 issueDiagnostic = true;
3622 if (getLangOpts().ObjCAutoRefCount)
3623 issueError = true;
3624 break;
3628 if (issueDiagnostic) {
3629 if (issueError)
3630 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3631 else if (strictSelectorMatch)
3632 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3633 else
3634 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3636 Diag(Methods[0]->getBeginLoc(),
3637 issueError ? diag::note_possibility : diag::note_using)
3638 << Methods[0]->getSourceRange();
3639 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3640 Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3641 << Methods[I]->getSourceRange();
3646 ObjCMethodDecl *SemaObjC::LookupImplementedMethodInGlobalPool(Selector Sel) {
3647 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3648 if (Pos == MethodPool.end())
3649 return nullptr;
3651 auto &Methods = Pos->second;
3652 for (const ObjCMethodList *Method = &Methods.first; Method;
3653 Method = Method->getNext())
3654 if (Method->getMethod() &&
3655 (Method->getMethod()->isDefined() ||
3656 Method->getMethod()->isPropertyAccessor()))
3657 return Method->getMethod();
3659 for (const ObjCMethodList *Method = &Methods.second; Method;
3660 Method = Method->getNext())
3661 if (Method->getMethod() &&
3662 (Method->getMethod()->isDefined() ||
3663 Method->getMethod()->isPropertyAccessor()))
3664 return Method->getMethod();
3665 return nullptr;
3668 static void
3669 HelperSelectorsForTypoCorrection(
3670 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3671 StringRef Typo, const ObjCMethodDecl * Method) {
3672 const unsigned MaxEditDistance = 1;
3673 unsigned BestEditDistance = MaxEditDistance + 1;
3674 std::string MethodName = Method->getSelector().getAsString();
3676 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3677 if (MinPossibleEditDistance > 0 &&
3678 Typo.size() / MinPossibleEditDistance < 1)
3679 return;
3680 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3681 if (EditDistance > MaxEditDistance)
3682 return;
3683 if (EditDistance == BestEditDistance)
3684 BestMethod.push_back(Method);
3685 else if (EditDistance < BestEditDistance) {
3686 BestMethod.clear();
3687 BestMethod.push_back(Method);
3691 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3692 QualType ObjectType) {
3693 if (ObjectType.isNull())
3694 return true;
3695 if (S.ObjC().LookupMethodInObjectType(Sel, ObjectType,
3696 true /*Instance method*/))
3697 return true;
3698 return S.ObjC().LookupMethodInObjectType(Sel, ObjectType,
3699 false /*Class method*/) != nullptr;
3702 const ObjCMethodDecl *
3703 SemaObjC::SelectorsForTypoCorrection(Selector Sel, QualType ObjectType) {
3704 unsigned NumArgs = Sel.getNumArgs();
3705 SmallVector<const ObjCMethodDecl *, 8> Methods;
3706 bool ObjectIsId = true, ObjectIsClass = true;
3707 if (ObjectType.isNull())
3708 ObjectIsId = ObjectIsClass = false;
3709 else if (!ObjectType->isObjCObjectPointerType())
3710 return nullptr;
3711 else if (const ObjCObjectPointerType *ObjCPtr =
3712 ObjectType->getAsObjCInterfacePointerType()) {
3713 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3714 ObjectIsId = ObjectIsClass = false;
3716 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3717 ObjectIsClass = false;
3718 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3719 ObjectIsId = false;
3720 else
3721 return nullptr;
3723 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3724 e = MethodPool.end(); b != e; b++) {
3725 // instance methods
3726 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3727 if (M->getMethod() &&
3728 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3729 (M->getMethod()->getSelector() != Sel)) {
3730 if (ObjectIsId)
3731 Methods.push_back(M->getMethod());
3732 else if (!ObjectIsClass &&
3733 HelperIsMethodInObjCType(
3734 SemaRef, M->getMethod()->getSelector(), ObjectType))
3735 Methods.push_back(M->getMethod());
3737 // class methods
3738 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3739 if (M->getMethod() &&
3740 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3741 (M->getMethod()->getSelector() != Sel)) {
3742 if (ObjectIsClass)
3743 Methods.push_back(M->getMethod());
3744 else if (!ObjectIsId &&
3745 HelperIsMethodInObjCType(
3746 SemaRef, M->getMethod()->getSelector(), ObjectType))
3747 Methods.push_back(M->getMethod());
3751 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3752 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3753 HelperSelectorsForTypoCorrection(SelectedMethods,
3754 Sel.getAsString(), Methods[i]);
3756 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3759 /// DiagnoseDuplicateIvars -
3760 /// Check for duplicate ivars in the entire class at the start of
3761 /// \@implementation. This becomes necessary because class extension can
3762 /// add ivars to a class in random order which will not be known until
3763 /// class's \@implementation is seen.
3764 void SemaObjC::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3765 ObjCInterfaceDecl *SID) {
3766 for (auto *Ivar : ID->ivars()) {
3767 if (Ivar->isInvalidDecl())
3768 continue;
3769 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3770 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3771 if (prevIvar) {
3772 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3773 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3774 Ivar->setInvalidDecl();
3780 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3781 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3782 if (S.getLangOpts().ObjCWeak) return;
3784 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3785 ivar; ivar = ivar->getNextIvar()) {
3786 if (ivar->isInvalidDecl()) continue;
3787 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3788 if (S.getLangOpts().ObjCWeakRuntime) {
3789 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3790 } else {
3791 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3797 /// Diagnose attempts to use flexible array member with retainable object type.
3798 static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3799 ObjCInterfaceDecl *ID) {
3800 if (!S.getLangOpts().ObjCAutoRefCount)
3801 return;
3803 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3804 ivar = ivar->getNextIvar()) {
3805 if (ivar->isInvalidDecl())
3806 continue;
3807 QualType IvarTy = ivar->getType();
3808 if (IvarTy->isIncompleteArrayType() &&
3809 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3810 IvarTy->isObjCLifetimeType()) {
3811 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3812 ivar->setInvalidDecl();
3817 SemaObjC::ObjCContainerKind SemaObjC::getObjCContainerKind() const {
3818 switch (SemaRef.CurContext->getDeclKind()) {
3819 case Decl::ObjCInterface:
3820 return SemaObjC::OCK_Interface;
3821 case Decl::ObjCProtocol:
3822 return SemaObjC::OCK_Protocol;
3823 case Decl::ObjCCategory:
3824 if (cast<ObjCCategoryDecl>(SemaRef.CurContext)->IsClassExtension())
3825 return SemaObjC::OCK_ClassExtension;
3826 return SemaObjC::OCK_Category;
3827 case Decl::ObjCImplementation:
3828 return SemaObjC::OCK_Implementation;
3829 case Decl::ObjCCategoryImpl:
3830 return SemaObjC::OCK_CategoryImplementation;
3832 default:
3833 return SemaObjC::OCK_None;
3837 static bool IsVariableSizedType(QualType T) {
3838 if (T->isIncompleteArrayType())
3839 return true;
3840 const auto *RecordTy = T->getAs<RecordType>();
3841 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3844 static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3845 ObjCInterfaceDecl *IntfDecl = nullptr;
3846 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3847 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3848 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3849 Ivars = IntfDecl->ivars();
3850 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3851 IntfDecl = ImplDecl->getClassInterface();
3852 Ivars = ImplDecl->ivars();
3853 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3854 if (CategoryDecl->IsClassExtension()) {
3855 IntfDecl = CategoryDecl->getClassInterface();
3856 Ivars = CategoryDecl->ivars();
3860 // Check if variable sized ivar is in interface and visible to subclasses.
3861 if (!isa<ObjCInterfaceDecl>(OCD)) {
3862 for (auto *ivar : Ivars) {
3863 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3864 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3865 << ivar->getDeclName() << ivar->getType();
3870 // Subsequent checks require interface decl.
3871 if (!IntfDecl)
3872 return;
3874 // Check if variable sized ivar is followed by another ivar.
3875 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3876 ivar = ivar->getNextIvar()) {
3877 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3878 continue;
3879 QualType IvarTy = ivar->getType();
3880 bool IsInvalidIvar = false;
3881 if (IvarTy->isIncompleteArrayType()) {
3882 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3883 << ivar->getDeclName() << IvarTy
3884 << llvm::to_underlying(TagTypeKind::Class); // Use "class" for Obj-C.
3885 IsInvalidIvar = true;
3886 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3887 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3888 S.Diag(ivar->getLocation(),
3889 diag::err_objc_variable_sized_type_not_at_end)
3890 << ivar->getDeclName() << IvarTy;
3891 IsInvalidIvar = true;
3894 if (IsInvalidIvar) {
3895 S.Diag(ivar->getNextIvar()->getLocation(),
3896 diag::note_next_ivar_declaration)
3897 << ivar->getNextIvar()->getSynthesize();
3898 ivar->setInvalidDecl();
3902 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3903 // Perform the check only if OCD is the first container to declare ivars to
3904 // avoid multiple warnings for the same ivar.
3905 ObjCIvarDecl *FirstIvar =
3906 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3907 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3908 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3909 while (SuperClass && SuperClass->ivar_empty())
3910 SuperClass = SuperClass->getSuperClass();
3911 if (SuperClass) {
3912 auto IvarIter = SuperClass->ivar_begin();
3913 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3914 const ObjCIvarDecl *LastIvar = *IvarIter;
3915 if (IsVariableSizedType(LastIvar->getType())) {
3916 S.Diag(FirstIvar->getLocation(),
3917 diag::warn_superclass_variable_sized_type_not_at_end)
3918 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3919 << LastIvar->getType() << SuperClass->getDeclName();
3920 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3921 << LastIvar->getDeclName();
3927 static void DiagnoseCategoryDirectMembersProtocolConformance(
3928 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
3930 static void DiagnoseCategoryDirectMembersProtocolConformance(
3931 Sema &S, ObjCCategoryDecl *CDecl,
3932 const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
3933 for (auto *PI : Protocols)
3934 DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl);
3937 static void DiagnoseCategoryDirectMembersProtocolConformance(
3938 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
3939 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
3940 PDecl = PDecl->getDefinition();
3942 llvm::SmallVector<const Decl *, 4> DirectMembers;
3943 const auto *IDecl = CDecl->getClassInterface();
3944 for (auto *MD : PDecl->methods()) {
3945 if (!MD->isPropertyAccessor()) {
3946 if (const auto *CMD =
3947 IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
3948 if (CMD->isDirectMethod())
3949 DirectMembers.push_back(CMD);
3953 for (auto *PD : PDecl->properties()) {
3954 if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
3955 PD->getIdentifier(),
3956 PD->isClassProperty()
3957 ? ObjCPropertyQueryKind::OBJC_PR_query_class
3958 : ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
3959 if (CPD->isDirectProperty())
3960 DirectMembers.push_back(CPD);
3963 if (!DirectMembers.empty()) {
3964 S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
3965 << CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
3966 for (const auto *MD : DirectMembers)
3967 S.Diag(MD->getLocation(), diag::note_direct_member_here);
3968 return;
3971 // Check on this protocols's referenced protocols, recursively.
3972 DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl,
3973 PDecl->protocols());
3976 // Note: For class/category implementations, allMethods is always null.
3977 Decl *SemaObjC::ActOnAtEnd(Scope *S, SourceRange AtEnd,
3978 ArrayRef<Decl *> allMethods,
3979 ArrayRef<DeclGroupPtrTy> allTUVars) {
3980 ASTContext &Context = getASTContext();
3981 if (getObjCContainerKind() == SemaObjC::OCK_None)
3982 return nullptr;
3984 assert(AtEnd.isValid() && "Invalid location for '@end'");
3986 auto *OCD = cast<ObjCContainerDecl>(SemaRef.CurContext);
3987 Decl *ClassDecl = OCD;
3989 bool isInterfaceDeclKind =
3990 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3991 || isa<ObjCProtocolDecl>(ClassDecl);
3992 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3994 // Make synthesized accessor stub functions visible.
3995 // ActOnPropertyImplDecl() creates them as not visible in case
3996 // they are overridden by an explicit method that is encountered
3997 // later.
3998 if (auto *OID = dyn_cast<ObjCImplementationDecl>(SemaRef.CurContext)) {
3999 for (auto *PropImpl : OID->property_impls()) {
4000 if (auto *Getter = PropImpl->getGetterMethodDecl())
4001 if (Getter->isSynthesizedAccessorStub())
4002 OID->addDecl(Getter);
4003 if (auto *Setter = PropImpl->getSetterMethodDecl())
4004 if (Setter->isSynthesizedAccessorStub())
4005 OID->addDecl(Setter);
4009 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
4010 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
4011 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
4013 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
4014 ObjCMethodDecl *Method =
4015 cast_or_null<ObjCMethodDecl>(allMethods[i]);
4017 if (!Method) continue; // Already issued a diagnostic.
4018 if (Method->isInstanceMethod()) {
4019 /// Check for instance method of the same name with incompatible types
4020 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
4021 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4022 : false;
4023 if ((isInterfaceDeclKind && PrevMethod && !match)
4024 || (checkIdenticalMethods && match)) {
4025 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4026 << Method->getDeclName();
4027 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4028 Method->setInvalidDecl();
4029 } else {
4030 if (PrevMethod) {
4031 Method->setAsRedeclaration(PrevMethod);
4032 if (!Context.getSourceManager().isInSystemHeader(
4033 Method->getLocation()))
4034 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4035 << Method->getDeclName();
4036 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4038 InsMap[Method->getSelector()] = Method;
4039 /// The following allows us to typecheck messages to "id".
4040 AddInstanceMethodToGlobalPool(Method);
4042 } else {
4043 /// Check for class method of the same name with incompatible types
4044 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
4045 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4046 : false;
4047 if ((isInterfaceDeclKind && PrevMethod && !match)
4048 || (checkIdenticalMethods && match)) {
4049 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4050 << Method->getDeclName();
4051 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4052 Method->setInvalidDecl();
4053 } else {
4054 if (PrevMethod) {
4055 Method->setAsRedeclaration(PrevMethod);
4056 if (!Context.getSourceManager().isInSystemHeader(
4057 Method->getLocation()))
4058 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4059 << Method->getDeclName();
4060 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4062 ClsMap[Method->getSelector()] = Method;
4063 AddFactoryMethodToGlobalPool(Method);
4067 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
4068 // Nothing to do here.
4069 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
4070 // Categories are used to extend the class by declaring new methods.
4071 // By the same token, they are also used to add new properties. No
4072 // need to compare the added property to those in the class.
4074 if (C->IsClassExtension()) {
4075 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
4076 DiagnoseClassExtensionDupMethods(C, CCPrimary);
4079 DiagnoseCategoryDirectMembersProtocolConformance(SemaRef, C,
4080 C->protocols());
4082 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
4083 if (CDecl->getIdentifier())
4084 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
4085 // user-defined setter/getter. It also synthesizes setter/getter methods
4086 // and adds them to the DeclContext and global method pools.
4087 for (auto *I : CDecl->properties())
4088 ProcessPropertyDecl(I);
4089 CDecl->setAtEndRange(AtEnd);
4091 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
4092 IC->setAtEndRange(AtEnd);
4093 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
4094 // Any property declared in a class extension might have user
4095 // declared setter or getter in current class extension or one
4096 // of the other class extensions. Mark them as synthesized as
4097 // property will be synthesized when property with same name is
4098 // seen in the @implementation.
4099 for (const auto *Ext : IDecl->visible_extensions()) {
4100 for (const auto *Property : Ext->instance_properties()) {
4101 // Skip over properties declared @dynamic
4102 if (const ObjCPropertyImplDecl *PIDecl
4103 = IC->FindPropertyImplDecl(Property->getIdentifier(),
4104 Property->getQueryKind()))
4105 if (PIDecl->getPropertyImplementation()
4106 == ObjCPropertyImplDecl::Dynamic)
4107 continue;
4109 for (const auto *Ext : IDecl->visible_extensions()) {
4110 if (ObjCMethodDecl *GetterMethod =
4111 Ext->getInstanceMethod(Property->getGetterName()))
4112 GetterMethod->setPropertyAccessor(true);
4113 if (!Property->isReadOnly())
4114 if (ObjCMethodDecl *SetterMethod
4115 = Ext->getInstanceMethod(Property->getSetterName()))
4116 SetterMethod->setPropertyAccessor(true);
4120 ImplMethodsVsClassMethods(S, IC, IDecl);
4121 AtomicPropertySetterGetterRules(IC, IDecl);
4122 DiagnoseOwningPropertyGetterSynthesis(IC);
4123 DiagnoseUnusedBackingIvarInAccessor(S, IC);
4124 if (IDecl->hasDesignatedInitializers())
4125 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
4126 DiagnoseWeakIvars(SemaRef, IC);
4127 DiagnoseRetainableFlexibleArrayMember(SemaRef, IDecl);
4129 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4130 if (IDecl->getSuperClass() == nullptr) {
4131 // This class has no superclass, so check that it has been marked with
4132 // __attribute((objc_root_class)).
4133 if (!HasRootClassAttr) {
4134 SourceLocation DeclLoc(IDecl->getLocation());
4135 SourceLocation SuperClassLoc(SemaRef.getLocForEndOfToken(DeclLoc));
4136 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4137 << IDecl->getIdentifier();
4138 // See if NSObject is in the current scope, and if it is, suggest
4139 // adding " : NSObject " to the class declaration.
4140 NamedDecl *IF = SemaRef.LookupSingleName(
4141 SemaRef.TUScope, NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4142 DeclLoc, Sema::LookupOrdinaryName);
4143 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4144 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4145 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4146 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4147 } else {
4148 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4151 } else if (HasRootClassAttr) {
4152 // Complain that only root classes may have this attribute.
4153 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4156 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4157 // An interface can subclass another interface with a
4158 // objc_subclassing_restricted attribute when it has that attribute as
4159 // well (because of interfaces imported from Swift). Therefore we have
4160 // to check if we can subclass in the implementation as well.
4161 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4162 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4163 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4164 Diag(Super->getLocation(), diag::note_class_declared);
4168 if (IDecl->hasAttr<ObjCClassStubAttr>())
4169 Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4171 if (getLangOpts().ObjCRuntime.isNonFragile()) {
4172 while (IDecl->getSuperClass()) {
4173 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4174 IDecl = IDecl->getSuperClass();
4178 SetIvarInitializers(IC);
4179 } else if (ObjCCategoryImplDecl* CatImplClass =
4180 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4181 CatImplClass->setAtEndRange(AtEnd);
4183 // Find category interface decl and then check that all methods declared
4184 // in this interface are implemented in the category @implementation.
4185 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4186 if (ObjCCategoryDecl *Cat
4187 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4188 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4191 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4192 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4193 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4194 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4195 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4196 Diag(Super->getLocation(), diag::note_class_declared);
4200 if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4201 !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
4202 Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
4204 DiagnoseVariableSizedIvars(SemaRef, OCD);
4205 if (isInterfaceDeclKind) {
4206 // Reject invalid vardecls.
4207 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4208 DeclGroupRef DG = allTUVars[i].get();
4209 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4210 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4211 if (!VDecl->hasExternalStorage())
4212 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4216 ActOnObjCContainerFinishDefinition();
4218 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4219 DeclGroupRef DG = allTUVars[i].get();
4220 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4221 (*I)->setTopLevelDeclInObjCContainer();
4222 SemaRef.Consumer.HandleTopLevelDeclInObjCContainer(DG);
4225 SemaRef.ActOnDocumentableDecl(ClassDecl);
4226 return ClassDecl;
4229 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4230 /// objective-c's type qualifier from the parser version of the same info.
4231 static Decl::ObjCDeclQualifier
4232 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
4233 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4236 /// Check whether the declared result type of the given Objective-C
4237 /// method declaration is compatible with the method's class.
4239 static SemaObjC::ResultTypeCompatibilityKind
4240 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4241 ObjCInterfaceDecl *CurrentClass) {
4242 QualType ResultType = Method->getReturnType();
4244 // If an Objective-C method inherits its related result type, then its
4245 // declared result type must be compatible with its own class type. The
4246 // declared result type is compatible if:
4247 if (const ObjCObjectPointerType *ResultObjectType
4248 = ResultType->getAs<ObjCObjectPointerType>()) {
4249 // - it is id or qualified id, or
4250 if (ResultObjectType->isObjCIdType() ||
4251 ResultObjectType->isObjCQualifiedIdType())
4252 return SemaObjC::RTC_Compatible;
4254 if (CurrentClass) {
4255 if (ObjCInterfaceDecl *ResultClass
4256 = ResultObjectType->getInterfaceDecl()) {
4257 // - it is the same as the method's class type, or
4258 if (declaresSameEntity(CurrentClass, ResultClass))
4259 return SemaObjC::RTC_Compatible;
4261 // - it is a superclass of the method's class type
4262 if (ResultClass->isSuperClassOf(CurrentClass))
4263 return SemaObjC::RTC_Compatible;
4265 } else {
4266 // Any Objective-C pointer type might be acceptable for a protocol
4267 // method; we just don't know.
4268 return SemaObjC::RTC_Unknown;
4272 return SemaObjC::RTC_Incompatible;
4275 namespace {
4276 /// A helper class for searching for methods which a particular method
4277 /// overrides.
4278 class OverrideSearch {
4279 public:
4280 const ObjCMethodDecl *Method;
4281 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4282 bool Recursive;
4284 public:
4285 OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4286 Selector selector = method->getSelector();
4288 // Bypass this search if we've never seen an instance/class method
4289 // with this selector before.
4290 SemaObjC::GlobalMethodPool::iterator it =
4291 S.ObjC().MethodPool.find(selector);
4292 if (it == S.ObjC().MethodPool.end()) {
4293 if (!S.getExternalSource()) return;
4294 S.ObjC().ReadMethodPool(selector);
4296 it = S.ObjC().MethodPool.find(selector);
4297 if (it == S.ObjC().MethodPool.end())
4298 return;
4300 const ObjCMethodList &list =
4301 method->isInstanceMethod() ? it->second.first : it->second.second;
4302 if (!list.getMethod()) return;
4304 const ObjCContainerDecl *container
4305 = cast<ObjCContainerDecl>(method->getDeclContext());
4307 // Prevent the search from reaching this container again. This is
4308 // important with categories, which override methods from the
4309 // interface and each other.
4310 if (const ObjCCategoryDecl *Category =
4311 dyn_cast<ObjCCategoryDecl>(container)) {
4312 searchFromContainer(container);
4313 if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4314 searchFromContainer(Interface);
4315 } else {
4316 searchFromContainer(container);
4320 typedef decltype(Overridden)::iterator iterator;
4321 iterator begin() const { return Overridden.begin(); }
4322 iterator end() const { return Overridden.end(); }
4324 private:
4325 void searchFromContainer(const ObjCContainerDecl *container) {
4326 if (container->isInvalidDecl()) return;
4328 switch (container->getDeclKind()) {
4329 #define OBJCCONTAINER(type, base) \
4330 case Decl::type: \
4331 searchFrom(cast<type##Decl>(container)); \
4332 break;
4333 #define ABSTRACT_DECL(expansion)
4334 #define DECL(type, base) \
4335 case Decl::type:
4336 #include "clang/AST/DeclNodes.inc"
4337 llvm_unreachable("not an ObjC container!");
4341 void searchFrom(const ObjCProtocolDecl *protocol) {
4342 if (!protocol->hasDefinition())
4343 return;
4345 // A method in a protocol declaration overrides declarations from
4346 // referenced ("parent") protocols.
4347 search(protocol->getReferencedProtocols());
4350 void searchFrom(const ObjCCategoryDecl *category) {
4351 // A method in a category declaration overrides declarations from
4352 // the main class and from protocols the category references.
4353 // The main class is handled in the constructor.
4354 search(category->getReferencedProtocols());
4357 void searchFrom(const ObjCCategoryImplDecl *impl) {
4358 // A method in a category definition that has a category
4359 // declaration overrides declarations from the category
4360 // declaration.
4361 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4362 search(category);
4363 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4364 search(Interface);
4366 // Otherwise it overrides declarations from the class.
4367 } else if (const auto *Interface = impl->getClassInterface()) {
4368 search(Interface);
4372 void searchFrom(const ObjCInterfaceDecl *iface) {
4373 // A method in a class declaration overrides declarations from
4374 if (!iface->hasDefinition())
4375 return;
4377 // - categories,
4378 for (auto *Cat : iface->known_categories())
4379 search(Cat);
4381 // - the super class, and
4382 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4383 search(super);
4385 // - any referenced protocols.
4386 search(iface->getReferencedProtocols());
4389 void searchFrom(const ObjCImplementationDecl *impl) {
4390 // A method in a class implementation overrides declarations from
4391 // the class interface.
4392 if (const auto *Interface = impl->getClassInterface())
4393 search(Interface);
4396 void search(const ObjCProtocolList &protocols) {
4397 for (const auto *Proto : protocols)
4398 search(Proto);
4401 void search(const ObjCContainerDecl *container) {
4402 // Check for a method in this container which matches this selector.
4403 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4404 Method->isInstanceMethod(),
4405 /*AllowHidden=*/true);
4407 // If we find one, record it and bail out.
4408 if (meth) {
4409 Overridden.insert(meth);
4410 return;
4413 // Otherwise, search for methods that a hypothetical method here
4414 // would have overridden.
4416 // Note that we're now in a recursive case.
4417 Recursive = true;
4419 searchFromContainer(container);
4422 } // end anonymous namespace
4424 void SemaObjC::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
4425 ObjCMethodDecl *overridden) {
4426 if (overridden->isDirectMethod()) {
4427 const auto *attr = overridden->getAttr<ObjCDirectAttr>();
4428 Diag(method->getLocation(), diag::err_objc_override_direct_method);
4429 Diag(attr->getLocation(), diag::note_previous_declaration);
4430 } else if (method->isDirectMethod()) {
4431 const auto *attr = method->getAttr<ObjCDirectAttr>();
4432 Diag(attr->getLocation(), diag::err_objc_direct_on_override)
4433 << isa<ObjCProtocolDecl>(overridden->getDeclContext());
4434 Diag(overridden->getLocation(), diag::note_previous_declaration);
4438 void SemaObjC::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4439 ObjCInterfaceDecl *CurrentClass,
4440 ResultTypeCompatibilityKind RTC) {
4441 ASTContext &Context = getASTContext();
4442 if (!ObjCMethod)
4443 return;
4444 auto IsMethodInCurrentClass = [CurrentClass](const ObjCMethodDecl *M) {
4445 // Checking canonical decl works across modules.
4446 return M->getClassInterface()->getCanonicalDecl() ==
4447 CurrentClass->getCanonicalDecl();
4449 // Search for overridden methods and merge information down from them.
4450 OverrideSearch overrides(SemaRef, ObjCMethod);
4451 // Keep track if the method overrides any method in the class's base classes,
4452 // its protocols, or its categories' protocols; we will keep that info
4453 // in the ObjCMethodDecl.
4454 // For this info, a method in an implementation is not considered as
4455 // overriding the same method in the interface or its categories.
4456 bool hasOverriddenMethodsInBaseOrProtocol = false;
4457 for (ObjCMethodDecl *overridden : overrides) {
4458 if (!hasOverriddenMethodsInBaseOrProtocol) {
4459 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4460 !IsMethodInCurrentClass(overridden) || overridden->isOverriding()) {
4461 CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
4462 hasOverriddenMethodsInBaseOrProtocol = true;
4463 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4464 // OverrideSearch will return as "overridden" the same method in the
4465 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4466 // check whether a category of a base class introduced a method with the
4467 // same selector, after the interface method declaration.
4468 // To avoid unnecessary lookups in the majority of cases, we use the
4469 // extra info bits in GlobalMethodPool to check whether there were any
4470 // category methods with this selector.
4471 GlobalMethodPool::iterator It =
4472 MethodPool.find(ObjCMethod->getSelector());
4473 if (It != MethodPool.end()) {
4474 ObjCMethodList &List =
4475 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4476 unsigned CategCount = List.getBits();
4477 if (CategCount > 0) {
4478 // If the method is in a category we'll do lookup if there were at
4479 // least 2 category methods recorded, otherwise only one will do.
4480 if (CategCount > 1 ||
4481 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4482 OverrideSearch overrides(SemaRef, overridden);
4483 for (ObjCMethodDecl *SuperOverridden : overrides) {
4484 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4485 !IsMethodInCurrentClass(SuperOverridden)) {
4486 CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
4487 hasOverriddenMethodsInBaseOrProtocol = true;
4488 overridden->setOverriding(true);
4489 break;
4498 // Propagate down the 'related result type' bit from overridden methods.
4499 if (RTC != SemaObjC::RTC_Incompatible && overridden->hasRelatedResultType())
4500 ObjCMethod->setRelatedResultType();
4502 // Then merge the declarations.
4503 SemaRef.mergeObjCMethodDecls(ObjCMethod, overridden);
4505 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4506 continue; // Conflicting properties are detected elsewhere.
4508 // Check for overriding methods
4509 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4510 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4511 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4512 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4514 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4515 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4516 !overridden->isImplicit() /* not meant for properties */) {
4517 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4518 E = ObjCMethod->param_end();
4519 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4520 PrevE = overridden->param_end();
4521 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4522 assert(PrevI != overridden->param_end() && "Param mismatch");
4523 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4524 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4525 // If type of argument of method in this class does not match its
4526 // respective argument type in the super class method, issue warning;
4527 if (!Context.typesAreCompatible(T1, T2)) {
4528 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4529 << T1 << T2;
4530 Diag(overridden->getLocation(), diag::note_previous_declaration);
4531 break;
4537 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4540 /// Merge type nullability from for a redeclaration of the same entity,
4541 /// producing the updated type of the redeclared entity.
4542 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4543 QualType type,
4544 bool usesCSKeyword,
4545 SourceLocation prevLoc,
4546 QualType prevType,
4547 bool prevUsesCSKeyword) {
4548 // Determine the nullability of both types.
4549 auto nullability = type->getNullability();
4550 auto prevNullability = prevType->getNullability();
4552 // Easy case: both have nullability.
4553 if (nullability.has_value() == prevNullability.has_value()) {
4554 // Neither has nullability; continue.
4555 if (!nullability)
4556 return type;
4558 // The nullabilities are equivalent; do nothing.
4559 if (*nullability == *prevNullability)
4560 return type;
4562 // Complain about mismatched nullability.
4563 S.Diag(loc, diag::err_nullability_conflicting)
4564 << DiagNullabilityKind(*nullability, usesCSKeyword)
4565 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4566 return type;
4569 // If it's the redeclaration that has nullability, don't change anything.
4570 if (nullability)
4571 return type;
4573 // Otherwise, provide the result with the same nullability.
4574 return S.Context.getAttributedType(*prevNullability, type, type);
4577 /// Merge information from the declaration of a method in the \@interface
4578 /// (or a category/extension) into the corresponding method in the
4579 /// @implementation (for a class or category).
4580 static void mergeInterfaceMethodToImpl(Sema &S,
4581 ObjCMethodDecl *method,
4582 ObjCMethodDecl *prevMethod) {
4583 // Merge the objc_requires_super attribute.
4584 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4585 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4586 // merge the attribute into implementation.
4587 method->addAttr(
4588 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4589 method->getLocation()));
4592 // Merge nullability of the result type.
4593 QualType newReturnType
4594 = mergeTypeNullabilityForRedecl(
4595 S, method->getReturnTypeSourceRange().getBegin(),
4596 method->getReturnType(),
4597 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4598 prevMethod->getReturnTypeSourceRange().getBegin(),
4599 prevMethod->getReturnType(),
4600 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4601 method->setReturnType(newReturnType);
4603 // Handle each of the parameters.
4604 unsigned numParams = method->param_size();
4605 unsigned numPrevParams = prevMethod->param_size();
4606 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4607 ParmVarDecl *param = method->param_begin()[i];
4608 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4610 // Merge nullability.
4611 QualType newParamType
4612 = mergeTypeNullabilityForRedecl(
4613 S, param->getLocation(), param->getType(),
4614 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4615 prevParam->getLocation(), prevParam->getType(),
4616 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4617 param->setType(newParamType);
4621 /// Verify that the method parameters/return value have types that are supported
4622 /// by the x86 target.
4623 static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4624 const ObjCMethodDecl *Method) {
4625 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4626 llvm::Triple::x86 &&
4627 "x86-specific check invoked for a different target");
4628 SourceLocation Loc;
4629 QualType T;
4630 for (const ParmVarDecl *P : Method->parameters()) {
4631 if (P->getType()->isVectorType()) {
4632 Loc = P->getBeginLoc();
4633 T = P->getType();
4634 break;
4637 if (Loc.isInvalid()) {
4638 if (Method->getReturnType()->isVectorType()) {
4639 Loc = Method->getReturnTypeSourceRange().getBegin();
4640 T = Method->getReturnType();
4641 } else
4642 return;
4645 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4646 // iOS < 9 and macOS < 10.11.
4647 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4648 VersionTuple AcceptedInVersion;
4649 if (Triple.getOS() == llvm::Triple::IOS)
4650 AcceptedInVersion = VersionTuple(/*Major=*/9);
4651 else if (Triple.isMacOSX())
4652 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4653 else
4654 return;
4655 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
4656 AcceptedInVersion)
4657 return;
4658 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4659 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4660 : /*parameter*/ 0)
4661 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4664 static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4665 if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
4666 CD->hasAttr<ObjCDirectMembersAttr>()) {
4667 Method->addAttr(
4668 ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4672 static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl,
4673 ObjCMethodDecl *Method,
4674 ObjCImplDecl *ImpDecl = nullptr) {
4675 auto Sel = Method->getSelector();
4676 bool isInstance = Method->isInstanceMethod();
4677 bool diagnosed = false;
4679 auto diagClash = [&](const ObjCMethodDecl *IMD) {
4680 if (diagnosed || IMD->isImplicit())
4681 return;
4682 if (Method->isDirectMethod() || IMD->isDirectMethod()) {
4683 S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
4684 << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod()
4685 << Method->getDeclName();
4686 S.Diag(IMD->getLocation(), diag::note_previous_declaration);
4687 diagnosed = true;
4691 // Look for any other declaration of this method anywhere we can see in this
4692 // compilation unit.
4694 // We do not use IDecl->lookupMethod() because we have specific needs:
4696 // - we absolutely do not need to walk protocols, because
4697 // diag::err_objc_direct_on_protocol has already been emitted
4698 // during parsing if there's a conflict,
4700 // - when we do not find a match in a given @interface container,
4701 // we need to attempt looking it up in the @implementation block if the
4702 // translation unit sees it to find more clashes.
4704 if (auto *IMD = IDecl->getMethod(Sel, isInstance))
4705 diagClash(IMD);
4706 else if (auto *Impl = IDecl->getImplementation())
4707 if (Impl != ImpDecl)
4708 if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
4709 diagClash(IMD);
4711 for (const auto *Cat : IDecl->visible_categories())
4712 if (auto *IMD = Cat->getMethod(Sel, isInstance))
4713 diagClash(IMD);
4714 else if (auto CatImpl = Cat->getImplementation())
4715 if (CatImpl != ImpDecl)
4716 if (auto *IMD = Cat->getMethod(Sel, isInstance))
4717 diagClash(IMD);
4720 ParmVarDecl *SemaObjC::ActOnMethodParmDeclaration(Scope *S,
4721 ObjCArgInfo &ArgInfo,
4722 int ParamIndex,
4723 bool MethodDefinition) {
4724 ASTContext &Context = getASTContext();
4725 QualType ArgType;
4726 TypeSourceInfo *DI;
4728 if (!ArgInfo.Type) {
4729 ArgType = Context.getObjCIdType();
4730 DI = nullptr;
4731 } else {
4732 ArgType = SemaRef.GetTypeFromParser(ArgInfo.Type, &DI);
4734 LookupResult R(SemaRef, ArgInfo.Name, ArgInfo.NameLoc,
4735 Sema::LookupOrdinaryName,
4736 SemaRef.forRedeclarationInCurContext());
4737 SemaRef.LookupName(R, S);
4738 if (R.isSingleResult()) {
4739 NamedDecl *PrevDecl = R.getFoundDecl();
4740 if (S->isDeclScope(PrevDecl)) {
4741 Diag(ArgInfo.NameLoc,
4742 (MethodDefinition ? diag::warn_method_param_redefinition
4743 : diag::warn_method_param_declaration))
4744 << ArgInfo.Name;
4745 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4748 SourceLocation StartLoc =
4749 DI ? DI->getTypeLoc().getBeginLoc() : ArgInfo.NameLoc;
4751 // Temporarily put parameter variables in the translation unit. This is what
4752 // ActOnParamDeclarator does in the case of C arguments to the Objective-C
4753 // method too.
4754 ParmVarDecl *Param = SemaRef.CheckParameter(
4755 Context.getTranslationUnitDecl(), StartLoc, ArgInfo.NameLoc, ArgInfo.Name,
4756 ArgType, DI, SC_None);
4757 Param->setObjCMethodScopeInfo(ParamIndex);
4758 Param->setObjCDeclQualifier(
4759 CvtQTToAstBitMask(ArgInfo.DeclSpec.getObjCDeclQualifier()));
4761 // Apply the attributes to the parameter.
4762 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, Param, ArgInfo.ArgAttrs);
4763 SemaRef.AddPragmaAttributes(SemaRef.TUScope, Param);
4764 if (Param->hasAttr<BlocksAttr>()) {
4765 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4766 Param->setInvalidDecl();
4769 S->AddDecl(Param);
4770 SemaRef.IdResolver.AddDecl(Param);
4771 return Param;
4774 Decl *SemaObjC::ActOnMethodDeclaration(
4775 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4776 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4777 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4778 // optional arguments. The number of types/arguments is obtained
4779 // from the Sel.getNumArgs().
4780 ParmVarDecl **ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4781 unsigned CNumArgs, // c-style args
4782 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4783 bool isVariadic, bool MethodDefinition) {
4784 ASTContext &Context = getASTContext();
4785 // Make sure we can establish a context for the method.
4786 if (!SemaRef.CurContext->isObjCContainer()) {
4787 Diag(MethodLoc, diag::err_missing_method_context);
4788 return nullptr;
4791 Decl *ClassDecl = cast<ObjCContainerDecl>(SemaRef.CurContext);
4792 QualType resultDeclType;
4794 bool HasRelatedResultType = false;
4795 TypeSourceInfo *ReturnTInfo = nullptr;
4796 if (ReturnType) {
4797 resultDeclType = SemaRef.GetTypeFromParser(ReturnType, &ReturnTInfo);
4799 if (SemaRef.CheckFunctionReturnType(resultDeclType, MethodLoc))
4800 return nullptr;
4802 QualType bareResultType = resultDeclType;
4803 (void)AttributedType::stripOuterNullability(bareResultType);
4804 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4805 } else { // get the type for "id".
4806 resultDeclType = Context.getObjCIdType();
4807 Diag(MethodLoc, diag::warn_missing_method_return_type)
4808 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4811 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4812 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo,
4813 SemaRef.CurContext, MethodType == tok::minus, isVariadic,
4814 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4815 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4816 MethodDeclKind == tok::objc_optional
4817 ? ObjCImplementationControl::Optional
4818 : ObjCImplementationControl::Required,
4819 HasRelatedResultType);
4821 SmallVector<ParmVarDecl*, 16> Params;
4822 for (unsigned I = 0; I < Sel.getNumArgs(); ++I) {
4823 ParmVarDecl *Param = ArgInfo[I];
4824 Param->setDeclContext(ObjCMethod);
4825 SemaRef.ProcessAPINotes(Param);
4826 Params.push_back(Param);
4829 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4830 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4831 QualType ArgType = Param->getType();
4832 if (ArgType.isNull())
4833 ArgType = Context.getObjCIdType();
4834 else
4835 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4836 ArgType = Context.getAdjustedParameterType(ArgType);
4838 Param->setDeclContext(ObjCMethod);
4839 Params.push_back(Param);
4842 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4843 ObjCMethod->setObjCDeclQualifier(
4844 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4846 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, ObjCMethod, AttrList);
4847 SemaRef.AddPragmaAttributes(SemaRef.TUScope, ObjCMethod);
4848 SemaRef.ProcessAPINotes(ObjCMethod);
4850 // Add the method now.
4851 const ObjCMethodDecl *PrevMethod = nullptr;
4852 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4853 if (MethodType == tok::minus) {
4854 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4855 ImpDecl->addInstanceMethod(ObjCMethod);
4856 } else {
4857 PrevMethod = ImpDecl->getClassMethod(Sel);
4858 ImpDecl->addClassMethod(ObjCMethod);
4861 // If this method overrides a previous @synthesize declaration,
4862 // register it with the property. Linear search through all
4863 // properties here, because the autosynthesized stub hasn't been
4864 // made visible yet, so it can be overridden by a later
4865 // user-specified implementation.
4866 for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4867 if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4868 if (Setter->getSelector() == Sel &&
4869 Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4870 assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4871 PropertyImpl->setSetterMethodDecl(ObjCMethod);
4873 if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4874 if (Getter->getSelector() == Sel &&
4875 Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4876 assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4877 PropertyImpl->setGetterMethodDecl(ObjCMethod);
4878 break;
4882 // A method is either tagged direct explicitly, or inherits it from its
4883 // canonical declaration.
4885 // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4886 // because IDecl->lookupMethod() returns more possible matches than just
4887 // the canonical declaration.
4888 if (!ObjCMethod->isDirectMethod()) {
4889 const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4890 if (CanonicalMD->isDirectMethod()) {
4891 const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4892 ObjCMethod->addAttr(
4893 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4897 // Merge information from the @interface declaration into the
4898 // @implementation.
4899 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4900 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4901 ObjCMethod->isInstanceMethod())) {
4902 mergeInterfaceMethodToImpl(SemaRef, ObjCMethod, IMD);
4904 // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4905 // in one of these places:
4907 // (1) the canonical declaration in an @interface container paired
4908 // with the ImplDecl,
4909 // (2) non canonical declarations in @interface not paired with the
4910 // ImplDecl for the same Class,
4911 // (3) any superclass container.
4913 // Direct methods only allow for canonical declarations in the matching
4914 // container (case 1).
4916 // Direct methods overriding a superclass declaration (case 3) is
4917 // handled during overrides checks in CheckObjCMethodOverrides().
4919 // We deal with same-class container mismatches (Case 2) here.
4920 if (IDecl == IMD->getClassInterface()) {
4921 auto diagContainerMismatch = [&] {
4922 int decl = 0, impl = 0;
4924 if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4925 decl = Cat->IsClassExtension() ? 1 : 2;
4927 if (isa<ObjCCategoryImplDecl>(ImpDecl))
4928 impl = 1 + (decl != 0);
4930 Diag(ObjCMethod->getLocation(),
4931 diag::err_objc_direct_impl_decl_mismatch)
4932 << decl << impl;
4933 Diag(IMD->getLocation(), diag::note_previous_declaration);
4936 if (ObjCMethod->isDirectMethod()) {
4937 const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4938 if (ObjCMethod->getCanonicalDecl() != IMD) {
4939 diagContainerMismatch();
4940 } else if (!IMD->isDirectMethod()) {
4941 Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4942 Diag(IMD->getLocation(), diag::note_previous_declaration);
4944 } else if (IMD->isDirectMethod()) {
4945 const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4946 if (ObjCMethod->getCanonicalDecl() != IMD) {
4947 diagContainerMismatch();
4948 } else {
4949 ObjCMethod->addAttr(
4950 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4955 // Warn about defining -dealloc in a category.
4956 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4957 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4958 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4959 << ObjCMethod->getDeclName();
4961 } else {
4962 mergeObjCDirectMembers(SemaRef, ClassDecl, ObjCMethod);
4963 checkObjCDirectMethodClashes(SemaRef, IDecl, ObjCMethod, ImpDecl);
4966 // Warn if a method declared in a protocol to which a category or
4967 // extension conforms is non-escaping and the implementation's method is
4968 // escaping.
4969 for (auto *C : IDecl->visible_categories())
4970 for (auto &P : C->protocols())
4971 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4972 ObjCMethod->isInstanceMethod())) {
4973 assert(ObjCMethod->parameters().size() ==
4974 IMD->parameters().size() &&
4975 "Methods have different number of parameters");
4976 auto OI = IMD->param_begin(), OE = IMD->param_end();
4977 auto NI = ObjCMethod->param_begin();
4978 for (; OI != OE; ++OI, ++NI)
4979 diagnoseNoescape(*NI, *OI, C, P, SemaRef);
4982 } else {
4983 if (!isa<ObjCProtocolDecl>(ClassDecl)) {
4984 mergeObjCDirectMembers(SemaRef, ClassDecl, ObjCMethod);
4986 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4987 if (!IDecl)
4988 IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
4989 // For valid code, we should always know the primary interface
4990 // declaration by now, however for invalid code we'll keep parsing
4991 // but we won't find the primary interface and IDecl will be nil.
4992 if (IDecl)
4993 checkObjCDirectMethodClashes(SemaRef, IDecl, ObjCMethod);
4996 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4999 if (PrevMethod) {
5000 // You can never have two method definitions with the same name.
5001 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
5002 << ObjCMethod->getDeclName();
5003 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
5004 ObjCMethod->setInvalidDecl();
5005 return ObjCMethod;
5008 // If this Objective-C method does not have a related result type, but we
5009 // are allowed to infer related result types, try to do so based on the
5010 // method family.
5011 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
5012 if (!CurrentClass) {
5013 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
5014 CurrentClass = Cat->getClassInterface();
5015 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
5016 CurrentClass = Impl->getClassInterface();
5017 else if (ObjCCategoryImplDecl *CatImpl
5018 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
5019 CurrentClass = CatImpl->getClassInterface();
5022 ResultTypeCompatibilityKind RTC =
5023 CheckRelatedResultTypeCompatibility(SemaRef, ObjCMethod, CurrentClass);
5025 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
5027 bool ARCError = false;
5028 if (getLangOpts().ObjCAutoRefCount)
5029 ARCError = CheckARCMethodDecl(ObjCMethod);
5031 // Infer the related result type when possible.
5032 if (!ARCError && RTC == SemaObjC::RTC_Compatible &&
5033 !ObjCMethod->hasRelatedResultType() &&
5034 getLangOpts().ObjCInferRelatedResultType) {
5035 bool InferRelatedResultType = false;
5036 switch (ObjCMethod->getMethodFamily()) {
5037 case OMF_None:
5038 case OMF_copy:
5039 case OMF_dealloc:
5040 case OMF_finalize:
5041 case OMF_mutableCopy:
5042 case OMF_release:
5043 case OMF_retainCount:
5044 case OMF_initialize:
5045 case OMF_performSelector:
5046 break;
5048 case OMF_alloc:
5049 case OMF_new:
5050 InferRelatedResultType = ObjCMethod->isClassMethod();
5051 break;
5053 case OMF_init:
5054 case OMF_autorelease:
5055 case OMF_retain:
5056 case OMF_self:
5057 InferRelatedResultType = ObjCMethod->isInstanceMethod();
5058 break;
5061 if (InferRelatedResultType &&
5062 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
5063 ObjCMethod->setRelatedResultType();
5066 if (MethodDefinition &&
5067 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5068 checkObjCMethodX86VectorTypes(SemaRef, ObjCMethod);
5070 // + load method cannot have availability attributes. It get called on
5071 // startup, so it has to have the availability of the deployment target.
5072 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
5073 if (ObjCMethod->isClassMethod() &&
5074 ObjCMethod->getSelector().getAsString() == "load") {
5075 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
5076 << 0;
5077 ObjCMethod->dropAttr<AvailabilityAttr>();
5081 // Insert the invisible arguments, self and _cmd!
5082 ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
5084 SemaRef.ActOnDocumentableDecl(ObjCMethod);
5086 return ObjCMethod;
5089 bool SemaObjC::CheckObjCDeclScope(Decl *D) {
5090 // Following is also an error. But it is caused by a missing @end
5091 // and diagnostic is issued elsewhere.
5092 if (isa<ObjCContainerDecl>(SemaRef.CurContext->getRedeclContext()))
5093 return false;
5095 // If we switched context to translation unit while we are still lexically in
5096 // an objc container, it means the parser missed emitting an error.
5097 if (isa<TranslationUnitDecl>(
5098 SemaRef.getCurLexicalContext()->getRedeclContext()))
5099 return false;
5101 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
5102 D->setInvalidDecl();
5104 return true;
5107 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
5108 /// instance variables of ClassName into Decls.
5109 void SemaObjC::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
5110 const IdentifierInfo *ClassName,
5111 SmallVectorImpl<Decl *> &Decls) {
5112 ASTContext &Context = getASTContext();
5113 // Check that ClassName is a valid class
5114 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
5115 if (!Class) {
5116 Diag(DeclStart, diag::err_undef_interface) << ClassName;
5117 return;
5119 if (getLangOpts().ObjCRuntime.isNonFragile()) {
5120 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
5121 return;
5124 // Collect the instance variables
5125 SmallVector<const ObjCIvarDecl*, 32> Ivars;
5126 Context.DeepCollectObjCIvars(Class, true, Ivars);
5127 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
5128 for (unsigned i = 0; i < Ivars.size(); i++) {
5129 const FieldDecl* ID = Ivars[i];
5130 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
5131 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
5132 /*FIXME: StartL=*/ID->getLocation(),
5133 ID->getLocation(),
5134 ID->getIdentifier(), ID->getType(),
5135 ID->getBitWidth());
5136 Decls.push_back(FD);
5139 // Introduce all of these fields into the appropriate scope.
5140 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
5141 D != Decls.end(); ++D) {
5142 FieldDecl *FD = cast<FieldDecl>(*D);
5143 if (getLangOpts().CPlusPlus)
5144 SemaRef.PushOnScopeChains(FD, S);
5145 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
5146 Record->addDecl(FD);
5150 /// Build a type-check a new Objective-C exception variable declaration.
5151 VarDecl *SemaObjC::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
5152 SourceLocation StartLoc,
5153 SourceLocation IdLoc,
5154 const IdentifierInfo *Id,
5155 bool Invalid) {
5156 ASTContext &Context = getASTContext();
5157 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5158 // duration shall not be qualified by an address-space qualifier."
5159 // Since all parameters have automatic store duration, they can not have
5160 // an address space.
5161 if (T.getAddressSpace() != LangAS::Default) {
5162 Diag(IdLoc, diag::err_arg_with_address_space);
5163 Invalid = true;
5166 // An @catch parameter must be an unqualified object pointer type;
5167 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
5168 if (Invalid) {
5169 // Don't do any further checking.
5170 } else if (T->isDependentType()) {
5171 // Okay: we don't know what this type will instantiate to.
5172 } else if (T->isObjCQualifiedIdType()) {
5173 Invalid = true;
5174 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
5175 } else if (T->isObjCIdType()) {
5176 // Okay: we don't know what this type will instantiate to.
5177 } else if (!T->isObjCObjectPointerType()) {
5178 Invalid = true;
5179 Diag(IdLoc, diag::err_catch_param_not_objc_type);
5180 } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) {
5181 Invalid = true;
5182 Diag(IdLoc, diag::err_catch_param_not_objc_type);
5185 VarDecl *New = VarDecl::Create(Context, SemaRef.CurContext, StartLoc, IdLoc,
5186 Id, T, TInfo, SC_None);
5187 New->setExceptionVariable(true);
5189 // In ARC, infer 'retaining' for variables of retainable type.
5190 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
5191 Invalid = true;
5193 if (Invalid)
5194 New->setInvalidDecl();
5195 return New;
5198 Decl *SemaObjC::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
5199 const DeclSpec &DS = D.getDeclSpec();
5201 // We allow the "register" storage class on exception variables because
5202 // GCC did, but we drop it completely. Any other storage class is an error.
5203 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
5204 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
5205 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
5206 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5207 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
5208 << DeclSpec::getSpecifierName(SCS);
5210 if (DS.isInlineSpecified())
5211 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5212 << getLangOpts().CPlusPlus17;
5213 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
5214 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5215 diag::err_invalid_thread)
5216 << DeclSpec::getSpecifierName(TSCS);
5217 D.getMutableDeclSpec().ClearStorageClassSpecs();
5219 SemaRef.DiagnoseFunctionSpecifiers(D.getDeclSpec());
5221 // Check that there are no default arguments inside the type of this
5222 // exception object (C++ only).
5223 if (getLangOpts().CPlusPlus)
5224 SemaRef.CheckExtraCXXDefaultArguments(D);
5226 TypeSourceInfo *TInfo = SemaRef.GetTypeForDeclarator(D);
5227 QualType ExceptionType = TInfo->getType();
5229 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
5230 D.getSourceRange().getBegin(),
5231 D.getIdentifierLoc(),
5232 D.getIdentifier(),
5233 D.isInvalidType());
5235 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5236 if (D.getCXXScopeSpec().isSet()) {
5237 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
5238 << D.getCXXScopeSpec().getRange();
5239 New->setInvalidDecl();
5242 // Add the parameter declaration into this scope.
5243 S->AddDecl(New);
5244 if (D.getIdentifier())
5245 SemaRef.IdResolver.AddDecl(New);
5247 SemaRef.ProcessDeclAttributes(S, New, D);
5249 if (New->hasAttr<BlocksAttr>())
5250 Diag(New->getLocation(), diag::err_block_on_nonlocal);
5251 return New;
5254 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
5255 /// initialization.
5256 void SemaObjC::CollectIvarsToConstructOrDestruct(
5257 ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl *> &Ivars) {
5258 ASTContext &Context = getASTContext();
5259 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
5260 Iv= Iv->getNextIvar()) {
5261 QualType QT = Context.getBaseElementType(Iv->getType());
5262 if (QT->isRecordType())
5263 Ivars.push_back(Iv);
5267 void SemaObjC::DiagnoseUseOfUnimplementedSelectors() {
5268 ASTContext &Context = getASTContext();
5269 // Load referenced selectors from the external source.
5270 if (SemaRef.ExternalSource) {
5271 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
5272 SemaRef.ExternalSource->ReadReferencedSelectors(Sels);
5273 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
5274 ReferencedSelectors[Sels[I].first] = Sels[I].second;
5277 // Warning will be issued only when selector table is
5278 // generated (which means there is at lease one implementation
5279 // in the TU). This is to match gcc's behavior.
5280 if (ReferencedSelectors.empty() ||
5281 !Context.AnyObjCImplementation())
5282 return;
5283 for (auto &SelectorAndLocation : ReferencedSelectors) {
5284 Selector Sel = SelectorAndLocation.first;
5285 SourceLocation Loc = SelectorAndLocation.second;
5286 if (!LookupImplementedMethodInGlobalPool(Sel))
5287 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
5291 ObjCIvarDecl *
5292 SemaObjC::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
5293 const ObjCPropertyDecl *&PDecl) const {
5294 if (Method->isClassMethod())
5295 return nullptr;
5296 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
5297 if (!IDecl)
5298 return nullptr;
5299 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
5300 /*shallowCategoryLookup=*/false,
5301 /*followSuper=*/false);
5302 if (!Method || !Method->isPropertyAccessor())
5303 return nullptr;
5304 if ((PDecl = Method->findPropertyDecl()))
5305 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5306 // property backing ivar must belong to property's class
5307 // or be a private ivar in class's implementation.
5308 // FIXME. fix the const-ness issue.
5309 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5310 IV->getIdentifier());
5311 return IV;
5313 return nullptr;
5316 namespace {
5317 /// Used by SemaObjC::DiagnoseUnusedBackingIvarInAccessor to check if a property
5318 /// accessor references the backing ivar.
5319 class UnusedBackingIvarChecker : public DynamicRecursiveASTVisitor {
5320 public:
5321 Sema &S;
5322 const ObjCMethodDecl *Method;
5323 const ObjCIvarDecl *IvarD;
5324 bool AccessedIvar;
5325 bool InvokedSelfMethod;
5327 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5328 const ObjCIvarDecl *IvarD)
5329 : S(S), Method(Method), IvarD(IvarD), AccessedIvar(false),
5330 InvokedSelfMethod(false) {
5331 assert(IvarD);
5334 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) override {
5335 if (E->getDecl() == IvarD) {
5336 AccessedIvar = true;
5337 return false;
5339 return true;
5342 bool VisitObjCMessageExpr(ObjCMessageExpr *E) override {
5343 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5344 S.ObjC().isSelfExpr(E->getInstanceReceiver(), Method)) {
5345 InvokedSelfMethod = true;
5347 return true;
5350 } // end anonymous namespace
5352 void SemaObjC::DiagnoseUnusedBackingIvarInAccessor(
5353 Scope *S, const ObjCImplementationDecl *ImplD) {
5354 if (S->hasUnrecoverableErrorOccurred())
5355 return;
5357 for (const auto *CurMethod : ImplD->instance_methods()) {
5358 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5359 SourceLocation Loc = CurMethod->getLocation();
5360 if (getDiagnostics().isIgnored(DIAG, Loc))
5361 continue;
5363 const ObjCPropertyDecl *PDecl;
5364 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5365 if (!IV)
5366 continue;
5368 if (CurMethod->isSynthesizedAccessorStub())
5369 continue;
5371 UnusedBackingIvarChecker Checker(SemaRef, CurMethod, IV);
5372 Checker.TraverseStmt(CurMethod->getBody());
5373 if (Checker.AccessedIvar)
5374 continue;
5376 // Do not issue this warning if backing ivar is used somewhere and accessor
5377 // implementation makes a self call. This is to prevent false positive in
5378 // cases where the ivar is accessed by another method that the accessor
5379 // delegates to.
5380 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5381 Diag(Loc, DIAG) << IV;
5382 Diag(PDecl->getLocation(), diag::note_property_declare);
5387 QualType SemaObjC::AdjustParameterTypeForObjCAutoRefCount(
5388 QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo) {
5389 ASTContext &Context = getASTContext();
5390 // In ARC, infer a lifetime qualifier for appropriate parameter types.
5391 if (!getLangOpts().ObjCAutoRefCount ||
5392 T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType())
5393 return T;
5395 Qualifiers::ObjCLifetime Lifetime;
5397 // Special cases for arrays:
5398 // - if it's const, use __unsafe_unretained
5399 // - otherwise, it's an error
5400 if (T->isArrayType()) {
5401 if (!T.isConstQualified()) {
5402 if (SemaRef.DelayedDiagnostics.shouldDelayDiagnostics())
5403 SemaRef.DelayedDiagnostics.add(
5404 sema::DelayedDiagnostic::makeForbiddenType(
5405 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
5406 else
5407 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
5408 << TSInfo->getTypeLoc().getSourceRange();
5410 Lifetime = Qualifiers::OCL_ExplicitNone;
5411 } else {
5412 Lifetime = T->getObjCARCImplicitLifetime();
5414 T = Context.getLifetimeQualifiedType(T, Lifetime);
5416 return T;
5419 ObjCInterfaceDecl *SemaObjC::getObjCInterfaceDecl(const IdentifierInfo *&Id,
5420 SourceLocation IdLoc,
5421 bool DoTypoCorrection) {
5422 // The third "scope" argument is 0 since we aren't enabling lazy built-in
5423 // creation from this context.
5424 NamedDecl *IDecl = SemaRef.LookupSingleName(SemaRef.TUScope, Id, IdLoc,
5425 Sema::LookupOrdinaryName);
5427 if (!IDecl && DoTypoCorrection) {
5428 // Perform typo correction at the given location, but only if we
5429 // find an Objective-C class name.
5430 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
5431 if (TypoCorrection C = SemaRef.CorrectTypo(
5432 DeclarationNameInfo(Id, IdLoc), Sema::LookupOrdinaryName,
5433 SemaRef.TUScope, nullptr, CCC, Sema::CTK_ErrorRecovery)) {
5434 SemaRef.diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
5435 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
5436 Id = IDecl->getIdentifier();
5439 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
5440 // This routine must always return a class definition, if any.
5441 if (Def && Def->getDefinition())
5442 Def = Def->getDefinition();
5443 return Def;
5446 bool SemaObjC::inferObjCARCLifetime(ValueDecl *decl) {
5447 ASTContext &Context = getASTContext();
5448 QualType type = decl->getType();
5449 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5450 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5451 // Various kinds of declaration aren't allowed to be __autoreleasing.
5452 unsigned kind = -1U;
5453 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5454 if (var->hasAttr<BlocksAttr>())
5455 kind = 0; // __block
5456 else if (!var->hasLocalStorage())
5457 kind = 1; // global
5458 } else if (isa<ObjCIvarDecl>(decl)) {
5459 kind = 3; // ivar
5460 } else if (isa<FieldDecl>(decl)) {
5461 kind = 2; // field
5464 if (kind != -1U) {
5465 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) << kind;
5467 } else if (lifetime == Qualifiers::OCL_None) {
5468 // Try to infer lifetime.
5469 if (!type->isObjCLifetimeType())
5470 return false;
5472 lifetime = type->getObjCARCImplicitLifetime();
5473 type = Context.getLifetimeQualifiedType(type, lifetime);
5474 decl->setType(type);
5477 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5478 // Thread-local variables cannot have lifetime.
5479 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5480 var->getTLSKind()) {
5481 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5482 << var->getType();
5483 return true;
5487 return false;
5490 ObjCContainerDecl *SemaObjC::getObjCDeclContext() const {
5491 return (dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext));
5494 void SemaObjC::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
5495 if (!getLangOpts().CPlusPlus)
5496 return;
5497 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
5498 ASTContext &Context = getASTContext();
5499 SmallVector<ObjCIvarDecl *, 8> ivars;
5500 CollectIvarsToConstructOrDestruct(OID, ivars);
5501 if (ivars.empty())
5502 return;
5503 SmallVector<CXXCtorInitializer *, 32> AllToInit;
5504 for (unsigned i = 0; i < ivars.size(); i++) {
5505 FieldDecl *Field = ivars[i];
5506 if (Field->isInvalidDecl())
5507 continue;
5509 CXXCtorInitializer *Member;
5510 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
5511 InitializationKind InitKind =
5512 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
5514 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5515 ExprResult MemberInit =
5516 InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5517 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5518 // Note, MemberInit could actually come back empty if no initialization
5519 // is required (e.g., because it would call a trivial default constructor)
5520 if (!MemberInit.get() || MemberInit.isInvalid())
5521 continue;
5523 Member = new (Context)
5524 CXXCtorInitializer(Context, Field, SourceLocation(), SourceLocation(),
5525 MemberInit.getAs<Expr>(), SourceLocation());
5526 AllToInit.push_back(Member);
5528 // Be sure that the destructor is accessible and is marked as referenced.
5529 if (const RecordType *RecordTy =
5530 Context.getBaseElementType(Field->getType())
5531 ->getAs<RecordType>()) {
5532 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
5533 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(RD)) {
5534 SemaRef.MarkFunctionReferenced(Field->getLocation(), Destructor);
5535 SemaRef.CheckDestructorAccess(
5536 Field->getLocation(), Destructor,
5537 PDiag(diag::err_access_dtor_ivar)
5538 << Context.getBaseElementType(Field->getType()));
5542 ObjCImplementation->setIvarInitializers(Context, AllToInit.data(),
5543 AllToInit.size());
5547 /// TranslateIvarVisibility - Translate visibility from a token ID to an
5548 /// AST enum value.
5549 static ObjCIvarDecl::AccessControl
5550 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
5551 switch (ivarVisibility) {
5552 default:
5553 llvm_unreachable("Unknown visitibility kind");
5554 case tok::objc_private:
5555 return ObjCIvarDecl::Private;
5556 case tok::objc_public:
5557 return ObjCIvarDecl::Public;
5558 case tok::objc_protected:
5559 return ObjCIvarDecl::Protected;
5560 case tok::objc_package:
5561 return ObjCIvarDecl::Package;
5565 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
5566 /// in order to create an IvarDecl object for it.
5567 Decl *SemaObjC::ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D,
5568 Expr *BitWidth, tok::ObjCKeywordKind Visibility) {
5570 const IdentifierInfo *II = D.getIdentifier();
5571 SourceLocation Loc = DeclStart;
5572 if (II)
5573 Loc = D.getIdentifierLoc();
5575 // FIXME: Unnamed fields can be handled in various different ways, for
5576 // example, unnamed unions inject all members into the struct namespace!
5578 TypeSourceInfo *TInfo = SemaRef.GetTypeForDeclarator(D);
5579 QualType T = TInfo->getType();
5581 if (BitWidth) {
5582 // 6.7.2.1p3, 6.7.2.1p4
5583 BitWidth =
5584 SemaRef.VerifyBitField(Loc, II, T, /*IsMsStruct*/ false, BitWidth)
5585 .get();
5586 if (!BitWidth)
5587 D.setInvalidType();
5588 } else {
5589 // Not a bitfield.
5591 // validate II.
5593 if (T->isReferenceType()) {
5594 Diag(Loc, diag::err_ivar_reference_type);
5595 D.setInvalidType();
5597 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5598 // than a variably modified type.
5599 else if (T->isVariablyModifiedType()) {
5600 if (!SemaRef.tryToFixVariablyModifiedVarType(
5601 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
5602 D.setInvalidType();
5605 // Get the visibility (access control) for this ivar.
5606 ObjCIvarDecl::AccessControl ac = Visibility != tok::objc_not_keyword
5607 ? TranslateIvarVisibility(Visibility)
5608 : ObjCIvarDecl::None;
5609 // Must set ivar's DeclContext to its enclosing interface.
5610 ObjCContainerDecl *EnclosingDecl =
5611 cast<ObjCContainerDecl>(SemaRef.CurContext);
5612 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
5613 return nullptr;
5614 ObjCContainerDecl *EnclosingContext;
5615 if (ObjCImplementationDecl *IMPDecl =
5616 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5617 if (getLangOpts().ObjCRuntime.isFragile()) {
5618 // Case of ivar declared in an implementation. Context is that of its
5619 // class.
5620 EnclosingContext = IMPDecl->getClassInterface();
5621 assert(EnclosingContext && "Implementation has no class interface!");
5622 } else
5623 EnclosingContext = EnclosingDecl;
5624 } else {
5625 if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
5626 if (getLangOpts().ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
5627 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
5628 return nullptr;
5631 EnclosingContext = EnclosingDecl;
5634 // Construct the decl.
5635 ObjCIvarDecl *NewID =
5636 ObjCIvarDecl::Create(getASTContext(), EnclosingContext, DeclStart, Loc,
5637 II, T, TInfo, ac, BitWidth);
5639 if (T->containsErrors())
5640 NewID->setInvalidDecl();
5642 if (II) {
5643 NamedDecl *PrevDecl =
5644 SemaRef.LookupSingleName(S, II, Loc, Sema::LookupMemberName,
5645 RedeclarationKind::ForVisibleRedeclaration);
5646 if (PrevDecl && SemaRef.isDeclInScope(PrevDecl, EnclosingContext, S) &&
5647 !isa<TagDecl>(PrevDecl)) {
5648 Diag(Loc, diag::err_duplicate_member) << II;
5649 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5650 NewID->setInvalidDecl();
5654 // Process attributes attached to the ivar.
5655 SemaRef.ProcessDeclAttributes(S, NewID, D);
5657 if (D.isInvalidType())
5658 NewID->setInvalidDecl();
5660 // In ARC, infer 'retaining' for ivars of retainable type.
5661 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
5662 NewID->setInvalidDecl();
5664 if (D.getDeclSpec().isModulePrivateSpecified())
5665 NewID->setModulePrivate();
5667 if (II) {
5668 // FIXME: When interfaces are DeclContexts, we'll need to add
5669 // these to the interface.
5670 S->AddDecl(NewID);
5671 SemaRef.IdResolver.AddDecl(NewID);
5674 if (getLangOpts().ObjCRuntime.isNonFragile() && !NewID->isInvalidDecl() &&
5675 isa<ObjCInterfaceDecl>(EnclosingDecl))
5676 Diag(Loc, diag::warn_ivars_in_interface);
5678 return NewID;