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

source code of clang/lib/Sema/SemaDeclObjC.cpp