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