Coverage Report

Created: 2022-01-18 06:27

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