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