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