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