Coverage Report

Created: 2020-09-19 12:23

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