Coverage Report

Created: 2020-02-25 14:32

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