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