clang 24.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() &&
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;
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() &&
104 SemaRef.getSourceManager().isInSystemHeader(loc)) {
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
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();
370 SemaRef.ImplicitlyRetainedSelfLocs.clear();
371 assert((SemaRef.getCurMethodDecl() == nullptr) && "Methodparsing confused");
372 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
373
374 SemaRef.PushExpressionEvaluationContext(
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);
390 SemaRef.PushFunctionScope();
391
392 // Create Decl objects for each parameter, entrring them in the scope for
393 // binding to their use.
394
395 // Insert the invisible arguments, self and _cmd!
396 MDecl->createImplicitParams(Context, 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.
402 SemaRef.CheckParmsForFunctionDef(MDecl->parameters(),
403 /*CheckParameterNames=*/false);
404
405 // Introduce all of the other parameters into this scope.
406 for (auto *Param : MDecl->parameters()) {
407 if (!Param->isInvalidDecl() && getLangOpts().ObjCAutoRefCount &&
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) {
471 SemaRef.getCurFunction()->ObjCIsDesignatedInit = true;
472 SemaRef.getCurFunction()->ObjCWarnForNoDesignatedInitChain =
473 IC->getSuperClass() != nullptr;
474 } else if (IC->hasDesignatedInitializers()) {
475 SemaRef.getCurFunction()->ObjCIsSecondaryInit = true;
476 SemaRef.getCurFunction()->ObjCWarnForNoInitDelegation = true;
477 }
478 }
479
480 // If this is "dealloc" or "finalize", set some bit here.
481 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
482 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
483 // Only do this if the current class actually has a superclass.
484 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
485 ObjCMethodFamily Family = MDecl->getMethodFamily();
486 if (Family == OMF_dealloc) {
487 if (!(getLangOpts().ObjCAutoRefCount ||
488 getLangOpts().getGC() == LangOptions::GCOnly))
489 SemaRef.getCurFunction()->ObjCShouldCallSuper = true;
490
491 } else if (Family == OMF_finalize) {
492 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
493 SemaRef.getCurFunction()->ObjCShouldCallSuper = true;
494
495 } else {
496 const ObjCMethodDecl *SuperMethod =
497 SuperClass->lookupMethod(MDecl->getSelector(),
498 MDecl->isInstanceMethod());
499 SemaRef.getCurFunction()->ObjCShouldCallSuper =
500 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
501 }
502 }
503 }
504
505 // Some function attributes (like OptimizeNoneAttr) need actions before
506 // parsing body started.
507 SemaRef.applyFunctionAttributesBeforeParsingBody(D);
508}
509
510namespace {
511
512// Callback to only accept typo corrections that are Objective-C classes.
513// If an ObjCInterfaceDecl* is given to the constructor, then the validation
514// function will reject corrections to that class.
515class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
516 public:
517 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
518 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
519 : CurrentIDecl(IDecl) {}
520
521 bool ValidateCandidate(const TypoCorrection &candidate) override {
522 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
523 return ID && !declaresSameEntity(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.
559 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
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,
568 SemaRef.TUScope, nullptr, CCC, CorrectTypoKind::ErrorRecovery)) {
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
606 (void)SemaRef.DiagnoseUseOfDecl(
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);
627 else if (SemaRef.RequireCompleteType(
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 =
684 SemaRef.getLocForEndOfToken(typeBoundInfo->getTypeLoc().getEndLoc());
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()) &&
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()
898 (newVarianceStr + " ").str());
899 } else {
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.
987 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
988 SemaRef.TUScope, ClassName, ClassLoc, Sema::LookupOrdinaryName,
989 SemaRef.forRedeclarationInCurContext());
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(),
1039 Context.getTrivialTypeSourceInfo(
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 SemaRef.isFromSameSingleIncludeHeader(Def, ClassLoc))) {
1059 SkipBody->CheckSameAsPrevious = true;
1060 SkipBody->New = IDecl;
1061 SkipBody->Previous = Def;
1062 } else {
1063 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1064 << PrevIDecl->getDeclName();
1065 Diag(Def->getLocation(), diag::note_previous_definition);
1066 IDecl->setInvalidDecl();
1067 }
1068 }
1069 }
1070
1071 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, IDecl, AttrList);
1072 SemaRef.AddPragmaAttributes(SemaRef.TUScope, IDecl);
1073 SemaRef.ProcessAPINotes(IDecl);
1074
1075 // Merge attributes from previous declarations.
1076 if (PrevIDecl)
1077 SemaRef.mergeDeclAttributes(IDecl, PrevIDecl);
1078
1079 SemaRef.PushOnScopeChains(IDecl, SemaRef.TUScope);
1080
1081 // Start the definition of this class. If we're in a redefinition case, there
1082 // may already be a definition, so we'll end up adding to it.
1083 if (SkipBody && SkipBody->CheckSameAsPrevious)
1085 else if (!IDecl->hasDefinition())
1086 IDecl->startDefinition();
1087
1088 if (SuperName) {
1089 // Diagnose availability in the context of the @interface.
1090 Sema::ContextRAII SavedContext(SemaRef, IDecl);
1091
1092 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1093 ClassName, ClassLoc,
1094 SuperName, SuperLoc, SuperTypeArgs,
1095 SuperTypeArgsRange);
1096 } else { // we have a root class.
1097 IDecl->setEndOfDefinitionLoc(ClassLoc);
1098 }
1099
1100 // Check then save referenced protocols.
1101 if (NumProtoRefs) {
1102 diagnoseUseOfProtocols(SemaRef, IDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1103 NumProtoRefs, ProtoLocs);
1104 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1105 ProtoLocs, Context);
1106 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1107 }
1108
1109 CheckObjCDeclScope(IDecl);
1111 return IDecl;
1112}
1113
1114/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1115/// typedef'ed use for a qualified super class and adds them to the list
1116/// of the protocols.
1118 SmallVectorImpl<Decl *> &ProtocolRefs,
1119 SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName,
1120 SourceLocation SuperLoc) {
1121 if (!SuperName)
1122 return;
1123 NamedDecl *IDecl = SemaRef.LookupSingleName(
1124 SemaRef.TUScope, SuperName, SuperLoc, Sema::LookupOrdinaryName);
1125 if (!IDecl)
1126 return;
1127
1128 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1129 QualType T = TDecl->getUnderlyingType();
1130 if (T->isObjCObjectType())
1131 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1132 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1133 // FIXME: Consider whether this should be an invalid loc since the loc
1134 // is not actually pointing to a protocol name reference but to the
1135 // typedef reference. Note that the base class name loc is also pointing
1136 // at the typedef.
1137 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1138 }
1139 }
1140}
1141
1142/// ActOnCompatibilityAlias - this action is called after complete parsing of
1143/// a \@compatibility_alias declaration. It sets up the alias relationships.
1145 IdentifierInfo *AliasName,
1146 SourceLocation AliasLocation,
1147 IdentifierInfo *ClassName,
1148 SourceLocation ClassLocation) {
1149 ASTContext &Context = getASTContext();
1150 // Look for previous declaration of alias name
1151 NamedDecl *ADecl = SemaRef.LookupSingleName(
1152 SemaRef.TUScope, AliasName, AliasLocation, Sema::LookupOrdinaryName,
1153 SemaRef.forRedeclarationInCurContext());
1154 if (ADecl) {
1155 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1156 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1157 return nullptr;
1158 }
1159 // Check for class declaration
1160 NamedDecl *CDeclU = SemaRef.LookupSingleName(
1161 SemaRef.TUScope, ClassName, ClassLocation, Sema::LookupOrdinaryName,
1162 SemaRef.forRedeclarationInCurContext());
1163 if (const TypedefNameDecl *TDecl =
1164 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1165 QualType T = TDecl->getUnderlyingType();
1166 if (T->isObjCObjectType()) {
1167 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
1168 ClassName = IDecl->getIdentifier();
1169 CDeclU = SemaRef.LookupSingleName(
1170 SemaRef.TUScope, ClassName, ClassLocation, Sema::LookupOrdinaryName,
1171 SemaRef.forRedeclarationInCurContext());
1172 }
1173 }
1174 }
1175 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1176 if (!CDecl) {
1177 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1178 if (CDeclU)
1179 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1180 return nullptr;
1181 }
1182
1183 // Everything checked out, instantiate a new alias declaration AST.
1185 Context, SemaRef.CurContext, AtLoc, AliasName, CDecl);
1186
1188 SemaRef.PushOnScopeChains(AliasDecl, SemaRef.TUScope);
1189
1190 return AliasDecl;
1191}
1192
1194 IdentifierInfo *PName, SourceLocation &Ploc, SourceLocation PrevLoc,
1195 const ObjCList<ObjCProtocolDecl> &PList) {
1196
1197 bool res = false;
1199 E = PList.end(); I != E; ++I) {
1200 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), Ploc)) {
1201 if (PDecl->getIdentifier() == PName) {
1202 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1203 Diag(PrevLoc, diag::note_previous_definition);
1204 res = true;
1205 }
1206
1207 if (!PDecl->hasDefinition())
1208 continue;
1209
1211 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1212 res = true;
1213 }
1214 }
1215 return res;
1216}
1217
1219 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1220 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1221 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1222 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
1223 ASTContext &Context = getASTContext();
1224 bool err = false;
1225 // FIXME: Deal with AttrList.
1226 assert(ProtocolName && "Missing protocol identifier");
1227 ObjCProtocolDecl *PrevDecl = LookupProtocol(
1228 ProtocolName, ProtocolLoc, SemaRef.forRedeclarationInCurContext());
1229 ObjCProtocolDecl *PDecl = nullptr;
1230 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1231 // Create a new protocol that is completely distinct from previous
1232 // declarations, and do not make this protocol available for name lookup.
1233 // That way, we'll end up completely ignoring the duplicate.
1234 // FIXME: Can we turn this into an error?
1235 PDecl = ObjCProtocolDecl::Create(Context, SemaRef.CurContext, ProtocolName,
1236 ProtocolLoc, AtProtoInterfaceLoc,
1237 /*PrevDecl=*/Def);
1238
1239 if (SkipBody && (!SemaRef.hasVisibleDefinition(Def) ||
1240 SemaRef.isFromSameSingleIncludeHeader(Def, ProtocolLoc))) {
1241 SkipBody->CheckSameAsPrevious = true;
1242 SkipBody->New = PDecl;
1243 SkipBody->Previous = Def;
1244 } else {
1245 // If we already have a definition, complain.
1246 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1247 Diag(Def->getLocation(), diag::note_previous_definition);
1248 }
1249
1250 // If we are using modules, add the decl to the context in order to
1251 // serialize something meaningful.
1252 if (getLangOpts().Modules)
1253 SemaRef.PushOnScopeChains(PDecl, SemaRef.TUScope);
1255 } else {
1256 if (PrevDecl) {
1257 // Check for circular dependencies among protocol declarations. This can
1258 // only happen if this protocol was forward-declared.
1260 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1262 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1263 }
1264
1265 // Create the new declaration.
1266 PDecl = ObjCProtocolDecl::Create(Context, SemaRef.CurContext, ProtocolName,
1267 ProtocolLoc, AtProtoInterfaceLoc,
1268 /*PrevDecl=*/PrevDecl);
1269
1270 SemaRef.PushOnScopeChains(PDecl, SemaRef.TUScope);
1271 PDecl->startDefinition();
1272 }
1273
1274 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, PDecl, AttrList);
1275 SemaRef.AddPragmaAttributes(SemaRef.TUScope, PDecl);
1276 SemaRef.ProcessAPINotes(PDecl);
1277
1278 // Merge attributes from previous declarations.
1279 if (PrevDecl)
1280 SemaRef.mergeDeclAttributes(PDecl, PrevDecl);
1281
1282 if (!err && NumProtoRefs ) {
1283 /// Check then save referenced protocols.
1284 diagnoseUseOfProtocols(SemaRef, PDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1285 NumProtoRefs, ProtoLocs);
1286 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1287 ProtoLocs, Context);
1288 }
1289
1290 CheckObjCDeclScope(PDecl);
1292 return PDecl;
1293}
1294
1296 ObjCProtocolDecl *&UndefinedProtocol) {
1297 if (!PDecl->hasDefinition() ||
1299 UndefinedProtocol = PDecl;
1300 return true;
1301 }
1302
1303 for (auto *PI : PDecl->protocols())
1304 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1305 UndefinedProtocol = PI;
1306 return true;
1307 }
1308 return false;
1309}
1310
1311/// FindProtocolDeclaration - This routine looks up protocols and
1312/// issues an error if they are not declared. It returns list of
1313/// protocol declarations in its 'Protocols' argument.
1314void SemaObjC::FindProtocolDeclaration(bool WarnOnDeclarations,
1315 bool ForObjCContainer,
1316 ArrayRef<IdentifierLoc> ProtocolId,
1317 SmallVectorImpl<Decl *> &Protocols) {
1318 for (const IdentifierLoc &Pair : ProtocolId) {
1319 ObjCProtocolDecl *PDecl =
1320 LookupProtocol(Pair.getIdentifierInfo(), Pair.getLoc());
1321 if (!PDecl) {
1323 TypoCorrection Corrected = SemaRef.CorrectTypo(
1324 DeclarationNameInfo(Pair.getIdentifierInfo(), Pair.getLoc()),
1325 Sema::LookupObjCProtocolName, SemaRef.TUScope, nullptr, CCC,
1327 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1328 SemaRef.diagnoseTypo(Corrected,
1329 PDiag(diag::err_undeclared_protocol_suggest)
1330 << Pair.getIdentifierInfo());
1331 }
1332
1333 if (!PDecl) {
1334 Diag(Pair.getLoc(), diag::err_undeclared_protocol)
1335 << Pair.getIdentifierInfo();
1336 continue;
1337 }
1338 // If this is a forward protocol declaration, get its definition.
1339 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1340 PDecl = PDecl->getDefinition();
1341
1342 // For an objc container, delay protocol reference checking until after we
1343 // can set the objc decl as the availability context, otherwise check now.
1344 if (!ForObjCContainer) {
1345 (void)SemaRef.DiagnoseUseOfDecl(PDecl, Pair.getLoc());
1346 }
1347
1348 // If this is a forward declaration and we are supposed to warn in this
1349 // case, do it.
1350 // FIXME: Recover nicely in the hidden case.
1351 ObjCProtocolDecl *UndefinedProtocol;
1352
1353 if (WarnOnDeclarations &&
1354 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1355 Diag(Pair.getLoc(), diag::warn_undef_protocolref)
1356 << Pair.getIdentifierInfo();
1357 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1358 << UndefinedProtocol;
1359 }
1360 Protocols.push_back(PDecl);
1361 }
1362}
1363
1364namespace {
1365// Callback to only accept typo corrections that are either
1366// Objective-C protocols or valid Objective-C type arguments.
1367class ObjCTypeArgOrProtocolValidatorCCC final
1369 ASTContext &Context;
1370 Sema::LookupNameKind LookupKind;
1371 public:
1372 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1373 Sema::LookupNameKind lookupKind)
1374 : Context(context), LookupKind(lookupKind) { }
1375
1376 bool ValidateCandidate(const TypoCorrection &candidate) override {
1377 // If we're allowed to find protocols and we have a protocol, accept it.
1378 if (LookupKind != Sema::LookupOrdinaryName) {
1379 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1380 return true;
1381 }
1382
1383 // If we're allowed to find type names and we have one, accept it.
1384 if (LookupKind != Sema::LookupObjCProtocolName) {
1385 // If we have a type declaration, we might accept this result.
1386 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1387 // If we found a tag declaration outside of C++, skip it. This
1388 // can happy because we look for any name when there is no
1389 // bias to protocol or type names.
1390 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1391 return false;
1392
1393 // Make sure the type is something we would accept as a type
1394 // argument.
1395 if (CanQualType type = Context.getCanonicalTypeDeclType(typeDecl);
1396 type->isDependentType() ||
1398 return true;
1399
1400 return false;
1401 }
1402
1403 // If we have an Objective-C class type, accept it; there will
1404 // be another fix to add the '*'.
1405 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1406 return true;
1407
1408 return false;
1409 }
1410
1411 return false;
1412 }
1413
1414 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1415 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1416 }
1417};
1418} // end anonymous namespace
1419
1421 SourceLocation ProtocolLoc,
1422 IdentifierInfo *TypeArgId,
1423 SourceLocation TypeArgLoc,
1424 bool SelectProtocolFirst) {
1425 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1426 << SelectProtocolFirst << TypeArgId << ProtocolId
1427 << SourceRange(ProtocolLoc);
1428}
1429
1431 Scope *S, ParsedType baseType, SourceLocation lAngleLoc,
1432 ArrayRef<IdentifierInfo *> identifiers,
1433 ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc,
1434 SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs,
1435 SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc,
1436 SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc,
1437 bool warnOnIncompleteProtocols) {
1438 ASTContext &Context = getASTContext();
1439 // Local function that updates the declaration specifiers with
1440 // protocol information.
1441 unsigned numProtocolsResolved = 0;
1442 auto resolvedAsProtocols = [&] {
1443 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1444
1445 // Determine whether the base type is a parameterized class, in
1446 // which case we want to warn about typos such as
1447 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1448 ObjCInterfaceDecl *baseClass = nullptr;
1449 QualType base = SemaRef.GetTypeFromParser(baseType, nullptr);
1450 bool allAreTypeNames = false;
1451 SourceLocation firstClassNameLoc;
1452 if (!base.isNull()) {
1453 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1454 baseClass = objcObjectType->getInterface();
1455 if (baseClass) {
1456 if (auto typeParams = baseClass->getTypeParamList()) {
1457 if (typeParams->size() == numProtocolsResolved) {
1458 // Note that we should be looking for type names, too.
1459 allAreTypeNames = true;
1460 }
1461 }
1462 }
1463 }
1464 }
1465
1466 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1467 ObjCProtocolDecl *&proto
1468 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1469 // For an objc container, delay protocol reference checking until after we
1470 // can set the objc decl as the availability context, otherwise check now.
1471 if (!warnOnIncompleteProtocols) {
1472 (void)SemaRef.DiagnoseUseOfDecl(proto, identifierLocs[i]);
1473 }
1474
1475 // If this is a forward protocol declaration, get its definition.
1476 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1477 proto = proto->getDefinition();
1478
1479 // If this is a forward declaration and we are supposed to warn in this
1480 // case, do it.
1481 // FIXME: Recover nicely in the hidden case.
1482 ObjCProtocolDecl *forwardDecl = nullptr;
1483 if (warnOnIncompleteProtocols &&
1484 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1485 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1486 << proto->getDeclName();
1487 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1488 << forwardDecl;
1489 }
1490
1491 // If everything this far has been a type name (and we care
1492 // about such things), check whether this name refers to a type
1493 // as well.
1494 if (allAreTypeNames) {
1495 if (auto *decl =
1496 SemaRef.LookupSingleName(S, identifiers[i], identifierLocs[i],
1499 if (firstClassNameLoc.isInvalid())
1500 firstClassNameLoc = identifierLocs[i];
1501 } else if (!isa<TypeDecl>(decl)) {
1502 // Not a type.
1503 allAreTypeNames = false;
1504 }
1505 } else {
1506 allAreTypeNames = false;
1507 }
1508 }
1509 }
1510
1511 // All of the protocols listed also have type names, and at least
1512 // one is an Objective-C class name. Check whether all of the
1513 // protocol conformances are declared by the base class itself, in
1514 // which case we warn.
1515 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1517 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1518 bool allProtocolsDeclared = true;
1519 for (auto *proto : protocols) {
1520 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1521 allProtocolsDeclared = false;
1522 break;
1523 }
1524 }
1525
1526 if (allProtocolsDeclared) {
1527 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1528 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1530 SemaRef.getLocForEndOfToken(firstClassNameLoc), " *");
1531 }
1532 }
1533
1534 protocolLAngleLoc = lAngleLoc;
1535 protocolRAngleLoc = rAngleLoc;
1536 assert(protocols.size() == identifierLocs.size());
1537 };
1538
1539 // Attempt to resolve all of the identifiers as protocols.
1540 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1541 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1542 protocols.push_back(proto);
1543 if (proto)
1544 ++numProtocolsResolved;
1545 }
1546
1547 // If all of the names were protocols, these were protocol qualifiers.
1548 if (numProtocolsResolved == identifiers.size())
1549 return resolvedAsProtocols();
1550
1551 // Attempt to resolve all of the identifiers as type names or
1552 // Objective-C class names. The latter is technically ill-formed,
1553 // but is probably something like \c NSArray<NSView *> missing the
1554 // \c*.
1555 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1557 unsigned numTypeDeclsResolved = 0;
1558 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1559 NamedDecl *decl = SemaRef.LookupSingleName(
1560 S, identifiers[i], identifierLocs[i], Sema::LookupOrdinaryName);
1561 if (!decl) {
1562 typeDecls.push_back(TypeOrClassDecl());
1563 continue;
1564 }
1565
1566 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1567 typeDecls.push_back(typeDecl);
1568 ++numTypeDeclsResolved;
1569 continue;
1570 }
1571
1572 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1573 typeDecls.push_back(objcClass);
1574 ++numTypeDeclsResolved;
1575 continue;
1576 }
1577
1578 typeDecls.push_back(TypeOrClassDecl());
1579 }
1580
1581 AttributeFactory attrFactory;
1582
1583 // Local function that forms a reference to the given type or
1584 // Objective-C class declaration.
1585 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1586 -> TypeResult {
1587 // Form declaration specifiers. They simply refer to the type.
1588 DeclSpec DS(attrFactory);
1589 const char* prevSpec; // unused
1590 unsigned diagID; // unused
1591 QualType type;
1592 if (auto *actualTypeDecl = dyn_cast<TypeDecl *>(typeDecl))
1593 type =
1594 Context.getTypeDeclType(ElaboratedTypeKeyword::None,
1595 /*Qualifier=*/std::nullopt, actualTypeDecl);
1596 else
1597 type = Context.getObjCInterfaceType(cast<ObjCInterfaceDecl *>(typeDecl));
1598 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1599 ParsedType parsedType = SemaRef.CreateParsedType(type, parsedTSInfo);
1600 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1601 parsedType, Context.getPrintingPolicy());
1602 // Use the identifier location for the type source range.
1603 DS.SetRangeStart(loc);
1604 DS.SetRangeEnd(loc);
1605
1606 // Form the declarator.
1608
1609 // If we have a typedef of an Objective-C class type that is missing a '*',
1610 // add the '*'.
1611 if (type->getAs<ObjCInterfaceType>()) {
1612 SourceLocation starLoc = SemaRef.getLocForEndOfToken(loc);
1613 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1618 SourceLocation()),
1619 starLoc);
1620
1621 // Diagnose the missing '*'.
1622 Diag(loc, diag::err_objc_type_arg_missing_star)
1623 << type
1624 << FixItHint::CreateInsertion(starLoc, " *");
1625 }
1626
1627 // Convert this to a type.
1628 return SemaRef.ActOnTypeName(D);
1629 };
1630
1631 // Local function that updates the declaration specifiers with
1632 // type argument information.
1633 auto resolvedAsTypeDecls = [&] {
1634 // We did not resolve these as protocols.
1635 protocols.clear();
1636
1637 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1638 // Map type declarations to type arguments.
1639 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1640 // Map type reference to a type.
1641 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1642 if (!type.isUsable()) {
1643 typeArgs.clear();
1644 return;
1645 }
1646
1647 typeArgs.push_back(type.get());
1648 }
1649
1650 typeArgsLAngleLoc = lAngleLoc;
1651 typeArgsRAngleLoc = rAngleLoc;
1652 };
1653
1654 // If all of the identifiers can be resolved as type names or
1655 // Objective-C class names, we have type arguments.
1656 if (numTypeDeclsResolved == identifiers.size())
1657 return resolvedAsTypeDecls();
1658
1659 // Error recovery: some names weren't found, or we have a mix of
1660 // type and protocol names. Go resolve all of the unresolved names
1661 // and complain if we can't find a consistent answer.
1663 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1664 // If we already have a protocol or type. Check whether it is the
1665 // right thing.
1666 if (protocols[i] || typeDecls[i]) {
1667 // If we haven't figured out whether we want types or protocols
1668 // yet, try to figure it out from this name.
1669 if (lookupKind == Sema::LookupAnyName) {
1670 // If this name refers to both a protocol and a type (e.g., \c
1671 // NSObject), don't conclude anything yet.
1672 if (protocols[i] && typeDecls[i])
1673 continue;
1674
1675 // Otherwise, let this name decide whether we'll be correcting
1676 // toward types or protocols.
1677 lookupKind = protocols[i] ? Sema::LookupObjCProtocolName
1679 continue;
1680 }
1681
1682 // If we want protocols and we have a protocol, there's nothing
1683 // more to do.
1684 if (lookupKind == Sema::LookupObjCProtocolName && protocols[i])
1685 continue;
1686
1687 // If we want types and we have a type declaration, there's
1688 // nothing more to do.
1689 if (lookupKind == Sema::LookupOrdinaryName && typeDecls[i])
1690 continue;
1691
1692 // We have a conflict: some names refer to protocols and others
1693 // refer to types.
1694 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1695 identifiers[i], identifierLocs[i],
1696 protocols[i] != nullptr);
1697
1698 protocols.clear();
1699 typeArgs.clear();
1700 return;
1701 }
1702
1703 // Perform typo correction on the name.
1704 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1705 TypoCorrection corrected = SemaRef.CorrectTypo(
1706 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1707 nullptr, CCC, CorrectTypoKind::ErrorRecovery);
1708 if (corrected) {
1709 // Did we find a protocol?
1710 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1711 SemaRef.diagnoseTypo(corrected,
1712 PDiag(diag::err_undeclared_protocol_suggest)
1713 << identifiers[i]);
1714 lookupKind = Sema::LookupObjCProtocolName;
1715 protocols[i] = proto;
1716 ++numProtocolsResolved;
1717 continue;
1718 }
1719
1720 // Did we find a type?
1721 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1722 SemaRef.diagnoseTypo(corrected,
1723 PDiag(diag::err_unknown_typename_suggest)
1724 << identifiers[i]);
1725 lookupKind = Sema::LookupOrdinaryName;
1726 typeDecls[i] = typeDecl;
1727 ++numTypeDeclsResolved;
1728 continue;
1729 }
1730
1731 // Did we find an Objective-C class?
1732 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1733 SemaRef.diagnoseTypo(corrected,
1734 PDiag(diag::err_unknown_type_or_class_name_suggest)
1735 << identifiers[i] << true);
1736 lookupKind = Sema::LookupOrdinaryName;
1737 typeDecls[i] = objcClass;
1738 ++numTypeDeclsResolved;
1739 continue;
1740 }
1741 }
1742
1743 // We couldn't find anything.
1744 Diag(identifierLocs[i],
1745 (lookupKind == Sema::LookupAnyName ? diag::err_objc_type_arg_missing
1746 : lookupKind == Sema::LookupObjCProtocolName
1747 ? diag::err_undeclared_protocol
1748 : diag::err_unknown_typename))
1749 << identifiers[i];
1750 protocols.clear();
1751 typeArgs.clear();
1752 return;
1753 }
1754
1755 // If all of the names were (corrected to) protocols, these were
1756 // protocol qualifiers.
1757 if (numProtocolsResolved == identifiers.size())
1758 return resolvedAsProtocols();
1759
1760 // Otherwise, all of the names were (corrected to) types.
1761 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1762 return resolvedAsTypeDecls();
1763}
1764
1765/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1766/// a class method in its extension.
1767///
1769 ObjCInterfaceDecl *ID) {
1770 if (!ID)
1771 return; // Possibly due to previous error
1772
1773 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1774 for (auto *MD : ID->methods())
1775 MethodMap[MD->getSelector()] = MD;
1776
1777 if (MethodMap.empty())
1778 return;
1779 for (const auto *Method : CAT->methods()) {
1780 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1781 if (PrevMethod &&
1782 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1783 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1784 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1785 << Method->getDeclName();
1786 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1787 }
1788 }
1789}
1790
1791/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1793 SourceLocation AtProtocolLoc, ArrayRef<IdentifierLoc> IdentList,
1794 const ParsedAttributesView &attrList) {
1795 ASTContext &Context = getASTContext();
1796 SmallVector<Decl *, 8> DeclsInGroup;
1797 for (const IdentifierLoc &IdentPair : IdentList) {
1798 IdentifierInfo *Ident = IdentPair.getIdentifierInfo();
1799 ObjCProtocolDecl *PrevDecl = LookupProtocol(
1800 Ident, IdentPair.getLoc(), SemaRef.forRedeclarationInCurContext());
1801 ObjCProtocolDecl *PDecl =
1802 ObjCProtocolDecl::Create(Context, SemaRef.CurContext, Ident,
1803 IdentPair.getLoc(), AtProtocolLoc, PrevDecl);
1804
1805 SemaRef.PushOnScopeChains(PDecl, SemaRef.TUScope);
1806 CheckObjCDeclScope(PDecl);
1807
1808 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, PDecl, attrList);
1809 SemaRef.AddPragmaAttributes(SemaRef.TUScope, PDecl);
1810
1811 if (PrevDecl)
1812 SemaRef.mergeDeclAttributes(PDecl, PrevDecl);
1813
1814 DeclsInGroup.push_back(PDecl);
1815 }
1816
1817 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
1818}
1819
1821 SourceLocation AtInterfaceLoc, const IdentifierInfo *ClassName,
1822 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1823 const IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1824 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1825 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1826 const ParsedAttributesView &AttrList) {
1827 ASTContext &Context = getASTContext();
1828 ObjCCategoryDecl *CDecl;
1829 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1830
1831 /// Check that class of this category is already completely declared.
1832
1833 if (!IDecl ||
1834 SemaRef.RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1835 diag::err_category_forward_interface,
1836 CategoryName == nullptr)) {
1837 // Create an invalid ObjCCategoryDecl to serve as context for
1838 // the enclosing method declarations. We mark the decl invalid
1839 // to make it clear that this isn't a valid AST.
1840 CDecl = ObjCCategoryDecl::Create(Context, SemaRef.CurContext,
1841 AtInterfaceLoc, ClassLoc, CategoryLoc,
1842 CategoryName, IDecl, typeParamList);
1843 CDecl->setInvalidDecl();
1844 SemaRef.CurContext->addDecl(CDecl);
1845
1846 if (!IDecl)
1847 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1849 return CDecl;
1850 }
1851
1852 if (!CategoryName && IDecl->getImplementation()) {
1853 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1855 diag::note_implementation_declared);
1856 }
1857
1858 if (CategoryName) {
1859 /// Check for duplicate interface declaration for this category
1861 = IDecl->FindCategoryDeclaration(CategoryName)) {
1862 // Class extensions can be declared multiple times, categories cannot.
1863 Diag(CategoryLoc, diag::warn_dup_category_def)
1864 << ClassName << CategoryName;
1865 Diag(Previous->getLocation(), diag::note_previous_definition);
1866 }
1867 }
1868
1869 // If we have a type parameter list, check it.
1870 if (typeParamList) {
1871 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1873 SemaRef, prevTypeParamList, typeParamList,
1874 CategoryName ? TypeParamListContext::Category
1875 : TypeParamListContext::Extension))
1876 typeParamList = nullptr;
1877 } else {
1878 Diag(typeParamList->getLAngleLoc(),
1879 diag::err_objc_parameterized_category_nonclass)
1880 << (CategoryName != nullptr)
1881 << ClassName
1882 << typeParamList->getSourceRange();
1883
1884 typeParamList = nullptr;
1885 }
1886 }
1887
1888 CDecl = ObjCCategoryDecl::Create(Context, SemaRef.CurContext, AtInterfaceLoc,
1889 ClassLoc, CategoryLoc, CategoryName, IDecl,
1890 typeParamList);
1891 // FIXME: PushOnScopeChains?
1892 SemaRef.CurContext->addDecl(CDecl);
1893
1894 // Process the attributes before looking at protocols to ensure that the
1895 // availability attribute is attached to the category to provide availability
1896 // checking for protocol uses.
1897 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, CDecl, AttrList);
1898 SemaRef.AddPragmaAttributes(SemaRef.TUScope, CDecl);
1899
1900 if (NumProtoRefs) {
1901 diagnoseUseOfProtocols(SemaRef, CDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1902 NumProtoRefs, ProtoLocs);
1903 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1904 ProtoLocs, Context);
1905 // Protocols in the class extension belong to the class.
1906 if (CDecl->IsClassExtension())
1907 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1908 NumProtoRefs, Context);
1909 }
1910
1911 CheckObjCDeclScope(CDecl);
1913 return CDecl;
1914}
1915
1916/// ActOnStartCategoryImplementation - Perform semantic checks on the
1917/// category implementation declaration and build an ObjCCategoryImplDecl
1918/// object.
1920 SourceLocation AtCatImplLoc, const IdentifierInfo *ClassName,
1921 SourceLocation ClassLoc, const IdentifierInfo *CatName,
1922 SourceLocation CatLoc, const ParsedAttributesView &Attrs) {
1923 ASTContext &Context = getASTContext();
1924 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1925 ObjCCategoryDecl *CatIDecl = nullptr;
1926 if (IDecl && IDecl->hasDefinition()) {
1927 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1928 if (!CatIDecl) {
1929 // Category @implementation with no corresponding @interface.
1930 // Create and install one.
1931 CatIDecl =
1932 ObjCCategoryDecl::Create(Context, SemaRef.CurContext, AtCatImplLoc,
1933 ClassLoc, CatLoc, CatName, IDecl,
1934 /*typeParamList=*/nullptr);
1935 CatIDecl->setImplicit();
1936 }
1937 }
1938
1939 ObjCCategoryImplDecl *CDecl =
1940 ObjCCategoryImplDecl::Create(Context, SemaRef.CurContext, CatName, IDecl,
1941 ClassLoc, AtCatImplLoc, CatLoc);
1942 /// Check that class of this category is already completely declared.
1943 if (!IDecl) {
1944 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1945 CDecl->setInvalidDecl();
1946 } else if (SemaRef.RequireCompleteType(ClassLoc,
1947 Context.getObjCInterfaceType(IDecl),
1948 diag::err_undef_interface)) {
1949 CDecl->setInvalidDecl();
1950 }
1951
1952 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, CDecl, Attrs);
1953 SemaRef.AddPragmaAttributes(SemaRef.TUScope, CDecl);
1954
1955 // FIXME: PushOnScopeChains?
1956 SemaRef.CurContext->addDecl(CDecl);
1957
1958 // If the interface has the objc_runtime_visible attribute, we
1959 // cannot implement a category for it.
1960 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1961 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1962 << IDecl->getDeclName();
1963 }
1964
1965 /// Check that CatName, category name, is not used in another implementation.
1966 if (CatIDecl) {
1967 if (CatIDecl->getImplementation()) {
1968 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1969 << CatName;
1970 Diag(CatIDecl->getImplementation()->getLocation(),
1971 diag::note_previous_definition);
1972 CDecl->setInvalidDecl();
1973 } else {
1974 CatIDecl->setImplementation(CDecl);
1975 // Warn on implementating category of deprecated class under
1976 // -Wdeprecated-implementations flag.
1978 CDecl->getLocation());
1979 }
1980 }
1981
1982 CheckObjCDeclScope(CDecl);
1984 return CDecl;
1985}
1986
1988 SourceLocation AtClassImplLoc, const IdentifierInfo *ClassName,
1989 SourceLocation ClassLoc, const IdentifierInfo *SuperClassname,
1990 SourceLocation SuperClassLoc, const ParsedAttributesView &Attrs) {
1991 ASTContext &Context = getASTContext();
1992 ObjCInterfaceDecl *IDecl = nullptr;
1993 // Check for another declaration kind with the same name.
1994 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
1995 SemaRef.TUScope, ClassName, ClassLoc, Sema::LookupOrdinaryName,
1996 SemaRef.forRedeclarationInCurContext());
1997 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1998 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1999 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2000 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
2001 // FIXME: This will produce an error if the definition of the interface has
2002 // been imported from a module but is not visible.
2003 SemaRef.RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
2004 diag::warn_undef_interface);
2005 } else {
2006 // We did not find anything with the name ClassName; try to correct for
2007 // typos in the class name.
2008 ObjCInterfaceValidatorCCC CCC{};
2009 TypoCorrection Corrected = SemaRef.CorrectTypo(
2010 DeclarationNameInfo(ClassName, ClassLoc), Sema::LookupOrdinaryName,
2011 SemaRef.TUScope, nullptr, CCC, CorrectTypoKind::NonError);
2012 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2013 // Suggest the (potentially) correct interface name. Don't provide a
2014 // code-modification hint or use the typo name for recovery, because
2015 // this is just a warning. The program may actually be correct.
2016 SemaRef.diagnoseTypo(
2017 Corrected, PDiag(diag::warn_undef_interface_suggest) << ClassName,
2018 /*ErrorRecovery*/ false);
2019 } else {
2020 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
2021 }
2022 }
2023
2024 // Check that super class name is valid class name
2025 ObjCInterfaceDecl *SDecl = nullptr;
2026 if (SuperClassname) {
2027 // Check if a different kind of symbol declared in this scope.
2028 PrevDecl =
2029 SemaRef.LookupSingleName(SemaRef.TUScope, SuperClassname, SuperClassLoc,
2031 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2032 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2033 << SuperClassname;
2034 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2035 } else {
2036 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2037 if (SDecl && !SDecl->hasDefinition())
2038 SDecl = nullptr;
2039 if (!SDecl)
2040 Diag(SuperClassLoc, diag::err_undef_superclass)
2041 << SuperClassname << ClassName;
2042 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2043 // This implementation and its interface do not have the same
2044 // super class.
2045 Diag(SuperClassLoc, diag::err_conflicting_super_class)
2046 << SDecl->getDeclName();
2047 Diag(SDecl->getLocation(), diag::note_previous_definition);
2048 }
2049 }
2050 }
2051
2052 if (!IDecl) {
2053 // Legacy case of @implementation with no corresponding @interface.
2054 // Build, chain & install the interface decl into the identifier.
2055
2056 // FIXME: Do we support attributes on the @implementation? If so we should
2057 // copy them over.
2058 IDecl =
2059 ObjCInterfaceDecl::Create(Context, SemaRef.CurContext, AtClassImplLoc,
2060 ClassName, /*typeParamList=*/nullptr,
2061 /*PrevDecl=*/nullptr, ClassLoc, true);
2062 SemaRef.AddPragmaAttributes(SemaRef.TUScope, IDecl);
2063 IDecl->startDefinition();
2064 if (SDecl) {
2065 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2066 Context.getObjCInterfaceType(SDecl),
2067 SuperClassLoc));
2068 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2069 } else {
2070 IDecl->setEndOfDefinitionLoc(ClassLoc);
2071 }
2072
2073 SemaRef.PushOnScopeChains(IDecl, SemaRef.TUScope);
2074 } else {
2075 // Mark the interface as being completed, even if it was just as
2076 // @class ....;
2077 // declaration; the user cannot reopen it.
2078 if (!IDecl->hasDefinition())
2079 IDecl->startDefinition();
2080 }
2081
2082 ObjCImplementationDecl *IMPDecl =
2083 ObjCImplementationDecl::Create(Context, SemaRef.CurContext, IDecl, SDecl,
2084 ClassLoc, AtClassImplLoc, SuperClassLoc);
2085
2086 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, IMPDecl, Attrs);
2087 SemaRef.AddPragmaAttributes(SemaRef.TUScope, IMPDecl);
2088
2089 if (CheckObjCDeclScope(IMPDecl)) {
2091 return IMPDecl;
2092 }
2093
2094 // Check that there is no duplicate implementation of this class.
2095 if (IDecl->getImplementation()) {
2096 // FIXME: Don't leak everything!
2097 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2099 diag::note_previous_definition);
2100 IMPDecl->setInvalidDecl();
2101 } else { // add it to the list.
2102 IDecl->setImplementation(IMPDecl);
2103 SemaRef.PushOnScopeChains(IMPDecl, SemaRef.TUScope);
2104 // Warn on implementating deprecated class under
2105 // -Wdeprecated-implementations flag.
2107 }
2108
2109 // If the superclass has the objc_runtime_visible attribute, we
2110 // cannot implement a subclass of it.
2111 if (IDecl->getSuperClass() &&
2112 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2113 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2114 << IDecl->getDeclName()
2115 << IDecl->getSuperClass()->getDeclName();
2116 }
2117
2119 return IMPDecl;
2120}
2121
2124 ArrayRef<Decl *> Decls) {
2125 SmallVector<Decl *, 64> DeclsInGroup;
2126 DeclsInGroup.reserve(Decls.size() + 1);
2127
2128 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2129 Decl *Dcl = Decls[i];
2130 if (!Dcl)
2131 continue;
2132 if (Dcl->getDeclContext()->isFileContext())
2134 DeclsInGroup.push_back(Dcl);
2135 }
2136
2137 DeclsInGroup.push_back(ObjCImpDecl);
2138
2139 // Reset the cached layout if there are any ivars added to
2140 // the implementation.
2141 if (auto *ImplD = dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
2142 if (!ImplD->ivar_empty())
2143 getASTContext().ResetObjCLayout(ImplD->getClassInterface());
2144
2145 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
2146}
2147
2149 ObjCIvarDecl **ivars, unsigned numIvars,
2150 SourceLocation RBrace) {
2151 assert(ImpDecl && "missing implementation decl");
2152 ASTContext &Context = getASTContext();
2153 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2154 if (!IDecl)
2155 return;
2156 /// Check case of non-existing \@interface decl.
2157 /// (legacy objective-c \@implementation decl without an \@interface decl).
2158 /// Add implementations's ivar to the synthesize class's ivar list.
2159 if (IDecl->isImplicitInterfaceDecl()) {
2160 IDecl->setEndOfDefinitionLoc(RBrace);
2161 // Add ivar's to class's DeclContext.
2162 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2163 ivars[i]->setLexicalDeclContext(ImpDecl);
2164 // In a 'fragile' runtime the ivar was added to the implicit
2165 // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is
2166 // only in the ObjCImplementationDecl. In the non-fragile case the ivar
2167 // therefore also needs to be propagated to the ObjCInterfaceDecl.
2169 IDecl->makeDeclVisibleInContext(ivars[i]);
2170 ImpDecl->addDecl(ivars[i]);
2171 }
2172
2173 return;
2174 }
2175 // If implementation has empty ivar list, just return.
2176 if (numIvars == 0)
2177 return;
2178
2179 assert(ivars && "missing @implementation ivars");
2181 if (ImpDecl->getSuperClass())
2182 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2183 for (unsigned i = 0; i < numIvars; i++) {
2184 ObjCIvarDecl* ImplIvar = ivars[i];
2185 if (const ObjCIvarDecl *ClsIvar =
2186 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2187 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2188 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2189 continue;
2190 }
2191 // Check class extensions (unnamed categories) for duplicate ivars.
2192 for (const auto *CDecl : IDecl->visible_extensions()) {
2193 if (const ObjCIvarDecl *ClsExtIvar =
2194 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2195 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2196 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2197 continue;
2198 }
2199 }
2200 // Instance ivar to Implementation's DeclContext.
2201 ImplIvar->setLexicalDeclContext(ImpDecl);
2202 IDecl->makeDeclVisibleInContext(ImplIvar);
2203 ImpDecl->addDecl(ImplIvar);
2204 }
2205 return;
2206 }
2207 // Check interface's Ivar list against those in the implementation.
2208 // names and types must match.
2209 //
2210 unsigned j = 0;
2212 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2213 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2214 ObjCIvarDecl* ImplIvar = ivars[j++];
2215 ObjCIvarDecl* ClsIvar = *IVI;
2216 assert (ImplIvar && "missing implementation ivar");
2217 assert (ClsIvar && "missing class ivar");
2218
2219 // First, make sure the types match.
2220 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2221 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2222 << ImplIvar->getIdentifier()
2223 << ImplIvar->getType() << ClsIvar->getType();
2224 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2225 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2226 ImplIvar->getBitWidthValue() != ClsIvar->getBitWidthValue()) {
2227 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2228 diag::err_conflicting_ivar_bitwidth)
2229 << ImplIvar->getIdentifier();
2230 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2231 diag::note_previous_definition);
2232 }
2233 // Make sure the names are identical.
2234 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2235 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2236 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2237 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2238 }
2239 --numIvars;
2240 }
2241
2242 if (numIvars > 0)
2243 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2244 else if (IVI != IVE)
2245 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2246}
2247
2249 // No point warning no definition of method which is 'unavailable'.
2250 return M->getAvailability() != AR_Unavailable;
2251}
2252
2254 ObjCMethodDecl *method, bool &IncompleteImpl,
2255 unsigned DiagID,
2256 NamedDecl *NeededFor = nullptr) {
2257 if (!shouldWarnUndefinedMethod(method))
2258 return;
2259
2260 // FIXME: For now ignore 'IncompleteImpl'.
2261 // Previously we grouped all unimplemented methods under a single
2262 // warning, but some users strongly voiced that they would prefer
2263 // separate warnings. We will give that approach a try, as that
2264 // matches what we do with protocols.
2265 {
2267 S.Diag(Impl->getLocation(), DiagID);
2268 B << method;
2269 if (NeededFor)
2270 B << NeededFor;
2271
2272 // Add an empty definition at the end of the @implementation.
2273 std::string FixItStr;
2274 llvm::raw_string_ostream Out(FixItStr);
2275 method->print(Out, Impl->getASTContext().getPrintingPolicy());
2276 Out << " {\n}\n\n";
2277
2278 SourceLocation Loc = Impl->getAtEndRange().getBegin();
2279 B << FixItHint::CreateInsertion(Loc, FixItStr);
2280 }
2281
2282 // Issue a note to the original declaration.
2283 SourceLocation MethodLoc = method->getBeginLoc();
2284 if (MethodLoc.isValid())
2285 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2286}
2287
2288/// Determines if type B can be substituted for type A. Returns true if we can
2289/// guarantee that anything that the user will do to an object of type A can
2290/// also be done to an object of type B. This is trivially true if the two
2291/// types are the same, or if B is a subclass of A. It becomes more complex
2292/// in cases where protocols are involved.
2293///
2294/// Object types in Objective-C describe the minimum requirements for an
2295/// object, rather than providing a complete description of a type. For
2296/// example, if A is a subclass of B, then B* may refer to an instance of A.
2297/// The principle of substitutability means that we may use an instance of A
2298/// anywhere that we may use an instance of B - it will implement all of the
2299/// ivars of B and all of the methods of B.
2300///
2301/// This substitutability is important when type checking methods, because
2302/// the implementation may have stricter type definitions than the interface.
2303/// The interface specifies minimum requirements, but the implementation may
2304/// have more accurate ones. For example, a method may privately accept
2305/// instances of B, but only publish that it accepts instances of A. Any
2306/// object passed to it will be type checked against B, and so will implicitly
2307/// by a valid A*. Similarly, a method may return a subclass of the class that
2308/// it is declared as returning.
2309///
2310/// This is most important when considering subclassing. A method in a
2311/// subclass must accept any object as an argument that its superclass's
2312/// implementation accepts. It may, however, accept a more general type
2313/// without breaking substitutability (i.e. you can still use the subclass
2314/// anywhere that you can use the superclass, but not vice versa). The
2315/// converse requirement applies to return types: the return type for a
2316/// subclass method must be a valid object of the kind that the superclass
2317/// advertises, but it may be specified more accurately. This avoids the need
2318/// for explicit down-casting by callers.
2319///
2320/// Note: This is a stricter requirement than for assignment.
2322 const ObjCObjectPointerType *A,
2323 const ObjCObjectPointerType *B,
2324 bool rejectId) {
2325 // Reject a protocol-unqualified id.
2326 if (rejectId && B->isObjCIdType()) return false;
2327
2328 // If B is a qualified id, then A must also be a qualified id and it must
2329 // implement all of the protocols in B. It may not be a qualified class.
2330 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2331 // stricter definition so it is not substitutable for id<A>.
2332 if (B->isObjCQualifiedIdType()) {
2333 return A->isObjCQualifiedIdType() &&
2334 Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2335 }
2336
2337 /*
2338 // id is a special type that bypasses type checking completely. We want a
2339 // warning when it is used in one place but not another.
2340 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2341
2342
2343 // If B is a qualified id, then A must also be a qualified id (which it isn't
2344 // if we've got this far)
2345 if (B->isObjCQualifiedIdType()) return false;
2346 */
2347
2348 // Now we know that A and B are (potentially-qualified) class types. The
2349 // normal rules for assignment apply.
2350 return Context.canAssignObjCInterfaces(A, B);
2351}
2352
2354 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2355}
2356
2357/// Determine whether two set of Objective-C declaration qualifiers conflict.
2360 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2361 (y & ~Decl::OBJC_TQ_CSNullability);
2362}
2363
2365 ObjCMethodDecl *MethodImpl,
2366 ObjCMethodDecl *MethodDecl,
2367 bool IsProtocolMethodDecl,
2368 bool IsOverridingMode,
2369 bool Warn) {
2370 if (IsProtocolMethodDecl &&
2372 MethodImpl->getObjCDeclQualifier())) {
2373 if (Warn) {
2374 S.Diag(MethodImpl->getLocation(),
2375 (IsOverridingMode
2376 ? diag::warn_conflicting_overriding_ret_type_modifiers
2377 : diag::warn_conflicting_ret_type_modifiers))
2378 << MethodImpl->getDeclName()
2379 << MethodImpl->getReturnTypeSourceRange();
2380 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2381 << MethodDecl->getReturnTypeSourceRange();
2382 }
2383 else
2384 return false;
2385 }
2386 if (Warn && IsOverridingMode &&
2389 MethodDecl->getReturnType(),
2390 false)) {
2391 auto nullabilityMethodImpl = *MethodImpl->getReturnType()->getNullability();
2392 auto nullabilityMethodDecl = *MethodDecl->getReturnType()->getNullability();
2393 S.Diag(MethodImpl->getLocation(),
2394 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2395 << DiagNullabilityKind(nullabilityMethodImpl,
2396 ((MethodImpl->getObjCDeclQualifier() &
2398 << DiagNullabilityKind(nullabilityMethodDecl,
2399 ((MethodDecl->getObjCDeclQualifier() &
2401 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2402 }
2403
2404 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2405 MethodDecl->getReturnType()))
2406 return true;
2407 if (!Warn)
2408 return false;
2409
2410 unsigned DiagID =
2411 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2412 : diag::warn_conflicting_ret_types;
2413
2414 // Mismatches between ObjC pointers go into a different warning
2415 // category, and sometimes they're even completely explicitly allowed.
2416 if (const ObjCObjectPointerType *ImplPtrTy =
2417 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2418 if (const ObjCObjectPointerType *IfacePtrTy =
2419 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2420 // Allow non-matching return types as long as they don't violate
2421 // the principle of substitutability. Specifically, we permit
2422 // return types that are subclasses of the declared return type,
2423 // or that are more-qualified versions of the declared type.
2424 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2425 return false;
2426
2427 DiagID =
2428 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2429 : diag::warn_non_covariant_ret_types;
2430 }
2431 }
2432
2433 S.Diag(MethodImpl->getLocation(), DiagID)
2434 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2435 << MethodImpl->getReturnType()
2436 << MethodImpl->getReturnTypeSourceRange();
2437 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2438 ? diag::note_previous_declaration
2439 : diag::note_previous_definition)
2440 << MethodDecl->getReturnTypeSourceRange();
2441 return false;
2442}
2443
2445 ObjCMethodDecl *MethodImpl,
2446 ObjCMethodDecl *MethodDecl,
2447 ParmVarDecl *ImplVar,
2448 ParmVarDecl *IfaceVar,
2449 bool IsProtocolMethodDecl,
2450 bool IsOverridingMode,
2451 bool Warn) {
2452 if (IsProtocolMethodDecl &&
2454 IfaceVar->getObjCDeclQualifier())) {
2455 if (Warn) {
2456 if (IsOverridingMode)
2457 S.Diag(ImplVar->getLocation(),
2458 diag::warn_conflicting_overriding_param_modifiers)
2459 << getTypeRange(ImplVar->getTypeSourceInfo())
2460 << MethodImpl->getDeclName();
2461 else S.Diag(ImplVar->getLocation(),
2462 diag::warn_conflicting_param_modifiers)
2463 << getTypeRange(ImplVar->getTypeSourceInfo())
2464 << MethodImpl->getDeclName();
2465 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2466 << getTypeRange(IfaceVar->getTypeSourceInfo());
2467 }
2468 else
2469 return false;
2470 }
2471
2472 QualType ImplTy = ImplVar->getType();
2473 QualType IfaceTy = IfaceVar->getType();
2474 if (Warn && IsOverridingMode &&
2476 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2477 S.Diag(ImplVar->getLocation(),
2478 diag::warn_conflicting_nullability_attr_overriding_param_types)
2479 << DiagNullabilityKind(*ImplTy->getNullability(),
2480 ((ImplVar->getObjCDeclQualifier() &
2482 << DiagNullabilityKind(*IfaceTy->getNullability(),
2483 ((IfaceVar->getObjCDeclQualifier() &
2485 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2486 }
2487 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2488 return true;
2489
2490 if (!Warn)
2491 return false;
2492 unsigned DiagID =
2493 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2494 : diag::warn_conflicting_param_types;
2495
2496 // Mismatches between ObjC pointers go into a different warning
2497 // category, and sometimes they're even completely explicitly allowed..
2498 if (const ObjCObjectPointerType *ImplPtrTy =
2499 ImplTy->getAs<ObjCObjectPointerType>()) {
2500 if (const ObjCObjectPointerType *IfacePtrTy =
2501 IfaceTy->getAs<ObjCObjectPointerType>()) {
2502 // Allow non-matching argument types as long as they don't
2503 // violate the principle of substitutability. Specifically, the
2504 // implementation must accept any objects that the superclass
2505 // accepts, however it may also accept others.
2506 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2507 return false;
2508
2509 DiagID =
2510 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2511 : diag::warn_non_contravariant_param_types;
2512 }
2513 }
2514
2515 S.Diag(ImplVar->getLocation(), DiagID)
2516 << getTypeRange(ImplVar->getTypeSourceInfo())
2517 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2518 S.Diag(IfaceVar->getLocation(),
2519 (IsOverridingMode ? diag::note_previous_declaration
2520 : diag::note_previous_definition))
2521 << getTypeRange(IfaceVar->getTypeSourceInfo());
2522 return false;
2523}
2524
2525/// In ARC, check whether the conventional meanings of the two methods
2526/// match. If they don't, it's a hard error.
2529 ObjCMethodFamily implFamily = impl->getMethodFamily();
2530 ObjCMethodFamily declFamily = decl->getMethodFamily();
2531 if (implFamily == declFamily) return false;
2532
2533 // Since conventions are sorted by selector, the only possibility is
2534 // that the types differ enough to cause one selector or the other
2535 // to fall out of the family.
2536 assert(implFamily == OMF_None || declFamily == OMF_None);
2537
2538 // No further diagnostics required on invalid declarations.
2539 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2540
2541 const ObjCMethodDecl *unmatched = impl;
2542 ObjCMethodFamily family = declFamily;
2543 unsigned errorID = diag::err_arc_lost_method_convention;
2544 unsigned noteID = diag::note_arc_lost_method_convention;
2545 if (declFamily == OMF_None) {
2546 unmatched = decl;
2547 family = implFamily;
2548 errorID = diag::err_arc_gained_method_convention;
2549 noteID = diag::note_arc_gained_method_convention;
2550 }
2551
2552 // Indexes into a %select clause in the diagnostic.
2553 enum FamilySelector {
2554 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2555 };
2556 FamilySelector familySelector = FamilySelector();
2557
2558 switch (family) {
2559 case OMF_None: llvm_unreachable("logic error, no method convention");
2560 case OMF_retain:
2561 case OMF_release:
2562 case OMF_autorelease:
2563 case OMF_dealloc:
2564 case OMF_finalize:
2565 case OMF_retainCount:
2566 case OMF_self:
2567 case OMF_initialize:
2569 // Mismatches for these methods don't change ownership
2570 // conventions, so we don't care.
2571 return false;
2572
2573 case OMF_init: familySelector = F_init; break;
2574 case OMF_alloc: familySelector = F_alloc; break;
2575 case OMF_copy: familySelector = F_copy; break;
2576 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2577 case OMF_new: familySelector = F_new; break;
2578 }
2579
2580 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2581 ReasonSelector reasonSelector;
2582
2583 // The only reason these methods don't fall within their families is
2584 // due to unusual result types.
2585 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2586 reasonSelector = R_UnrelatedReturn;
2587 } else {
2588 reasonSelector = R_NonObjectReturn;
2589 }
2590
2591 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2592 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2593
2594 return true;
2595}
2596
2598 ObjCMethodDecl *MethodDecl,
2599 bool IsProtocolMethodDecl) {
2600 if (getLangOpts().ObjCAutoRefCount &&
2601 checkMethodFamilyMismatch(SemaRef, ImpMethodDecl, MethodDecl))
2602 return;
2603
2604 CheckMethodOverrideReturn(SemaRef, ImpMethodDecl, MethodDecl,
2605 IsProtocolMethodDecl, false, true);
2606
2607 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2608 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2609 EF = MethodDecl->param_end();
2610 IM != EM && IF != EF; ++IM, ++IF) {
2611 CheckMethodOverrideParam(SemaRef, ImpMethodDecl, MethodDecl, *IM, *IF,
2612 IsProtocolMethodDecl, false, true);
2613 }
2614
2615 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2616 Diag(ImpMethodDecl->getLocation(),
2617 diag::warn_conflicting_variadic);
2618 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2619 }
2620}
2621
2623 ObjCMethodDecl *Overridden,
2624 bool IsProtocolMethodDecl) {
2625
2626 CheckMethodOverrideReturn(SemaRef, Method, Overridden, IsProtocolMethodDecl,
2627 true, true);
2628
2629 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2630 IF = Overridden->param_begin(), EM = Method->param_end(),
2631 EF = Overridden->param_end();
2632 IM != EM && IF != EF; ++IM, ++IF) {
2633 CheckMethodOverrideParam(SemaRef, Method, Overridden, *IM, *IF,
2634 IsProtocolMethodDecl, true, true);
2635 }
2636
2637 if (Method->isVariadic() != Overridden->isVariadic()) {
2638 Diag(Method->getLocation(),
2639 diag::warn_conflicting_overriding_variadic);
2640 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2641 }
2642}
2643
2644/// WarnExactTypedMethods - This routine issues a warning if method
2645/// implementation declaration matches exactly that of its declaration.
2647 ObjCMethodDecl *MethodDecl,
2648 bool IsProtocolMethodDecl) {
2649 ASTContext &Context = getASTContext();
2650 // don't issue warning when protocol method is optional because primary
2651 // class is not required to implement it and it is safe for protocol
2652 // to implement it.
2653 if (MethodDecl->getImplementationControl() ==
2655 return;
2656 // don't issue warning when primary class's method is
2657 // deprecated/unavailable.
2658 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2659 MethodDecl->hasAttr<DeprecatedAttr>())
2660 return;
2661
2662 bool match = CheckMethodOverrideReturn(SemaRef, ImpMethodDecl, MethodDecl,
2663 IsProtocolMethodDecl, false, false);
2664 if (match)
2665 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2666 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2667 EF = MethodDecl->param_end();
2668 IM != EM && IF != EF; ++IM, ++IF) {
2669 match = CheckMethodOverrideParam(SemaRef, ImpMethodDecl, MethodDecl, *IM,
2670 *IF, IsProtocolMethodDecl, false, false);
2671 if (!match)
2672 break;
2673 }
2674 if (match)
2675 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2676 if (match)
2677 match = !(MethodDecl->isClassMethod() &&
2678 MethodDecl->getSelector() == GetNullarySelector("load", Context));
2679
2680 if (match) {
2681 Diag(ImpMethodDecl->getLocation(),
2682 diag::warn_category_method_impl_match);
2683 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2684 << MethodDecl->getDeclName();
2685 }
2686}
2687
2688/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2689/// improve the efficiency of selector lookups and type checking by associating
2690/// with each protocol / interface / category the flattened instance tables. If
2691/// we used an immutable set to keep the table then it wouldn't add significant
2692/// memory cost and it would be handy for lookups.
2693
2694typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2695typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2696
2698 ProtocolNameSet &PNS) {
2699 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2700 PNS.insert(PDecl->getIdentifier());
2701 for (const auto *PI : PDecl->protocols())
2703}
2704
2705/// Recursively populates a set with all conformed protocols in a class
2706/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2707/// attribute.
2709 ProtocolNameSet &PNS) {
2710 if (!Super)
2711 return;
2712
2713 for (const auto *I : Super->all_referenced_protocols())
2715
2717}
2718
2719/// CheckProtocolMethodDefs - This routine checks unimplemented methods
2720/// Declared in protocol, and those referenced by it.
2722 Sema &S, ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool &IncompleteImpl,
2723 const SemaObjC::SelectorSet &InsMap, const SemaObjC::SelectorSet &ClsMap,
2724 ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) {
2725 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2726 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2727 : dyn_cast<ObjCInterfaceDecl>(CDecl);
2728 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2729
2730 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2731 ObjCInterfaceDecl *NSIDecl = nullptr;
2732
2733 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2734 // then we should check if any class in the super class hierarchy also
2735 // conforms to this protocol, either directly or via protocol inheritance.
2736 // If so, we can skip checking this protocol completely because we
2737 // know that a parent class already satisfies this protocol.
2738 //
2739 // Note: we could generalize this logic for all protocols, and merely
2740 // add the limit on looking at the super class chain for just
2741 // specially marked protocols. This may be a good optimization. This
2742 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2743 // protocols for now for controlled evaluation.
2744 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2745 if (!ProtocolsExplictImpl) {
2746 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2747 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2748 }
2749 if (ProtocolsExplictImpl->contains(PDecl->getIdentifier()))
2750 return;
2751
2752 // If no super class conforms to the protocol, we should not search
2753 // for methods in the super class to implicitly satisfy the protocol.
2754 Super = nullptr;
2755 }
2756
2758 // check to see if class implements forwardInvocation method and objects
2759 // of this class are derived from 'NSProxy' so that to forward requests
2760 // from one object to another.
2761 // Under such conditions, which means that every method possible is
2762 // implemented in the class, we should not issue "Method definition not
2763 // found" warnings.
2764 // FIXME: Use a general GetUnarySelector method for this.
2765 const IdentifierInfo *II = &S.Context.Idents.get("forwardInvocation");
2766 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2767 if (InsMap.count(fISelector))
2768 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2769 // need be implemented in the implementation.
2770 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2771 }
2772
2773 // If this is a forward protocol declaration, get its definition.
2774 if (!PDecl->isThisDeclarationADefinition() &&
2775 PDecl->getDefinition())
2776 PDecl = PDecl->getDefinition();
2777
2778 // If a method lookup fails locally we still need to look and see if
2779 // the method was implemented by a base class or an inherited
2780 // protocol. This lookup is slow, but occurs rarely in correct code
2781 // and otherwise would terminate in a warning.
2782
2783 // check unimplemented instance methods.
2784 if (!NSIDecl)
2785 for (auto *method : PDecl->instance_methods()) {
2786 if (method->getImplementationControl() !=
2788 !method->isPropertyAccessor() &&
2789 !InsMap.count(method->getSelector()) &&
2790 (!Super || !Super->lookupMethod(
2791 method->getSelector(), true /* instance */,
2792 false /* shallowCategory */, true /* followsSuper */,
2793 nullptr /* category */))) {
2794 // If a method is not implemented in the category implementation but
2795 // has been declared in its primary class, superclass,
2796 // or in one of their protocols, no need to issue the warning.
2797 // This is because method will be implemented in the primary class
2798 // or one of its super class implementation.
2799
2800 // Ugly, but necessary. Method declared in protocol might have
2801 // have been synthesized due to a property declared in the class which
2802 // uses the protocol.
2803 if (ObjCMethodDecl *MethodInClass = IDecl->lookupMethod(
2804 method->getSelector(), true /* instance */,
2805 true /* shallowCategoryLookup */, false /* followSuper */))
2806 if (C || MethodInClass->isPropertyAccessor())
2807 continue;
2808 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2809 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2810 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2811 }
2812 }
2813 }
2814 // check unimplemented class methods
2815 for (auto *method : PDecl->class_methods()) {
2816 if (method->getImplementationControl() !=
2818 !ClsMap.count(method->getSelector()) &&
2819 (!Super || !Super->lookupMethod(
2820 method->getSelector(), false /* class method */,
2821 false /* shallowCategoryLookup */,
2822 true /* followSuper */, nullptr /* category */))) {
2823 // See above comment for instance method lookups.
2824 if (C && IDecl->lookupMethod(method->getSelector(),
2825 false /* class */,
2826 true /* shallowCategoryLookup */,
2827 false /* followSuper */))
2828 continue;
2829
2830 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2831 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2832 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2833 }
2834 }
2835 }
2836 // Check on this protocols's referenced protocols, recursively.
2837 for (auto *PI : PDecl->protocols())
2838 CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
2839 ProtocolsExplictImpl);
2840}
2841
2842/// MatchAllMethodDeclarations - Check methods declared in interface
2843/// or protocol against those declared in their implementations.
2844///
2846 const SelectorSet &InsMap, const SelectorSet &ClsMap,
2847 SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl *IMPDecl,
2848 ObjCContainerDecl *CDecl, bool &IncompleteImpl, bool ImmediateClass,
2849 bool WarnCategoryMethodImpl) {
2850 // Check and see if instance methods in class interface have been
2851 // implemented in the implementation class. If so, their types match.
2852 for (auto *I : CDecl->instance_methods()) {
2853 if (!InsMapSeen.insert(I->getSelector()).second)
2854 continue;
2855 if (!I->isPropertyAccessor() &&
2856 !InsMap.count(I->getSelector())) {
2857 if (ImmediateClass)
2858 WarnUndefinedMethod(SemaRef, IMPDecl, I, IncompleteImpl,
2859 diag::warn_undef_method_impl);
2860 continue;
2861 } else {
2862 ObjCMethodDecl *ImpMethodDecl =
2863 IMPDecl->getInstanceMethod(I->getSelector());
2864 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2865 "Expected to find the method through lookup as well");
2866 // ImpMethodDecl may be null as in a @dynamic property.
2867 if (ImpMethodDecl) {
2868 // Skip property accessor function stubs.
2869 if (ImpMethodDecl->isSynthesizedAccessorStub())
2870 continue;
2871 if (!WarnCategoryMethodImpl)
2872 WarnConflictingTypedMethods(ImpMethodDecl, I,
2873 isa<ObjCProtocolDecl>(CDecl));
2874 else if (!I->isPropertyAccessor())
2875 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2876 }
2877 }
2878 }
2879
2880 // Check and see if class methods in class interface have been
2881 // implemented in the implementation class. If so, their types match.
2882 for (auto *I : CDecl->class_methods()) {
2883 if (!ClsMapSeen.insert(I->getSelector()).second)
2884 continue;
2885 if (!I->isPropertyAccessor() &&
2886 !ClsMap.count(I->getSelector())) {
2887 if (ImmediateClass)
2888 WarnUndefinedMethod(SemaRef, IMPDecl, I, IncompleteImpl,
2889 diag::warn_undef_method_impl);
2890 } else {
2891 ObjCMethodDecl *ImpMethodDecl =
2892 IMPDecl->getClassMethod(I->getSelector());
2893 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2894 "Expected to find the method through lookup as well");
2895 // ImpMethodDecl may be null as in a @dynamic property.
2896 if (ImpMethodDecl) {
2897 // Skip property accessor function stubs.
2898 if (ImpMethodDecl->isSynthesizedAccessorStub())
2899 continue;
2900 if (!WarnCategoryMethodImpl)
2901 WarnConflictingTypedMethods(ImpMethodDecl, I,
2902 isa<ObjCProtocolDecl>(CDecl));
2903 else if (!I->isPropertyAccessor())
2904 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2905 }
2906 }
2907 }
2908
2909 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2910 // Also, check for methods declared in protocols inherited by
2911 // this protocol.
2912 for (auto *PI : PD->protocols())
2913 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2914 IMPDecl, PI, IncompleteImpl, false,
2915 WarnCategoryMethodImpl);
2916 }
2917
2918 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2919 // when checking that methods in implementation match their declaration,
2920 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2921 // extension; as well as those in categories.
2922 if (!WarnCategoryMethodImpl) {
2923 for (auto *Cat : I->visible_categories())
2924 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2925 IMPDecl, Cat, IncompleteImpl,
2926 ImmediateClass && Cat->IsClassExtension(),
2927 WarnCategoryMethodImpl);
2928 } else {
2929 // Also methods in class extensions need be looked at next.
2930 for (auto *Ext : I->visible_extensions())
2931 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2932 IMPDecl, Ext, IncompleteImpl, false,
2933 WarnCategoryMethodImpl);
2934 }
2935
2936 // Check for any implementation of a methods declared in protocol.
2937 for (auto *PI : I->all_referenced_protocols())
2938 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2939 IMPDecl, PI, IncompleteImpl, false,
2940 WarnCategoryMethodImpl);
2941
2942 // FIXME. For now, we are not checking for exact match of methods
2943 // in category implementation and its primary class's super class.
2944 if (!WarnCategoryMethodImpl && I->getSuperClass())
2945 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2946 IMPDecl,
2947 I->getSuperClass(), IncompleteImpl, false);
2948 }
2949}
2950
2951/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2952/// category matches with those implemented in its primary class and
2953/// warns each time an exact match is found.
2955 ObjCCategoryImplDecl *CatIMPDecl) {
2956 // Get category's primary class.
2957 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2958 if (!CatDecl)
2959 return;
2960 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2961 if (!IDecl)
2962 return;
2963 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2964 SelectorSet InsMap, ClsMap;
2965
2966 for (const auto *I : CatIMPDecl->instance_methods()) {
2967 Selector Sel = I->getSelector();
2968 // When checking for methods implemented in the category, skip over
2969 // those declared in category class's super class. This is because
2970 // the super class must implement the method.
2971 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2972 continue;
2973 InsMap.insert(Sel);
2974 }
2975
2976 for (const auto *I : CatIMPDecl->class_methods()) {
2977 Selector Sel = I->getSelector();
2978 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2979 continue;
2980 ClsMap.insert(Sel);
2981 }
2982 if (InsMap.empty() && ClsMap.empty())
2983 return;
2984
2985 SelectorSet InsMapSeen, ClsMapSeen;
2986 bool IncompleteImpl = false;
2987 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2988 CatIMPDecl, IDecl,
2989 IncompleteImpl, false,
2990 true /*WarnCategoryMethodImpl*/);
2991}
2992
2994 ObjCContainerDecl *CDecl,
2995 bool IncompleteImpl) {
2996 SelectorSet InsMap;
2997 // Check and see if instance methods in class interface have been
2998 // implemented in the implementation class.
2999 for (const auto *I : IMPDecl->instance_methods())
3000 InsMap.insert(I->getSelector());
3001
3002 // Add the selectors for getters/setters of @dynamic properties.
3003 for (const auto *PImpl : IMPDecl->property_impls()) {
3004 // We only care about @dynamic implementations.
3005 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
3006 continue;
3007
3008 const auto *P = PImpl->getPropertyDecl();
3009 if (!P) continue;
3010
3011 InsMap.insert(P->getGetterName());
3012 if (!P->getSetterName().isNull())
3013 InsMap.insert(P->getSetterName());
3014 }
3015
3016 // Check and see if properties declared in the interface have either 1)
3017 // an implementation or 2) there is a @synthesize/@dynamic implementation
3018 // of the property in the @implementation.
3019 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
3020 bool SynthesizeProperties = getLangOpts().ObjCDefaultSynthProperties &&
3022 !IDecl->isObjCRequiresPropertyDefs();
3023 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
3024 }
3025
3026 // Diagnose null-resettable synthesized setters.
3028
3029 SelectorSet ClsMap;
3030 for (const auto *I : IMPDecl->class_methods())
3031 ClsMap.insert(I->getSelector());
3032
3033 // Check for type conflict of methods declared in a class/protocol and
3034 // its implementation; if any.
3035 SelectorSet InsMapSeen, ClsMapSeen;
3036 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3037 IMPDecl, CDecl,
3038 IncompleteImpl, true);
3039
3040 // check all methods implemented in category against those declared
3041 // in its primary class.
3042 if (ObjCCategoryImplDecl *CatDecl =
3043 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3045
3046 // Check the protocol list for unimplemented methods in the @implementation
3047 // class.
3048 // Check and see if class methods in class interface have been
3049 // implemented in the implementation class.
3050
3051 LazyProtocolNameSet ExplicitImplProtocols;
3052
3053 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3054 for (auto *PI : I->all_referenced_protocols())
3055 CheckProtocolMethodDefs(SemaRef, IMPDecl, PI, IncompleteImpl, InsMap,
3056 ClsMap, I, ExplicitImplProtocols);
3057 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3058 // For extended class, unimplemented methods in its protocols will
3059 // be reported in the primary class.
3060 if (!C->IsClassExtension()) {
3061 for (auto *P : C->protocols())
3062 CheckProtocolMethodDefs(SemaRef, IMPDecl, P, IncompleteImpl, InsMap,
3063 ClsMap, CDecl, ExplicitImplProtocols);
3064 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3065 /*SynthesizeProperties=*/false);
3066 }
3067 } else
3068 llvm_unreachable("invalid ObjCContainerDecl type.");
3069}
3070
3072 SourceLocation AtClassLoc, IdentifierInfo **IdentList,
3073 SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists,
3074 unsigned NumElts) {
3075 ASTContext &Context = getASTContext();
3076 SmallVector<Decl *, 8> DeclsInGroup;
3077 for (unsigned i = 0; i != NumElts; ++i) {
3078 // Check for another declaration kind with the same name.
3079 NamedDecl *PrevDecl = SemaRef.LookupSingleName(
3080 SemaRef.TUScope, IdentList[i], IdentLocs[i], Sema::LookupOrdinaryName,
3081 SemaRef.forRedeclarationInCurContext());
3082 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3083 // GCC apparently allows the following idiom:
3084 //
3085 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3086 // @class XCElementToggler;
3087 //
3088 // Here we have chosen to ignore the forward class declaration
3089 // with a warning. Since this is the implied behavior.
3090 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3091 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3092 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3093 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3094 } else {
3095 // a forward class declaration matching a typedef name of a class refers
3096 // to the underlying class. Just ignore the forward class with a warning
3097 // as this will force the intended behavior which is to lookup the
3098 // typedef name.
3100 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3101 << IdentList[i];
3102 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3103 continue;
3104 }
3105 }
3106 }
3107
3108 // Create a declaration to describe this forward declaration.
3109 ObjCInterfaceDecl *PrevIDecl
3110 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3111
3112 IdentifierInfo *ClassName = IdentList[i];
3113 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3114 // A previous decl with a different name is because of
3115 // @compatibility_alias, for example:
3116 // \code
3117 // @class NewImage;
3118 // @compatibility_alias OldImage NewImage;
3119 // \endcode
3120 // A lookup for 'OldImage' will return the 'NewImage' decl.
3121 //
3122 // In such a case use the real declaration name, instead of the alias one,
3123 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3124 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3125 // has been aliased.
3126 ClassName = PrevIDecl->getIdentifier();
3127 }
3128
3129 // If this forward declaration has type parameters, compare them with the
3130 // type parameters of the previous declaration.
3131 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3132 if (PrevIDecl && TypeParams) {
3133 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3134 // Check for consistency with the previous declaration.
3136 SemaRef, PrevTypeParams, TypeParams,
3137 TypeParamListContext::ForwardDeclaration)) {
3138 TypeParams = nullptr;
3139 }
3140 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3141 // The @interface does not have type parameters. Complain.
3142 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3143 << ClassName
3144 << TypeParams->getSourceRange();
3145 Diag(Def->getLocation(), diag::note_defined_here)
3146 << ClassName;
3147
3148 TypeParams = nullptr;
3149 }
3150 }
3151
3153 Context, SemaRef.CurContext, AtClassLoc, ClassName, TypeParams,
3154 PrevIDecl, IdentLocs[i]);
3155 IDecl->setAtEndRange(IdentLocs[i]);
3156
3157 if (PrevIDecl)
3158 SemaRef.mergeDeclAttributes(IDecl, PrevIDecl);
3159
3160 SemaRef.PushOnScopeChains(IDecl, SemaRef.TUScope);
3161 CheckObjCDeclScope(IDecl);
3162 DeclsInGroup.push_back(IDecl);
3163 }
3164
3165 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
3166}
3167
3168static bool tryMatchRecordTypes(ASTContext &Context,
3170 const Type *left, const Type *right);
3171
3172static bool matchTypes(ASTContext &Context,
3173 SemaObjC::MethodMatchStrategy strategy, QualType leftQT,
3174 QualType rightQT) {
3175 const Type *left =
3176 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3177 const Type *right =
3178 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3179
3180 if (left == right) return true;
3181
3182 // If we're doing a strict match, the types have to match exactly.
3183 if (strategy == SemaObjC::MMS_strict)
3184 return false;
3185
3186 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3187
3188 // Otherwise, use this absurdly complicated algorithm to try to
3189 // validate the basic, low-level compatibility of the two types.
3190
3191 // As a minimum, require the sizes and alignments to match.
3192 TypeInfo LeftTI = Context.getTypeInfo(left);
3193 TypeInfo RightTI = Context.getTypeInfo(right);
3194 if (LeftTI.Width != RightTI.Width)
3195 return false;
3196
3197 if (LeftTI.Align != RightTI.Align)
3198 return false;
3199
3200 // Consider all the kinds of non-dependent canonical types:
3201 // - functions and arrays aren't possible as return and parameter types
3202
3203 // - vector types of equal size can be arbitrarily mixed
3204 if (isa<VectorType>(left)) return isa<VectorType>(right);
3205 if (isa<VectorType>(right)) return false;
3206
3207 // - references should only match references of identical type
3208 // - structs, unions, and Objective-C objects must match more-or-less
3209 // exactly
3210 // - everything else should be a scalar
3211 if (!left->isScalarType() || !right->isScalarType())
3212 return tryMatchRecordTypes(Context, strategy, left, right);
3213
3214 // Make scalars agree in kind, except count bools as chars, and group
3215 // all non-member pointers together.
3216 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3217 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3218 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3219 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3220 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3222 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3224
3225 // Note that data member pointers and function member pointers don't
3226 // intermix because of the size differences.
3227
3228 return (leftSK == rightSK);
3229}
3230
3231static bool tryMatchRecordTypes(ASTContext &Context,
3233 const Type *lt, const Type *rt) {
3234 assert(lt && rt && lt != rt);
3235
3236 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3237 RecordDecl *left = cast<RecordType>(lt)->getDecl()->getDefinitionOrSelf();
3238 RecordDecl *right = cast<RecordType>(rt)->getDecl()->getDefinitionOrSelf();
3239
3240 // Require union-hood to match.
3241 if (left->isUnion() != right->isUnion()) return false;
3242
3243 // Require an exact match if either is non-POD.
3244 if ((isa<CXXRecordDecl>(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 ||
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 &&
3384 ListWithSameDeclaration = List;
3385 continue;
3386 }
3387
3388 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3389
3390 // Propagate the 'defined' bit.
3391 if (Method->isDefined())
3392 PrevObjCMethod->setDefined(true);
3393 else {
3394 // Objective-C doesn't allow an @interface for a class after its
3395 // @implementation. So if Method is not defined and there already is
3396 // an entry for this type signature, Method has to be for a different
3397 // class than PrevObjCMethod.
3398 List->setHasMoreThanOneDecl(true);
3399 }
3400
3401 // If a method is deprecated, push it in the global pool.
3402 // This is used for better diagnostics.
3403 if (Method->isDeprecated()) {
3404 if (!PrevObjCMethod->isDeprecated())
3405 List->setMethod(Method);
3406 }
3407 // If the new method is unavailable, push it into global pool
3408 // unless previous one is deprecated.
3409 if (Method->isUnavailable()) {
3410 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3411 List->setMethod(Method);
3412 }
3413
3414 return;
3415 }
3416
3417 // We have a new signature for an existing method - add it.
3418 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3419 ObjCMethodList *Mem = SemaRef.BumpAlloc.Allocate<ObjCMethodList>();
3420
3421 // We insert it right before ListWithSameDeclaration.
3422 if (ListWithSameDeclaration) {
3423 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3424 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3425 ListWithSameDeclaration->setMethod(Method);
3426 ListWithSameDeclaration->setNext(List);
3427 return;
3428 }
3429
3430 Previous->setNext(new (Mem) ObjCMethodList(Method));
3431}
3432
3433/// Read the contents of the method pool for a given selector from
3434/// external storage.
3436 assert(SemaRef.ExternalSource && "We need an external AST source");
3437 SemaRef.ExternalSource->ReadMethodPool(Sel);
3438}
3439
3441 if (!SemaRef.ExternalSource)
3442 return;
3443 SemaRef.ExternalSource->updateOutOfDateSelector(Sel);
3444}
3445
3446void SemaObjC::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3447 bool instance) {
3448 // Ignore methods of invalid containers.
3449 if (cast<Decl>(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) {
3523 if (SemaRef.ExternalSource)
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.
4149 NamedDecl *IF = SemaRef.LookupSingleName(
4150 SemaRef.TUScope, NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
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();
4231 SemaRef.Consumer.HandleTopLevelDeclInObjCContainer(DG);
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.
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;
4290 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4291 bool Recursive;
4292
4293public:
4294 OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4295 Selector selector = method->getSelector();
4296
4297 // Bypass this search if we've never seen an instance/class method
4298 // with this selector before.
4299 SemaObjC::GlobalMethodPool::iterator it =
4300 S.ObjC().MethodPool.find(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
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()) ||
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");
4637 SourceLocation Loc;
4638 QualType T;
4639 for (const ParmVarDecl *P : Method->parameters()) {
4640 if (P->getType()->isVectorType()) {
4641 Loc = P->getBeginLoc();
4642 T = P->getType();
4643 break;
4644 }
4645 }
4646 if (Loc.isInvalid()) {
4647 if (Method->getReturnType()->isVectorType()) {
4648 Loc = Method->getReturnTypeSourceRange().getBegin();
4649 T = Method->getReturnType();
4650 } else
4651 return;
4652 }
4653
4654 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4655 // iOS < 9 and macOS < 10.11.
4656 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4657 VersionTuple AcceptedInVersion;
4658 if (Triple.getOS() == llvm::Triple::IOS)
4659 AcceptedInVersion = VersionTuple(/*Major=*/9);
4660 else if (Triple.isMacOSX())
4661 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4662 else
4663 return;
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
4673static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4674 if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
4675 CD->hasAttr<ObjCDirectMembersAttr>()) {
4676 Method->addAttr(
4677 ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4678 }
4679}
4680
4682 ObjCMethodDecl *Method,
4683 ObjCImplDecl *ImpDecl = nullptr) {
4684 auto Sel = Method->getSelector();
4685 bool isInstance = Method->isInstanceMethod();
4686 bool diagnosed = false;
4687
4688 auto diagClash = [&](const ObjCMethodDecl *IMD) {
4689 if (diagnosed || IMD->isImplicit())
4690 return;
4691 if (Method->isDirectMethod() || IMD->isDirectMethod()) {
4692 S.Diag(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();
4735 TypeSourceInfo *TSI;
4736
4737 if (!ArgInfo.Type) {
4738 ArgType = Context.getObjCIdType();
4739 TSI = nullptr;
4740 } else {
4741 ArgType = SemaRef.GetTypeFromParser(ArgInfo.Type, &TSI);
4742 }
4743 LookupResult R(SemaRef, ArgInfo.Name, ArgInfo.NameLoc,
4745 SemaRef.forRedeclarationInCurContext());
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 TSI ? TSI->getTypeLoc().getBeginLoc() : ArgInfo.NameLoc;
4759
4760 // Temporarily put parameter variables in the translation unit. This is what
4761 // ActOnParamDeclarator does in the case of C arguments to the Objective-C
4762 // method too.
4763 ParmVarDecl *Param = SemaRef.CheckParameter(
4764 Context.getTranslationUnitDecl(), StartLoc, ArgInfo.NameLoc, ArgInfo.Name,
4765 ArgType, TSI, SC_None);
4766 Param->setObjCMethodScopeInfo(ParamIndex);
4767 Param->setObjCDeclQualifier(
4769
4770 // Apply the attributes to the parameter.
4771 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, Param, ArgInfo.ArgAttrs);
4772 SemaRef.AddPragmaAttributes(SemaRef.TUScope, Param);
4773 if (Param->hasAttr<BlocksAttr>()) {
4774 Diag(Param->getLocation(), diag::err_block_not_allowed_on)
4775 << diag::NotAllowedBlockVarReason::NonlocalVariable;
4776 Param->setInvalidDecl();
4777 }
4778
4779 S->AddDecl(Param);
4780 SemaRef.IdResolver.AddDecl(Param);
4781 return Param;
4782}
4783
4785 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4786 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4787 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4788 // optional arguments. The number of types/arguments is obtained
4789 // from the Sel.getNumArgs().
4790 ParmVarDecl **ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4791 unsigned CNumArgs, // c-style args
4792 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4793 bool isVariadic, bool MethodDefinition) {
4794 ASTContext &Context = getASTContext();
4795 // Make sure we can establish a context for the method.
4796 if (!SemaRef.CurContext->isObjCContainer()) {
4797 Diag(MethodLoc, diag::err_missing_method_context);
4798 return nullptr;
4799 }
4800
4801 Decl *ClassDecl = cast<ObjCContainerDecl>(SemaRef.CurContext);
4802 QualType resultDeclType;
4803
4804 bool HasRelatedResultType = false;
4805 TypeSourceInfo *ReturnTInfo = nullptr;
4806 if (ReturnType) {
4807 resultDeclType = SemaRef.GetTypeFromParser(ReturnType, &ReturnTInfo);
4808
4809 if (SemaRef.CheckFunctionReturnType(resultDeclType, MethodLoc))
4810 return nullptr;
4811
4812 QualType bareResultType = resultDeclType;
4813 (void)AttributedType::stripOuterNullability(bareResultType);
4814 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4815 } else { // get the type for "id".
4816 resultDeclType = Context.getObjCIdType();
4817 Diag(MethodLoc, diag::warn_missing_method_return_type)
4818 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4819 }
4820
4822 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo,
4823 SemaRef.CurContext, MethodType == tok::minus, isVariadic,
4824 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4825 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4826 MethodDeclKind == tok::objc_optional
4829 HasRelatedResultType);
4830
4832 for (unsigned I = 0; I < Sel.getNumArgs(); ++I) {
4833 ParmVarDecl *Param = ArgInfo[I];
4834 Param->setDeclContext(ObjCMethod);
4835 SemaRef.ProcessAPINotes(Param);
4836 Params.push_back(Param);
4837 }
4838
4839 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4840 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4841 QualType ArgType = Param->getType();
4842 if (ArgType.isNull())
4843 ArgType = Context.getObjCIdType();
4844 else
4845 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4846 ArgType = Context.getAdjustedParameterType(ArgType);
4847
4848 Param->setDeclContext(ObjCMethod);
4849 Params.push_back(Param);
4850 }
4851
4852 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4853 ObjCMethod->setObjCDeclQualifier(
4855
4856 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, ObjCMethod, AttrList);
4857 SemaRef.AddPragmaAttributes(SemaRef.TUScope, ObjCMethod);
4858 SemaRef.ProcessAPINotes(ObjCMethod);
4859
4860 // Add the method now.
4861 const ObjCMethodDecl *PrevMethod = nullptr;
4862 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4863 if (MethodType == tok::minus) {
4864 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4865 ImpDecl->addInstanceMethod(ObjCMethod);
4866 } else {
4867 PrevMethod = ImpDecl->getClassMethod(Sel);
4868 ImpDecl->addClassMethod(ObjCMethod);
4869 }
4870
4871 // If this method overrides a previous @synthesize declaration,
4872 // register it with the property. Linear search through all
4873 // properties here, because the autosynthesized stub hasn't been
4874 // made visible yet, so it can be overridden by a later
4875 // user-specified implementation.
4876 for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4877 if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4878 if (Setter->getSelector() == Sel &&
4879 Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4880 assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4881 PropertyImpl->setSetterMethodDecl(ObjCMethod);
4882 }
4883 if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4884 if (Getter->getSelector() == Sel &&
4885 Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4886 assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4887 PropertyImpl->setGetterMethodDecl(ObjCMethod);
4888 break;
4889 }
4890 }
4891
4892 // A method is either tagged direct explicitly, or inherits it from its
4893 // canonical declaration.
4894 //
4895 // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4896 // because IDecl->lookupMethod() returns more possible matches than just
4897 // the canonical declaration.
4898 if (!ObjCMethod->isDirectMethod()) {
4899 const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4900 if (CanonicalMD->isDirectMethod()) {
4901 const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4902 ObjCMethod->addAttr(
4903 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4904 }
4905 }
4906
4907 // Merge information from the @interface declaration into the
4908 // @implementation.
4909 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4910 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4911 ObjCMethod->isInstanceMethod())) {
4912 mergeInterfaceMethodToImpl(SemaRef, ObjCMethod, IMD);
4913
4914 // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4915 // in one of these places:
4916 //
4917 // (1) the canonical declaration in an @interface container paired
4918 // with the ImplDecl,
4919 // (2) non canonical declarations in @interface not paired with the
4920 // ImplDecl for the same Class,
4921 // (3) any superclass container.
4922 //
4923 // Direct methods only allow for canonical declarations in the matching
4924 // container (case 1).
4925 //
4926 // Direct methods overriding a superclass declaration (case 3) is
4927 // handled during overrides checks in CheckObjCMethodOverrides().
4928 //
4929 // We deal with same-class container mismatches (Case 2) here.
4930 if (IDecl == IMD->getClassInterface()) {
4931 auto diagContainerMismatch = [&] {
4932 int decl = 0, impl = 0;
4933
4934 if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4935 decl = Cat->IsClassExtension() ? 1 : 2;
4936
4937 if (isa<ObjCCategoryImplDecl>(ImpDecl))
4938 impl = 1 + (decl != 0);
4939
4940 Diag(ObjCMethod->getLocation(),
4941 diag::err_objc_direct_impl_decl_mismatch)
4942 << decl << impl;
4943 Diag(IMD->getLocation(), diag::note_previous_declaration);
4944 };
4945
4946 if (ObjCMethod->isDirectMethod()) {
4947 const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4948 if (ObjCMethod->getCanonicalDecl() != IMD) {
4949 diagContainerMismatch();
4950 } else if (!IMD->isDirectMethod()) {
4951 Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4952 Diag(IMD->getLocation(), diag::note_previous_declaration);
4953 }
4954 } else if (IMD->isDirectMethod()) {
4955 const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4956 if (ObjCMethod->getCanonicalDecl() != IMD) {
4957 diagContainerMismatch();
4958 } else {
4959 ObjCMethod->addAttr(
4960 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4961 }
4962 }
4963 }
4964
4965 // Warn about defining -dealloc in a category.
4966 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4967 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4968 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4969 << ObjCMethod->getDeclName();
4970 }
4971 } else {
4972 mergeObjCDirectMembers(SemaRef, ClassDecl, ObjCMethod);
4973 checkObjCDirectMethodClashes(SemaRef, IDecl, ObjCMethod, ImpDecl);
4974 }
4975
4976 // Warn if a method declared in a protocol to which a category or
4977 // extension conforms is non-escaping and the implementation's method is
4978 // escaping.
4979 for (auto *C : IDecl->visible_categories())
4980 for (auto &P : C->protocols())
4981 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4982 ObjCMethod->isInstanceMethod())) {
4983 assert(ObjCMethod->parameters().size() ==
4984 IMD->parameters().size() &&
4985 "Methods have different number of parameters");
4986 auto OI = IMD->param_begin(), OE = IMD->param_end();
4987 auto NI = ObjCMethod->param_begin();
4988 for (; OI != OE; ++OI, ++NI)
4989 diagnoseNoescape(*NI, *OI, C, P, SemaRef);
4990 }
4991 }
4992 } else {
4993 if (!isa<ObjCProtocolDecl>(ClassDecl)) {
4994 mergeObjCDirectMembers(SemaRef, ClassDecl, ObjCMethod);
4995
4996 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4997 if (!IDecl)
4998 IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
4999 // For valid code, we should always know the primary interface
5000 // declaration by now, however for invalid code we'll keep parsing
5001 // but we won't find the primary interface and IDecl will be nil.
5002 if (IDecl)
5003 checkObjCDirectMethodClashes(SemaRef, IDecl, ObjCMethod);
5004 }
5005
5006 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
5007 }
5008
5009 if (PrevMethod) {
5010 // You can never have two method definitions with the same name.
5011 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
5012 << ObjCMethod->getDeclName();
5013 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
5014 ObjCMethod->setInvalidDecl();
5015 return ObjCMethod;
5016 }
5017
5018 // If this Objective-C method does not have a related result type, but we
5019 // are allowed to infer related result types, try to do so based on the
5020 // method family.
5021 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
5022 if (!CurrentClass) {
5023 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
5024 CurrentClass = Cat->getClassInterface();
5025 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
5026 CurrentClass = Impl->getClassInterface();
5027 else if (ObjCCategoryImplDecl *CatImpl
5028 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
5029 CurrentClass = CatImpl->getClassInterface();
5030 }
5031
5033 CheckRelatedResultTypeCompatibility(SemaRef, ObjCMethod, CurrentClass);
5034
5035 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
5036
5037 bool ARCError = false;
5038 if (getLangOpts().ObjCAutoRefCount)
5039 ARCError = CheckARCMethodDecl(ObjCMethod);
5040
5041 // Infer the related result type when possible.
5042 if (!ARCError && RTC == SemaObjC::RTC_Compatible &&
5043 !ObjCMethod->hasRelatedResultType() &&
5044 getLangOpts().ObjCInferRelatedResultType) {
5045 bool InferRelatedResultType = false;
5046 switch (ObjCMethod->getMethodFamily()) {
5047 case OMF_None:
5048 case OMF_copy:
5049 case OMF_dealloc:
5050 case OMF_finalize:
5051 case OMF_mutableCopy:
5052 case OMF_release:
5053 case OMF_retainCount:
5054 case OMF_initialize:
5056 break;
5057
5058 case OMF_alloc:
5059 case OMF_new:
5060 InferRelatedResultType = ObjCMethod->isClassMethod();
5061 break;
5062
5063 case OMF_init:
5064 case OMF_autorelease:
5065 case OMF_retain:
5066 case OMF_self:
5067 InferRelatedResultType = ObjCMethod->isInstanceMethod();
5068 break;
5069 }
5070
5071 if (InferRelatedResultType &&
5072 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
5073 ObjCMethod->setRelatedResultType();
5074 }
5075
5076 if (MethodDefinition &&
5077 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5079
5080 // + load method cannot have availability attributes. It get called on
5081 // startup, so it has to have the availability of the deployment target.
5082 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
5083 if (ObjCMethod->isClassMethod() &&
5084 ObjCMethod->getSelector().getAsString() == "load") {
5085 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
5086 << 0;
5087 ObjCMethod->dropAttr<AvailabilityAttr>();
5088 }
5089 }
5090
5091 // Insert the invisible arguments, self and _cmd!
5092 ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
5093
5094 SemaRef.ActOnDocumentableDecl(ObjCMethod);
5095
5096 return ObjCMethod;
5097}
5098
5100 // Following is also an error. But it is caused by a missing @end
5101 // and diagnostic is issued elsewhere.
5102 if (isa<ObjCContainerDecl>(SemaRef.CurContext->getRedeclContext()))
5103 return false;
5104
5105 // If we switched context to translation unit while we are still lexically in
5106 // an objc container, it means the parser missed emitting an error.
5108 SemaRef.getCurLexicalContext()->getRedeclContext()))
5109 return false;
5110
5111 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
5112 D->setInvalidDecl();
5113
5114 return true;
5115}
5116
5117/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
5118/// instance variables of ClassName into Decls.
5120 const IdentifierInfo *ClassName,
5121 SmallVectorImpl<Decl *> &Decls) {
5122 ASTContext &Context = getASTContext();
5123 // Check that ClassName is a valid class
5124 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
5125 if (!Class) {
5126 Diag(DeclStart, diag::err_undef_interface) << ClassName;
5127 return;
5128 }
5130 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
5131 return;
5132 }
5133
5134 // Collect the instance variables
5136 Context.DeepCollectObjCIvars(Class, true, Ivars);
5137 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
5138 for (unsigned i = 0; i < Ivars.size(); i++) {
5139 const FieldDecl* ID = Ivars[i];
5140 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
5142 /*FIXME: StartL=*/ID->getLocation(),
5143 ID->getLocation(),
5144 ID->getIdentifier(), ID->getType(),
5145 ID->getBitWidth());
5146 Decls.push_back(FD);
5147 }
5148
5149 // Introduce all of these fields into the appropriate scope.
5150 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
5151 D != Decls.end(); ++D) {
5152 FieldDecl *FD = cast<FieldDecl>(*D);
5153 if (getLangOpts().CPlusPlus)
5154 SemaRef.PushOnScopeChains(FD, S);
5155 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
5156 Record->addDecl(FD);
5157 }
5158}
5159
5160/// Build a type-check a new Objective-C exception variable declaration.
5162 SourceLocation StartLoc,
5163 SourceLocation IdLoc,
5164 const IdentifierInfo *Id,
5165 bool Invalid) {
5166 ASTContext &Context = getASTContext();
5167 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5168 // duration shall not be qualified by an address-space qualifier."
5169 // Since all parameters have automatic store duration, they can not have
5170 // an address space.
5171 if (T.getAddressSpace() != LangAS::Default) {
5172 Diag(IdLoc, diag::err_arg_with_address_space);
5173 Invalid = true;
5174 }
5175
5176 // An @catch parameter must be an unqualified object pointer type;
5177 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
5178 if (Invalid) {
5179 // Don't do any further checking.
5180 } else if (T->isDependentType()) {
5181 // Okay: we don't know what this type will instantiate to.
5182 } else if (T->isObjCQualifiedIdType()) {
5183 Invalid = true;
5184 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
5185 } else if (T->isObjCIdType()) {
5186 // Okay: we don't know what this type will instantiate to.
5187 } else if (!T->isObjCObjectPointerType()) {
5188 Invalid = true;
5189 Diag(IdLoc, diag::err_catch_param_not_objc_type);
5190 } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) {
5191 Invalid = true;
5192 Diag(IdLoc, diag::err_catch_param_not_objc_type);
5193 }
5194
5195 VarDecl *New = VarDecl::Create(Context, SemaRef.CurContext, StartLoc, IdLoc,
5196 Id, T, TInfo, SC_None);
5197 New->setExceptionVariable(true);
5198
5199 // In ARC, infer 'retaining' for variables of retainable type.
5200 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
5201 Invalid = true;
5202
5203 if (Invalid)
5204 New->setInvalidDecl();
5205 return New;
5206}
5207
5209 const DeclSpec &DS = D.getDeclSpec();
5210
5211 // We allow the "register" storage class on exception variables because
5212 // GCC did, but we drop it completely. Any other storage class is an error.
5214 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
5216 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5217 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
5219 }
5220 if (DS.isInlineSpecified())
5221 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5222 << getLangOpts().CPlusPlus17;
5225 diag::err_invalid_thread)
5228
5229 SemaRef.DiagnoseFunctionSpecifiers(D.getDeclSpec());
5230
5231 // Check that there are no default arguments inside the type of this
5232 // exception object (C++ only).
5233 if (getLangOpts().CPlusPlus)
5234 SemaRef.CheckExtraCXXDefaultArguments(D);
5235
5236 TypeSourceInfo *TInfo = SemaRef.GetTypeForDeclarator(D);
5237 QualType ExceptionType = TInfo->getType();
5238
5239 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
5241 D.getIdentifierLoc(),
5242 D.getIdentifier(),
5243 D.isInvalidType());
5244
5245 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5246 if (D.getCXXScopeSpec().isSet()) {
5247 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
5248 << D.getCXXScopeSpec().getRange();
5249 New->setInvalidDecl();
5250 }
5251
5252 // Add the parameter declaration into this scope.
5253 S->AddDecl(New);
5254 if (D.getIdentifier())
5255 SemaRef.IdResolver.AddDecl(New);
5256
5257 SemaRef.ProcessDeclAttributes(S, New, D);
5258
5259 if (New->hasAttr<BlocksAttr>())
5260 Diag(New->getLocation(), diag::err_block_not_allowed_on)
5261 << diag::NotAllowedBlockVarReason::NonlocalVariable;
5262 return New;
5263}
5264
5265/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
5266/// initialization.
5269 ASTContext &Context = getASTContext();
5270 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
5271 Iv= Iv->getNextIvar()) {
5272 QualType QT = Context.getBaseElementType(Iv->getType());
5273 if (QT->isRecordType())
5274 Ivars.push_back(Iv);
5275 }
5276}
5277
5279 ASTContext &Context = getASTContext();
5280 // Load referenced selectors from the external source.
5281 if (SemaRef.ExternalSource) {
5283 SemaRef.ExternalSource->ReadReferencedSelectors(Sels);
5284 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
5285 ReferencedSelectors[Sels[I].first] = Sels[I].second;
5286 }
5287
5288 // Warning will be issued only when selector table is
5289 // generated (which means there is at lease one implementation
5290 // in the TU). This is to match gcc's behavior.
5291 if (ReferencedSelectors.empty() ||
5292 !Context.AnyObjCImplementation())
5293 return;
5294 for (auto &SelectorAndLocation : ReferencedSelectors) {
5295 Selector Sel = SelectorAndLocation.first;
5296 SourceLocation Loc = SelectorAndLocation.second;
5298 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
5299 }
5300}
5301
5304 const ObjCPropertyDecl *&PDecl) const {
5305 if (Method->isClassMethod())
5306 return nullptr;
5307 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
5308 if (!IDecl)
5309 return nullptr;
5310 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
5311 /*shallowCategoryLookup=*/false,
5312 /*followSuper=*/false);
5313 if (!Method || !Method->isPropertyAccessor())
5314 return nullptr;
5315 if ((PDecl = Method->findPropertyDecl()))
5316 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5317 // property backing ivar must belong to property's class
5318 // or be a private ivar in class's implementation.
5319 // FIXME. fix the const-ness issue.
5320 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5321 IV->getIdentifier());
5322 return IV;
5323 }
5324 return nullptr;
5325}
5326
5327namespace {
5328/// Used by SemaObjC::DiagnoseUnusedBackingIvarInAccessor to check if a property
5329/// accessor references the backing ivar.
5330class UnusedBackingIvarChecker : public DynamicRecursiveASTVisitor {
5331public:
5332 Sema &S;
5333 const ObjCMethodDecl *Method;
5334 const ObjCIvarDecl *IvarD;
5335 bool AccessedIvar;
5336 bool InvokedSelfMethod;
5337
5338 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5339 const ObjCIvarDecl *IvarD)
5340 : S(S), Method(Method), IvarD(IvarD), AccessedIvar(false),
5341 InvokedSelfMethod(false) {
5342 assert(IvarD);
5343 }
5344
5345 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) override {
5346 if (E->getDecl() == IvarD) {
5347 AccessedIvar = true;
5348 return false;
5349 }
5350 return true;
5351 }
5352
5353 bool VisitObjCMessageExpr(ObjCMessageExpr *E) override {
5356 InvokedSelfMethod = true;
5357 }
5358 return true;
5359 }
5360};
5361} // end anonymous namespace
5362
5364 Scope *S, const ObjCImplementationDecl *ImplD) {
5366 return;
5367
5368 for (const auto *CurMethod : ImplD->instance_methods()) {
5369 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5370 SourceLocation Loc = CurMethod->getLocation();
5371 if (getDiagnostics().isIgnored(DIAG, Loc))
5372 continue;
5373
5374 const ObjCPropertyDecl *PDecl;
5375 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5376 if (!IV)
5377 continue;
5378
5379 if (CurMethod->isSynthesizedAccessorStub())
5380 continue;
5381
5382 UnusedBackingIvarChecker Checker(SemaRef, CurMethod, IV);
5383 Checker.TraverseStmt(CurMethod->getBody());
5384 if (Checker.AccessedIvar)
5385 continue;
5386
5387 // Do not issue this warning if backing ivar is used somewhere and accessor
5388 // implementation makes a self call. This is to prevent false positive in
5389 // cases where the ivar is accessed by another method that the accessor
5390 // delegates to.
5391 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5392 Diag(Loc, DIAG) << IV;
5393 Diag(PDecl->getLocation(), diag::note_property_declare);
5394 }
5395 }
5396}
5397
5399 QualType T, SourceLocation NameLoc, TypeSourceInfo *TSInfo) {
5400 ASTContext &Context = getASTContext();
5401 // In ARC, infer a lifetime qualifier for appropriate parameter types.
5402 if (!getLangOpts().ObjCAutoRefCount ||
5403 T.getObjCLifetime() != Qualifiers::OCL_None || !T->isObjCLifetimeType())
5404 return T;
5405
5406 Qualifiers::ObjCLifetime Lifetime;
5407
5408 // Special cases for arrays:
5409 // - if it's const, use __unsafe_unretained
5410 // - otherwise, it's an error
5411 if (T->isArrayType()) {
5412 if (!T.isConstQualified()) {
5413 if (SemaRef.DelayedDiagnostics.shouldDelayDiagnostics())
5414 SemaRef.DelayedDiagnostics.add(
5416 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
5417 else
5418 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
5419 << TSInfo->getTypeLoc().getSourceRange();
5420 }
5422 } else {
5423 Lifetime = T->getObjCARCImplicitLifetime();
5424 }
5425 T = Context.getLifetimeQualifiedType(T, Lifetime);
5426
5427 return T;
5428}
5429
5431 SourceLocation IdLoc,
5432 bool DoTypoCorrection) {
5433 // The third "scope" argument is 0 since we aren't enabling lazy built-in
5434 // creation from this context.
5435 NamedDecl *IDecl = SemaRef.LookupSingleName(SemaRef.TUScope, Id, IdLoc,
5437
5438 if (!IDecl && DoTypoCorrection) {
5439 // Perform typo correction at the given location, but only if we
5440 // find an Objective-C class name.
5442 if (TypoCorrection C = SemaRef.CorrectTypo(
5444 SemaRef.TUScope, nullptr, CCC, CorrectTypoKind::ErrorRecovery)) {
5445 SemaRef.diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
5446 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
5447 Id = IDecl->getIdentifier();
5448 }
5449 }
5450 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
5451 // This routine must always return a class definition, if any.
5452 if (Def && Def->getDefinition())
5453 Def = Def->getDefinition();
5454 return Def;
5455}
5456
5458 ASTContext &Context = getASTContext();
5459 QualType type = decl->getType();
5460 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5461 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5462 // Various kinds of declaration aren't allowed to be __autoreleasing.
5463 unsigned kind = -1U;
5464 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5465 if (var->hasAttr<BlocksAttr>())
5466 kind = 0; // __block
5467 else if (!var->hasLocalStorage())
5468 kind = 1; // global
5469 } else if (isa<ObjCIvarDecl>(decl)) {
5470 kind = 3; // ivar
5471 } else if (isa<FieldDecl>(decl)) {
5472 kind = 2; // field
5473 }
5474
5475 if (kind != -1U) {
5476 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var) << kind;
5477 }
5478 } else if (lifetime == Qualifiers::OCL_None) {
5479 // Try to infer lifetime.
5480 if (!type->isObjCLifetimeType())
5481 return false;
5482
5483 lifetime = type->getObjCARCImplicitLifetime();
5484 type = Context.getLifetimeQualifiedType(type, lifetime);
5485 decl->setType(type);
5486 }
5487
5488 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5489 // Thread-local variables cannot have lifetime.
5490 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5491 var->getTLSKind()) {
5492 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5493 << var->getType();
5494 return true;
5495 }
5496 }
5497
5498 return false;
5499}
5500
5502 return (dyn_cast_or_null<ObjCContainerDecl>(SemaRef.CurContext));
5503}
5504
5506 if (!getLangOpts().CPlusPlus)
5507 return;
5508 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
5509 ASTContext &Context = getASTContext();
5512 if (ivars.empty())
5513 return;
5515 for (unsigned i = 0; i < ivars.size(); i++) {
5516 FieldDecl *Field = ivars[i];
5517 if (Field->isInvalidDecl())
5518 continue;
5519
5522 InitializationKind InitKind =
5523 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
5524
5525 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5526 ExprResult MemberInit =
5527 InitSeq.Perform(SemaRef, InitEntity, InitKind, {});
5528 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
5529 // Note, MemberInit could actually come back empty if no initialization
5530 // is required (e.g., because it would call a trivial default constructor)
5531 if (!MemberInit.get() || MemberInit.isInvalid())
5532 continue;
5533
5534 Member = new (Context)
5536 MemberInit.getAs<Expr>(), SourceLocation());
5537 AllToInit.push_back(Member);
5538
5539 // Be sure that the destructor is accessible and is marked as referenced.
5540 if (auto *RD = Context.getBaseElementType(Field->getType())
5541 ->getAsCXXRecordDecl()) {
5542 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(RD)) {
5543 SemaRef.MarkFunctionReferenced(Field->getLocation(), Destructor);
5544 SemaRef.CheckDestructorAccess(
5545 Field->getLocation(), Destructor,
5546 PDiag(diag::err_access_dtor_ivar)
5547 << Context.getBaseElementType(Field->getType()));
5548 }
5549 }
5550 }
5551 ObjCImplementation->setIvarInitializers(Context, AllToInit.data(),
5552 AllToInit.size());
5553 }
5554}
5555
5556/// TranslateIvarVisibility - Translate visibility from a token ID to an
5557/// AST enum value.
5560 switch (ivarVisibility) {
5561 default:
5562 llvm_unreachable("Unknown visitibility kind");
5563 case tok::objc_private:
5564 return ObjCIvarDecl::Private;
5565 case tok::objc_public:
5566 return ObjCIvarDecl::Public;
5567 case tok::objc_protected:
5569 case tok::objc_package:
5570 return ObjCIvarDecl::Package;
5571 }
5572}
5573
5574/// ActOnIvar - Each ivar field of an objective-c class is passed into this
5575/// in order to create an IvarDecl object for it.
5578
5579 const IdentifierInfo *II = D.getIdentifier();
5580 SourceLocation Loc = DeclStart;
5581 if (II)
5582 Loc = D.getIdentifierLoc();
5583
5584 // FIXME: Unnamed fields can be handled in various different ways, for
5585 // example, unnamed unions inject all members into the struct namespace!
5586
5587 TypeSourceInfo *TInfo = SemaRef.GetTypeForDeclarator(D);
5588 QualType T = TInfo->getType();
5589 ASTContext &Context = getASTContext();
5590 if (Context.getLangOpts().PointerAuthObjcInterfaceSel &&
5591 !T.getPointerAuth()) {
5592 if (Context.isObjCSelType(T.getUnqualifiedType())) {
5593 if (auto PAQ = Context.getObjCMemberSelTypePtrAuth())
5594 T = Context.getPointerAuthType(T, PAQ);
5595 }
5596 }
5597
5598 if (BitWidth) {
5599 // 6.7.2.1p3, 6.7.2.1p4
5600 BitWidth =
5601 SemaRef.VerifyBitField(Loc, II, T, /*IsMsStruct*/ false, BitWidth)
5602 .get();
5603 if (!BitWidth)
5604 D.setInvalidType();
5605 } else {
5606 // Not a bitfield.
5607
5608 // validate II.
5609 }
5610 if (T->isReferenceType()) {
5611 Diag(Loc, diag::err_ivar_reference_type);
5612 D.setInvalidType();
5613 }
5614 // C99 6.7.2.1p8: A member of a structure or union may have any type other
5615 // than a variably modified type.
5616 else if (T->isVariablyModifiedType()) {
5617 if (!SemaRef.tryToFixVariablyModifiedVarType(
5618 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
5619 D.setInvalidType();
5620 }
5621
5622 // Get the visibility (access control) for this ivar.
5623 ObjCIvarDecl::AccessControl ac = Visibility != tok::objc_not_keyword
5626 // Must set ivar's DeclContext to its enclosing interface.
5627 ObjCContainerDecl *EnclosingDecl =
5628 cast<ObjCContainerDecl>(SemaRef.CurContext);
5629 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
5630 return nullptr;
5631 ObjCContainerDecl *EnclosingContext;
5632 if (ObjCImplementationDecl *IMPDecl =
5633 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
5635 // Case of ivar declared in an implementation. Context is that of its
5636 // class.
5637 EnclosingContext = IMPDecl->getClassInterface();
5638 assert(EnclosingContext && "Implementation has no class interface!");
5639 } else
5640 EnclosingContext = EnclosingDecl;
5641 } else {
5642 if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
5643 if (getLangOpts().ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
5644 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
5645 return nullptr;
5646 }
5647 }
5648 EnclosingContext = EnclosingDecl;
5649 }
5650
5651 // Construct the decl.
5652 ObjCIvarDecl *NewID =
5653 ObjCIvarDecl::Create(getASTContext(), EnclosingContext, DeclStart, Loc,
5654 II, T, TInfo, ac, BitWidth);
5655
5656 if (T->containsErrors())
5657 NewID->setInvalidDecl();
5658
5659 if (II) {
5660 NamedDecl *PrevDecl =
5661 SemaRef.LookupSingleName(S, II, Loc, Sema::LookupMemberName,
5663 if (PrevDecl && SemaRef.isDeclInScope(PrevDecl, EnclosingContext, S) &&
5664 !isa<TagDecl>(PrevDecl)) {
5665 Diag(Loc, diag::err_duplicate_member) << II;
5666 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5667 NewID->setInvalidDecl();
5668 }
5669 }
5670
5671 // Process attributes attached to the ivar.
5672 SemaRef.ProcessDeclAttributes(S, NewID, D);
5673
5674 if (D.isInvalidType())
5675 NewID->setInvalidDecl();
5676
5677 // In ARC, infer 'retaining' for ivars of retainable type.
5678 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
5679 NewID->setInvalidDecl();
5680
5682 NewID->setModulePrivate();
5683
5684 if (II) {
5685 // FIXME: When interfaces are DeclContexts, we'll need to add
5686 // these to the interface.
5687 S->AddDecl(NewID);
5688 SemaRef.IdResolver.AddDecl(NewID);
5689 }
5690
5691 if (getLangOpts().ObjCRuntime.isNonFragile() && !NewID->isInvalidDecl() &&
5692 isa<ObjCInterfaceDecl>(EnclosingDecl))
5693 Diag(Loc, diag::warn_ivars_in_interface);
5694
5695 return NewID;
5696}
Defines the clang::ASTContext interface.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the classes clang::DelayedDiagnostic and clang::AccessedEntity.
#define DIAG(ENUM, CLASS, DEFAULT_SEVERITY, DESC, GROUP, SFINAE, NOWERROR, SHOWINSYSHEADER, SHOWINSYSMACRO, DEFERRABLE, CATEGORY, STABLE_ID, LEGACY_STABLE_IDS)
static QualType getObjectType(APValue::LValueBase B)
Retrieves the "underlying object type" of the given expression, as used by __builtin_object_size.
FormatToken * Previous
The previous token in the unwrapped line.
llvm::MachO::Record Record
Definition MachO.h:31
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
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)
This file declares semantic analysis for Objective-C.
Defines the SourceManager interface.
__DEVICE__ long long abs(long long __n)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig, ObjCTypeParamDecl *New) const
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType, const Attr *attr=nullptr) const
IdentifierTable & Idents
Definition ASTContext.h:846
const LangOptions & getLangOpts() const
SelectorTable & Selectors
Definition ASTContext.h:847
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:899
void ResetObjCLayout(const ObjCInterfaceDecl *D)
CanQualType getCanonicalTypeDeclType(const TypeDecl *TD) const
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:965
bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT, bool IsParam) const
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
void addObjCSubClass(const ObjCInterfaceDecl *D, const ObjCInterfaceDecl *SubClass)
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:1008
Represents a C++ base or member initializer.
Definition DeclCXX.h:2406
Represents a C++ destructor within a class.
Definition DeclCXX.h:2906
SourceRange getRange() const
Definition DeclSpec.h:82
bool isSet() const
Deprecated.
Definition DeclSpec.h:201
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
bool isFileContext() const
Definition DeclBase.h:2197
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
void addDecl(Decl *D)
Add the declaration D into this context.
Decl::Kind getDeclKind() const
Definition DeclBase.h:2119
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
iterator begin()
Definition DeclGroup.h:95
Captures information about "declaration specifiers".
Definition DeclSpec.h:220
bool isModulePrivateSpecified() const
Definition DeclSpec.h:836
static const TST TST_typename
Definition DeclSpec.h:279
ThreadStorageClassSpecifier TSCS
Definition DeclSpec.h:237
void ClearStorageClassSpecs()
Definition DeclSpec.h:500
SourceLocation getStorageClassSpecLoc() const
Definition DeclSpec.h:495
SCS getStorageClassSpec() const
Definition DeclSpec.h:486
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition DeclSpec.cpp:846
void SetRangeEnd(SourceLocation Loc)
Definition DeclSpec.h:716
void SetRangeStart(SourceLocation Loc)
Definition DeclSpec.h:715
SCS
storage-class-specifier
Definition DeclSpec.h:224
TSCS getThreadStorageClassSpec() const
Definition DeclSpec.h:487
bool isInlineSpecified() const
Definition DeclSpec.h:644
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 getThreadStorageClassSpecLoc() const
Definition DeclSpec.h:496
SourceLocation getInlineSpecLoc() const
Definition DeclSpec.h:647
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition DeclBase.h:443
T * getAttr() const
Definition DeclBase.h:581
void addAttr(Attr *A)
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition DeclBase.cpp:779
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition DeclBase.h:871
void setTopLevelDeclInObjCContainer(bool V=true)
Definition DeclBase.h:646
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition DeclBase.cpp:604
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:596
SourceLocation getLocation() const
Definition DeclBase.h:447
bool isDeprecated(std::string *Message=nullptr) const
Determine whether this declaration is marked 'deprecated'.
Definition DeclBase.h:774
void setImplicit(bool I=true)
Definition DeclBase.h:602
DeclContext * getDeclContext()
Definition DeclBase.h:456
void dropAttr()
Definition DeclBase.h:564
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:385
bool hasAttr() const
Definition DeclBase.h:585
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:810
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1952
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2099
SourceLocation getIdentifierLoc() const
Definition DeclSpec.h:2388
void setInvalidType(bool Val=true)
Definition DeclSpec.h:2765
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition DeclSpec.h:2114
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition DeclSpec.h:2405
bool isInvalidType() const
Definition DeclSpec.h:2766
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2134
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition DeclSpec.h:2106
const IdentifierInfo * getIdentifier() const
Definition DeclSpec.h:2382
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:972
This represents one expression.
Definition Expr.h:113
Represents a member of a struct/union/class.
Definition Decl.h:3295
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3398
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
Definition Decl.cpp:4816
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition Decl.h:3411
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:142
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:131
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:105
One of these records is kept for each identifier that is lexed.
A simple pair of identifier info and location.
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)
Create the initialization entity for a member subobject.
clang::ObjCRuntime ObjCRuntime
Represents the results of name lookup.
Definition Lookup.h:147
@ ClassId_NSObject
Definition NSAPI.h:30
This represents a decl that may have a name.
Definition Decl.h:275
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:296
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:341
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition DeclBase.h:718
static ObjCAtDefsFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, Expr *BW)
ObjCCategoryDecl - Represents a category declaration.
Definition DeclObjC.h:2335
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())
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:2397
ObjCCategoryImplDecl * getImplementation() const
ObjCInterfaceDecl * getClassInterface()
Definition DeclObjC.h:2378
bool IsClassExtension() const
Definition DeclObjC.h:2443
const ObjCProtocolList & getReferencedProtocols() const
Definition DeclObjC.h:2402
void setImplementation(ObjCCategoryImplDecl *ImplD)
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition DeclObjC.h:2551
ObjCCategoryDecl * getCategoryDecl() const
static ObjCCategoryImplDecl * Create(ASTContext &C, DeclContext *DC, const IdentifierInfo *Id, ObjCInterfaceDecl *classInterface, SourceLocation nameLoc, SourceLocation atStartLoc, SourceLocation CategoryNameLoc)
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition DeclObjC.h:2781
static ObjCCompatibleAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, ObjCInterfaceDecl *aliasedClass)
ObjCContainerDecl - Represents a container for method declarations.
Definition DeclObjC.h:954
ObjCMethodDecl * getMethod(Selector Sel, bool isInstance, bool AllowHidden=false) const
Definition DeclObjC.cpp:90
method_range methods() const
Definition DeclObjC.h:1022
instmeth_range instance_methods() const
Definition DeclObjC.h:1039
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:1111
ObjCMethodDecl * getClassMethod(Selector Sel, bool AllowHidden=false) const
Definition DeclObjC.h:1077
prop_range properties() const
Definition DeclObjC.h:973
classmeth_range class_methods() const
Definition DeclObjC.h:1056
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition DeclObjC.h:1072
Captures information about "declaration specifiers" specific to Objective-C.
Definition DeclSpec.h:911
ObjCDeclQualifier
ObjCDeclQualifier - Qualifier used on types in method declarations.
Definition DeclSpec.h:919
ObjCDeclQualifier getObjCDeclQualifier() const
Definition DeclSpec.h:935
propimpl_range property_impls() const
Definition DeclObjC.h:2519
const ObjCInterfaceDecl * getClassInterface() const
Definition DeclObjC.h:2492
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition DeclObjC.h:2603
static ObjCImplementationDecl * Create(ASTContext &C, DeclContext *DC, ObjCInterfaceDecl *classInterface, ObjCInterfaceDecl *superDecl, SourceLocation nameLoc, SourceLocation atStartLoc, SourceLocation superLoc=SourceLocation(), SourceLocation IvarLBraceLoc=SourceLocation(), SourceLocation IvarRBraceLoc=SourceLocation())
void setIvarInitializers(ASTContext &C, CXXCtorInitializer **initializers, unsigned numInitializers)
const ObjCInterfaceDecl * getSuperClass() const
Definition DeclObjC.h:2741
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
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:1467
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, const IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
unsigned ivar_size() const
Definition DeclObjC.h:1475
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:1491
bool hasDefinition() const
Determine whether this class has been defined.
Definition DeclObjC.h:1534
ivar_range ivars() const
Definition DeclObjC.h:1457
all_protocol_range all_referenced_protocols() const
Definition DeclObjC.h:1423
visible_extensions_range visible_extensions() const
Definition DeclObjC.h:1729
bool isImplicitInterfaceDecl() const
isImplicitInterfaceDecl - check that this is an implicitly declared ObjCInterfaceDecl node.
Definition DeclObjC.h:1899
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
ObjCCategoryDecl * FindCategoryDeclaration(const IdentifierInfo *CategoryId) const
FindCategoryDeclaration - Finds category declaration in the list of categories for this class and ret...
ivar_iterator ivar_begin() const
Definition DeclObjC.h:1459
llvm::iterator_range< specific_decl_iterator< ObjCIvarDecl > > ivar_range
Definition DeclObjC.h:1455
bool ivar_empty() const
Definition DeclObjC.h:1479
void setImplementation(ObjCImplementationDecl *ImplD)
known_categories_range known_categories() const
Definition DeclObjC.h:1693
void setSuperClass(TypeSourceInfo *superClass)
Definition DeclObjC.h:1594
const ObjCProtocolList & getReferencedProtocols() const
Definition DeclObjC.h:1339
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
void setEndOfDefinitionLoc(SourceLocation LE)
Definition DeclObjC.h:1891
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:1659
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition DeclObjC.h:1921
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:1548
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:1816
specific_decl_iterator< ObjCIvarDecl > ivar_iterator
Definition DeclObjC.h:1454
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8003
ObjCIvarDecl - Represents an ObjC instance variable.
Definition DeclObjC.h:1958
ObjCIvarDecl * getNextIvar()
Definition DeclObjC.h:1993
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)
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition ExprObjC.h:581
ObjCIvarDecl * getDecl()
Definition ExprObjC.h:611
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
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition ExprObjC.h:1300
@ Instance
The receiver is an object instance.
Definition ExprObjC.h:980
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition ExprObjC.h:1261
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:907
ImplicitParamDecl * getSelfDecl() const
Definition DeclObjC.h:421
void setObjCDeclQualifier(ObjCDeclQualifier QV)
Definition DeclObjC.h:253
void setDefined(bool isDefined)
Definition DeclObjC.h:456
ObjCDeclQualifier getObjCDeclQualifier() const
Definition DeclObjC.h:246
ArrayRef< ParmVarDecl * > parameters() const
Definition DeclObjC.h:376
unsigned param_size() const
Definition DeclObjC.h:350
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:361
param_const_iterator param_begin() const
Definition DeclObjC.h:357
bool isVariadic() const
Definition DeclObjC.h:434
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
void setMethodParams(ASTContext &C, ArrayRef< ParmVarDecl * > Params, ArrayRef< SourceLocation > SelLocs={})
Sets the method's parameters and selector source locations.
Definition DeclObjC.cpp:962
void setRelatedResultType(bool RRT=true)
Note whether this method has a related result type.
Definition DeclObjC.h:264
bool isSynthesizedAccessorStub() const
Definition DeclObjC.h:447
SourceLocation getSelectorLoc(unsigned Index) const
Definition DeclObjC.h:297
SourceRange getReturnTypeSourceRange() const
void setOverriding(bool IsOver)
Definition DeclObjC.h:466
const ParmVarDecl *const * param_const_iterator
Definition DeclObjC.h:352
bool hasRelatedResultType() const
Determine whether this method has a result type that is related to the message receiver's type.
Definition DeclObjC.h:259
SourceLocation getBeginLoc() const LLVM_READONLY
Definition DeclObjC.h:285
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition DeclObjC.cpp:889
Selector getSelector() const
Definition DeclObjC.h:330
ImplicitParamDecl * getCmdDecl() const
Definition DeclObjC.h:423
bool isInstanceMethod() const
Definition DeclObjC.h:429
void setReturnType(QualType T)
Definition DeclObjC.h:333
ObjCMethodFamily getMethodFamily() const
Determines the family of this method.
void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID)
createImplicitParams - Used to lazily create the self and cmd implicit parameters.
QualType getReturnType() const
Definition DeclObjC.h:332
ParmVarDecl *const * param_iterator
Definition DeclObjC.h:353
ObjCImplementationControl getImplementationControl() const
Definition DeclObjC.h:503
bool isClassMethod() const
Definition DeclObjC.h:437
ObjCInterfaceDecl * getClassInterface()
Wraps an ObjCPointerType with source location information.
Definition TypeLoc.h:1617
void setStarLoc(SourceLocation Loc)
Definition TypeLoc.h:1623
Represents a pointer to an Objective C object.
Definition TypeBase.h:8059
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition TypeBase.h:8134
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8117
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1915
Represents one property declaration in an Objective-C interface.
Definition DeclObjC.h:734
ObjCIvarDecl * getPropertyIvarDecl() const
Definition DeclObjC.h:930
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition DeclObjC.h:2811
Represents an Objective-C protocol declaration.
Definition DeclObjC.h:2090
void startDuplicateDefinitionForComparison()
Starts the definition without sharing it with other redeclarations.
bool hasDefinition() const
Determine whether this protocol has a definition.
Definition DeclObjC.h:2244
bool isThisDeclarationADefinition() const
Determine whether this particular declaration is also the definition.
Definition DeclObjC.h:2267
static ObjCProtocolDecl * Create(ASTContext &C, DeclContext *DC, IdentifierInfo *Id, SourceLocation nameLoc, SourceLocation atStartLoc, ObjCProtocolDecl *PrevDecl)
const ObjCProtocolList & getReferencedProtocols() const
Definition DeclObjC.h:2159
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:2215
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition DeclObjC.h:2256
void startDefinition()
Starts the definition of this Objective-C protocol.
protocol_range protocols() const
Definition DeclObjC.h:2167
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?
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:581
static ObjCTypeParamDecl * Create(ASTContext &ctx, DeclContext *dc, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, SourceLocation nameLoc, IdentifierInfo *name, SourceLocation colonLoc, TypeSourceInfo *boundInfo)
bool hasExplicitBound() const
Whether this type parameter has an explicitly-written type bound, e.g., "T : NSView".
Definition DeclObjC.h:643
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition DeclObjC.h:626
void setVariance(ObjCTypeParamVariance variance)
Set the variance of this type parameter.
Definition DeclObjC.h:631
SourceLocation getVarianceLoc() const
Retrieve the location of the variance keyword.
Definition DeclObjC.h:636
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition DeclObjC.h:665
SourceRange getSourceRange() const
Definition DeclObjC.h:715
unsigned size() const
Determine the number of type parameters in this list.
Definition DeclObjC.h:692
ObjCTypeParamDecl * back() const
Definition DeclObjC.h:708
static ObjCTypeParamList * create(ASTContext &ctx, SourceLocation lAngleLoc, ArrayRef< ObjCTypeParamDecl * > typeParams, SourceLocation rAngleLoc)
Create a new Objective-C type parameter list.
SourceLocation getLAngleLoc() const
Definition DeclObjC.h:713
Represents a parameter to a function.
Definition Decl.h:1820
ObjCDeclQualifier getObjCDeclQualifier() const
Definition Decl.h:1884
static const ParsedAttributesView & none()
Definition ParsedAttr.h:817
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3396
A (possibly-)qualified type.
Definition TypeBase.h:938
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8507
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8458
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getCanonicalType() const
Definition TypeBase.h:8470
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8512
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1348
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void removeCVRQualifiers(unsigned mask)
Definition TypeBase.h:496
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
bool empty() const
Definition TypeBase.h:648
std::string getAsString() const
Represents a struct/union/class.
Definition Decl.h:4460
bool hasFlexibleArrayMember() const
Definition Decl.h:4493
field_iterator field_end() const
Definition Decl.h:4666
specific_decl_iterator< FieldDecl > field_iterator
Definition Decl.h:4660
field_iterator field_begin() const
Definition Decl.cpp:5339
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3658
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
void AddDecl(Decl *D)
Definition Scope.h:348
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition Scope.h:384
void RemoveDecl(Decl *D)
Definition Scope.h:356
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred within this scope.
Definition Scope.h:406
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
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
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
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)
llvm::SmallPtrSet< Selector, 8 > SelectorSet
Definition SemaObjC.h:222
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()
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.
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)
OpaquePtr< DeclGroupRef > DeclGroupPtrTy
Definition SemaObjC.h:303
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)
A RAII object to temporarily push a declaration context.
Definition Sema.h:3532
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:863
LookupNameKind
Describes the kind of name lookup to perform.
Definition Sema.h:9366
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9370
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition Sema.h:9407
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9378
@ LookupAnyName
Look up any declaration with any name.
Definition Sema.h:9415
ASTContext & Context
Definition Sema.h:1304
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:228
SemaObjC & ObjC()
Definition Sema.h:1516
ASTContext & getASTContext() const
Definition Sema.h:935
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:928
IntrusiveRefCntPtr< ExternalSemaSource > ExternalSource
Source of additional semantic information.
Definition Sema.h:1582
DiagnosticsEngine & Diags
Definition Sema.h:1306
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
bool isInvalid() const
SourceLocation getEnd() const
SourceLocation getBegin() const
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
bool isUnion() const
Definition Decl.h:4063
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled.
Represents a declaration of a type.
Definition Decl.h:3648
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:3682
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:454
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:8389
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8400
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9027
bool isIncompleteArrayType() const
Definition TypeBase.h:8762
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9071
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9321
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition Type.cpp:1976
bool isScalarType() const
Definition TypeBase.h:9133
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8855
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition Type.cpp:2486
bool isObjCIdType() const
Definition TypeBase.h:8867
bool isObjCObjectType() const
Definition TypeBase.h:8838
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition Type.cpp:5459
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2559
bool isObjCObjectPointerType() const
Definition TypeBase.h:8834
bool isObjCQualifiedClassType() const
Definition TypeBase.h:8861
bool isObjCClassType() const
Definition TypeBase.h:8873
@ STK_ObjCObjectPointer
Definition TypeBase.h:2835
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9254
bool isRecordType() const
Definition TypeBase.h:8782
bool isObjCIndependentClassType() const
Definition Type.cpp:5434
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5159
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3697
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:3747
QualType getUnderlyingType() const
Definition Decl.h:3752
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:713
void setType(QualType newType)
Definition Decl.h:725
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2133
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Defines the clang::TargetInfo interface.
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:49
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:33
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
ActionResult< Decl * > DeclResult
Definition Ownership.h:255
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ SC_None
Definition Specifiers.h:251
ObjCMethodFamily
A family of Objective-C methods.
@ OMF_performSelector
@ OMF_None
No particular method family.
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
@ Property
The type of a property.
Definition TypeBase.h:912
ActionResult< ParsedType > TypeResult
Definition Ownership.h:251
const FunctionProtoType * T
Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
@ Class
The "class" keyword.
Definition TypeBase.h:6019
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
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
ObjCTypeParamVariance
Describes the variance of a given generic parameter.
Definition DeclObjC.h:556
@ Invariant
The parameter is invariant: must match exactly.
Definition DeclObjC.h:558
@ Contravariant
The parameter is contravariant, e.g., X<T> is a subtype of X when the type parameter is covariant and...
Definition DeclObjC.h:566
@ Covariant
The parameter is covariant, e.g., X<T> is a subtype of X when the type parameter is covariant and T i...
Definition DeclObjC.h:562
U cast(CodeGen::Address addr)
Definition Address.h:327
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition Ownership.h:230
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5988
@ None
No keyword precedes the qualified type name.
Definition TypeBase.h:6004
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5994
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
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:1377
static DeclaratorChunk getPointer(unsigned TypeQuals, SourceLocation Loc, SourceLocation ConstQualLoc, SourceLocation VolatileQualLoc, SourceLocation RestrictQualLoc, SourceLocation AtomicQualLoc, SourceLocation UnalignedQualLoc, SourceLocation OverflowBehaviorLoc={}, bool OverflowBehaviorIsWrap=false)
Return a DeclaratorChunk for a pointer.
Definition DeclSpec.h:1711
a linked list of methods with the same selector name but different signatures.
ObjCMethodDecl * getMethod() const
unsigned getBits() const
void setMethod(ObjCMethodDecl *M)
void setNext(ObjCMethodList *L)
void setHasMoreThanOneDecl(bool B)
void setBits(unsigned B)
bool hasMoreThanOneDecl() const
ObjCMethodList * getNext() const
ParsedAttributesView ArgAttrs
ArgAttrs - Attribute list for this argument.
Definition SemaObjC.h:351
IdentifierInfo * Name
Definition SemaObjC.h:343
bool CheckSameAsPrevious
Definition Sema.h:360
NamedDecl * Previous
Definition Sema.h:361
NamedDecl * New
Definition Sema.h:362