Coverage Report

Created: 2021-09-21 08:58

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaExprObjC.cpp
<
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
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 expressions.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/DeclObjC.h"
15
#include "clang/AST/ExprObjC.h"
16
#include "clang/AST/StmtVisitor.h"
17
#include "clang/AST/TypeLoc.h"
18
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
19
#include "clang/Basic/Builtins.h"
20
#include "clang/Edit/Commit.h"
21
#include "clang/Edit/Rewriters.h"
22
#include "clang/Lex/Preprocessor.h"
23
#include "clang/Sema/Initialization.h"
24
#include "clang/Sema/Lookup.h"
25
#include "clang/Sema/Scope.h"
26
#include "clang/Sema/ScopeInfo.h"
27
#include "clang/Sema/SemaInternal.h"
28
#include "llvm/ADT/SmallString.h"
29
#include "llvm/Support/ConvertUTF.h"
30
31
using namespace clang;
32
using namespace sema;
33
using llvm::makeArrayRef;
34
35
ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
36
6.13k
                                        ArrayRef<Expr *> Strings) {
37
  // Most ObjC strings are formed out of a single piece.  However, we *can*
38
  // have strings formed out of multiple @ strings with multiple pptokens in
39
  // each one, e.g. @"foo" "bar" @"baz" "qux"   which need to be turned into one
40
  // StringLiteral for ObjCStringLiteral to hold onto.
41
6.13k
  StringLiteral *S = cast<StringLiteral>(Strings[0]);
42
43
  // If we have a multi-part string, merge it all together.
44
6.13k
  if (Strings.size() != 1) {
45
    // Concatenate objc strings.
46
222
    SmallString<128> StrBuf;
47
222
    SmallVector<SourceLocation, 8> StrLocs;
48
49
2.24k
    for (Expr *E : Strings) {
50
2.24k
      S = cast<StringLiteral>(E);
51
52
      // ObjC strings can't be wide or UTF.
53
2.24k
      if (!S->isAscii()) {
54
0
        Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
55
0
            << S->getSourceRange();
56
0
        return true;
57
0
      }
58
59
      // Append the string.
60
2.24k
      StrBuf += S->getString();
61
62
      // Get the locations of the string tokens.
63
2.24k
      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
64
2.24k
    }
65
66
    // Create the aggregate string with the appropriate content and location
67
    // information.
68
222
    const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
69
222
    assert(CAT && "String literal not of constant array type!");
70
0
    QualType StrTy = Context.getConstantArrayType(
71
222
        CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), nullptr,
72
222
        CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
73
222
    S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
74
222
                              /*Pascal=*/false, StrTy, &StrLocs[0],
75
222
                              StrLocs.size());
76
222
  }
77
78
6.13k
  return BuildObjCStringLiteral(AtLocs[0], S);
79
6.13k
}
80
81
6.16k
ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
82
  // Verify that this composite string is acceptable for ObjC strings.
83
6.16k
  if (CheckObjCString(S))
84
0
    return true;
85
86
  // Initialize the constant string interface lazily. This assumes
87
  // the NSString interface is seen in this translation unit. Note: We
88
  // don't use NSConstantString, since the runtime team considers this
89
  // interface private (even though it appears in the header files).
90
6.16k
  QualType Ty = Context.getObjCConstantStringInterface();
91
6.16k
  if (!Ty.isNull()) {
92
5.46k
    Ty = Context.getObjCObjectPointerType(Ty);
93
5.46k
  } else 
if (699
getLangOpts().NoConstantCFStrings699
) {
94
5
    IdentifierInfo *NSIdent=nullptr;
95
5
    std::string StringClass(getLangOpts().ObjCConstantStringClass);
96
97
5
    if (StringClass.empty())
98
2
      NSIdent = &Context.Idents.get("NSConstantString");
99
3
    else
100
3
      NSIdent = &Context.Idents.get(StringClass);
101
102
5
    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
103
5
                                     LookupOrdinaryName);
104
5
    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
105
5
      Context.setObjCConstantStringInterface(StrIF);
106
5
      Ty = Context.getObjCConstantStringInterface();
107
5
      Ty = Context.getObjCObjectPointerType(Ty);
108
5
    } else {
109
      // If there is no NSConstantString interface defined then treat this
110
      // as error and recover from it.
111
0
      Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
112
0
          << NSIdent << S->getSourceRange();
113
0
      Ty = Context.getObjCIdType();
114
0
    }
115
694
  } else {
116
694
    IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
117
694
    NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
118
694
                                     LookupOrdinaryName);
119
694
    if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
120
481
      Context.setObjCConstantStringInterface(StrIF);
121
481
      Ty = Context.getObjCConstantStringInterface();
122
481
      Ty = Context.getObjCObjectPointerType(Ty);
123
481
    } else {
124
      // If there is no NSString interface defined, implicitly declare
125
      // a @class NSString; and use that instead. This is to make sure
126
      // type of an NSString literal is represented correctly, instead of
127
      // being an 'id' type.
128
213
      Ty = Context.getObjCNSStringType();
129
213
      if (Ty.isNull()) {
130
87
        ObjCInterfaceDecl *NSStringIDecl =
131
87
          ObjCInterfaceDecl::Create (Context,
132
87
                                     Context.getTranslationUnitDecl(),
133
87
                                     SourceLocation(), NSIdent,
134
87
                                     nullptr, nullptr, SourceLocation());
135
87
        Ty = Context.getObjCInterfaceType(NSStringIDecl);
136
87
        Context.setObjCNSStringType(Ty);
137
87
      }
138
213
      Ty = Context.getObjCObjectPointerType(Ty);
139
213
    }
140
694
  }
141
142
6.16k
  return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
143
6.16k
}
144
145
/// Emits an error if the given method does not exist, or if the return
146
/// type is not an Objective-C object.
147
static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
148
                                 const ObjCInterfaceDecl *Class,
149
872
                                 Selector Sel, const ObjCMethodDecl *Method) {
150
872
  if (!Method) {
151
    // FIXME: Is there a better way to avoid quotes than using getName()?
152
3
    S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
153
3
    return false;
154
3
  }
155
156
  // Make sure the return type is reasonable.
157
869
  QualType ReturnType = Method->getReturnType();
158
869
  if (!ReturnType->isObjCObjectPointerType()) {
159
4
    S.Diag(Loc, diag::err_objc_literal_method_sig)
160
4
      << Sel;
161
4
    S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
162
4
      << ReturnType;
163
4
    return false;
164
4
  }
165
166
865
  return true;
167
869
}
168
169
/// Maps ObjCLiteralKind to NSClassIdKindKind
170
static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
171
598
                                            Sema::ObjCLiteralKind LiteralKind) {
172
598
  switch (LiteralKind) {
173
173
    case Sema::LK_Array:
174
173
      return NSAPI::ClassId_NSArray;
175
186
    case Sema::LK_Dictionary:
176
186
      return NSAPI::ClassId_NSDictionary;
177
180
    case Sema::LK_Numeric:
178
180
      return NSAPI::ClassId_NSNumber;
179
44
    case Sema::LK_String:
180
44
      return NSAPI::ClassId_NSString;
181
15
    case Sema::LK_Boxed:
182
15
      return NSAPI::ClassId_NSValue;
183
184
    // there is no corresponding matching
185
    // between LK_None/LK_Block and NSClassIdKindKind
186
0
    case Sema::LK_Block:
187
0
    case Sema::LK_None:
188
0
      break;
189
598
  }
190
0
  llvm_unreachable("LiteralKind can't be converted into a ClassKind");
191
0
}
192
193
/// Validates ObjCInterfaceDecl availability.
194
/// ObjCInterfaceDecl, used to create ObjC literals, should be defined
195
/// if clang not in a debugger mode.
196
static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
197
                                            SourceLocation Loc,
198
574
                                            Sema::ObjCLiteralKind LiteralKind) {
199
574
  if (!Decl) {
200
24
    NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
201
24
    IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
202
24
    S.Diag(Loc, diag::err_undeclared_objc_literal_class)
203
24
      << II->getName() << LiteralKind;
204
24
    return false;
205
550
  } else if (!Decl->hasDefinition() && 
!S.getLangOpts().DebuggerObjCLiteral13
) {
206
7
    S.Diag(Loc, diag::err_undeclared_objc_literal_class)
207
7
      << Decl->getName() << LiteralKind;
208
7
    S.Diag(Decl->getLocation(), diag::note_forward_class);
209
7
    return false;
210
7
  }
211
212
543
  return true;
213
574
}
214
215
/// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
216
/// Used to create ObjC literals, such as NSDictionary (@{}),
217
/// NSArray (@[]) and Boxed Expressions (@())
218
static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
219
                                            SourceLocation Loc,
220
574
                                            Sema::ObjCLiteralKind LiteralKind) {
221
574
  NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
222
574
  IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
223
574
  NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
224
574
                                     Sema::LookupOrdinaryName);
225
574
  ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
226
574
  if (!ID && 
S.getLangOpts().DebuggerObjCLiteral28
) {
227
4
    ASTContext &Context = S.Context;
228
4
    TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
229
4
    ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
230
4
                                    nullptr, nullptr, SourceLocation());
231
4
  }
232
233
574
  if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
234
31
    ID = nullptr;
235
31
  }
236
237
574
  return ID;
238
574
}
239
240
/// Retrieve the NSNumber factory method that should be used to create
241
/// an Objective-C literal for the given type.
242
static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
243
                                                QualType NumberType,
244
                                                bool isLiteral = false,
245
1.19k
                                                SourceRange R = SourceRange()) {
246
1.19k
  Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
247
1.19k
      S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
248
249
1.19k
  if (!Kind) {
250
2
    if (isLiteral) {
251
1
      S.Diag(Loc, diag::err_invalid_nsnumber_type)
252
1
        << NumberType << R;
253
1
    }
254
2
    return nullptr;
255
2
  }
256
257
  // If we already looked up this method, we're done.
258
1.19k
  if (S.NSNumberLiteralMethods[*Kind])
259
680
    return S.NSNumberLiteralMethods[*Kind];
260
261
510
  Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
262
510
                                                        /*Instance=*/false);
263
264
510
  ASTContext &CX = S.Context;
265
266
  // Look up the NSNumber class, if we haven't done so already. It's cached
267
  // in the Sema instance.
268
510
  if (!S.NSNumberDecl) {
269
178
    S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
270
178
                                                       Sema::LK_Numeric);
271
178
    if (!S.NSNumberDecl) {
272
4
      return nullptr;
273
4
    }
274
178
  }
275
276
506
  if (S.NSNumberPointer.isNull()) {
277
    // generate the pointer to NSNumber type.
278
174
    QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
279
174
    S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
280
174
  }
281
282
  // Look for the appropriate method within NSNumber.
283
506
  ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
284
506
  if (!Method && 
S.getLangOpts().DebuggerObjCLiteral12
) {
285
    // create a stub definition this NSNumber factory method.
286
10
    TypeSourceInfo *ReturnTInfo = nullptr;
287
10
    Method =
288
10
        ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
289
10
                               S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
290
10
                               /*isInstance=*/false, /*isVariadic=*/false,
291
10
                               /*isPropertyAccessor=*/false,
292
10
                               /*isSynthesizedAccessorStub=*/false,
293
10
                               /*isImplicitlyDeclared=*/true,
294
10
                               /*isDefined=*/false, ObjCMethodDecl::Required,
295
10
                               /*HasRelatedResultType=*/false);
296
10
    ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
297
10
                                             SourceLocation(), SourceLocation(),
298
10
                                             &CX.Idents.get("value"),
299
10
                                             NumberType, /*TInfo=*/nullptr,
300
10
                                             SC_None, nullptr);
301
10
    Method->setMethodParams(S.Context, value, None);
302
10
  }
303
304
506
  if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
305
4
    return nullptr;
306
307
  // Note: if the parameter type is out-of-line, we'll catch it later in the
308
  // implicit conversion.
309
310
502
  S.NSNumberLiteralMethods[*Kind] = Method;
311
502
  return Method;
312
506
}
313
314
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
315
/// numeric literal expression. Type of the expression will be "NSNumber *".
316
1.08k
ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
317
  // Determine the type of the literal.
318
1.08k
  QualType NumberType = Number->getType();
319
1.08k
  if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
320
    // In C, character literals have type 'int'. That's not the type we want
321
    // to use to determine the Objective-c literal kind.
322
52
    switch (Char->getKind()) {
323
52
    case CharacterLiteral::Ascii:
324
52
    case CharacterLiteral::UTF8:
325
52
      NumberType = Context.CharTy;
326
52
      break;
327
328
0
    case CharacterLiteral::Wide:
329
0
      NumberType = Context.getWideCharType();
330
0
      break;
331
332
0
    case CharacterLiteral::UTF16:
333
0
      NumberType = Context.Char16Ty;
334
0
      break;
335
336
0
    case CharacterLiteral::UTF32:
337
0
      NumberType = Context.Char32Ty;
338
0
      break;
339
52
    }
340
52
  }
341
342
  // Look for the appropriate method within NSNumber.
343
  // Construct the literal.
344
1.08k
  SourceRange NR(Number->getSourceRange());
345
1.08k
  ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
346
1.08k
                                                    true, NR);
347
1.08k
  if (!Method)
348
7
    return ExprError();
349
350
  // Convert the number to the type that the parameter expects.
351
1.07k
  ParmVarDecl *ParamDecl = Method->parameters()[0];
352
1.07k
  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
353
1.07k
                                                                    ParamDecl);
354
1.07k
  ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
355
1.07k
                                                         SourceLocation(),
356
1.07k
                                                         Number);
357
1.07k
  if (ConvertedNumber.isInvalid())
358
0
    return ExprError();
359
1.07k
  Number = ConvertedNumber.get();
360
361
  // Use the effective source range of the literal, including the leading '@'.
362
1.07k
  return MaybeBindToTemporary(
363
1.07k
           new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
364
1.07k
                                       SourceRange(AtLoc, NR.getEnd())));
365
1.07k
}
366
367
ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
368
                                      SourceLocation ValueLoc,
369
111
                                      bool Value) {
370
111
  ExprResult Inner;
371
111
  if (getLangOpts().CPlusPlus) {
372
20
    Inner = ActOnCXXBoolLiteral(ValueLoc, Value? 
tok::kw_true13
:
tok::kw_false7
);
373
91
  } else {
374
    // C doesn't actually have a way to represent literal values of type
375
    // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
376
91
    Inner = ActOnIntegerConstant(ValueLoc, Value? 
157
:
034
);
377
91
    Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
378
91
                              CK_IntegralToBoolean);
379
91
  }
380
381
111
  return BuildObjCNumericLiteral(AtLoc, Inner.get());
382
111
}
383
384
/// Check that the given expression is a valid element of an Objective-C
385
/// collection literal.
386
static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
387
                                                    QualType T,
388
1.13k
                                                    bool ArrayLiteral = false) {
389
  // If the expression is type-dependent, there's nothing for us to do.
390
1.13k
  if (Element->isTypeDependent())
391
16
    return Element;
392
393
1.12k
  ExprResult Result = S.CheckPlaceholderExpr(Element);
394
1.12k
  if (Result.isInvalid())
395
0
    return ExprError();
396
1.12k
  Element = Result.get();
397
398
  // In C++, check for an implicit conversion to an Objective-C object pointer
399
  // type.
400
1.12k
  if (S.getLangOpts().CPlusPlus && 
Element->getType()->isRecordType()259
) {
401
21
    InitializedEntity Entity
402
21
      = InitializedEntity::InitializeParameter(S.Context, T,
403
21
                                               /*Consumed=*/false);
404
21
    InitializationKind Kind = InitializationKind::CreateCopy(
405
21
        Element->getBeginLoc(), SourceLocation());
406
21
    InitializationSequence Seq(S, Entity, Kind, Element);
407
21
    if (!Seq.Failed())
408
19
      return Seq.Perform(S, Entity, Kind, Element);
409
21
  }
410
411
1.10k
  Expr *OrigElement = Element;
412
413
  // Perform lvalue-to-rvalue conversion.
414
1.10k
  Result = S.DefaultLvalueConversion(Element);
415
1.10k
  if (Result.isInvalid())
416
0
    return ExprError();
417
1.10k
  Element = Result.get();
418
419
  // Make sure that we have an Objective-C pointer type or block.
420
1.10k
  if (!Element->getType()->isObjCObjectPointerType() &&
421
1.10k
      
!Element->getType()->isBlockPointerType()21
) {
422
20
    bool Recovered = false;
423
424
    // If this is potentially an Objective-C numeric literal, add the '@'.
425
20
    if (isa<IntegerLiteral>(OrigElement) ||
426
20
        
isa<CharacterLiteral>(OrigElement)18
||
427
20
        
isa<FloatingLiteral>(OrigElement)16
||
428
20
        
isa<ObjCBoolLiteralExpr>(OrigElement)16
||
429
20
        
isa<CXXBoolLiteralExpr>(OrigElement)16
) {
430
4
      if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
431
4
        int Which = isa<CharacterLiteral>(OrigElement) ? 
12
432
4
                  : 
(2
isa<CXXBoolLiteralExpr>(OrigElement)2
||
433
2
                     isa<ObjCBoolLiteralExpr>(OrigElement)) ? 
20
434
2
                  : 3;
435
436
4
        S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
437
4
            << Which << OrigElement->getSourceRange()
438
4
            << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
439
440
4
        Result =
441
4
            S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
442
4
        if (Result.isInvalid())
443
0
          return ExprError();
444
445
4
        Element = Result.get();
446
4
        Recovered = true;
447
4
      }
448
4
    }
449
    // If this is potentially an Objective-C string literal, add the '@'.
450
16
    else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
451
4
      if (String->isAscii()) {
452
4
        S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
453
4
            << 0 << OrigElement->getSourceRange()
454
4
            << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
455
456
4
        Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
457
4
        if (Result.isInvalid())
458
0
          return ExprError();
459
460
4
        Element = Result.get();
461
4
        Recovered = true;
462
4
      }
463
4
    }
464
465
20
    if (!Recovered) {
466
12
      S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
467
12
          << Element->getType();
468
12
      return ExprError();
469
12
    }
470
20
  }
471
1.08k
  if (ArrayLiteral)
472
454
    if (ObjCStringLiteral *getString =
473
454
          dyn_cast<ObjCStringLiteral>(OrigElement)) {
474
270
      if (StringLiteral *SL = getString->getString()) {
475
270
        unsigned numConcat = SL->getNumConcatenated();
476
270
        if (numConcat > 1) {
477
          // Only warn if the concatenated string doesn't come from a macro.
478
6
          bool hasMacro = false;
479
14
          for (unsigned i = 0; i < numConcat ; 
++i8
)
480
10
            if (SL->getStrTokenLoc(i).isMacroID()) {
481
2
              hasMacro = true;
482
2
              break;
483
2
            }
484
6
          if (!hasMacro)
485
4
            S.Diag(Element->getBeginLoc(),
486
4
                   diag::warn_concatenated_nsarray_literal)
487
4
                << Element->getType();
488
6
        }
489
270
      }
490
270
    }
491
492
  // Make sure that the element has the type that the container factory
493
  // function expects.
494
1.08k
  return S.PerformCopyInitialization(
495
1.08k
      InitializedEntity::InitializeParameter(S.Context, T,
496
1.08k
                                             /*Consumed=*/false),
497
1.08k
      Element->getBeginLoc(), Element);
498
1.10k
}
499
500
272
ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
501
272
  if (ValueExpr->isTypeDependent()) {
502
16
    ObjCBoxedExpr *BoxedExpr =
503
16
      new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
504
16
    return BoxedExpr;
505
16
  }
506
256
  ObjCMethodDecl *BoxingMethod = nullptr;
507
256
  QualType BoxedType;
508
  // Convert the expression to an RValue, so we can check for pointer types...
509
256
  ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
510
256
  if (RValue.isInvalid()) {
511
0
    return ExprError();
512
0
  }
513
256
  SourceLocation Loc = SR.getBegin();
514
256
  ValueExpr = RValue.get();
515
256
  QualType ValueType(ValueExpr->getType());
516
256
  if (const PointerType *PT = ValueType->getAs<PointerType>()) {
517
80
    QualType PointeeType = PT->getPointeeType();
518
80
    if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
519
520
71
      if (!NSStringDecl) {
521
44
        NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
522
44
                                                         Sema::LK_String);
523
44
        if (!NSStringDecl) {
524
0
          return ExprError();
525
0
        }
526
44
        QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
527
44
        NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
528
44
      }
529
530
      // The boxed expression can be emitted as a compile time constant if it is
531
      // a string literal whose character encoding is compatible with UTF-8.
532
71
      if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
533
61
        if (CE->getCastKind() == CK_ArrayToPointerDecay)
534
19
          if (auto *SL =
535
19
                  dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
536
18
            assert((SL->isAscii() || SL->isUTF8()) &&
537
18
                   "unexpected character encoding");
538
0
            StringRef Str = SL->getString();
539
18
            const llvm::UTF8 *StrBegin = Str.bytes_begin();
540
18
            const llvm::UTF8 *StrEnd = Str.bytes_end();
541
            // Check that this is a valid UTF-8 string.
542
18
            if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
543
14
              BoxedType = Context.getAttributedType(
544
14
                  AttributedType::getNullabilityAttrKind(
545
14
                      NullabilityKind::NonNull),
546
14
                  NSStringPointer, NSStringPointer);
547
14
              return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
548
14
            }
549
550
4
            Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
551
4
                << NSStringPointer << SL->getSourceRange();
552
4
          }
553
554
57
      if (!StringWithUTF8StringMethod) {
555
39
        IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
556
39
        Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
557
558
        // Look for the appropriate method within NSString.
559
39
        BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
560
39
        if (!BoxingMethod && 
getLangOpts().DebuggerObjCLiteral1
) {
561
          // Debugger needs to work even if NSString hasn't been defined.
562
0
          TypeSourceInfo *ReturnTInfo = nullptr;
563
0
          ObjCMethodDecl *M = ObjCMethodDecl::Create(
564
0
              Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
565
0
              NSStringPointer, ReturnTInfo, NSStringDecl,
566
0
              /*isInstance=*/false, /*isVariadic=*/false,
567
0
              /*isPropertyAccessor=*/false,
568
0
              /*isSynthesizedAccessorStub=*/false,
569
0
              /*isImplicitlyDeclared=*/true,
570
0
              /*isDefined=*/false, ObjCMethodDecl::Required,
571
0
              /*HasRelatedResultType=*/false);
572
0
          QualType ConstCharType = Context.CharTy.withConst();
573
0
          ParmVarDecl *value =
574
0
            ParmVarDecl::Create(Context, M,
575
0
                                SourceLocation(), SourceLocation(),
576
0
                                &Context.Idents.get("value"),
577
0
                                Context.getPointerType(ConstCharType),
578
0
                                /*TInfo=*/nullptr,
579
0
                                SC_None, nullptr);
580
0
          M->setMethodParams(Context, value, None);
581
0
          BoxingMethod = M;
582
0
        }
583
584
39
        if (!validateBoxingMethod(*this, Loc, NSStringDecl,
585
39
                                  stringWithUTF8String, BoxingMethod))
586
3
           return ExprError();
587
588
36
        StringWithUTF8StringMethod = BoxingMethod;
589
36
      }
590
591
54
      BoxingMethod = StringWithUTF8StringMethod;
592
54
      BoxedType = NSStringPointer;
593
      // Transfer the nullability from method's return type.
594
54
      Optional<NullabilityKind> Nullability =
595
54
          BoxingMethod->getReturnType()->getNullability(Context);
596
54
      if (Nullability)
597
7
        BoxedType = Context.getAttributedType(
598
7
            AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
599
7
            BoxedType);
600
54
    }
601
176
  } else if (ValueType->isBuiltinType()) {
602
    // The other types we support are numeric, char and BOOL/bool. We could also
603
    // provide limited support for structure types, such as NSRange, NSRect, and
604
    // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
605
    // for more details.
606
607
    // Check for a top-level character literal.
608
105
    if (const CharacterLiteral *Char =
609
105
        dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
610
      // In C, character literals have type 'int'. That's not the type we want
611
      // to use to determine the Objective-c literal kind.
612
4
      switch (Char->getKind()) {
613
4
      case CharacterLiteral::Ascii:
614
4
      case CharacterLiteral::UTF8:
615
4
        ValueType = Context.CharTy;
616
4
        break;
617
618
0
      case CharacterLiteral::Wide:
619
0
        ValueType = Context.getWideCharType();
620
0
        break;
621
622
0
      case CharacterLiteral::UTF16:
623
0
        ValueType = Context.Char16Ty;
624
0
        break;
625
626
0
      case CharacterLiteral::UTF32:
627
0
        ValueType = Context.Char32Ty;
628
0
        break;
629
4
      }
630
4
    }
631
    // FIXME:  Do I need to do anything special with BoolTy expressions?
632
633
    // Look for the appropriate method within NSNumber.
634
105
    BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
635
105
    BoxedType = NSNumberPointer;
636
105
  } else 
if (const EnumType *71
ET71
= ValueType->getAs<EnumType>()) {
637
8
    if (!ET->getDecl()->isComplete()) {
638
2
      Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
639
2
        << ValueType << ValueExpr->getSourceRange();
640
2
      return ExprError();
641
2
    }
642
643
6
    BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
644
6
                                            ET->getDecl()->getIntegerType());
645
6
    BoxedType = NSNumberPointer;
646
63
  } else if (ValueType->isObjCBoxableRecordType()) {
647
    // Support for structure types, that marked as objc_boxable
648
    // struct __attribute__((objc_boxable)) s { ... };
649
650
    // Look up the NSValue class, if we haven't done so already. It's cached
651
    // in the Sema instance.
652
57
    if (!NSValueDecl) {
653
13
      NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
654
13
                                                      Sema::LK_Boxed);
655
13
      if (!NSValueDecl) {
656
2
        return ExprError();
657
2
      }
658
659
      // generate the pointer to NSValue type.
660
11
      QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
661
11
      NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
662
11
    }
663
664
55
    if (!ValueWithBytesObjCTypeMethod) {
665
11
      IdentifierInfo *II[] = {
666
11
        &Context.Idents.get("valueWithBytes"),
667
11
        &Context.Idents.get("objCType")
668
11
      };
669
11
      Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
670
671
      // Look for the appropriate method within NSValue.
672
11
      BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
673
11
      if (!BoxingMethod && 
getLangOpts().DebuggerObjCLiteral0
) {
674
        // Debugger needs to work even if NSValue hasn't been defined.
675
0
        TypeSourceInfo *ReturnTInfo = nullptr;
676
0
        ObjCMethodDecl *M = ObjCMethodDecl::Create(
677
0
            Context, SourceLocation(), SourceLocation(), ValueWithBytesObjCType,
678
0
            NSValuePointer, ReturnTInfo, NSValueDecl,
679
0
            /*isInstance=*/false,
680
0
            /*isVariadic=*/false,
681
0
            /*isPropertyAccessor=*/false,
682
0
            /*isSynthesizedAccessorStub=*/false,
683
0
            /*isImplicitlyDeclared=*/true,
684
0
            /*isDefined=*/false, ObjCMethodDecl::Required,
685
0
            /*HasRelatedResultType=*/false);
686
687
0
        SmallVector<ParmVarDecl *, 2> Params;
688
689
0
        ParmVarDecl *bytes =
690
0
        ParmVarDecl::Create(Context, M,
691
0
                            SourceLocation(), SourceLocation(),
692
0
                            &Context.Idents.get("bytes"),
693
0
                            Context.VoidPtrTy.withConst(),
694
0
                            /*TInfo=*/nullptr,
695
0
                            SC_None, nullptr);
696
0
        Params.push_back(bytes);
697
698
0
        QualType ConstCharType = Context.CharTy.withConst();
699
0
        ParmVarDecl *type =
700
0
        ParmVarDecl::Create(Context, M,
701
0
                            SourceLocation(), SourceLocation(),
702
0
                            &Context.Idents.get("type"),
703
0
                            Context.getPointerType(ConstCharType),
704
0
                            /*TInfo=*/nullptr,
705
0
                            SC_None, nullptr);
706
0
        Params.push_back(type);
707
708
0
        M->setMethodParams(Context, Params, None);
709
0
        BoxingMethod = M;
710
0
      }
711
712
11
      if (!validateBoxingMethod(*this, Loc, NSValueDecl,
713
11
                                ValueWithBytesObjCType, BoxingMethod))
714
0
        return ExprError();
715
716
11
      ValueWithBytesObjCTypeMethod = BoxingMethod;
717
11
    }
718
719
55
    if (!ValueType.isTriviallyCopyableType(Context)) {
720
3
      Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
721
3
        << ValueType << ValueExpr->getSourceRange();
722
3
      return ExprError();
723
3
    }
724
725
52
    BoxingMethod = ValueWithBytesObjCTypeMethod;
726
52
    BoxedType = NSValuePointer;
727
52
  }
728
729
232
  if (!BoxingMethod) {
730
18
    Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
731
18
      << ValueType << ValueExpr->getSourceRange();
732
18
    return ExprError();
733
18
  }
734
735
214
  DiagnoseUseOfDecl(BoxingMethod, Loc);
736
737
214
  ExprResult ConvertedValueExpr;
738
214
  if (ValueType->isObjCBoxableRecordType()) {
739
52
    InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
740
52
    ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
741
52
                                                   ValueExpr);
742
162
  } else {
743
    // Convert the expression to the type that the parameter requires.
744
162
    ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
745
162
    InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
746
162
                                                                  ParamDecl);
747
162
    ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
748
162
                                                   ValueExpr);
749
162
  }
750
751
214
  if (ConvertedValueExpr.isInvalid())
752
0
    return ExprError();
753
214
  ValueExpr = ConvertedValueExpr.get();
754
755
214
  ObjCBoxedExpr *BoxedExpr =
756
214
    new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
757
214
                                      BoxingMethod, SR);
758
214
  return MaybeBindToTemporary(BoxedExpr);
759
214
}
760
761
/// Build an ObjC subscript pseudo-object expression, given that
762
/// that's supported by the runtime.
763
ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
764
                                        Expr *IndexExpr,
765
                                        ObjCMethodDecl *getterMethod,
766
295
                                        ObjCMethodDecl *setterMethod) {
767
295
  assert(!LangOpts.isSubscriptPointerArithmetic());
768
769
  // We can't get dependent types here; our callers should have
770
  // filtered them out.
771
0
  assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
772
295
         "base or index cannot have dependent type here");
773
774
  // Filter out placeholders in the index.  In theory, overloads could
775
  // be preserved here, although that might not actually work correctly.
776
0
  ExprResult Result = CheckPlaceholderExpr(IndexExpr);
777
295
  if (Result.isInvalid())
778
0
    return ExprError();
779
295
  IndexExpr = Result.get();
780
781
  // Perform lvalue-to-rvalue conversion on the base.
782
295
  Result = DefaultLvalueConversion(BaseExpr);
783
295
  if (Result.isInvalid())
784
0
    return ExprError();
785
295
  BaseExpr = Result.get();
786
787
  // Build the pseudo-object expression.
788
295
  return new (Context) ObjCSubscriptRefExpr(
789
295
      BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
790
295
      getterMethod, setterMethod, RB);
791
295
}
792
793
295
ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
794
295
  SourceLocation Loc = SR.getBegin();
795
796
295
  if (!NSArrayDecl) {
797
171
    NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
798
171
                                                    Sema::LK_Array);
799
171
    if (!NSArrayDecl) {
800
4
      return ExprError();
801
4
    }
802
171
  }
803
804
  // Find the arrayWithObjects:count: method, if we haven't done so already.
805
291
  QualType IdT = Context.getObjCIdType();
806
291
  if (!ArrayWithObjectsMethod) {
807
168
    Selector
808
168
      Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
809
168
    ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
810
168
    if (!Method && 
getLangOpts().DebuggerObjCLiteral3
) {
811
3
      TypeSourceInfo *ReturnTInfo = nullptr;
812
3
      Method = ObjCMethodDecl::Create(
813
3
          Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
814
3
          Context.getTranslationUnitDecl(), false /*Instance*/,
815
3
          false /*isVariadic*/,
816
3
          /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
817
3
          /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
818
3
          ObjCMethodDecl::Required, false);
819
3
      SmallVector<ParmVarDecl *, 2> Params;
820
3
      ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
821
3
                                                 SourceLocation(),
822
3
                                                 SourceLocation(),
823
3
                                                 &Context.Idents.get("objects"),
824
3
                                                 Context.getPointerType(IdT),
825
3
                                                 /*TInfo=*/nullptr,
826
3
                                                 SC_None, nullptr);
827
3
      Params.push_back(objects);
828
3
      ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
829
3
                                             SourceLocation(),
830
3
                                             SourceLocation(),
831
3
                                             &Context.Idents.get("cnt"),
832
3
                                             Context.UnsignedLongTy,
833
3
                                             /*TInfo=*/nullptr, SC_None,
834
3
                                             nullptr);
835
3
      Params.push_back(cnt);
836
3
      Method->setMethodParams(Context, Params, None);
837
3
    }
838
839
168
    if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
840
0
      return ExprError();
841
842
    // Dig out the type that all elements should be converted to.
843
168
    QualType T = Method->parameters()[0]->getType();
844
168
    const PointerType *PtrT = T->getAs<PointerType>();
845
168
    if (!PtrT ||
846
168
        !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
847
2
      Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
848
2
        << Sel;
849
2
      Diag(Method->parameters()[0]->getLocation(),
850
2
           diag::note_objc_literal_method_param)
851
2
        << 0 << T
852
2
        << Context.getPointerType(IdT.withConst());
853
2
      return ExprError();
854
2
    }
855
856
    // Check that the 'count' parameter is integral.
857
166
    if (!Method->parameters()[1]->getType()->isIntegerType()) {
858
0
      Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
859
0
        << Sel;
860
0
      Diag(Method->parameters()[1]->getLocation(),
861
0
           diag::note_objc_literal_method_param)
862
0
        << 1
863
0
        << Method->parameters()[1]->getType()
864
0
        << "integral";
865
0
      return ExprError();
866
0
    }
867
868
    // We've found a good +arrayWithObjects:count: method. Save it!
869
166
    ArrayWithObjectsMethod = Method;
870
166
  }
871
872
289
  QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
873
289
  QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
874
875
  // Check that each of the elements provided is valid in a collection literal,
876
  // performing conversions as necessary.
877
289
  Expr **ElementsBuffer = Elements.data();
878
759
  for (unsigned I = 0, N = Elements.size(); I != N; 
++I470
) {
879
477
    ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
880
477
                                                             ElementsBuffer[I],
881
477
                                                             RequiredType, true);
882
477
    if (Converted.isInvalid())
883
7
      return ExprError();
884
885
470
    ElementsBuffer[I] = Converted.get();
886
470
  }
887
888
282
  QualType Ty
889
282
    = Context.getObjCObjectPointerType(
890
282
                                    Context.getObjCInterfaceType(NSArrayDecl));
891
892
282
  return MaybeBindToTemporary(
893
282
           ObjCArrayLiteral::Create(Context, Elements, Ty,
894
282
                                    ArrayWithObjectsMethod, SR));
895
289
}
896
897
/// Check for duplicate keys in an ObjC dictionary literal. For instance:
898
///   NSDictionary *nd = @{ @"foo" : @"bar", @"foo" : @"baz" };
899
static void
900
CheckObjCDictionaryLiteralDuplicateKeys(Sema &S,
901
210
                                        ObjCDictionaryLiteral *Literal) {
902
210
  if (Literal->isValueDependent() || 
Literal->isTypeDependent()205
)
903
5
    return;
904
905
  // NSNumber has quite relaxed equality semantics (for instance, @YES is
906
  // considered equal to @1.0). For now, ignore floating points and just do a
907
  // bit-width and sign agnostic integer compare.
908
205
  struct APSIntCompare {
909
205
    bool operator()(const llvm::APSInt &LHS, const llvm::APSInt &RHS) const {
910
156
      return llvm::APSInt::compareValues(LHS, RHS) < 0;
911
156
    }
912
205
  };
913
914
205
  llvm::DenseMap<StringRef, SourceLocation> StringKeys;
915
205
  std::map<llvm::APSInt, SourceLocation, APSIntCompare> IntegralKeys;
916
917
248
  auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
918
248
    auto Pair = Map.insert({Key, Loc});
919
248
    if (!Pair.second) {
920
21
      S.Diag(Loc, diag::warn_nsdictionary_duplicate_key);
921
21
      S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here);
922
21
    }
923
248
  };
SemaExprObjC.cpp:auto CheckObjCDictionaryLiteralDuplicateKeys(clang::Sema&, clang::ObjCDictionaryLiteral*)::$_0::operator()<llvm::DenseMap<llvm::StringRef, clang::SourceLocation, llvm::DenseMapInfo<llvm::StringRef>, llvm::detail::DenseMapPair<llvm::StringRef, clang::SourceLocation> >, llvm::StringRef>(llvm::DenseMap<llvm::StringRef, clang::SourceLocation, llvm::DenseMapInfo<llvm::StringRef>, llvm::detail::DenseMapPair<llvm::StringRef, clang::SourceLocation> >&, llvm::StringRef const&, clang::SourceLocation) const
Line
Count
Source
917
176
  auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
918
176
    auto Pair = Map.insert({Key, Loc});
919
176
    if (!Pair.second) {
920
4
      S.Diag(Loc, diag::warn_nsdictionary_duplicate_key);
921
4
      S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here);
922
4
    }
923
176
  };
SemaExprObjC.cpp:auto CheckObjCDictionaryLiteralDuplicateKeys(clang::Sema&, clang::ObjCDictionaryLiteral*)::$_0::operator()<std::__1::map<llvm::APSInt, clang::SourceLocation, CheckObjCDictionaryLiteralDuplicateKeys(clang::Sema&, clang::ObjCDictionaryLiteral*)::APSIntCompare, std::__1::allocator<std::__1::pair<llvm::APSInt const, clang::SourceLocation> > >, llvm::APSInt>(std::__1::map<llvm::APSInt, clang::SourceLocation, CheckObjCDictionaryLiteralDuplicateKeys(clang::Sema&, clang::ObjCDictionaryLiteral*)::APSIntCompare, std::__1::allocator<std::__1::pair<llvm::APSInt const, clang::SourceLocation> > >&, llvm::APSInt const&, clang::SourceLocation) const
Line
Count
Source
917
72
  auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
918
72
    auto Pair = Map.insert({Key, Loc});
919
72
    if (!Pair.second) {
920
17
      S.Diag(Loc, diag::warn_nsdictionary_duplicate_key);
921
17
      S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here);
922
17
    }
923
72
  };
924
925
517
  for (unsigned Idx = 0, End = Literal->getNumElements(); Idx != End; 
++Idx312
) {
926
312
    Expr *Key = Literal->getKeyValueElement(Idx).Key->IgnoreParenImpCasts();
927
928
312
    if (auto *StrLit = dyn_cast<ObjCStringLiteral>(Key)) {
929
174
      StringRef Bytes = StrLit->getString()->getBytes();
930
174
      SourceLocation Loc = StrLit->getExprLoc();
931
174
      checkOneKey(StringKeys, Bytes, Loc);
932
174
    }
933
934
312
    if (auto *BE = dyn_cast<ObjCBoxedExpr>(Key)) {
935
76
      Expr *Boxed = BE->getSubExpr();
936
76
      SourceLocation Loc = BE->getExprLoc();
937
938
      // Check for @("foo").
939
76
      if (auto *Str = dyn_cast<StringLiteral>(Boxed->IgnoreParenImpCasts())) {
940
2
        checkOneKey(StringKeys, Str->getBytes(), Loc);
941
2
        continue;
942
2
      }
943
944
74
      Expr::EvalResult Result;
945
74
      if (Boxed->EvaluateAsInt(Result, S.getASTContext(),
946
74
                               Expr::SE_AllowSideEffects)) {
947
72
        checkOneKey(IntegralKeys, Result.Val.getInt(), Loc);
948
72
      }
949
74
    }
950
312
  }
951
205
}
952
953
ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
954
239
                              MutableArrayRef<ObjCDictionaryElement> Elements) {
955
239
  SourceLocation Loc = SR.getBegin();
956
957
239
  if (!NSDictionaryDecl) {
958
168
    NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
959
168
                                                         Sema::LK_Dictionary);
960
168
    if (!NSDictionaryDecl) {
961
21
      return ExprError();
962
21
    }
963
168
  }
964
965
  // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
966
  // so already.
967
218
  QualType IdT = Context.getObjCIdType();
968
218
  if (!DictionaryWithObjectsMethod) {
969
148
    Selector Sel = NSAPIObj->getNSDictionarySelector(
970
148
                               NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
971
148
    ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
972
148
    if (!Method && 
getLangOpts().DebuggerObjCLiteral6
) {
973
6
      Method = ObjCMethodDecl::Create(
974
6
          Context, SourceLocation(), SourceLocation(), Sel, IdT,
975
6
          nullptr /*TypeSourceInfo */, Context.getTranslationUnitDecl(),
976
6
          false /*Instance*/, false /*isVariadic*/,
977
6
          /*isPropertyAccessor=*/false,
978
6
          /*isSynthesizedAccessorStub=*/false,
979
6
          /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
980
6
          ObjCMethodDecl::Required, false);
981
6
      SmallVector<ParmVarDecl *, 3> Params;
982
6
      ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
983
6
                                                 SourceLocation(),
984
6
                                                 SourceLocation(),
985
6
                                                 &Context.Idents.get("objects"),
986
6
                                                 Context.getPointerType(IdT),
987
6
                                                 /*TInfo=*/nullptr, SC_None,
988
6
                                                 nullptr);
989
6
      Params.push_back(objects);
990
6
      ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
991
6
                                              SourceLocation(),
992
6
                                              SourceLocation(),
993
6
                                              &Context.Idents.get("keys"),
994
6
                                              Context.getPointerType(IdT),
995
6
                                              /*TInfo=*/nullptr, SC_None,
996
6
                                              nullptr);
997
6
      Params.push_back(keys);
998
6
      ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
999
6
                                             SourceLocation(),
1000
6
                                             SourceLocation(),
1001
6
                                             &Context.Idents.get("cnt"),
1002
6
                                             Context.UnsignedLongTy,
1003
6
                                             /*TInfo=*/nullptr, SC_None,
1004
6
                                             nullptr);
1005
6
      Params.push_back(cnt);
1006
6
      Method->setMethodParams(Context, Params, None);
1007
6
    }
1008
1009
148
    if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
1010
148
                              Method))
1011
0
       return ExprError();
1012
1013
    // Dig out the type that all values should be converted to.
1014
148
    QualType ValueT = Method->parameters()[0]->getType();
1015
148
    const PointerType *PtrValue = ValueT->getAs<PointerType>();
1016
148
    if (!PtrValue ||
1017
148
        !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
1018
0
      Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1019
0
        << Sel;
1020
0
      Diag(Method->parameters()[0]->getLocation(),
1021
0
           diag::note_objc_literal_method_param)
1022
0
        << 0 << ValueT
1023
0
        << Context.getPointerType(IdT.withConst());
1024
0
      return ExprError();
1025
0
    }
1026
1027
    // Dig out the type that all keys should be converted to.
1028
148
    QualType KeyT = Method->parameters()[1]->getType();
1029
148
    const PointerType *PtrKey = KeyT->getAs<PointerType>();
1030
148
    if (!PtrKey ||
1031
148
        !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1032
148
                                        IdT)) {
1033
97
      bool err = true;
1034
97
      if (PtrKey) {
1035
97
        if (QIDNSCopying.isNull()) {
1036
          // key argument of selector is id<NSCopying>?
1037
97
          if (ObjCProtocolDecl *NSCopyingPDecl =
1038
97
              LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
1039
95
            ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
1040
95
            QIDNSCopying =
1041
95
              Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
1042
95
                                        llvm::makeArrayRef(
1043
95
                                          (ObjCProtocolDecl**) PQ,
1044
95
                                          1),
1045
95
                                        false);
1046
95
            QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
1047
95
          }
1048
97
        }
1049
97
        if (!QIDNSCopying.isNull())
1050
95
          err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1051
95
                                                QIDNSCopying);
1052
97
      }
1053
1054
97
      if (err) {
1055
2
        Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1056
2
          << Sel;
1057
2
        Diag(Method->parameters()[1]->getLocation(),
1058
2
             diag::note_objc_literal_method_param)
1059
2
          << 1 << KeyT
1060
2
          << Context.getPointerType(IdT.withConst());
1061
2
        return ExprError();
1062
2
      }
1063
97
    }
1064
1065
    // Check that the 'count' parameter is integral.
1066
146
    QualType CountType = Method->parameters()[2]->getType();
1067
146
    if (!CountType->isIntegerType()) {
1068
0
      Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1069
0
        << Sel;
1070
0
      Diag(Method->parameters()[2]->getLocation(),
1071
0
           diag::note_objc_literal_method_param)
1072
0
        << 2 << CountType
1073
0
        << "integral";
1074
0
      return ExprError();
1075
0
    }
1076
1077
    // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1078
146
    DictionaryWithObjectsMethod = Method;
1079
146
  }
1080
1081
216
  QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1082
216
  QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1083
216
  QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1084
216
  QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1085
1086
  // Check that each of the keys and values provided is valid in a collection
1087
  // literal, performing conversions as necessary.
1088
216
  bool HasPackExpansions = false;
1089
331
  for (ObjCDictionaryElement &Element : Elements) {
1090
    // Check the key.
1091
331
    ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1092
331
                                                       KeyT);
1093
331
    if (Key.isInvalid())
1094
3
      return ExprError();
1095
1096
    // Check the value.
1097
328
    ExprResult Value
1098
328
      = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1099
328
    if (Value.isInvalid())
1100
3
      return ExprError();
1101
1102
325
    Element.Key = Key.get();
1103
325
    Element.Value = Value.get();
1104
1105
325
    if (Element.EllipsisLoc.isInvalid())
1106
319
      continue;
1107
1108
6
    if (!Element.Key->containsUnexpandedParameterPack() &&
1109
6
        
!Element.Value->containsUnexpandedParameterPack()2
) {
1110
0
      Diag(Element.EllipsisLoc,
1111
0
           diag::err_pack_expansion_without_parameter_packs)
1112
0
          << SourceRange(Element.Key->getBeginLoc(),
1113
0
                         Element.Value->getEndLoc());
1114
0
      return ExprError();
1115
0
    }
1116
1117
6
    HasPackExpansions = true;
1118
6
  }
1119
1120
210
  QualType Ty = Context.getObjCObjectPointerType(
1121
210
      Context.getObjCInterfaceType(NSDictionaryDecl));
1122
1123
210
  auto *Literal =
1124
210
      ObjCDictionaryLiteral::Create(Context, Elements, HasPackExpansions, Ty,
1125
210
                                    DictionaryWithObjectsMethod, SR);
1126
210
  CheckObjCDictionaryLiteralDuplicateKeys(*this, Literal);
1127
210
  return MaybeBindToTemporary(Literal);
1128
216
}
1129
1130
ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1131
                                      TypeSourceInfo *EncodedTypeInfo,
1132
206
                                      SourceLocation RParenLoc) {
1133
206
  QualType EncodedType = EncodedTypeInfo->getType();
1134
206
  QualType StrTy;
1135
206
  if (EncodedType->isDependentType())
1136
1
    StrTy = Context.DependentTy;
1137
205
  else {
1138
205
    if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1139
205
        
!EncodedType->isVoidType()200
) // void is handled too.
1140
199
      if (RequireCompleteType(AtLoc, EncodedType,
1141
199
                              diag::err_incomplete_type_objc_at_encode,
1142
199
                              EncodedTypeInfo->getTypeLoc()))
1143
2
        return ExprError();
1144
1145
203
    std::string Str;
1146
203
    QualType NotEncodedT;
1147
203
    Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1148
203
    if (!NotEncodedT.isNull())
1149
1
      Diag(AtLoc, diag::warn_incomplete_encoded_type)
1150
1
        << EncodedType << NotEncodedT;
1151
1152
    // The type of @encode is the same as the type of the corresponding string,
1153
    // which is an array type.
1154
203
    StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
1155
203
  }
1156
1157
204
  return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1158
206
}
1159
1160
ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1161
                                           SourceLocation EncodeLoc,
1162
                                           SourceLocation LParenLoc,
1163
                                           ParsedType ty,
1164
203
                                           SourceLocation RParenLoc) {
1165
  // FIXME: Preserve type source info ?
1166
203
  TypeSourceInfo *TInfo;
1167
203
  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1168
203
  if (!TInfo)
1169
0
    TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1170
0
                                             getLocForEndOfToken(LParenLoc));
1171
1172
203
  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1173
203
}
1174
1175
static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1176
                                               SourceLocation AtLoc,
1177
                                               SourceLocation LParenLoc,
1178
                                               SourceLocation RParenLoc,
1179
                                               ObjCMethodDecl *Method,
1180
452
                                               ObjCMethodList &MethList) {
1181
452
  ObjCMethodList *M = &MethList;
1182
452
  bool Warned = false;
1183
572
  for (M = M->getNext(); M; 
M=M->getNext()120
) {
1184
120
    ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1185
120
    if (MatchingMethodDecl == Method ||
1186
120
        isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1187
120
        
MatchingMethodDecl->getSelector() != Method->getSelector()113
)
1188
109
      continue;
1189
11
    if (!S.MatchTwoMethodDeclarations(Method,
1190
11
                                      MatchingMethodDecl, Sema::MMS_loose)) {
1191
9
      if (!Warned) {
1192
9
        Warned = true;
1193
9
        S.Diag(AtLoc, diag::warn_multiple_selectors)
1194
9
          << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1195
9
          << FixItHint::CreateInsertion(RParenLoc, ")");
1196
9
        S.Diag(Method->getLocation(), diag::note_method_declared_at)
1197
9
          << Method->getDeclName();
1198
9
      }
1199
9
      S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1200
9
        << MatchingMethodDecl->getDeclName();
1201
9
    }
1202
11
  }
1203
452
  return Warned;
1204
452
}
1205
1206
static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1207
                                        ObjCMethodDecl *Method,
1208
                                        SourceLocation LParenLoc,
1209
                                        SourceLocation RParenLoc,
1210
274
                                        bool WarnMultipleSelectors) {
1211
274
  if (!WarnMultipleSelectors ||
1212
274
      
S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation())268
)
1213
245
    return;
1214
29
  bool Warned = false;
1215
29
  for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1216
246
       e = S.MethodPool.end(); b != e; 
b++217
) {
1217
    // first, instance methods
1218
226
    ObjCMethodList &InstMethList = b->second.first;
1219
226
    if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1220
226
                                                      Method, InstMethList))
1221
9
      Warned = true;
1222
1223
    // second, class methods
1224
226
    ObjCMethodList &ClsMethList = b->second.second;
1225
226
    if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1226
226
                                                      Method, ClsMethList) || Warned)
1227
9
      return;
1228
226
  }
1229
29
}
1230
1231
static ObjCMethodDecl *LookupDirectMethodInMethodList(Sema &S, Selector Sel,
1232
                                                      ObjCMethodList &MethList,
1233
                                                      bool &onlyDirect,
1234
548
                                                      bool &anyDirect) {
1235
548
  (void)Sel;
1236
548
  ObjCMethodList *M = &MethList;
1237
548
  ObjCMethodDecl *DirectMethod = nullptr;
1238
1.39k
  for (; M; 
M = M->getNext()851
) {
1239
851
    ObjCMethodDecl *Method = M->getMethod();
1240
851
    if (!Method)
1241
270
      continue;
1242
581
    assert(Method->getSelector() == Sel && "Method with wrong selector in method list");
1243
581
    if (Method->isDirectMethod()) {
1244
112
      anyDirect = true;
1245
112
      DirectMethod = Method;
1246
112
    } else
1247
469
      onlyDirect = false;
1248
581
  }
1249
1250
548
  return DirectMethod;
1251
548
}
1252
1253
// Search the global pool for (potentially) direct methods matching the given
1254
// selector. If a non-direct method is found, set \param onlyDirect to false. If
1255
// a direct method is found, set \param anyDirect to true. Returns a direct
1256
// method, if any.
1257
static ObjCMethodDecl *LookupDirectMethodInGlobalPool(Sema &S, Selector Sel,
1258
                                                      bool &onlyDirect,
1259
274
                                                      bool &anyDirect) {
1260
274
  auto Iter = S.MethodPool.find(Sel);
1261
274
  if (Iter == S.MethodPool.end())
1262
0
    return nullptr;
1263
1264
274
  ObjCMethodDecl *DirectInstance = LookupDirectMethodInMethodList(
1265
274
      S, Sel, Iter->second.first, onlyDirect, anyDirect);
1266
274
  ObjCMethodDecl *DirectClass = LookupDirectMethodInMethodList(
1267
274
      S, Sel, Iter->second.second, onlyDirect, anyDirect);
1268
1269
274
  return DirectInstance ? 
DirectInstance82
:
DirectClass192
;
1270
274
}
1271
1272
111
static ObjCMethodDecl *findMethodInCurrentClass(Sema &S, Selector Sel) {
1273
111
  auto *CurMD = S.getCurMethodDecl();
1274
111
  if (!CurMD)
1275
23
    return nullptr;
1276
88
  ObjCInterfaceDecl *IFace = CurMD->getClassInterface();
1277
1278
  // The language enforce that only one direct method is present in a given
1279
  // class, so we just need to find one method in the current class to know
1280
  // whether Sel is potentially direct in this context.
1281
88
  if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/true))
1282
28
    return MD;
1283
60
  if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*isInstance=*/true))
1284
12
    return MD;
1285
48
  if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/false))
1286
14
    return MD;
1287
34
  if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*isInstance=*/false))
1288
0
    return MD;
1289
1290
34
  return nullptr;
1291
34
}
1292
1293
ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1294
                                             SourceLocation AtLoc,
1295
                                             SourceLocation SelLoc,
1296
                                             SourceLocation LParenLoc,
1297
                                             SourceLocation RParenLoc,
1298
402
                                             bool WarnMultipleSelectors) {
1299
402
  ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1300
402
                             SourceRange(LParenLoc, RParenLoc));
1301
402
  if (!Method)
1302
177
    Method = LookupFactoryMethodInGlobalPool(Sel,
1303
177
                                          SourceRange(LParenLoc, RParenLoc));
1304
402
  if (!Method) {
1305
128
    if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1306
5
      Selector MatchedSel = OM->getSelector();
1307
5
      SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1308
5
                                RParenLoc.getLocWithOffset(-1));
1309
5
      Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1310
5
        << Sel << MatchedSel
1311
5
        << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1312
1313
5
    } else
1314
123
        Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1315
274
  } else {
1316
274
    DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1317
274
                                WarnMultipleSelectors);
1318
1319
274
    bool onlyDirect = true;
1320
274
    bool anyDirect = false;
1321
274
    ObjCMethodDecl *GlobalDirectMethod =
1322
274
        LookupDirectMethodInGlobalPool(*this, Sel, onlyDirect, anyDirect);
1323
1324
274
    if (onlyDirect) {
1325
1
      Diag(AtLoc, diag::err_direct_selector_expression)
1326
1
          << Method->getSelector();
1327
1
      Diag(Method->getLocation(), diag::note_direct_method_declared_at)
1328
1
          << Method->getDeclName();
1329
273
    } else if (anyDirect) {
1330
      // If we saw any direct methods, see if we see a direct member of the
1331
      // current class. If so, the @selector will likely be used to refer to
1332
      // this direct method.
1333
111
      ObjCMethodDecl *LikelyTargetMethod = findMethodInCurrentClass(*this, Sel);
1334
111
      if (LikelyTargetMethod && 
LikelyTargetMethod->isDirectMethod()54
) {
1335
32
        Diag(AtLoc, diag::warn_potentially_direct_selector_expression) << Sel;
1336
32
        Diag(LikelyTargetMethod->getLocation(),
1337
32
             diag::note_direct_method_declared_at)
1338
32
            << LikelyTargetMethod->getDeclName();
1339
79
      } else if (!LikelyTargetMethod) {
1340
        // Otherwise, emit the "strict" variant of this diagnostic, unless
1341
        // LikelyTargetMethod is non-direct.
1342
57
        Diag(AtLoc, diag::warn_strict_potentially_direct_selector_expression)
1343
57
            << Sel;
1344
57
        Diag(GlobalDirectMethod->getLocation(),
1345
57
             diag::note_direct_method_declared_at)
1346
57
            << GlobalDirectMethod->getDeclName();
1347
57
      }
1348
111
    }
1349
274
  }
1350
1351
402
  if (Method &&
1352
402
      
Method->getImplementationControl() != ObjCMethodDecl::Optional274
&&
1353
402
      
!getSourceManager().isInSystemHeader(Method->getLocation())273
)
1354
229
    ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1355
1356
  // In ARC, forbid the user from using @selector for
1357
  // retain/release/autorelease/dealloc/retainCount.
1358
402
  if (getLangOpts().ObjCAutoRefCount) {
1359
52
    switch (Sel.getMethodFamily()) {
1360
3
    case OMF_retain:
1361
6
    case OMF_release:
1362
9
    case OMF_autorelease:
1363
9
    case OMF_retainCount:
1364
12
    case OMF_dealloc:
1365
12
      Diag(AtLoc, diag::err_arc_illegal_selector) <<
1366
12
        Sel << SourceRange(LParenLoc, RParenLoc);
1367
12
      break;
1368
1369
36
    case OMF_None:
1370
36
    case OMF_alloc:
1371
37
    case OMF_copy:
1372
37
    case OMF_finalize:
1373
38
    case OMF_init:
1374
38
    case OMF_mutableCopy:
1375
39
    case OMF_new:
1376
40
    case OMF_self:
1377
40
    case OMF_initialize:
1378
40
    case OMF_performSelector:
1379
40
      break;
1380
52
    }
1381
52
  }
1382
402
  QualType Ty = Context.getObjCSelType();
1383
402
  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1384
402
}
1385
1386
ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1387
                                             SourceLocation AtLoc,
1388
                                             SourceLocation ProtoLoc,
1389
                                             SourceLocation LParenLoc,
1390
                                             SourceLocation ProtoIdLoc,
1391
41
                                             SourceLocation RParenLoc) {
1392
41
  ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1393
41
  if (!PDecl) {
1394
2
    Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1395
2
    return true;
1396
2
  }
1397
39
  if (PDecl->isNonRuntimeProtocol())
1398
1
    Diag(ProtoLoc, diag::err_objc_non_runtime_protocol_in_protocol_expr)
1399
1
        << PDecl;
1400
39
  if (!PDecl->hasDefinition()) {
1401
3
    Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1402
3
    Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1403
36
  } else {
1404
36
    PDecl = PDecl->getDefinition();
1405
36
  }
1406
1407
39
  QualType Ty = Context.getObjCProtoType();
1408
39
  if (Ty.isNull())
1409
0
    return true;
1410
39
  Ty = Context.getObjCObjectPointerType(Ty);
1411
39
  return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1412
39
}
1413
1414
/// Try to capture an implicit reference to 'self'.
1415
1.24k
ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1416
1.24k
  DeclContext *DC = getFunctionLevelDeclContext();
1417
1418
  // If we're not in an ObjC method, error out.  Note that, unlike the
1419
  // C++ case, we don't require an instance method --- class methods
1420
  // still have a 'self', and we really do still need to capture it!
1421
1.24k
  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1422
1.24k
  if (!method)
1423
0
    return nullptr;
1424
1425
1.24k
  tryCaptureVariable(method->getSelfDecl(), Loc);
1426
1427
1.24k
  return method;
1428
1.24k
}
1429
1430
84
static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1431
84
  QualType origType = T;
1432
84
  if (auto nullability = AttributedType::stripOuterNullability(T)) {
1433
3
    if (T == Context.getObjCInstanceType()) {
1434
3
      return Context.getAttributedType(
1435
3
               AttributedType::getNullabilityAttrKind(*nullability),
1436
3
               Context.getObjCIdType(),
1437
3
               Context.getObjCIdType());
1438
3
    }
1439
1440
0
    return origType;
1441
3
  }
1442
1443
81
  if (T == Context.getObjCInstanceType())
1444
33
    return Context.getObjCIdType();
1445
1446
48
  return origType;
1447
81
}
1448
1449
/// Determine the result type of a message send based on the receiver type,
1450
/// method, and the kind of message send.
1451
///
1452
/// This is the "base" result type, which will still need to be adjusted
1453
/// to account for nullability.
1454
static QualType getBaseMessageSendResultType(Sema &S,
1455
                                             QualType ReceiverType,
1456
                                             ObjCMethodDecl *Method,
1457
                                             bool isClassMessage,
1458
24.1k
                                             bool isSuperMessage) {
1459
24.1k
  assert(Method && "Must have a method");
1460
24.1k
  if (!Method->hasRelatedResultType())
1461
15.8k
    return Method->getSendResultType(ReceiverType);
1462
1463
8.29k
  ASTContext &Context = S.Context;
1464
1465
  // Local function that transfers the nullability of the method's
1466
  // result type to the returned result.
1467
8.29k
  auto transferNullability = [&](QualType type) -> QualType {
1468
    // If the method's result type has nullability, extract it.
1469
8.20k
    if (auto nullability = Method->getSendResultType(ReceiverType)
1470
8.20k
                             ->getNullability(Context)){
1471
      // Strip off any outer nullability sugar from the provided type.
1472
2.74k
      (void)AttributedType::stripOuterNullability(type);
1473
1474
      // Form a new attributed type using the method result type's nullability.
1475
2.74k
      return Context.getAttributedType(
1476
2.74k
               AttributedType::getNullabilityAttrKind(*nullability),
1477
2.74k
               type,
1478
2.74k
               type);
1479
2.74k
    }
1480
1481
5.45k
    return type;
1482
8.20k
  };
1483
1484
  // If a method has a related return type:
1485
  //   - if the method found is an instance method, but the message send
1486
  //     was a class message send, T is the declared return type of the method
1487
  //     found
1488
8.29k
  if (Method->isInstanceMethod() && 
isClassMessage3.50k
)
1489
24
    return stripObjCInstanceType(Context,
1490
24
                                 Method->getSendResultType(ReceiverType));
1491
1492
  //   - if the receiver is super, T is a pointer to the class of the
1493
  //     enclosing method definition
1494
8.26k
  if (isSuperMessage) {
1495
477
    if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1496
477
      if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1497
477
        return transferNullability(
1498
477
                 Context.getObjCObjectPointerType(
1499
477
                   Context.getObjCInterfaceType(Class)));
1500
477
      }
1501
477
  }
1502
1503
  //   - if the receiver is the name of a class U, T is a pointer to U
1504
7.79k
  if (ReceiverType->getAsObjCInterfaceType())
1505
4.69k
    return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1506
  //   - if the receiver is of type Class or qualified Class type,
1507
  //     T is the declared return type of the method.
1508
3.09k
  if (ReceiverType->isObjCClassType() ||
1509
3.09k
      
ReceiverType->isObjCQualifiedClassType()3.04k
)
1510
60
    return stripObjCInstanceType(Context,
1511
60
                                 Method->getSendResultType(ReceiverType));
1512
1513
  //   - if the receiver is id, qualified id, Class, or qualified Class, T
1514
  //     is the receiver type, otherwise
1515
  //   - T is the type of the receiver expression.
1516
3.03k
  return transferNullability(ReceiverType);
1517
3.09k
}
1518
1519
QualType Sema::getMessageSendResultType(const Expr *Receiver,
1520
                                        QualType ReceiverType,
1521
                                        ObjCMethodDecl *Method,
1522
                                        bool isClassMessage,
1523
24.1k
                                        bool isSuperMessage) {
1524
  // Produce the result type.
1525
24.1k
  QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1526
24.1k
                                                     Method,
1527
24.1k
                                                     isClassMessage,
1528
24.1k
                                                     isSuperMessage);
1529
1530
  // If this is a class message, ignore the nullability of the receiver.
1531
24.1k
  if (isClassMessage) {
1532
    // In a class method, class messages to 'self' that return instancetype can
1533
    // be typed as the current class.  We can safely do this in ARC because self
1534
    // can't be reassigned, and we do it unsafely outside of ARC because in
1535
    // practice people never reassign self in class methods and there's some
1536
    // virtue in not being aggressively pedantic.
1537
7.95k
    if (Receiver && 
Receiver->isObjCSelfExpr()250
) {
1538
87
      assert(ReceiverType->isObjCClassType() && "expected a Class self");
1539
0
      QualType T = Method->getSendResultType(ReceiverType);
1540
87
      AttributedType::stripOuterNullability(T);
1541
87
      if (T == Context.getObjCInstanceType()) {
1542
25
        const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1543
25
            cast<ImplicitParamDecl>(
1544
25
                cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1545
25
                ->getDeclContext());
1546
25
        assert(MD->isClassMethod() && "expected a class method");
1547
0
        QualType NewResultType = Context.getObjCObjectPointerType(
1548
25
            Context.getObjCInterfaceType(MD->getClassInterface()));
1549
25
        if (auto Nullability = resultType->getNullability(Context))
1550
2
          NewResultType = Context.getAttributedType(
1551
2
              AttributedType::getNullabilityAttrKind(*Nullability),
1552
2
              NewResultType, NewResultType);
1553
25
        return NewResultType;
1554
25
      }
1555
87
    }
1556
7.92k
    return resultType;
1557
7.95k
  }
1558
1559
  // There is nothing left to do if the result type cannot have a nullability
1560
  // specifier.
1561
16.1k
  if (!resultType->canHaveNullability())
1562
9.00k
    return resultType;
1563
1564
  // Map the nullability of the result into a table index.
1565
7.18k
  unsigned receiverNullabilityIdx = 0;
1566
7.18k
  if (Optional<NullabilityKind> nullability =
1567
7.18k
          ReceiverType->getNullability(Context)) {
1568
86
    if (*nullability == NullabilityKind::NullableResult)
1569
5
      nullability = NullabilityKind::Nullable;
1570
86
    receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1571
86
  }
1572
1573
7.18k
  unsigned resultNullabilityIdx = 0;
1574
7.18k
  if (Optional<NullabilityKind> nullability =
1575
7.18k
          resultType->getNullability(Context)) {
1576
1.83k
    if (*nullability == NullabilityKind::NullableResult)
1577
1
      nullability = NullabilityKind::Nullable;
1578
1.83k
    resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1579
1.83k
  }
1580
1581
  // The table of nullability mappings, indexed by the receiver's nullability
1582
  // and then the result type's nullability.
1583
7.18k
  static const uint8_t None = 0;
1584
7.18k
  static const uint8_t NonNull = 1;
1585
7.18k
  static const uint8_t Nullable = 2;
1586
7.18k
  static const uint8_t Unspecified = 3;
1587
7.18k
  static const uint8_t nullabilityMap[4][4] = {
1588
    //                  None        NonNull       Nullable    Unspecified
1589
7.18k
    /* None */        { None,       None,         Nullable,   None },
1590
7.18k
    /* NonNull */     { None,       NonNull,      Nullable,   Unspecified },
1591
7.18k
    /* Nullable */    { Nullable,   Nullable,     Nullable,   Nullable },
1592
7.18k
    /* Unspecified */ { None,       Unspecified,  Nullable,   Unspecified }
1593
7.18k
  };
1594
1595
7.18k
  unsigned newResultNullabilityIdx
1596
7.18k
    = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1597
7.18k
  if (newResultNullabilityIdx == resultNullabilityIdx)
1598
5.71k
    return resultType;
1599
1600
  // Strip off the existing nullability. This removes as little type sugar as
1601
  // possible.
1602
1.47k
  do {
1603
1.47k
    if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1604
1.41k
      resultType = attributed->getModifiedType();
1605
1.41k
    } else {
1606
63
      resultType = resultType.getDesugaredType(Context);
1607
63
    }
1608
1.47k
  } while (resultType->getNullability(Context));
1609
1610
  // Add nullability back if needed.
1611
1.47k
  if (newResultNullabilityIdx > 0) {
1612
7
    auto newNullability
1613
7
      = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1614
7
    return Context.getAttributedType(
1615
7
             AttributedType::getNullabilityAttrKind(newNullability),
1616
7
             resultType, resultType);
1617
7
  }
1618
1619
1.47k
  return resultType;
1620
1.47k
}
1621
1622
/// Look for an ObjC method whose result type exactly matches the given type.
1623
static const ObjCMethodDecl *
1624
findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1625
32
                                 QualType instancetype) {
1626
32
  if (MD->getReturnType() == instancetype)
1627
10
    return MD;
1628
1629
  // For these purposes, a method in an @implementation overrides a
1630
  // declaration in the @interface.
1631
22
  if (const ObjCImplDecl *impl =
1632
22
        dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1633
20
    const ObjCContainerDecl *iface;
1634
20
    if (const ObjCCategoryImplDecl *catImpl =
1635
20
          dyn_cast<ObjCCategoryImplDecl>(impl)) {
1636
0
      iface = catImpl->getCategoryDecl();
1637
20
    } else {
1638
20
      iface = impl->getClassInterface();
1639
20
    }
1640
1641
20
    const ObjCMethodDecl *ifaceMD =
1642
20
      iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1643
20
    if (ifaceMD) 
return findExplicitInstancetypeDeclarer(ifaceMD, instancetype)4
;
1644
20
  }
1645
1646
18
  SmallVector<const ObjCMethodDecl *, 4> overrides;
1647
18
  MD->getOverriddenMethods(overrides);
1648
18
  for (unsigned i = 0, e = overrides.size(); i != e; 
++i0
) {
1649
6
    if (const ObjCMethodDecl *result =
1650
6
          findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1651
6
      return result;
1652
6
  }
1653
1654
12
  return nullptr;
1655
18
}
1656
1657
71
void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1658
  // Only complain if we're in an ObjC method and the required return
1659
  // type doesn't match the method's declared return type.
1660
71
  ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1661
71
  if (!MD || 
!MD->hasRelatedResultType()34
||
1662
71
      
Context.hasSameUnqualifiedType(destType, MD->getReturnType())22
)
1663
49
    return;
1664
1665
  // Look for a method overridden by this method which explicitly uses
1666
  // 'instancetype'.
1667
22
  if (const ObjCMethodDecl *overridden =
1668
22
        findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1669
10
    SourceRange range = overridden->getReturnTypeSourceRange();
1670
10
    SourceLocation loc = range.getBegin();
1671
10
    if (loc.isInvalid())
1672
0
      loc = overridden->getLocation();
1673
10
    Diag(loc, diag::note_related_result_type_explicit)
1674
10
      << /*current method*/ 1 << range;
1675
10
    return;
1676
10
  }
1677
1678
  // Otherwise, if we have an interesting method family, note that.
1679
  // This should always trigger if the above didn't.
1680
12
  if (ObjCMethodFamily family = MD->getMethodFamily())
1681
12
    Diag(MD->getLocation(), diag::note_related_result_type_family)
1682
12
      << /*current method*/ 1
1683
12
      << family;
1684
12
}
1685
1686
163
void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1687
163
  E = E->IgnoreParenImpCasts();
1688
163
  const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1689
163
  if (!MsgSend)
1690
135
    return;
1691
1692
28
  const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1693
28
  if (!Method)
1694
0
    return;
1695
1696
28
  if (!Method->hasRelatedResultType())
1697
10
    return;
1698
1699
18
  if (Context.hasSameUnqualifiedType(
1700
18
          Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1701
0
    return;
1702
1703
18
  if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1704
18
                                      Context.getObjCInstanceType()))
1705
0
    return;
1706
1707
18
  Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1708
18
    << Method->isInstanceMethod() << Method->getSelector()
1709
18
    << MsgSend->getType();
1710
18
}
1711
1712
bool Sema::CheckMessageArgumentTypes(
1713
    const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1714
    Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1715
    bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1716
    SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1717
25.3k
    ExprValueKind &VK) {
1718
25.3k
  SourceLocation SelLoc;
1719
25.3k
  if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1720
25.3k
    SelLoc = SelectorLocs.front();
1721
0
  else
1722
0
    SelLoc = lbrac;
1723
1724
25.3k
  if (!Method) {
1725
    // Apply default argument promotion as for (C99 6.5.2.2p6).
1726
2.11k
    for (unsigned i = 0, e = Args.size(); i != e; 
i++928
) {
1727
928
      if (Args[i]->isTypeDependent())
1728
1
        continue;
1729
1730
927
      ExprResult result;
1731
927
      if (getLangOpts().DebuggerSupport) {
1732
522
        QualType paramTy; // ignored
1733
522
        result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1734
522
      } else {
1735
405
        result = DefaultArgumentPromotion(Args[i]);
1736
405
      }
1737
927
      if (result.isInvalid())
1738
0
        return true;
1739
927
      Args[i] = result.get();
1740
927
    }
1741
1742
1.18k
    unsigned DiagID;
1743
1.18k
    if (getLangOpts().ObjCAutoRefCount)
1744
3
      DiagID = diag::err_arc_method_not_found;
1745
1.18k
    else
1746
1.18k
      DiagID = isClassMessage ? 
diag::warn_class_method_not_found116
1747
1.18k
                              : 
diag::warn_inst_method_not_found1.07k
;
1748
1.18k
    if (!getLangOpts().DebuggerSupport) {
1749
632
      const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1750
632
      if (OMD && 
!OMD->isInvalidDecl()37
) {
1751
37
        if (getLangOpts().ObjCAutoRefCount)
1752
2
          DiagID = diag::err_method_not_found_with_typo;
1753
35
        else
1754
35
          DiagID = isClassMessage ? 
diag::warn_class_method_not_found_with_typo1
1755
35
                                  : 
diag::warn_instance_method_not_found_with_typo34
;
1756
37
        Selector MatchedSel = OMD->getSelector();
1757
37
        SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1758
37
        if (MatchedSel.isUnarySelector())
1759
35
          Diag(SelLoc, DiagID)
1760
35
            << Sel<< isClassMessage << MatchedSel
1761
35
            << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1762
2
        else
1763
2
          Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1764
37
      }
1765
595
      else
1766
595
        Diag(SelLoc, DiagID)
1767
595
          << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1768
595
                                                SelectorLocs.back());
1769
      // Find the class to which we are sending this message.
1770
632
      if (auto *ObjPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
1771
530
        if (ObjCInterfaceDecl *ThisClass = ObjPT->getInterfaceDecl()) {
1772
343
          Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1773
343
          if (!RecRange.isInvalid())
1774
343
            if (ThisClass->lookupClassMethod(Sel))
1775
56
              Diag(RecRange.getBegin(), diag::note_receiver_expr_here)
1776
56
                  << FixItHint::CreateReplacement(RecRange,
1777
56
                                                  ThisClass->getNameAsString());
1778
343
        }
1779
530
      }
1780
632
    }
1781
1782
    // In debuggers, we want to use __unknown_anytype for these
1783
    // results so that clients can cast them.
1784
1.18k
    if (getLangOpts().DebuggerSupport) {
1785
557
      ReturnType = Context.UnknownAnyTy;
1786
632
    } else {
1787
632
      ReturnType = Context.getObjCIdType();
1788
632
    }
1789
1.18k
    VK = VK_PRValue;
1790
1.18k
    return false;
1791
1.18k
  }
1792
1793
24.1k
  ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1794
24.1k
                                        isClassMessage, isSuperMessage);
1795
24.1k
  VK = Expr::getValueKindForType(Method->getReturnType());
1796
1797
24.1k
  unsigned NumNamedArgs = Sel.getNumArgs();
1798
  // Method might have more arguments than selector indicates. This is due
1799
  // to addition of c-style arguments in method.
1800
24.1k
  if (Method->param_size() > Sel.getNumArgs())
1801
4
    NumNamedArgs = Method->param_size();
1802
  // FIXME. This need be cleaned up.
1803
24.1k
  if (Args.size() < NumNamedArgs) {
1804
1
    Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1805
1
      << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1806
1
    return false;
1807
1
  }
1808
1809
  // Compute the set of type arguments to be substituted into each parameter
1810
  // type.
1811
24.1k
  Optional<ArrayRef<QualType>> typeArgs
1812
24.1k
    = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1813
24.1k
  bool IsError = false;
1814
39.6k
  for (unsigned i = 0; i < NumNamedArgs; 
i++15.5k
) {
1815
    // We can't do any type-checking on a type-dependent argument.
1816
15.5k
    if (Args[i]->isTypeDependent())
1817
10
      continue;
1818
1819
15.5k
    Expr *argExpr = Args[i];
1820
1821
15.5k
    ParmVarDecl *param = Method->parameters()[i];
1822
15.5k
    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1823
1824
15.5k
    if (param->hasAttr<NoEscapeAttr>() &&
1825
15.5k
        
param->getType()->isBlockPointerType()9
)
1826
3
      if (auto *BE = dyn_cast<BlockExpr>(
1827
3
              argExpr->IgnoreParenNoopCasts(Context)))
1828
2
        BE->getBlockDecl()->setDoesNotEscape();
1829
1830
    // Strip the unbridged-cast placeholder expression off unless it's
1831
    // a consumed argument.
1832
15.5k
    if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1833
15.5k
        
!param->hasAttr<CFConsumedAttr>()4
)
1834
2
      argExpr = stripARCUnbridgedCast(argExpr);
1835
1836
    // If the parameter is __unknown_anytype, infer its type
1837
    // from the argument.
1838
15.5k
    if (param->getType() == Context.UnknownAnyTy) {
1839
4
      QualType paramType;
1840
4
      ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1841
4
      if (argE.isInvalid()) {
1842
0
        IsError = true;
1843
4
      } else {
1844
4
        Args[i] = argE.get();
1845
1846
        // Update the parameter type in-place.
1847
4
        param->setType(paramType);
1848
4
      }
1849
4
      continue;
1850
4
    }
1851
1852
15.5k
    QualType origParamType = param->getType();
1853
15.5k
    QualType paramType = param->getType();
1854
15.5k
    if (typeArgs)
1855
3.72k
      paramType = paramType.substObjCTypeArgs(
1856
3.72k
                    Context,
1857
3.72k
                    *typeArgs,
1858
3.72k
                    ObjCSubstitutionContext::Parameter);
1859
1860
15.5k
    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1861
15.5k
                            paramType,
1862
15.5k
                            diag::err_call_incomplete_argument, argExpr))
1863
0
      return true;
1864
1865
15.5k
    InitializedEntity Entity
1866
15.5k
      = InitializedEntity::InitializeParameter(Context, param, paramType);
1867
15.5k
    ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1868
15.5k
    if (ArgE.isInvalid())
1869
32
      IsError = true;
1870
15.4k
    else {
1871
15.4k
      Args[i] = ArgE.getAs<Expr>();
1872
1873
      // If we are type-erasing a block to a block-compatible
1874
      // Objective-C pointer type, we may need to extend the lifetime
1875
      // of the block object.
1876
15.4k
      if (typeArgs && 
Args[i]->isPRValue()3.70k
&&
paramType->isBlockPointerType()3.70k
&&
1877
15.4k
          
Args[i]->getType()->isBlockPointerType()2
&&
1878
15.4k
          
origParamType->isObjCObjectPointerType()2
) {
1879
2
        ExprResult arg = Args[i];
1880
2
        maybeExtendBlockObject(arg);
1881
2
        Args[i] = arg.get();
1882
2
      }
1883
15.4k
    }
1884
15.5k
  }
1885
1886
  // Promote additional arguments to variadic methods.
1887
24.1k
  if (Method->isVariadic()) {
1888
3.48k
    for (unsigned i = NumNamedArgs, e = Args.size(); i < e; 
++i2.37k
) {
1889
2.37k
      if (Args[i]->isTypeDependent())
1890
6
        continue;
1891
1892
2.36k
      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1893
2.36k
                                                        nullptr);
1894
2.36k
      IsError |= Arg.isInvalid();
1895
2.36k
      Args[i] = Arg.get();
1896
2.36k
    }
1897
23.0k
  } else {
1898
    // Check for extra arguments to non-variadic methods.
1899
23.0k
    if (Args.size() != NumNamedArgs) {
1900
2
      Diag(Args[NumNamedArgs]->getBeginLoc(),
1901
2
           diag::err_typecheck_call_too_many_args)
1902
2
          << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1903
2
          << Method->getSourceRange()
1904
2
          << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
1905
2
                         Args.back()->getEndLoc());
1906
2
    }
1907
23.0k
  }
1908
1909
24.1k
  DiagnoseSentinelCalls(Method, SelLoc, Args);
1910
1911
  // Do additional checkings on method.
1912
24.1k
  IsError |= CheckObjCMethodCall(
1913
24.1k
      Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1914
1915
24.1k
  return IsError;
1916
24.1k
}
1917
1918
18.4k
bool Sema::isSelfExpr(Expr *RExpr) {
1919
  // 'self' is objc 'self' in an objc method only.
1920
18.4k
  ObjCMethodDecl *Method =
1921
18.4k
      dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1922
18.4k
  return isSelfExpr(RExpr, Method);
1923
18.4k
}
1924
1925
18.4k
bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1926
18.4k
  if (!method) 
return false14.5k
;
1927
1928
3.85k
  receiver = receiver->IgnoreParenLValueCasts();
1929
3.85k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1930
1.63k
    if (DRE->getDecl() == method->getSelfDecl())
1931
1.00k
      return true;
1932
2.85k
  return false;
1933
3.85k
}
1934
1935
/// LookupMethodInType - Look up a method in an ObjCObjectType.
1936
ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1937
10.8k
                                               bool isInstance) {
1938
10.8k
  const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1939
10.8k
  if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1940
    // Look it up in the main interface (and categories, etc.)
1941
10.7k
    if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1942
4.22k
      return method;
1943
1944
    // Okay, look for "private" methods declared in any
1945
    // @implementations we've seen.
1946
6.55k
    if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1947
14
      return method;
1948
6.55k
  }
1949
1950
  // Check qualifiers.
1951
6.60k
  for (const auto *I : objType->quals())
1952
27
    if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1953
23
      return method;
1954
1955
6.58k
  return nullptr;
1956
6.60k
}
1957
1958
/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1959
/// list of a qualified objective pointer type.
1960
ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1961
                                              const ObjCObjectPointerType *OPT,
1962
                                              bool Instance)
1963
3.44k
{
1964
3.44k
  ObjCMethodDecl *MD = nullptr;
1965
3.44k
  for (const auto *PROTO : OPT->quals()) {
1966
324
    if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1967
228
      return MD;
1968
228
    }
1969
324
  }
1970
3.21k
  return nullptr;
1971
3.44k
}
1972
1973
/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1974
/// objective C interface.  This is a property reference expression.
1975
ExprResult Sema::
1976
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1977
                          Expr *BaseExpr, SourceLocation OpLoc,
1978
                          DeclarationName MemberName,
1979
                          SourceLocation MemberLoc,
1980
                          SourceLocation SuperLoc, QualType SuperType,
1981
2.22k
                          bool Super) {
1982
2.22k
  const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1983
2.22k
  ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1984
1985
2.22k
  if (!MemberName.isIdentifier()) {
1986
1
    Diag(MemberLoc, diag::err_invalid_property_name)
1987
1
      << MemberName << QualType(OPT, 0);
1988
1
    return ExprError();
1989
1
  }
1990
1991
2.22k
  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1992
1993
2.22k
  SourceRange BaseRange = Super? 
SourceRange(SuperLoc)64
1994
2.22k
                               : 
BaseExpr->getSourceRange()2.16k
;
1995
2.22k
  if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1996
2.22k
                          diag::err_property_not_found_forward_class,
1997
2.22k
                          MemberName, BaseRange))
1998
1
    return ExprError();
1999
2000
2.22k
  if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
2001
2.22k
          Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2002
    // Check whether we can reference this property.
2003
1.90k
    if (DiagnoseUseOfDecl(PD, MemberLoc))
2004
0
      return ExprError();
2005
1.90k
    if (Super)
2006
58
      return new (Context)
2007
58
          ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2008
58
                              OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
2009
1.85k
    else
2010
1.85k
      return new (Context)
2011
1.85k
          ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2012
1.85k
                              OK_ObjCProperty, MemberLoc, BaseExpr);
2013
1.90k
  }
2014
  // Check protocols on qualified interfaces.
2015
318
  for (const auto *I : OPT->quals())
2016
11
    if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
2017
11
            Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2018
      // Check whether we can reference this property.
2019
2
      if (DiagnoseUseOfDecl(PD, MemberLoc))
2020
0
        return ExprError();
2021
2022
2
      if (Super)
2023
0
        return new (Context) ObjCPropertyRefExpr(
2024
0
            PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
2025
0
            SuperLoc, SuperType);
2026
2
      else
2027
2
        return new (Context)
2028
2
            ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2029
2
                                OK_ObjCProperty, MemberLoc, BaseExpr);
2030
2
    }
2031
  // If that failed, look for an "implicit" property by seeing if the nullary
2032
  // selector is implemented.
2033
2034
  // FIXME: The logic for looking up nullary and unary selectors should be
2035
  // shared with the code in ActOnInstanceMessage.
2036
2037
316
  Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2038
316
  ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2039
2040
  // May be found in property's qualified list.
2041
316
  if (!Getter)
2042
62
    Getter = LookupMethodInQualifiedType(Sel, OPT, true);
2043
2044
  // If this reference is in an @implementation, check for 'private' methods.
2045
316
  if (!Getter)
2046
61
    Getter = IFace->lookupPrivateMethod(Sel);
2047
2048
316
  if (Getter) {
2049
    // Check if we can reference this property.
2050
263
    if (DiagnoseUseOfDecl(Getter, MemberLoc))
2051
0
      return ExprError();
2052
263
  }
2053
  // If we found a getter then this may be a valid dot-reference, we
2054
  // will look for the matching setter, in case it is needed.
2055
316
  Selector SetterSel =
2056
316
    SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
2057
316
                                           PP.getSelectorTable(), Member);
2058
316
  ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2059
2060
  // May be found in property's qualified list.
2061
316
  if (!Setter)
2062
163
    Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
2063
2064
316
  if (!Setter) {
2065
    // If this reference is in an @implementation, also check for 'private'
2066
    // methods.
2067
163
    Setter = IFace->lookupPrivateMethod(SetterSel);
2068
163
  }
2069
2070
316
  if (Setter && 
DiagnoseUseOfDecl(Setter, MemberLoc)157
)
2071
0
    return ExprError();
2072
2073
  // Special warning if member name used in a property-dot for a setter accessor
2074
  // does not use a property with same name; e.g. obj.X = ... for a property with
2075
  // name 'x'.
2076
316
  if (Setter && 
Setter->isImplicit()157
&&
Setter->isPropertyAccessor()14
&&
2077
316
      !IFace->FindPropertyDeclaration(
2078
8
          Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2079
8
      if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
2080
        // Do not warn if user is using property-dot syntax to make call to
2081
        // user named setter.
2082
8
        if (!(PDecl->getPropertyAttributes() &
2083
8
              ObjCPropertyAttribute::kind_setter))
2084
5
          Diag(MemberLoc,
2085
5
               diag::warn_property_access_suggest)
2086
5
          << MemberName << QualType(OPT, 0) << PDecl->getName()
2087
5
          << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
2088
8
      }
2089
8
  }
2090
2091
316
  if (Getter || 
Setter53
) {
2092
291
    if (Super)
2093
6
      return new (Context)
2094
6
          ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2095
6
                              OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
2096
285
    else
2097
285
      return new (Context)
2098
285
          ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2099
285
                              OK_ObjCProperty, MemberLoc, BaseExpr);
2100
2101
291
  }
2102
2103
  // Attempt to correct for typos in property names.
2104
25
  DeclFilterCCC<ObjCPropertyDecl> CCC{};
2105
25
  if (TypoCorrection Corrected = CorrectTypo(
2106
25
          DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
2107
25
          nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
2108
12
    DeclarationName TypoResult = Corrected.getCorrection();
2109
12
    if (TypoResult.isIdentifier() &&
2110
12
        TypoResult.getAsIdentifierInfo() == Member) {
2111
      // There is no need to try the correction if it is the same.
2112
3
      NamedDecl *ChosenDecl =
2113
3
        Corrected.isKeyword() ? 
nullptr0
: Corrected.getFoundDecl();
2114
3
      if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
2115
3
        if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
2116
          // This is a class property, we should not use the instance to
2117
          // access it.
2118
3
          Diag(MemberLoc, diag::err_class_property_found) << MemberName
2119
3
          << OPT->getInterfaceDecl()->getName()
2120
3
          << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
2121
3
                                          OPT->getInterfaceDecl()->getName());
2122
3
          return ExprError();
2123
3
        }
2124
9
    } else {
2125
9
      diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
2126
9
                                << MemberName << QualType(OPT, 0));
2127
9
      return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
2128
9
                                       TypoResult, MemberLoc,
2129
9
                                       SuperLoc, SuperType, Super);
2130
9
    }
2131
12
  }
2132
13
  ObjCInterfaceDecl *ClassDeclared;
2133
13
  if (ObjCIvarDecl *Ivar =
2134
13
      IFace->lookupInstanceVariable(Member, ClassDeclared)) {
2135
3
    QualType T = Ivar->getType();
2136
3
    if (const ObjCObjectPointerType * OBJPT =
2137
3
        T->getAsObjCInterfacePointerType()) {
2138
1
      if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
2139
1
                              diag::err_property_not_as_forward_class,
2140
1
                              MemberName, BaseExpr))
2141
1
        return ExprError();
2142
1
    }
2143
2
    Diag(MemberLoc,
2144
2
         diag::err_ivar_access_using_property_syntax_suggest)
2145
2
    << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
2146
2
    << FixItHint::CreateReplacement(OpLoc, "->");
2147
2
    return ExprError();
2148
3
  }
2149
2150
10
  Diag(MemberLoc, diag::err_property_not_found)
2151
10
    << MemberName << QualType(OPT, 0);
2152
10
  if (Setter)
2153
0
    Diag(Setter->getLocation(), diag::note_getter_unavailable)
2154
0
          << MemberName << BaseExpr->getSourceRange();
2155
10
  return ExprError();
2156
13
}
2157
2158
ExprResult Sema::
2159
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
2160
                          IdentifierInfo &propertyName,
2161
                          SourceLocation receiverNameLoc,
2162
270
                          SourceLocation propertyNameLoc) {
2163
2164
270
  IdentifierInfo *receiverNamePtr = &receiverName;
2165
270
  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
2166
270
                                                  receiverNameLoc);
2167
2168
270
  QualType SuperType;
2169
270
  if (!IFace) {
2170
    // If the "receiver" is 'super' in a method, handle it as an expression-like
2171
    // property reference.
2172
77
    if (receiverNamePtr->isStr("super")) {
2173
77
      if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
2174
77
        if (auto classDecl = CurMethod->getClassInterface()) {
2175
76
          SuperType = QualType(classDecl->getSuperClassType(), 0);
2176
76
          if (CurMethod->isInstanceMethod()) {
2177
65
            if (SuperType.isNull()) {
2178
              // The current class does not have a superclass.
2179
1
              Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
2180
1
                << CurMethod->getClassInterface()->getIdentifier();
2181
1
              return ExprError();
2182
1
            }
2183
64
            QualType T = Context.getObjCObjectPointerType(SuperType);
2184
2185
64
            return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
2186
64
                                             /*BaseExpr*/nullptr,
2187
64
                                             SourceLocation()/*OpLoc*/,
2188
64
                                             &propertyName,
2189
64
                                             propertyNameLoc,
2190
64
                                             receiverNameLoc, T, true);
2191
65
          }
2192
2193
          // Otherwise, if this is a class method, try dispatching to our
2194
          // superclass.
2195
11
          IFace = CurMethod->getClassInterface()->getSuperClass();
2196
11
        }
2197
77
      }
2198
77
    }
2199
2200
12
    if (!IFace) {
2201
1
      Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2202
1
                                                       << tok::l_paren;
2203
1
      return ExprError();
2204
1
    }
2205
12
  }
2206
2207
204
  Selector GetterSel;
2208
204
  Selector SetterSel;
2209
204
  if (auto PD = IFace->FindPropertyDeclaration(
2210
204
          &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2211
99
    GetterSel = PD->getGetterName();
2212
99
    SetterSel = PD->getSetterName();
2213
105
  } else {
2214
105
    GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2215
105
    SetterSel = SelectorTable::constructSetterSelector(
2216
105
        PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2217
105
  }
2218
2219
  // Search for a declared property first.
2220
204
  ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2221
2222
  // If this reference is in an @implementation, check for 'private' methods.
2223
204
  if (!Getter)
2224
20
    Getter = IFace->lookupPrivateClassMethod(GetterSel);
2225
2226
204
  if (Getter) {
2227
    // FIXME: refactor/share with ActOnMemberReference().
2228
    // Check if we can reference this property.
2229
196
    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2230
0
      return ExprError();
2231
196
  }
2232
2233
  // Look for the matching setter, in case it is needed.
2234
204
  ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2235
204
  if (!Setter) {
2236
    // If this reference is in an @implementation, also check for 'private'
2237
    // methods.
2238
69
    Setter = IFace->lookupPrivateClassMethod(SetterSel);
2239
69
  }
2240
  // Look through local category implementations associated with the class.
2241
204
  if (!Setter)
2242
55
    Setter = IFace->getCategoryClassMethod(SetterSel);
2243
2244
204
  if (Setter && 
DiagnoseUseOfDecl(Setter, propertyNameLoc)149
)
2245
0
    return ExprError();
2246
2247
204
  if (Getter || 
Setter8
) {
2248
203
    if (!SuperType.isNull())
2249
11
      return new (Context)
2250
11
          ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2251
11
                              OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2252
11
                              SuperType);
2253
2254
192
    return new (Context) ObjCPropertyRefExpr(
2255
192
        Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2256
192
        propertyNameLoc, receiverNameLoc, IFace);
2257
203
  }
2258
1
  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2259
1
                     << &propertyName << Context.getObjCInterfaceType(IFace));
2260
204
}
2261
2262
namespace {
2263
2264
class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
2265
 public:
2266
13
  ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2267
    // Determine whether "super" is acceptable in the current context.
2268
13
    if (Method && 
Method->getClassInterface()7
)
2269
7
      WantObjCSuper = Method->getClassInterface()->getSuperClass();
2270
13
  }
2271
2272
16
  bool ValidateCandidate(const TypoCorrection &candidate) override {
2273
16
    return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2274
16
        
candidate.isKeyword("super")8
;
2275
16
  }
2276
2277
13
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
2278
13
    return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
2279
13
  }
2280
};
2281
2282
} // end anonymous namespace
2283
2284
Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2285
                                               IdentifierInfo *Name,
2286
                                               SourceLocation NameLoc,
2287
                                               bool IsSuper,
2288
                                               bool HasTrailingDot,
2289
16.0k
                                               ParsedType &ReceiverType) {
2290
16.0k
  ReceiverType = nullptr;
2291
2292
  // If the identifier is "super" and there is no trailing dot, we're
2293
  // messaging super. If the identifier is "super" and there is a
2294
  // trailing dot, it's an instance message.
2295
16.0k
  if (IsSuper && 
S->isInObjcMethodScope()1.12k
)
2296
1.04k
    return HasTrailingDot? 
ObjCInstanceMessage4
:
ObjCSuperMessage1.03k
;
2297
2298
15.0k
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2299
15.0k
  LookupName(Result, S);
2300
2301
15.0k
  switch (Result.getResultKind()) {
2302
416
  case LookupResult::NotFound:
2303
    // Normal name lookup didn't find anything. If we're in an
2304
    // Objective-C method, look for ivars. If we find one, we're done!
2305
    // FIXME: This is a hack. Ivar lookup should be part of normal
2306
    // lookup.
2307
416
    if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2308
410
      if (!Method->getClassInterface()) {
2309
        // Fall back: let the parser try to parse it as an instance message.
2310
1
        return ObjCInstanceMessage;
2311
1
      }
2312
2313
409
      ObjCInterfaceDecl *ClassDeclared;
2314
409
      if (Method->getClassInterface()->lookupInstanceVariable(Name,
2315
409
                                                              ClassDeclared))
2316
402
        return ObjCInstanceMessage;
2317
409
    }
2318
2319
    // Break out; we'll perform typo correction below.
2320
13
    break;
2321
2322
13
  case LookupResult::NotFoundInCurrentInstantiation:
2323
0
  case LookupResult::FoundOverloaded:
2324
0
  case LookupResult::FoundUnresolvedValue:
2325
0
  case LookupResult::Ambiguous:
2326
0
    Result.suppressDiagnostics();
2327
0
    return ObjCInstanceMessage;
2328
2329
14.6k
  case LookupResult::Found: {
2330
    // If the identifier is a class or not, and there is a trailing dot,
2331
    // it's an instance message.
2332
14.6k
    if (HasTrailingDot)
2333
69
      return ObjCInstanceMessage;
2334
    // We found something. If it's a type, then we have a class
2335
    // message. Otherwise, it's an instance message.
2336
14.5k
    NamedDecl *ND = Result.getFoundDecl();
2337
14.5k
    QualType T;
2338
14.5k
    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2339
5.89k
      T = Context.getObjCInterfaceType(Class);
2340
8.65k
    else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2341
87
      T = Context.getTypeDeclType(Type);
2342
87
      DiagnoseUseOfDecl(Type, NameLoc);
2343
87
    }
2344
8.56k
    else
2345
8.56k
      return ObjCInstanceMessage;
2346
2347
    //  We have a class message, and T is the type we're
2348
    //  messaging. Build source-location information for it.
2349
5.98k
    TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2350
5.98k
    ReceiverType = CreateParsedType(T, TSInfo);
2351
5.98k
    return ObjCClassMessage;
2352
14.5k
  }
2353
15.0k
  }
2354
2355
13
  ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
2356
13
  if (TypoCorrection Corrected = CorrectTypo(
2357
13
          Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
2358
13
          CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2359
8
    if (Corrected.isKeyword()) {
2360
      // If we've found the keyword "super" (the only keyword that would be
2361
      // returned by CorrectTypo), this is a send to super.
2362
4
      diagnoseTypo(Corrected,
2363
4
                   PDiag(diag::err_unknown_receiver_suggest) << Name);
2364
4
      return ObjCSuperMessage;
2365
4
    } else if (ObjCInterfaceDecl *Class =
2366
4
                   Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2367
      // If we found a declaration, correct when it refers to an Objective-C
2368
      // class.
2369
4
      diagnoseTypo(Corrected,
2370
4
                   PDiag(diag::err_unknown_receiver_suggest) << Name);
2371
4
      QualType T = Context.getObjCInterfaceType(Class);
2372
4
      TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2373
4
      ReceiverType = CreateParsedType(T, TSInfo);
2374
4
      return ObjCClassMessage;
2375
4
    }
2376
8
  }
2377
2378
  // Fall back: let the parser try to parse it as an instance message.
2379
5
  return ObjCInstanceMessage;
2380
13
}
2381
2382
ExprResult Sema::ActOnSuperMessage(Scope *S,
2383
                                   SourceLocation SuperLoc,
2384
                                   Selector Sel,
2385
                                   SourceLocation LBracLoc,
2386
                                   ArrayRef<SourceLocation> SelectorLocs,
2387
                                   SourceLocation RBracLoc,
2388
1.17k
                                   MultiExprArg Args) {
2389
  // Determine whether we are inside a method or not.
2390
1.17k
  ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2391
1.17k
  if (!Method) {
2392
0
    Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2393
0
    return ExprError();
2394
0
  }
2395
2396
1.17k
  ObjCInterfaceDecl *Class = Method->getClassInterface();
2397
1.17k
  if (!Class) {
2398
1
    Diag(SuperLoc, diag::err_no_super_class_message)
2399
1
      << Method->getDeclName();
2400
1
    return ExprError();
2401
1
  }
2402
2403
1.17k
  QualType SuperTy(Class->getSuperClassType(), 0);
2404
1.17k
  if (SuperTy.isNull()) {
2405
    // The current class does not have a superclass.
2406
2
    Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2407
2
      << Class->getIdentifier();
2408
2
    return ExprError();
2409
2
  }
2410
2411
  // We are in a method whose class has a superclass, so 'super'
2412
  // is acting as a keyword.
2413
1.16k
  if (Method->getSelector() == Sel)
2414
585
    getCurFunction()->ObjCShouldCallSuper = false;
2415
2416
1.16k
  if (Method->isInstanceMethod()) {
2417
    // Since we are in an instance method, this is an instance
2418
    // message to the superclass instance.
2419
961
    SuperTy = Context.getObjCObjectPointerType(SuperTy);
2420
961
    return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2421
961
                                Sel, /*Method=*/nullptr,
2422
961
                                LBracLoc, SelectorLocs, RBracLoc, Args);
2423
961
  }
2424
2425
  // Since we are in a class method, this is a class message to
2426
  // the superclass.
2427
208
  return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2428
208
                           SuperTy,
2429
208
                           SuperLoc, Sel, /*Method=*/nullptr,
2430
208
                           LBracLoc, SelectorLocs, RBracLoc, Args);
2431
1.16k
}
2432
2433
ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2434
                                           bool isSuperReceiver,
2435
                                           SourceLocation Loc,
2436
                                           Selector Sel,
2437
                                           ObjCMethodDecl *Method,
2438
217
                                           MultiExprArg Args) {
2439
217
  TypeSourceInfo *receiverTypeInfo = nullptr;
2440
217
  if (!ReceiverType.isNull())
2441
217
    receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2442
2443
217
  return BuildClassMessage(receiverTypeInfo, ReceiverType,
2444
217
                          /*SuperLoc=*/isSuperReceiver ? 
Loc11
:
SourceLocation()206
,
2445
217
                           Sel, Method, Loc, Loc, Loc, Args,
2446
217
                           /*isImplicit=*/true);
2447
217
}
2448
2449
static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2450
                               unsigned DiagID,
2451
                               bool (*refactor)(const ObjCMessageExpr *,
2452
21.3k
                                              const NSAPI &, edit::Commit &)) {
2453
21.3k
  SourceLocation MsgLoc = Msg->getExprLoc();
2454
21.3k
  if (S.Diags.isIgnored(DiagID, MsgLoc))
2455
9.55k
    return;
2456
2457
11.8k
  SourceManager &SM = S.SourceMgr;
2458
11.8k
  edit::Commit ECommit(SM, S.LangOpts);
2459
11.8k
  if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2460
12
    auto Builder = S.Diag(MsgLoc, DiagID)
2461
12
                   << Msg->getSelector() << Msg->getSourceRange();
2462
    // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2463
12
    if (!ECommit.isCommitable())
2464
0
      return;
2465
12
    for (edit::Commit::edit_iterator
2466
36
           I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; 
++I24
) {
2467
24
      const edit::Commit::Edit &Edit = *I;
2468
24
      switch (Edit.Kind) {
2469
0
      case edit::Commit::Act_Insert:
2470
0
        Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2471
0
                                                        Edit.Text,
2472
0
                                                        Edit.BeforePrev));
2473
0
        break;
2474
0
      case edit::Commit::Act_InsertFromRange:
2475
0
        Builder.AddFixItHint(
2476
0
            FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2477
0
                                                Edit.getInsertFromRange(SM),
2478
0
                                                Edit.BeforePrev));
2479
0
        break;
2480
24
      case edit::Commit::Act_Remove:
2481
24
        Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2482
24
        break;
2483
24
      }
2484
24
    }
2485
12
  }
2486
11.8k
}
2487
2488
21.3k
static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2489
21.3k
  applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2490
21.3k
                     edit::rewriteObjCRedundantCallWithLiteral);
2491
21.3k
}
2492
2493
static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2494
                               const ObjCMethodDecl *Method,
2495
                               ArrayRef<Expr *> Args, QualType ReceiverType,
2496
24.1k
                               bool IsClassObjectCall) {
2497
  // Check if this is a performSelector method that uses a selector that returns
2498
  // a record or a vector type.
2499
24.1k
  if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2500
24.1k
      
Args.empty()44
)
2501
24.0k
    return;
2502
44
  const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2503
44
  if (!SE)
2504
2
    return;
2505
42
  ObjCMethodDecl *ImpliedMethod;
2506
42
  if (!IsClassObjectCall) {
2507
35
    const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2508
35
    if (!OPT || !OPT->getInterfaceDecl())
2509
10
      return;
2510
25
    ImpliedMethod =
2511
25
        OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2512
25
    if (!ImpliedMethod)
2513
5
      ImpliedMethod =
2514
5
          OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2515
25
  } else {
2516
7
    const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2517
7
    if (!IT)
2518
1
      return;
2519
6
    ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2520
6
    if (!ImpliedMethod)
2521
1
      ImpliedMethod =
2522
1
          IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2523
6
  }
2524
31
  if (!ImpliedMethod)
2525
4
    return;
2526
27
  QualType Ret = ImpliedMethod->getReturnType();
2527
27
  if (Ret->isRecordType() || 
Ret->isVectorType()15
||
Ret->isExtVectorType()13
) {
2528
14
    S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2529
14
        << Method->getSelector()
2530
14
        << (!Ret->isRecordType()
2531
14
                ? /*Vector*/ 
22
2532
14
                : 
Ret->isUnionType()12
? /*Union*/
12
: /*Struct*/
010
);
2533
14
    S.Diag(ImpliedMethod->getBeginLoc(),
2534
14
           diag::note_objc_unsafe_perform_selector_method_declared_here)
2535
14
        << ImpliedMethod->getSelector() << Ret;
2536
14
  }
2537
27
}
2538
2539
/// Diagnose use of %s directive in an NSString which is being passed
2540
/// as formatting string to formatting method.
2541
static void
2542
DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2543
                                        ObjCMethodDecl *Method,
2544
                                        Selector Sel,
2545
25.2k
                                        Expr **Args, unsigned NumArgs) {
2546
25.2k
  unsigned Idx = 0;
2547
25.2k
  bool Format = false;
2548
25.2k
  ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2549
25.2k
  if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2550
698
    Idx = 0;
2551
698
    Format = true;
2552
698
  }
2553
24.5k
  else if (Method) {
2554
23.4k
    for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2555
15
      if (S.GetFormatNSStringIdx(I, Idx)) {
2556
14
        Format = true;
2557
14
        break;
2558
14
      }
2559
15
    }
2560
23.4k
  }
2561
25.2k
  if (!Format || 
NumArgs <= Idx712
)
2562
24.5k
    return;
2563
2564
709
  Expr *FormatExpr = Args[Idx];
2565
709
  if (ObjCStringLiteral *OSL =
2566
709
      dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2567
686
    StringLiteral *FormatString = OSL->getString();
2568
686
    if (S.FormatStringHasSArg(FormatString)) {
2569
92
      S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2570
92
        << "%s" << 0 << 0;
2571
92
      if (Method)
2572
92
        S.Diag(Method->getLocation(), diag::note_method_declared_at)
2573
92
          << Method->getDeclName();
2574
92
    }
2575
686
  }
2576
709
}
2577
2578
/// Build an Objective-C class message expression.
2579
///
2580
/// This routine takes care of both normal class messages and
2581
/// class messages to the superclass.
2582
///
2583
/// \param ReceiverTypeInfo Type source information that describes the
2584
/// receiver of this message. This may be NULL, in which case we are
2585
/// sending to the superclass and \p SuperLoc must be a valid source
2586
/// location.
2587
2588
/// \param ReceiverType The type of the object receiving the
2589
/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2590
/// type as that refers to. For a superclass send, this is the type of
2591
/// the superclass.
2592
///
2593
/// \param SuperLoc The location of the "super" keyword in a
2594
/// superclass message.
2595
///
2596
/// \param Sel The selector to which the message is being sent.
2597
///
2598
/// \param Method The method that this class message is invoking, if
2599
/// already known.
2600
///
2601
/// \param LBracLoc The location of the opening square bracket ']'.
2602
///
2603
/// \param RBracLoc The location of the closing square bracket ']'.
2604
///
2605
/// \param ArgsIn The message arguments.
2606
ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2607
                                   QualType ReceiverType,
2608
                                   SourceLocation SuperLoc,
2609
                                   Selector Sel,
2610
                                   ObjCMethodDecl *Method,
2611
                                   SourceLocation LBracLoc,
2612
                                   ArrayRef<SourceLocation> SelectorLocs,
2613
                                   SourceLocation RBracLoc,
2614
                                   MultiExprArg ArgsIn,
2615
7.82k
                                   bool isImplicit) {
2616
7.82k
  SourceLocation Loc = SuperLoc.isValid()? 
SuperLoc220
2617
7.82k
    : 
ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin()7.60k
;
2618
7.82k
  if (LBracLoc.isInvalid()) {
2619
247
    Diag(Loc, diag::err_missing_open_square_message_send)
2620
247
      << FixItHint::CreateInsertion(Loc, "[");
2621
247
    LBracLoc = Loc;
2622
247
  }
2623
7.82k
  ArrayRef<SourceLocation> SelectorSlotLocs;
2624
7.82k
  if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2625
7.82k
    SelectorSlotLocs = SelectorLocs;
2626
0
  else
2627
0
    SelectorSlotLocs = Loc;
2628
7.82k
  SourceLocation SelLoc = SelectorSlotLocs.front();
2629
2630
7.82k
  if (ReceiverType->isDependentType()) {
2631
    // If the receiver type is dependent, we can't type-check anything
2632
    // at this point. Build a dependent expression.
2633
2
    unsigned NumArgs = ArgsIn.size();
2634
2
    Expr **Args = ArgsIn.data();
2635
2
    assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2636
0
    return ObjCMessageExpr::Create(
2637
2
        Context, ReceiverType, VK_PRValue, LBracLoc, ReceiverTypeInfo, Sel,
2638
2
        SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2639
2
        isImplicit);
2640
2
  }
2641
2642
  // Find the class to which we are sending this message.
2643
7.82k
  ObjCInterfaceDecl *Class = nullptr;
2644
7.82k
  const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2645
7.82k
  if (!ClassType || 
!(Class = ClassType->getInterface())7.81k
) {
2646
12
    Diag(Loc, diag::err_invalid_receiver_class_message)
2647
12
      << ReceiverType;
2648
12
    return ExprError();
2649
12
  }
2650
7.81k
  assert(Class && "We don't know which class we're messaging?");
2651
  // objc++ diagnoses during typename annotation.
2652
7.81k
  if (!getLangOpts().CPlusPlus)
2653
6.39k
    (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
2654
  // Find the method we are messaging.
2655
7.81k
  if (!Method) {
2656
7.58k
    SourceRange TypeRange
2657
7.58k
      = SuperLoc.isValid()? 
SourceRange(SuperLoc)208
2658
7.58k
                          : 
ReceiverTypeInfo->getTypeLoc().getSourceRange()7.37k
;
2659
7.58k
    if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2660
7.58k
                            (getLangOpts().ObjCAutoRefCount
2661
7.58k
                               ? 
diag::err_arc_receiver_forward_class350
2662
7.58k
                               : 
diag::warn_receiver_forward_class7.23k
),
2663
7.58k
                            TypeRange)) {
2664
      // A forward class used in messaging is treated as a 'Class'
2665
38
      Method = LookupFactoryMethodInGlobalPool(Sel,
2666
38
                                               SourceRange(LBracLoc, RBracLoc));
2667
38
      if (Method && 
!getLangOpts().ObjCAutoRefCount35
)
2668
33
        Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2669
33
          << Method->getDeclName();
2670
38
    }
2671
7.58k
    if (!Method)
2672
7.54k
      Method = Class->lookupClassMethod(Sel);
2673
2674
    // If we have an implementation in scope, check "private" methods.
2675
7.58k
    if (!Method)
2676
309
      Method = Class->lookupPrivateClassMethod(Sel);
2677
2678
7.58k
    if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2679
7.47k
                                    nullptr, false, false, Class))
2680
0
      return ExprError();
2681
7.58k
  }
2682
2683
  // Check the argument types and determine the result type.
2684
7.81k
  QualType ReturnType;
2685
7.81k
  ExprValueKind VK = VK_PRValue;
2686
2687
7.81k
  unsigned NumArgs = ArgsIn.size();
2688
7.81k
  Expr **Args = ArgsIn.data();
2689
7.81k
  if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2690
7.81k
                                MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2691
7.81k
                                Method, true, SuperLoc.isValid(), LBracLoc,
2692
7.81k
                                RBracLoc, SourceRange(), ReturnType, VK))
2693
4
    return ExprError();
2694
2695
7.80k
  if (Method && 
!Method->getReturnType()->isVoidType()7.69k
&&
2696
7.80k
      RequireCompleteType(LBracLoc, Method->getReturnType(),
2697
7.25k
                          diag::err_illegal_message_expr_incomplete_type))
2698
3
    return ExprError();
2699
2700
7.80k
  if (Method && 
Method->isDirectMethod()7.69k
&&
SuperLoc.isValid()4
) {
2701
3
    Diag(SuperLoc, diag::err_messaging_super_with_direct_method)
2702
3
        << FixItHint::CreateReplacement(
2703
3
               SuperLoc, getLangOpts().ObjCAutoRefCount
2704
3
                             ? 
"self"1
2705
3
                             : 
Method->getClassInterface()->getName()2
);
2706
3
    Diag(Method->getLocation(), diag::note_direct_method_declared_at)
2707
3
        << Method->getDeclName();
2708
3
  }
2709
2710
  // Warn about explicit call of +initialize on its own class. But not on 'super'.
2711
7.80k
  if (Method && 
Method->getMethodFamily() == OMF_initialize7.69k
) {
2712
7
    if (!SuperLoc.isValid()) {
2713
5
      const ObjCInterfaceDecl *ID =
2714
5
        dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2715
5
      if (ID == Class) {
2716
2
        Diag(Loc, diag::warn_direct_initialize_call);
2717
2
        Diag(Method->getLocation(), diag::note_method_declared_at)
2718
2
          << Method->getDeclName();
2719
2
      }
2720
5
    }
2721
2
    else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2722
      // [super initialize] is allowed only within an +initialize implementation
2723
2
      if (CurMeth->getMethodFamily() != OMF_initialize) {
2724
1
        Diag(Loc, diag::warn_direct_super_initialize_call);
2725
1
        Diag(Method->getLocation(), diag::note_method_declared_at)
2726
1
          << Method->getDeclName();
2727
1
        Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2728
1
        << CurMeth->getDeclName();
2729
1
      }
2730
2
    }
2731
7
  }
2732
2733
7.80k
  DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2734
2735
  // Construct the appropriate ObjCMessageExpr.
2736
7.80k
  ObjCMessageExpr *Result;
2737
7.80k
  if (SuperLoc.isValid())
2738
220
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2739
220
                                     SuperLoc, /*IsInstanceSuper=*/false,
2740
220
                                     ReceiverType, Sel, SelectorLocs,
2741
220
                                     Method, makeArrayRef(Args, NumArgs),
2742
220
                                     RBracLoc, isImplicit);
2743
7.58k
  else {
2744
7.58k
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2745
7.58k
                                     ReceiverTypeInfo, Sel, SelectorLocs,
2746
7.58k
                                     Method, makeArrayRef(Args, NumArgs),
2747
7.58k
                                     RBracLoc, isImplicit);
2748
7.58k
    if (!isImplicit)
2749
7.37k
      checkCocoaAPI(*this, Result);
2750
7.58k
  }
2751
7.80k
  if (Method)
2752
7.69k
    checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2753
7.69k
                       ReceiverType, /*IsClassObjectCall=*/true);
2754
7.80k
  return MaybeBindToTemporary(Result);
2755
7.80k
}
2756
2757
// ActOnClassMessage - used for both unary and keyword messages.
2758
// ArgExprs is optional - if it is present, the number of expressions
2759
// is obtained from Sel.getNumArgs().
2760
ExprResult Sema::ActOnClassMessage(Scope *S,
2761
                                   ParsedType Receiver,
2762
                                   Selector Sel,
2763
                                   SourceLocation LBracLoc,
2764
                                   ArrayRef<SourceLocation> SelectorLocs,
2765
                                   SourceLocation RBracLoc,
2766
7.38k
                                   MultiExprArg Args) {
2767
7.38k
  TypeSourceInfo *ReceiverTypeInfo;
2768
7.38k
  QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2769
7.38k
  if (ReceiverType.isNull())
2770
0
    return ExprError();
2771
2772
7.38k
  if (!ReceiverTypeInfo)
2773
0
    ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2774
2775
7.38k
  return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2776
7.38k
                           /*SuperLoc=*/SourceLocation(), Sel,
2777
7.38k
                           /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2778
7.38k
                           Args);
2779
7.38k
}
2780
2781
ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2782
                                              QualType ReceiverType,
2783
                                              SourceLocation Loc,
2784
                                              Selector Sel,
2785
                                              ObjCMethodDecl *Method,
2786
2.53k
                                              MultiExprArg Args) {
2787
2.53k
  return BuildInstanceMessage(Receiver, ReceiverType,
2788
2.53k
                              /*SuperLoc=*/!Receiver ? 
Loc63
:
SourceLocation()2.46k
,
2789
2.53k
                              Sel, Method, Loc, Loc, Loc, Args,
2790
2.53k
                              /*isImplicit=*/true);
2791
2.53k
}
2792
2793
4
static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2794
4
  if (!S.NSAPIObj)
2795
0
    return false;
2796
4
  const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2797
4
  if (!Protocol)
2798
0
    return false;
2799
4
  const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2800
4
  if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2801
4
          S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
2802
4
                             Sema::LookupOrdinaryName))) {
2803
2
    for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2804
2
      if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2805
1
        return true;
2806
2
    }
2807
2
  }
2808
3
  return false;
2809
4
}
2810
2811
/// Build an Objective-C instance message expression.
2812
///
2813
/// This routine takes care of both normal instance messages and
2814
/// instance messages to the superclass instance.
2815
///
2816
/// \param Receiver The expression that computes the object that will
2817
/// receive this message. This may be empty, in which case we are
2818
/// sending to the superclass instance and \p SuperLoc must be a valid
2819
/// source location.
2820
///
2821
/// \param ReceiverType The (static) type of the object receiving the
2822
/// message. When a \p Receiver expression is provided, this is the
2823
/// same type as that expression. For a superclass instance send, this
2824
/// is a pointer to the type of the superclass.
2825
///
2826
/// \param SuperLoc The location of the "super" keyword in a
2827
/// superclass instance message.
2828
///
2829
/// \param Sel The selector to which the message is being sent.
2830
///
2831
/// \param Method The method that this instance message is invoking, if
2832
/// already known.
2833
///
2834
/// \param LBracLoc The location of the opening square bracket ']'.
2835
///
2836
/// \param RBracLoc The location of the closing square bracket ']'.
2837
///
2838
/// \param ArgsIn The message arguments.
2839
ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2840
                                      QualType ReceiverType,
2841
                                      SourceLocation SuperLoc,
2842
                                      Selector Sel,
2843
                                      ObjCMethodDecl *Method,
2844
                                      SourceLocation LBracLoc,
2845
                                      ArrayRef<SourceLocation> SelectorLocs,
2846
                                      SourceLocation RBracLoc,
2847
                                      MultiExprArg ArgsIn,
2848
17.5k
                                      bool isImplicit) {
2849
17.5k
  assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2850
17.5k
                                             "SuperLoc must be valid so we can "
2851
17.5k
                                             "use it instead.");
2852
2853
  // The location of the receiver.
2854
17.5k
  SourceLocation Loc = SuperLoc.isValid() ? 
SuperLoc1.02k
:
Receiver->getBeginLoc()16.5k
;
2855
17.5k
  SourceRange RecRange =
2856
17.5k
      SuperLoc.isValid()? 
SuperLoc1.02k
:
Receiver->getSourceRange()16.5k
;
2857
17.5k
  ArrayRef<SourceLocation> SelectorSlotLocs;
2858
17.5k
  if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2859
17.5k
    SelectorSlotLocs = SelectorLocs;
2860
0
  else
2861
0
    SelectorSlotLocs = Loc;
2862
17.5k
  SourceLocation SelLoc = SelectorSlotLocs.front();
2863
2864
17.5k
  if (LBracLoc.isInvalid()) {
2865
176
    Diag(Loc, diag::err_missing_open_square_message_send)
2866
176
      << FixItHint::CreateInsertion(Loc, "[");
2867
176
    LBracLoc = Loc;
2868
176
  }
2869
2870
  // If we have a receiver expression, perform appropriate promotions
2871
  // and determine receiver type.
2872
17.5k
  if (Receiver) {
2873
16.5k
    if (Receiver->hasPlaceholderType()) {
2874
110
      ExprResult Result;
2875
110
      if (Receiver->getType() == Context.UnknownAnyTy)
2876
12
        Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2877
98
      else
2878
98
        Result = CheckPlaceholderExpr(Receiver);
2879
110
      if (Result.isInvalid()) 
return ExprError()0
;
2880
110
      Receiver = Result.get();
2881
110
    }
2882
2883
16.5k
    if (Receiver->isTypeDependent()) {
2884
      // If the receiver is type-dependent, we can't type-check anything
2885
      // at this point. Build a dependent expression.
2886
4
      unsigned NumArgs = ArgsIn.size();
2887
4
      Expr **Args = ArgsIn.data();
2888
4
      assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2889
0
      return ObjCMessageExpr::Create(
2890
4
          Context, Context.DependentTy, VK_PRValue, LBracLoc, Receiver, Sel,
2891
4
          SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2892
4
          RBracLoc, isImplicit);
2893
4
    }
2894
2895
    // If necessary, apply function/array conversion to the receiver.
2896
    // C99 6.7.5.3p[7,8].
2897
16.5k
    ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2898
16.5k
    if (Result.isInvalid())
2899
0
      return ExprError();
2900
16.5k
    Receiver = Result.get();
2901
16.5k
    ReceiverType = Receiver->getType();
2902
2903
    // If the receiver is an ObjC pointer, a block pointer, or an
2904
    // __attribute__((NSObject)) pointer, we don't need to do any
2905
    // special conversion in order to look up a receiver.
2906
16.5k
    if (ReceiverType->isObjCRetainableType()) {
2907
      // do nothing
2908
16.4k
    } else 
if (52
!getLangOpts().ObjCAutoRefCount52
&&
2909
52
               
!Context.getObjCIdType().isNull()51
&&
2910
52
               
(51
ReceiverType->isPointerType()51
||
2911
51
                
ReceiverType->isIntegerType()17
)) {
2912
      // Implicitly convert integers and pointers to 'id' but emit a warning.
2913
      // But not in ARC.
2914
40
      Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << RecRange;
2915
40
      if (ReceiverType->isPointerType()) {
2916
34
        Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2917
34
                                     CK_CPointerToObjCPointerCast).get();
2918
34
      } else {
2919
        // TODO: specialized warning on null receivers?
2920
6
        bool IsNull = Receiver->isNullPointerConstant(Context,
2921
6
                                              Expr::NPC_ValueDependentIsNull);
2922
6
        CastKind Kind = IsNull ? 
CK_NullToPointer0
: CK_IntegralToPointer;
2923
6
        Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2924
6
                                     Kind).get();
2925
6
      }
2926
40
      ReceiverType = Receiver->getType();
2927
40
    } else 
if (12
getLangOpts().CPlusPlus12
) {
2928
      // The receiver must be a complete type.
2929
10
      if (RequireCompleteType(Loc, Receiver->getType(),
2930
10
                              diag::err_incomplete_receiver_type))
2931
1
        return ExprError();
2932
2933
9
      ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2934
9
      if (result.isUsable()) {
2935
9
        Receiver = result.get();
2936
9
        ReceiverType = Receiver->getType();
2937
9
      }
2938
9
    }
2939
16.5k
  }
2940
2941
  // There's a somewhat weird interaction here where we assume that we
2942
  // won't actually have a method unless we also don't need to do some
2943
  // of the more detailed type-checking on the receiver.
2944
2945
17.5k
  if (!Method) {
2946
    // Handle messages to id and __kindof types (where we use the
2947
    // global method pool).
2948
14.9k
    const ObjCObjectType *typeBound = nullptr;
2949
14.9k
    bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2950
14.9k
                                                                     typeBound);
2951
14.9k
    if (receiverIsIdLike || 
ReceiverType->isBlockPointerType()13.0k
||
2952
14.9k
        
(13.0k
Receiver13.0k
&&
Context.isObjCNSObjectType(Receiver->getType())12.0k
)) {
2953
1.94k
      SmallVector<ObjCMethodDecl*, 4> Methods;
2954
      // If we have a type bound, further filter the methods.
2955
1.94k
      CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2956
1.94k
                                         true/*CheckTheOther*/, typeBound);
2957
1.94k
      if (!Methods.empty()) {
2958
        // We choose the first method as the initial candidate, then try to
2959
        // select a better one.
2960
1.24k
        Method = Methods[0];
2961
2962
1.24k
        if (ObjCMethodDecl *BestMethod =
2963
1.24k
            SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2964
130
          Method = BestMethod;
2965
2966
1.24k
        if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2967
1.24k
                                            SourceRange(LBracLoc, RBracLoc),
2968
1.24k
                                            receiverIsIdLike, Methods))
2969
1.10k
          DiagnoseUseOfDecl(Method, SelectorSlotLocs);
2970
1.24k
      }
2971
13.0k
    } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2972
13.0k
               
ReceiverType->isObjCQualifiedClassType()12.8k
) {
2973
      // Handle messages to Class.
2974
      // We allow sending a message to a qualified Class ("Class<foo>"), which
2975
      // is ok as long as one of the protocols implements the selector (if not,
2976
      // warn).
2977
253
      if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2978
10
        const ObjCObjectPointerType *QClassTy
2979
10
          = ReceiverType->getAsObjCQualifiedClassType();
2980
        // Search protocols for class methods.
2981
10
        Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2982
10
        if (!Method) {
2983
6
          Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2984
          // warn if instance method found for a Class message.
2985
6
          if (Method && 
!isMethodDeclaredInRootProtocol(*this, Method)4
) {
2986
3
            Diag(SelLoc, diag::warn_instance_method_on_class_found)
2987
3
              << Method->getSelector() << Sel;
2988
3
            Diag(Method->getLocation(), diag::note_method_declared_at)
2989
3
              << Method->getDeclName();
2990
3
          }
2991
6
        }
2992
243
      } else {
2993
243
        if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2994
200
          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2995
            // As a guess, try looking for the method in the current interface.
2996
            // This very well may not produce the "right" method.
2997
2998
            // First check the public methods in the class interface.
2999
200
            Method = ClassDecl->lookupClassMethod(Sel);
3000
3001
200
            if (!Method)
3002
34
              Method = ClassDecl->lookupPrivateClassMethod(Sel);
3003
3004
200
            if (Method && 
DiagnoseUseOfDecl(Method, SelectorSlotLocs)194
)
3005
0
              return ExprError();
3006
200
          }
3007
200
        }
3008
243
        if (!Method) {
3009
          // If not messaging 'self', look for any factory method named 'Sel'.
3010
49
          if (!Receiver || !isSelfExpr(Receiver)) {
3011
            // If no class (factory) method was found, check if an _instance_
3012
            // method of the same name exists in the root class only.
3013
44
            SmallVector<ObjCMethodDecl*, 4> Methods;
3014
44
            CollectMultipleMethodsInGlobalPool(Sel, Methods,
3015
44
                                               false/*InstanceFirst*/,
3016
44
                                               true/*CheckTheOther*/);
3017
44
            if (!Methods.empty()) {
3018
              // We choose the first method as the initial candidate, then try
3019
              // to select a better one.
3020
43
              Method = Methods[0];
3021
3022
              // If we find an instance method, emit warning.
3023
43
              if (Method->isInstanceMethod()) {
3024
3
                if (const ObjCInterfaceDecl *ID =
3025
3
                    dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
3026
2
                  if (ID->getSuperClass())
3027
1
                    Diag(SelLoc, diag::warn_root_inst_method_not_found)
3028
1
                        << Sel << SourceRange(LBracLoc, RBracLoc);
3029
2
                }
3030
3
              }
3031
3032
43
             if (ObjCMethodDecl *BestMethod =
3033
43
                 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3034
43
                                  Methods))
3035
3
               Method = BestMethod;
3036
43
            }
3037
44
          }
3038
49
        }
3039
243
      }
3040
12.7k
    } else {
3041
12.7k
      ObjCInterfaceDecl *ClassDecl = nullptr;
3042
3043
      // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
3044
      // long as one of the protocols implements the selector (if not, warn).
3045
      // And as long as message is not deprecated/unavailable (warn if it is).
3046
12.7k
      if (const ObjCObjectPointerType *QIdTy
3047
12.7k
                                   = ReceiverType->getAsObjCQualifiedIdType()) {
3048
        // Search protocols for instance methods.
3049
222
        Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
3050
222
        if (!Method)
3051
32
          Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
3052
222
        if (Method && 
DiagnoseUseOfDecl(Method, SelectorSlotLocs)192
)
3053
0
          return ExprError();
3054
12.5k
      } else if (const ObjCObjectPointerType *OCIType
3055
12.5k
                   = ReceiverType->getAsObjCInterfacePointerType()) {
3056
        // We allow sending a message to a pointer to an interface (an object).
3057
12.5k
        ClassDecl = OCIType->getInterfaceDecl();
3058
3059
        // Try to complete the type. Under ARC, this is a hard error from which
3060
        // we don't try to recover.
3061
        // FIXME: In the non-ARC case, this will still be a hard error if the
3062
        // definition is found in a module that's not visible.
3063
12.5k
        const ObjCInterfaceDecl *forwardClass = nullptr;
3064
12.5k
        if (RequireCompleteType(Loc, OCIType->getPointeeType(),
3065
12.5k
                                getLangOpts().ObjCAutoRefCount
3066
12.5k
                                    ? 
diag::err_arc_receiver_forward_instance952
3067
12.5k
                                    : 
diag::warn_receiver_forward_instance11.6k
,
3068
12.5k
                                RecRange)) {
3069
68
          if (getLangOpts().ObjCAutoRefCount)
3070
4
            return ExprError();
3071
3072
64
          forwardClass = OCIType->getInterfaceDecl();
3073
64
          Diag(Receiver ? Receiver->getBeginLoc() : 
SuperLoc0
,
3074
64
               diag::note_receiver_is_id);
3075
64
          Method = nullptr;
3076
12.4k
        } else {
3077
12.4k
          Method = ClassDecl->lookupInstanceMethod(Sel);
3078
12.4k
        }
3079
3080
12.5k
        if (!Method)
3081
          // Search protocol qualifiers.
3082
2.92k
          Method = LookupMethodInQualifiedType(Sel, OCIType, true);
3083
3084
12.5k
        if (!Method) {
3085
          // If we have implementations in scope, check "private" methods.
3086
2.89k
          Method = ClassDecl->lookupPrivateMethod(Sel);
3087
3088
2.89k
          if (!Method && 
getLangOpts().ObjCAutoRefCount2.66k
) {
3089
3
            Diag(SelLoc, diag::err_arc_may_not_respond)
3090
3
              << OCIType->getPointeeType() << Sel << RecRange
3091
3
              << SourceRange(SelectorLocs.front(), SelectorLocs.back());
3092
3
            return ExprError();
3093
3
          }
3094
3095
2.89k
          if (!Method && 
(2.66k
!Receiver2.66k
||
!isSelfExpr(Receiver)2.63k
)) {
3096
            // If we still haven't found a method, look in the global pool. This
3097
            // behavior isn't very desirable, however we need it for GCC
3098
            // compatibility. FIXME: should we deviate??
3099
2.64k
            if (OCIType->qual_empty()) {
3100
2.62k
              SmallVector<ObjCMethodDecl*, 4> Methods;
3101
2.62k
              CollectMultipleMethodsInGlobalPool(Sel, Methods,
3102
2.62k
                                                 true/*InstanceFirst*/,
3103
2.62k
                                                 false/*CheckTheOther*/);
3104
2.62k
              if (!Methods.empty()) {
3105
                // We choose the first method as the initial candidate, then try
3106
                // to select a better one.
3107
2.31k
                Method = Methods[0];
3108
3109
2.31k
                if (ObjCMethodDecl *BestMethod =
3110
2.31k
                    SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3111
2.31k
                                     Methods))
3112
2.17k
                  Method = BestMethod;
3113
3114
2.31k
                AreMultipleMethodsInGlobalPool(Sel, Method,
3115
2.31k
                                               SourceRange(LBracLoc, RBracLoc),
3116
2.31k
                                               true/*receiverIdOrClass*/,
3117
2.31k
                                               Methods);
3118
2.31k
              }
3119
2.62k
              if (Method && 
!forwardClass2.31k
)
3120
2.25k
                Diag(SelLoc, diag::warn_maynot_respond)
3121
2.25k
                  << OCIType->getInterfaceDecl()->getIdentifier()
3122
2.25k
                  << Sel << RecRange;
3123
2.62k
            }
3124
2.64k
          }
3125
2.89k
        }
3126
12.5k
        if (Method && 
DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass)12.2k
)
3127
0
          return ExprError();
3128
12.5k
      } else {
3129
        // Reject other random receiver types (e.g. structs).
3130
2
        Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << RecRange;
3131
2
        return ExprError();
3132
2
      }
3133
12.7k
    }
3134
14.9k
  }
3135
3136
17.5k
  FunctionScopeInfo *DIFunctionScopeInfo =
3137
17.5k
    (Method && 
Method->getMethodFamily() == OMF_init16.4k
)
3138
17.5k
      ? 
getEnclosingFunction()2.65k
:
nullptr14.8k
;
3139
3140
17.5k
  if (Method && 
Method->isDirectMethod()16.4k
) {
3141
81
    if (ReceiverType->isObjCIdType() && 
!isImplicit1
) {
3142
1
      Diag(Receiver->getExprLoc(),
3143
1
           diag::err_messaging_unqualified_id_with_direct_method);
3144
1
      Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3145
1
          << Method->getDeclName();
3146
1
    }
3147
3148
    // Under ARC, self can't be assigned, and doing a direct call to `self`
3149
    // when it's a Class is hence safe.  For other cases, we can't trust `self`
3150
    // is what we think it is, so we reject it.
3151
81
    if (ReceiverType->isObjCClassType() && 
!isImplicit9
&&
3152
81
        
!(9
Receiver->isObjCSelfExpr()9
&&
getLangOpts().ObjCAutoRefCount7
)) {
3153
4
      {
3154
4
        auto Builder = Diag(Receiver->getExprLoc(),
3155
4
                            diag::err_messaging_class_with_direct_method);
3156
4
        if (Receiver->isObjCSelfExpr()) {
3157
2
          Builder.AddFixItHint(FixItHint::CreateReplacement(
3158
2
              RecRange, Method->getClassInterface()->getName()));
3159
2
        }
3160
4
      }
3161
4
      Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3162
4
          << Method->getDeclName();
3163
4
    }
3164
3165
81
    if (SuperLoc.isValid()) {
3166
3
      {
3167
3
        auto Builder =
3168
3
            Diag(SuperLoc, diag::err_messaging_super_with_direct_method);
3169
3
        if (ReceiverType->isObjCClassType()) {
3170
0
          Builder.AddFixItHint(FixItHint::CreateReplacement(
3171
0
              SuperLoc, Method->getClassInterface()->getName()));
3172
3
        } else {
3173
3
          Builder.AddFixItHint(FixItHint::CreateReplacement(SuperLoc, "self"));
3174
3
        }
3175
3
      }
3176
3
      Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3177
3
          << Method->getDeclName();
3178
3
    }
3179
17.4k
  } else if (ReceiverType->isObjCIdType() && 
!isImplicit1.91k
) {
3180
1.89k
    Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
3181
1.89k
  }
3182
3183
17.5k
  if (DIFunctionScopeInfo &&
3184
17.5k
      
DIFunctionScopeInfo->ObjCIsDesignatedInit2.65k
&&
3185
17.5k
      
(154
SuperLoc.isValid()154
||
isSelfExpr(Receiver)24
)) {
3186
133
    bool isDesignatedInitChain = false;
3187
133
    if (SuperLoc.isValid()) {
3188
130
      if (const ObjCObjectPointerType *
3189
130
            OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
3190
130
        if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
3191
          // Either we know this is a designated initializer or we
3192
          // conservatively assume it because we don't know for sure.
3193
130
          if (!ID->declaresOrInheritsDesignatedInitializers() ||
3194
130
              
ID->isDesignatedInitializer(Sel)127
) {
3195
126
            isDesignatedInitChain = true;
3196
126
            DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
3197
126
          }
3198
130
        }
3199
130
      }
3200
130
    }
3201
133
    if (!isDesignatedInitChain) {
3202
7
      const ObjCMethodDecl *InitMethod = nullptr;
3203
7
      bool isDesignated =
3204
7
        getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
3205
7
      assert(isDesignated && InitMethod);
3206
0
      (void)isDesignated;
3207
7
      Diag(SelLoc, SuperLoc.isValid() ?
3208
4
             diag::warn_objc_designated_init_non_designated_init_call :
3209
7
             
diag::warn_objc_designated_init_non_super_designated_init_call3
);
3210
7
      Diag(InitMethod->getLocation(),
3211
7
           diag::note_objc_designated_init_marked_here);
3212
7
    }
3213
133
  }
3214
3215
17.5k
  if (DIFunctionScopeInfo &&
3216
17.5k
      
DIFunctionScopeInfo->ObjCIsSecondaryInit2.65k
&&
3217
17.5k
      
(10
SuperLoc.isValid()10
||
isSelfExpr(Receiver)7
)) {
3218
9
    if (SuperLoc.isValid()) {
3219
3
      Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
3220
6
    } else {
3221
6
      DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
3222
6
    }
3223
9
  }
3224
3225
  // Check the message arguments.
3226
17.5k
  unsigned NumArgs = ArgsIn.size();
3227
17.5k
  Expr **Args = ArgsIn.data();
3228
17.5k
  QualType ReturnType;
3229
17.5k
  ExprValueKind VK = VK_PRValue;
3230
17.5k
  bool ClassMessage = (ReceiverType->isObjCClassType() ||
3231
17.5k
                       
ReceiverType->isObjCQualifiedClassType()17.2k
);
3232
17.5k
  if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3233
17.5k
                                MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3234
17.5k
                                Method, ClassMessage, SuperLoc.isValid(),
3235
17.5k
                                LBracLoc, RBracLoc, RecRange, ReturnType, VK))
3236
31
    return ExprError();
3237
3238
17.4k
  if (Method && 
!Method->getReturnType()->isVoidType()16.4k
&&
3239
17.4k
      RequireCompleteType(LBracLoc, Method->getReturnType(),
3240
9.50k
                          diag::err_illegal_message_expr_incomplete_type))
3241
0
    return ExprError();
3242
3243
  // In ARC, forbid the user from sending messages to
3244
  // retain/release/autorelease/dealloc/retainCount explicitly.
3245
17.4k
  if (getLangOpts().ObjCAutoRefCount) {
3246
1.63k
    ObjCMethodFamily family =
3247
1.63k
      (Method ? 
Method->getMethodFamily()1.63k
:
Sel.getMethodFamily()3
);
3248
1.63k
    switch (family) {
3249
202
    case OMF_init:
3250
202
      if (Method)
3251
202
        checkInitMethod(Method, ReceiverType);
3252
202
      break;
3253
3254
1.13k
    case OMF_None:
3255
1.13k
    case OMF_alloc:
3256
1.14k
    case OMF_copy:
3257
1.15k
    case OMF_finalize:
3258
1.15k
    case OMF_mutableCopy:
3259
1.15k
    case OMF_new:
3260
1.16k
    case OMF_self:
3261
1.16k
    case OMF_initialize:
3262
1.16k
      break;
3263
3264
12
    case OMF_dealloc:
3265
89
    case OMF_retain:
3266
209
    case OMF_release:
3267
236
    case OMF_autorelease:
3268
240
    case OMF_retainCount:
3269
240
      Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3270
240
        << Sel << RecRange;
3271
240
      break;
3272
3273
31
    case OMF_performSelector:
3274
31
      if (Method && NumArgs >= 1) {
3275
31
        if (const auto *SelExp =
3276
31
                dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
3277
30
          Selector ArgSel = SelExp->getSelector();
3278
30
          ObjCMethodDecl *SelMethod =
3279
30
            LookupInstanceMethodInGlobalPool(ArgSel,
3280
30
                                             SelExp->getSourceRange());
3281
30
          if (!SelMethod)
3282
3
            SelMethod =
3283
3
              LookupFactoryMethodInGlobalPool(ArgSel,
3284
3
                                              SelExp->getSourceRange());
3285
30
          if (SelMethod) {
3286
29
            ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3287
29
            switch (SelFamily) {
3288
0
              case OMF_alloc:
3289
1
              case OMF_copy:
3290
1
              case OMF_mutableCopy:
3291
2
              case OMF_new:
3292
3
              case OMF_init:
3293
                // Issue error, unless ns_returns_not_retained.
3294
3
                if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3295
                  // selector names a +1 method
3296
2
                  Diag(SelLoc,
3297
2
                       diag::err_arc_perform_selector_retains);
3298
2
                  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3299
2
                    << SelMethod->getDeclName();
3300
2
                }
3301
3
                break;
3302
26
              default:
3303
                // +0 call. OK. unless ns_returns_retained.
3304
26
                if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3305
                  // selector names a +1 method
3306
2
                  Diag(SelLoc,
3307
2
                       diag::err_arc_perform_selector_retains);
3308
2
                  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3309
2
                    << SelMethod->getDeclName();
3310
2
                }
3311
26
                break;
3312
29
            }
3313
29
          }
3314
30
        } else {
3315
          // error (may leak).
3316
1
          Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3317
1
          Diag(Args[0]->getExprLoc(), diag::note_used_here);
3318
1
        }
3319
31
      }
3320
31
      break;
3321
1.63k
    }
3322
1.63k
  }
3323
3324
17.4k
  DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3325
3326
  // Construct the appropriate ObjCMessageExpr instance.
3327
17.4k
  ObjCMessageExpr *Result;
3328
17.4k
  if (SuperLoc.isValid())
3329
1.02k
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3330
1.02k
                                     SuperLoc,  /*IsInstanceSuper=*/true,
3331
1.02k
                                     ReceiverType, Sel, SelectorLocs, Method,
3332
1.02k
                                     makeArrayRef(Args, NumArgs), RBracLoc,
3333
1.02k
                                     isImplicit);
3334
16.4k
  else {
3335
16.4k
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3336
16.4k
                                     Receiver, Sel, SelectorLocs, Method,
3337
16.4k
                                     makeArrayRef(Args, NumArgs), RBracLoc,
3338
16.4k
                                     isImplicit);
3339
16.4k
    if (!isImplicit)
3340
14.0k
      checkCocoaAPI(*this, Result);
3341
16.4k
  }
3342
17.4k
  if (Method) {
3343
16.4k
    bool IsClassObjectCall = ClassMessage;
3344
    // 'self' message receivers in class methods should be treated as message
3345
    // sends to the class object in order for the semantic checks to be
3346
    // performed correctly. Messages to 'super' already count as class messages,
3347
    // so they don't need to be handled here.
3348
16.4k
    if (Receiver && 
isSelfExpr(Receiver)15.4k
) {
3349
841
      if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3350
841
        if (OPT->getObjectType()->isObjCClass()) {
3351
87
          if (const auto *CurMeth = getCurMethodDecl()) {
3352
87
            IsClassObjectCall = true;
3353
87
            ReceiverType =
3354
87
                Context.getObjCInterfaceType(CurMeth->getClassInterface());
3355
87
          }
3356
87
        }
3357
841
      }
3358
841
    }
3359
16.4k
    checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3360
16.4k
                       ReceiverType, IsClassObjectCall);
3361
16.4k
  }
3362
3363
17.4k
  if (getLangOpts().ObjCAutoRefCount) {
3364
    // In ARC, annotate delegate init calls.
3365
1.63k
    if (Result->getMethodFamily() == OMF_init &&
3366
1.63k
        
(202
SuperLoc.isValid()202
||
isSelfExpr(Receiver)170
)) {
3367
      // Only consider init calls *directly* in init implementations,
3368
      // not within blocks.
3369
46
      ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3370
46
      if (method && method->getMethodFamily() == OMF_init) {
3371
        // The implicit assignment to self means we also don't want to
3372
        // consume the result.
3373
38
        Result->setDelegateInitCall(true);
3374
38
        return Result;
3375
38
      }
3376
46
    }
3377
3378
    // In ARC, check for message sends which are likely to introduce
3379
    // retain cycles.
3380
1.59k
    checkRetainCycles(Result);
3381
1.59k
  }
3382
3383
17.4k
  if (getLangOpts().ObjCWeak) {
3384
780
    if (!isImplicit && 
Method414
) {
3385
412
      if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3386
80
        bool IsWeak =
3387
80
            Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak;
3388
80
        if (!IsWeak && 
Sel.isUnarySelector()52
)
3389
27
          IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3390
80
        if (IsWeak && 
!isUnevaluatedContext()28
&&
3391
80
            
!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc)26
)
3392
26
          getCurFunction()->recordUseOfWeak(Result, Prop);
3393
80
      }
3394
412
    }
3395
780
  }
3396
3397
17.4k
  CheckObjCCircularContainer(Result);
3398
3399
17.4k
  return MaybeBindToTemporary(Result);
3400
17.4k
}
3401
3402
523
static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3403
523
  if (ObjCSelectorExpr *OSE =
3404
523
      dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3405
8
    Selector Sel = OSE->getSelector();
3406
8
    SourceLocation Loc = OSE->getAtLoc();
3407
8
    auto Pos = S.ReferencedSelectors.find(Sel);
3408
8
    if (Pos != S.ReferencedSelectors.end() && 
Pos->second == Loc1
)
3409
1
      S.ReferencedSelectors.erase(Pos);
3410
8
  }
3411
523
}
3412
3413
// ActOnInstanceMessage - used for both unary and keyword messages.
3414
// ArgExprs is optional - if it is present, the number of expressions
3415
// is obtained from Sel.getNumArgs().
3416
ExprResult Sema::ActOnInstanceMessage(Scope *S,
3417
                                      Expr *Receiver,
3418
                                      Selector Sel,
3419
                                      SourceLocation LBracLoc,
3420
                                      ArrayRef<SourceLocation> SelectorLocs,
3421
                                      SourceLocation RBracLoc,
3422
14.0k
                                      MultiExprArg Args) {
3423
14.0k
  if (!Receiver)
3424
0
    return ExprError();
3425
3426
  // A ParenListExpr can show up while doing error recovery with invalid code.
3427
14.0k
  if (isa<ParenListExpr>(Receiver)) {
3428
1
    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3429
1
    if (Result.isInvalid()) 
return ExprError()0
;
3430
1
    Receiver = Result.get();
3431
1
  }
3432
3433
14.0k
  if (RespondsToSelectorSel.isNull()) {
3434
2.02k
    IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3435
2.02k
    RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3436
2.02k
  }
3437
14.0k
  if (Sel == RespondsToSelectorSel)
3438
523
    RemoveSelectorFromWarningCache(*this, Args[0]);
3439
3440
14.0k
  return BuildInstanceMessage(Receiver, Receiver->getType(),
3441
14.0k
                              /*SuperLoc=*/SourceLocation(), Sel,
3442
14.0k
                              /*Method=*/nullptr, LBracLoc, SelectorLocs,
3443
14.0k
                              RBracLoc, Args);
3444
14.0k
}
3445
3446
enum ARCConversionTypeClass {
3447
  /// int, void, struct A
3448
  ACTC_none,
3449
3450
  /// id, void (^)()
3451
  ACTC_retainable,
3452
3453
  /// id*, id***, void (^*)(),
3454
  ACTC_indirectRetainable,
3455
3456
  /// void* might be a normal C type, or it might a CF type.
3457
  ACTC_voidPtr,
3458
3459
  /// struct A*
3460
  ACTC_coreFoundation
3461
};
3462
3463
1.70k
static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3464
1.70k
  return (ACTC == ACTC_retainable ||
3465
1.70k
          
ACTC == ACTC_coreFoundation1.04k
||
3466
1.70k
          
ACTC == ACTC_voidPtr244
);
3467
1.70k
}
3468
3469
2.79k
static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3470
2.79k
  return ACTC == ACTC_none ||
3471
2.79k
         
ACTC == ACTC_voidPtr2.01k
||
3472
2.79k
         
ACTC == ACTC_coreFoundation1.27k
;
3473
2.79k
}
3474
3475
12.0M
static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3476
12.0M
  bool isIndirect = false;
3477
3478
  // Ignore an outermost reference type.
3479
12.0M
  if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3480
18.7k
    type = ref->getPointeeType();
3481
18.7k
    isIndirect = true;
3482
18.7k
  }
3483
3484
  // Drill through pointers and arrays recursively.
3485
12.7M
  while (true) {
3486
12.7M
    if (const PointerType *ptr = type->getAs<PointerType>()) {
3487
986k
      type = ptr->getPointeeType();
3488
3489
      // The first level of pointer may be the innermost pointer on a CF type.
3490
986k
      if (!isIndirect) {
3491
971k
        if (type->isVoidType()) 
return ACTC_voidPtr220k
;
3492
751k
        if (type->isRecordType()) 
return ACTC_coreFoundation202k
;
3493
751k
      }
3494
11.7M
    } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3495
71.5k
      type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3496
11.6M
    } else {
3497
11.6M
      break;
3498
11.6M
    }
3499
635k
    isIndirect = true;
3500
635k
  }
3501
3502
11.6M
  if (isIndirect) {
3503
638k
    if (type->isObjCARCBridgableType())
3504
7.02k
      return ACTC_indirectRetainable;
3505
631k
    return ACTC_none;
3506
638k
  }
3507
3508
11.0M
  if (type->isObjCARCBridgableType())
3509
139k
    return ACTC_retainable;
3510
3511
10.8M
  return ACTC_none;
3512
11.0M
}
3513
3514
namespace {
3515
  /// A result from the cast checker.
3516
  enum ACCResult {
3517
    /// Cannot be casted.
3518
    ACC_invalid,
3519
3520
    /// Can be safely retained or not retained.
3521
    ACC_bottom,
3522
3523
    /// Can be casted at +0.
3524
    ACC_plusZero,
3525
3526
    /// Can be casted at +1.
3527
    ACC_plusOne
3528
  };
3529
82
  ACCResult merge(ACCResult left, ACCResult right) {
3530
82
    if (left == right) 
return left17
;
3531
65
    if (left == ACC_bottom) 
return right41
;
3532
24
    if (right == ACC_bottom) 
return left14
;
3533
10
    return ACC_invalid;
3534
24
  }
3535
3536
  /// A checker which white-lists certain expressions whose conversion
3537
  /// to or from retainable type would otherwise be forbidden in ARC.
3538
  class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3539
    typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3540
3541
    ASTContext &Context;
3542
    ARCConversionTypeClass SourceClass;
3543
    ARCConversionTypeClass TargetClass;
3544
    bool Diagnose;
3545
3546
149
    static bool isCFType(QualType type) {
3547
      // Someday this can use ns_bridged.  For now, it has to do this.
3548
149
      return type->isCARCBridgableType();
3549
149
    }
3550
3551
  public:
3552
    ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3553
                   ARCConversionTypeClass target, bool diagnose)
3554
      : Context(Context), SourceClass(source), TargetClass(target),
3555
943
        Diagnose(diagnose) {}
3556
3557
    using super::Visit;
3558
1.77k
    ACCResult Visit(Expr *e) {
3559
1.77k
      return super::Visit(e->IgnoreParens());
3560
1.77k
    }
3561
3562
0
    ACCResult VisitStmt(Stmt *s) {
3563
0
      return ACC_invalid;
3564
0
    }
3565
3566
    /// Null pointer constants can be casted however you please.
3567
260
    ACCResult VisitExpr(Expr *e) {
3568
260
      if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3569
156
        return ACC_bottom;
3570
104
      return ACC_invalid;
3571
260
    }
3572
3573
    /// Objective-C string literals can be safely casted.
3574
46
    ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3575
      // If we're casting to any retainable type, go ahead.  Global
3576
      // strings are immune to retains, so this is bottom.
3577
46
      if (isAnyRetainable(TargetClass)) return ACC_bottom;
3578
3579
0
      return ACC_invalid;
3580
46
    }
3581
3582
    /// Look through certain implicit and explicit casts.
3583
758
    ACCResult VisitCastExpr(CastExpr *e) {
3584
758
      switch (e->getCastKind()) {
3585
60
        case CK_NullToPointer:
3586
60
          return ACC_bottom;
3587
3588
41
        case CK_NoOp:
3589
580
        case CK_LValueToRValue:
3590
626
        case CK_BitCast:
3591
629
        case CK_CPointerToObjCPointerCast:
3592
629
        case CK_BlockPointerToObjCPointerCast:
3593
629
        case CK_AnyPointerToBlockPointerCast:
3594
629
          return Visit(e->getSubExpr());
3595
3596
69
        default:
3597
69
          return ACC_invalid;
3598
758
      }
3599
758
    }
3600
3601
    /// Look through unary extension.
3602
0
    ACCResult VisitUnaryExtension(UnaryOperator *e) {
3603
0
      return Visit(e->getSubExpr());
3604
0
    }
3605
3606
    /// Ignore the LHS of a comma operator.
3607
3
    ACCResult VisitBinComma(BinaryOperator *e) {
3608
3
      return Visit(e->getRHS());
3609
3
    }
3610
3611
    /// Conditional operators are okay if both sides are okay.
3612
90
    ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3613
90
      ACCResult left = Visit(e->getTrueExpr());
3614
90
      if (left == ACC_invalid) 
return ACC_invalid8
;
3615
82
      return merge(left, Visit(e->getFalseExpr()));
3616
90
    }
3617
3618
    /// Look through pseudo-objects.
3619
30
    ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3620
      // If we're getting here, we should always have a result.
3621
30
      return Visit(e->getResultExpr());
3622
30
    }
3623
3624
    /// Statement expressions are okay if their result expression is okay.
3625
0
    ACCResult VisitStmtExpr(StmtExpr *e) {
3626
0
      return Visit(e->getSubStmt()->body_back());
3627
0
    }
3628
3629
    /// Some declaration references are okay.
3630
513
    ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3631
513
      VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3632
      // References to global constants are okay.
3633
513
      if (isAnyRetainable(TargetClass) &&
3634
513
          
isAnyRetainable(SourceClass)492
&&
3635
513
          
var489
&&
3636
513
          
!var->hasDefinition(Context)489
&&
3637
513
          
var->getType().isConstQualified()62
) {
3638
3639
        // In system headers, they can also be assumed to be immune to retains.
3640
        // These are things like 'kCFStringTransformToLatin'.
3641
46
        if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3642
5
          return ACC_bottom;
3643
3644
41
        return ACC_plusZero;
3645
46
      }
3646
3647
      // Nothing else.
3648
467
      return ACC_invalid;
3649
513
    }
3650
3651
    /// Some calls are okay.
3652
98
    ACCResult VisitCallExpr(CallExpr *e) {
3653
98
      if (FunctionDecl *fn = e->getDirectCallee())
3654
98
        if (ACCResult result = checkCallToFunction(fn))
3655
26
          return result;
3656
3657
72
      return super::VisitCallExpr(e);
3658
98
    }
3659
3660
98
    ACCResult checkCallToFunction(FunctionDecl *fn) {
3661
      // Require a CF*Ref return type.
3662
98
      if (!isCFType(fn->getReturnType()))
3663
0
        return ACC_invalid;
3664
3665
98
      if (!isAnyRetainable(TargetClass))
3666
0
        return ACC_invalid;
3667
3668
      // Honor an explicit 'not retained' attribute.
3669
98
      if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3670
2
        return ACC_plusZero;
3671
3672
      // Honor an explicit 'retained' attribute, except that for
3673
      // now we're not going to permit implicit handling of +1 results,
3674
      // because it's a bit frightening.
3675
96
      if (fn->hasAttr<CFReturnsRetainedAttr>())
3676
4
        return Diagnose ? 
ACC_plusOne2
3677
4
                        : 
ACC_invalid2
; // ACC_plusOne if we start accepting this
3678
3679
      // Recognize this specific builtin function, which is used by CFSTR.
3680
92
      unsigned builtinID = fn->getBuiltinID();
3681
92
      if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3682
1
        return ACC_bottom;
3683
3684
      // Otherwise, don't do anything implicit with an unaudited function.
3685
91
      if (!fn->hasAttr<CFAuditedTransferAttr>())
3686
58
        return ACC_invalid;
3687
3688
      // Otherwise, it's +0 unless it follows the create convention.
3689
33
      if (ento::coreFoundation::followsCreateRule(fn))
3690
24
        return Diagnose ? 
ACC_plusOne12
3691
24
                        : 
ACC_invalid12
; // ACC_plusOne if we start accepting this
3692
3693
9
      return ACC_plusZero;
3694
33
    }
3695
3696
51
    ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3697
51
      return checkCallToMethod(e->getMethodDecl());
3698
51
    }
3699
3700
0
    ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3701
0
      ObjCMethodDecl *method;
3702
0
      if (e->isExplicitProperty())
3703
0
        method = e->getExplicitProperty()->getGetterMethodDecl();
3704
0
      else
3705
0
        method = e->getImplicitPropertyGetter();
3706
0
      return checkCallToMethod(method);
3707
0
    }
3708
3709
51
    ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3710
51
      if (!method) 
return ACC_invalid0
;
3711
3712
      // Check for message sends to functions returning CF types.  We
3713
      // just obey the Cocoa conventions with these, even though the
3714
      // return type is CF.
3715
51
      if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3716
0
        return ACC_invalid;
3717
3718
      // If the method is explicitly marked not-retained, it's +0.
3719
51
      if (method->hasAttr<CFReturnsNotRetainedAttr>())
3720
0
        return ACC_plusZero;
3721
3722
      // If the method is explicitly marked as returning retained, or its
3723
      // selector follows a +1 Cocoa convention, treat it as +1.
3724
51
      if (method->hasAttr<CFReturnsRetainedAttr>())
3725
3
        return ACC_plusOne;
3726
3727
48
      switch (method->getSelector().getMethodFamily()) {
3728
0
      case OMF_alloc:
3729
0
      case OMF_copy:
3730
0
      case OMF_mutableCopy:
3731
11
      case OMF_new:
3732
11
        return ACC_plusOne;
3733
3734
37
      default:
3735
        // Otherwise, treat it as +0.
3736
37
        return ACC_plusZero;
3737
48
      }
3738
48
    }
3739
  };
3740
} // end anonymous namespace
3741
3742
303
bool Sema::isKnownName(StringRef name) {
3743
303
  if (name.empty())
3744
0
    return false;
3745
303
  LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3746
303
                 Sema::LookupOrdinaryName);
3747
303
  return LookupName(R, TUScope, false);
3748
303
}
3749
3750
template <typename DiagBuilderT>
3751
static void addFixitForObjCARCConversion(
3752
    Sema &S, DiagBuilderT &DiagB, Sema::CheckedConversionKind CCK,
3753
    SourceLocation afterLParen, QualType castType, Expr *castExpr,
3754
572
    Expr *realCast, const char *bridgeKeyword, const char *CFBridgeName) {
3755
  // We handle C-style and implicit casts here.
3756
572
  switch (CCK) {
3757
108
  case Sema::CCK_ImplicitConversion:
3758
108
  case Sema::CCK_ForBuiltinOverloadedOp:
3759
522
  case Sema::CCK_CStyleCast:
3760
572
  case Sema::CCK_OtherCast:
3761
572
    break;
3762
0
  case Sema::CCK_FunctionalCast:
3763
0
    return;
3764
572
  }
3765
3766
572
  if (CFBridgeName) {
3767
146
    if (CCK == Sema::CCK_OtherCast) {
3768
2
      if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3769
2
        SourceRange range(NCE->getOperatorLoc(),
3770
2
                          NCE->getAngleBrackets().getEnd());
3771
2
        SmallString<32> BridgeCall;
3772
3773
2
        SourceManager &SM = S.getSourceManager();
3774
2
        char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3775
2
        if (Lexer::isAsciiIdentifierContinueChar(PrevChar, S.getLangOpts()))
3776
0
          BridgeCall += ' ';
3777
3778
2
        BridgeCall += CFBridgeName;
3779
2
        DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3780
2
      }
3781
2
      return;
3782
2
    }
3783
144
    Expr *castedE = castExpr;
3784
144
    if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3785
4
      castedE = CCE->getSubExpr();
3786
144
    castedE = castedE->IgnoreImpCasts();
3787
144
    SourceRange range = castedE->getSourceRange();
3788
3789
144
    SmallString<32> BridgeCall;
3790
3791
144
    SourceManager &SM = S.getSourceManager();
3792
144
    char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3793
144
    if (Lexer::isAsciiIdentifierContinueChar(PrevChar, S.getLangOpts()))
3794
2
      BridgeCall += ' ';
3795
3796
144
    BridgeCall += CFBridgeName;
3797
3798
144
    if (isa<ParenExpr>(castedE)) {
3799
32
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3800
32
                         BridgeCall));
3801
112
    } else {
3802
112
      BridgeCall += '(';
3803
112
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3804
112
                                                    BridgeCall));
3805
112
      DiagB.AddFixItHint(FixItHint::CreateInsertion(
3806
112
                                       S.getLocForEndOfToken(range.getEnd()),
3807
112
                                       ")"));
3808
112
    }
3809
144
    return;
3810
146
  }
3811
3812
426
  if (CCK == Sema::CCK_CStyleCast) {
3813
319
    DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3814
319
  } else 
if (107
CCK == Sema::CCK_OtherCast107
) {
3815
48
    if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3816
20
      std::string castCode = "(";
3817
20
      castCode += bridgeKeyword;
3818
20
      castCode += castType.getAsString();
3819
20
      castCode += ")";
3820
20
      SourceRange Range(NCE->getOperatorLoc(),
3821
20
                        NCE->getAngleBrackets().getEnd());
3822
20
      DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3823
20
    }
3824
59
  } else {
3825
59
    std::string castCode = "(";
3826
59
    castCode += bridgeKeyword;
3827
59
    castCode += castType.getAsString();
3828
59
    castCode += ")";
3829
59
    Expr *castedE = castExpr->IgnoreImpCasts();
3830
59
    SourceRange range = castedE->getSourceRange();
3831
59
    if (isa<ParenExpr>(castedE)) {
3832
4
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3833
4
                         castCode));
3834
55
    } else {
3835
55
      castCode += "(";
3836
55
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3837
55
                                                    castCode));
3838
55
      DiagB.AddFixItHint(FixItHint::CreateInsertion(
3839
55
                                       S.getLocForEndOfToken(range.getEnd()),
3840
55
                                       ")"));
3841
55
    }
3842
59
  }
3843
426
}
3844
3845
template <typename T>
3846
2.41k
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3847
2.41k
  TypedefNameDecl *TDNDecl = TD->getDecl();
3848
2.41k
  QualType QT = TDNDecl->getUnderlyingType();
3849
2.41k
  if (QT->isPointerType()) {
3850
2.41k
    QT = QT->getPointeeType();
3851
2.41k
    if (const RecordType *RT = QT->getAs<RecordType>()) {
3852
2.55k
      for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
3853
2.55k
        if (auto *attr = Redecl->getAttr<T>())
3854
449
          return attr;
3855
2.55k
      }
3856
2.41k
    }
3857
2.41k
  }
3858
1.96k
  return nullptr;
3859
2.41k
}
SemaExprObjC.cpp:clang::ObjCBridgeRelatedAttr* getObjCBridgeAttr<clang::ObjCBridgeRelatedAttr>(clang::TypedefType const*)
Line
Count
Source
3846
1.26k
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3847
1.26k
  TypedefNameDecl *TDNDecl = TD->getDecl();
3848
1.26k
  QualType QT = TDNDecl->getUnderlyingType();
3849
1.26k
  if (QT->isPointerType()) {
3850
1.26k
    QT = QT->getPointeeType();
3851
1.26k
    if (const RecordType *RT = QT->getAs<RecordType>()) {
3852
1.40k
      for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
3853
1.40k
        if (auto *attr = Redecl->getAttr<T>())
3854
81
          return attr;
3855
1.40k
      }
3856
1.26k
    }
3857
1.26k
  }
3858
1.18k
  return nullptr;
3859
1.26k
}
SemaExprObjC.cpp:clang::ObjCBridgeAttr* getObjCBridgeAttr<clang::ObjCBridgeAttr>(clang::TypedefType const*)
Line
Count
Source
3846
699
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3847
699
  TypedefNameDecl *TDNDecl = TD->getDecl();
3848
699
  QualType QT = TDNDecl->getUnderlyingType();
3849
699
  if (QT->isPointerType()) {
3850
699
    QT = QT->getPointeeType();
3851
699
    if (const RecordType *RT = QT->getAs<RecordType>()) {
3852
700
      for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
3853
700
        if (auto *attr = Redecl->getAttr<T>())
3854
354
          return attr;
3855
700
      }
3856
699
    }
3857
699
  }
3858
345
  return nullptr;
3859
699
}
SemaExprObjC.cpp:clang::ObjCBridgeMutableAttr* getObjCBridgeAttr<clang::ObjCBridgeMutableAttr>(clang::TypedefType const*)
Line
Count
Source
3846
453
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3847
453
  TypedefNameDecl *TDNDecl = TD->getDecl();
3848
453
  QualType QT = TDNDecl->getUnderlyingType();
3849
453
  if (QT->isPointerType()) {
3850
453
    QT = QT->getPointeeType();
3851
453
    if (const RecordType *RT = QT->getAs<RecordType>()) {
3852
453
      for (auto *Redecl : RT->getDecl()->getMostRecentDecl()->redecls()) {
3853
453
        if (auto *attr = Redecl->getAttr<T>())
3854
14
          return attr;
3855
453
      }
3856
453
    }
3857
453
  }
3858
439
  return nullptr;
3859
453
}
3860
3861
static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3862
1.24k
                                                            TypedefNameDecl *&TDNDecl) {
3863
2.42k
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3864
1.26k
    TDNDecl = TD->getDecl();
3865
1.26k
    if (ObjCBridgeRelatedAttr *ObjCBAttr =
3866
1.26k
        getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3867
81
      return ObjCBAttr;
3868
1.18k
    T = TDNDecl->getUnderlyingType();
3869
1.18k
  }
3870
1.16k
  return nullptr;
3871
1.24k
}
3872
3873
static void
3874
diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3875
                          QualType castType, ARCConversionTypeClass castACTC,
3876
                          Expr *castExpr, Expr *realCast,
3877
                          ARCConversionTypeClass exprACTC,
3878
338
                          Sema::CheckedConversionKind CCK) {
3879
338
  SourceLocation loc =
3880
338
    (castRange.isValid() ? 
castRange.getBegin()264
:
castExpr->getExprLoc()74
);
3881
3882
338
  if (S.makeUnavailableInSystemHeader(loc,
3883
338
                                 UnavailableAttr::IR_ARCForbiddenConversion))
3884
4
    return;
3885
3886
334
  QualType castExprType = castExpr->getType();
3887
  // Defer emitting a diagnostic for bridge-related casts; that will be
3888
  // handled by CheckObjCBridgeRelatedConversions.
3889
334
  TypedefNameDecl *TDNDecl = nullptr;
3890
334
  if ((castACTC == ACTC_coreFoundation &&  
exprACTC == ACTC_retainable120
&&
3891
334
       
ObjCBridgeRelatedAttrFromType(castType, TDNDecl)119
) ||
3892
334
      
(325
exprACTC == ACTC_coreFoundation325
&&
castACTC == ACTC_retainable129
&&
3893
325
       
ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)128
))
3894
14
    return;
3895
3896
320
  unsigned srcKind = 0;
3897
320
  switch (exprACTC) {
3898
3
  case ACTC_none:
3899
127
  case ACTC_coreFoundation:
3900
153
  case ACTC_voidPtr:
3901
153
    srcKind = (castExprType->isPointerType() ? 
1150
:
03
);
3902
153
    break;
3903
163
  case ACTC_retainable:
3904
163
    srcKind = (castExprType->isBlockPointerType() ? 
24
:
3159
);
3905
163
    break;
3906
4
  case ACTC_indirectRetainable:
3907
4
    srcKind = 4;
3908
4
    break;
3909
320
  }
3910
3911
  // Check whether this could be fixed with a bridge cast.
3912
320
  SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3913
320
  SourceLocation noteLoc = afterLParen.isValid() ? 
afterLParen247
:
loc73
;
3914
3915
320
  unsigned convKindForDiag = Sema::isCast(CCK) ? 
0257
:
163
;
3916
3917
  // Bridge from an ARC type to a CF type.
3918
320
  if (castACTC == ACTC_retainable && 
isAnyRetainable(exprACTC)151
) {
3919
3920
145
    S.Diag(loc, diag::err_arc_cast_requires_bridge)
3921
145
      << convKindForDiag
3922
145
      << 2 // of C pointer type
3923
145
      << castExprType
3924
145
      << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3925
145
      << castType
3926
145
      << castRange
3927
145
      << castExpr->getSourceRange();
3928
145
    bool br = S.isKnownName("CFBridgingRelease");
3929
145
    ACCResult CreateRule =
3930
145
      ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3931
145
    assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3932
145
    if (CreateRule != ACC_plusOne)
3933
131
    {
3934
131
      auto DiagB = (CCK != Sema::CCK_OtherCast)
3935
131
                       ? 
S.Diag(noteLoc, diag::note_arc_bridge)117
3936
131
                       : 
S.Diag(noteLoc, diag::note_arc_cstyle_bridge)14
;
3937
3938
131
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3939
131
                                   castType, castExpr, realCast, "__bridge ",
3940
131
                                   nullptr);
3941
131
    }
3942
145
    if (CreateRule != ACC_plusZero)
3943
145
    {
3944
145
      auto DiagB = (CCK == Sema::CCK_OtherCast && 
!br14
)
3945
145
                       ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer)
3946
14
                             << castExprType
3947
145
                       : 
S.Diag(131
br131
?
castExpr->getExprLoc()67
:
noteLoc64
,
3948
131
                                diag::note_arc_bridge_transfer)
3949
131
                             << castExprType << br;
3950
3951
145
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3952
145
                                   castType, castExpr, realCast, "__bridge_transfer ",
3953
145
                                   br ? 
"CFBridgingRelease"67
:
nullptr78
);
3954
145
    }
3955
3956
145
    return;
3957
145
  }
3958
3959
  // Bridge from a CF type to an ARC type.
3960
175
  if (exprACTC == ACTC_retainable && 
isAnyRetainable(castACTC)163
) {
3961
148
    bool br = S.isKnownName("CFBridgingRetain");
3962
148
    S.Diag(loc, diag::err_arc_cast_requires_bridge)
3963
148
      << convKindForDiag
3964
148
      << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3965
148
      << castExprType
3966
148
      << 2 // to C pointer type
3967
148
      << castType
3968
148
      << castRange
3969
148
      << castExpr->getSourceRange();
3970
148
    ACCResult CreateRule =
3971
148
      ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3972
148
    assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3973
148
    if (CreateRule != ACC_plusOne)
3974
148
    {
3975
148
      auto DiagB = (CCK != Sema::CCK_OtherCast)
3976
148
                       ? 
S.Diag(noteLoc, diag::note_arc_bridge)137
3977
148
                       : 
S.Diag(noteLoc, diag::note_arc_cstyle_bridge)11
;
3978
148
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3979
148
                                   castType, castExpr, realCast, "__bridge ",
3980
148
                                   nullptr);
3981
148
    }
3982
148
    if (CreateRule != ACC_plusZero)
3983
148
    {
3984
148
      auto DiagB = (CCK == Sema::CCK_OtherCast && 
!br11
)
3985
148
                       ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained)
3986
9
                             << castType
3987
148
                       : 
S.Diag(139
br139
?
castExpr->getExprLoc()79
:
noteLoc60
,
3988
139
                                diag::note_arc_bridge_retained)
3989
139
                             << castType << br;
3990
3991
148
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3992
148
                                   castType, castExpr, realCast, "__bridge_retained ",
3993
148
                                   br ? 
"CFBridgingRetain"79
:
nullptr69
);
3994
148
    }
3995
3996
148
    return;
3997
148
  }
3998
3999
27
  S.Diag(loc, diag::err_arc_mismatched_cast)
4000
27
    << !convKindForDiag
4001
27
    << srcKind << castExprType << castType
4002
27
    << castRange << castExpr->getSourceRange();
4003
27
}
4004
4005
template <typename TB>
4006
static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
4007
1.11k
                                  bool &HadTheAttribute, bool warn) {
4008
1.11k
  QualType T = castExpr->getType();
4009
1.11k
  HadTheAttribute = false;
4010
1.63k
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4011
704
    TypedefNameDecl *TDNDecl = TD->getDecl();
4012
704
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4013
178
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4014
178
        HadTheAttribute = true;
4015
178
        if (Parm->isStr("id"))
4016
14
          return true;
4017
4018
        // Check for an existing type with this name.
4019
164
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4020
164
                       Sema::LookupOrdinaryName);
4021
164
        if (S.LookupName(R, S.TUScope)) {
4022
155
          NamedDecl *Target = R.getFoundDecl();
4023
155
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4024
155
            ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4025
155
            if (const ObjCObjectPointerType *InterfacePointerType =
4026
155
                  castType->getAsObjCInterfacePointerType()) {
4027
61
              ObjCInterfaceDecl *CastClass
4028
61
                = InterfacePointerType->getObjectType()->getInterface();
4029
61
              if ((CastClass == ExprClass) ||
4030
61
                  
(36
CastClass36
&&
CastClass->isSuperClassOf(ExprClass)36
))
4031
27
                return true;
4032
34
              if (warn)
4033
15
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4034
15
                    << T << Target->getName() << castType->getPointeeType();
4035
34
              return false;
4036
94
            } else if (castType->isObjCIdType() ||
4037
94
                       (S.Context.ObjCObjectAdoptsQTypeProtocols(
4038
80
                          castType, ExprClass)))
4039
              // ok to cast to 'id'.
4040
              // casting to id<p-list> is ok if bridge type adopts all of
4041
              // p-list protocols.
4042
50
              return true;
4043
44
            else {
4044
44
              if (warn) {
4045
22
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4046
22
                    << T << Target->getName() << castType;
4047
22
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4048
22
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4049
22
              }
4050
44
              return false;
4051
44
           }
4052
155
          }
4053
155
        } else 
if (9
!castType->isObjCIdType()9
) {
4054
7
          S.Diag(castExpr->getBeginLoc(),
4055
7
                 diag::err_objc_cf_bridged_not_interface)
4056
7
              << castExpr->getType() << Parm;
4057
7
          S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4058
7
        }
4059
9
        return true;
4060
164
      }
4061
0
      return false;
4062
178
    }
4063
526
    T = TDNDecl->getUnderlyingType();
4064
526
  }
4065
932
  return true;
4066
1.11k
}
SemaExprObjC.cpp:bool CheckObjCBridgeNSCast<clang::ObjCBridgeAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4007
620
                                  bool &HadTheAttribute, bool warn) {
4008
620
  QualType T = castExpr->getType();
4009
620
  HadTheAttribute = false;
4010
843
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4011
394
    TypedefNameDecl *TDNDecl = TD->getDecl();
4012
394
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4013
171
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4014
171
        HadTheAttribute = true;
4015
171
        if (Parm->isStr("id"))
4016
14
          return true;
4017
4018
        // Check for an existing type with this name.
4019
157
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4020
157
                       Sema::LookupOrdinaryName);
4021
157
        if (S.LookupName(R, S.TUScope)) {
4022
149
          NamedDecl *Target = R.getFoundDecl();
4023
149
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4024
149
            ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4025
149
            if (const ObjCObjectPointerType *InterfacePointerType =
4026
149
                  castType->getAsObjCInterfacePointerType()) {
4027
55
              ObjCInterfaceDecl *CastClass
4028
55
                = InterfacePointerType->getObjectType()->getInterface();
4029
55
              if ((CastClass == ExprClass) ||
4030
55
                  
(35
CastClass35
&&
CastClass->isSuperClassOf(ExprClass)35
))
4031
21
                return true;
4032
34
              if (warn)
4033
15
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4034
15
                    << T << Target->getName() << castType->getPointeeType();
4035
34
              return false;
4036
94
            } else if (castType->isObjCIdType() ||
4037
94
                       (S.Context.ObjCObjectAdoptsQTypeProtocols(
4038
80
                          castType, ExprClass)))
4039
              // ok to cast to 'id'.
4040
              // casting to id<p-list> is ok if bridge type adopts all of
4041
              // p-list protocols.
4042
50
              return true;
4043
44
            else {
4044
44
              if (warn) {
4045
22
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4046
22
                    << T << Target->getName() << castType;
4047
22
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4048
22
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4049
22
              }
4050
44
              return false;
4051
44
           }
4052
149
          }
4053
149
        } else 
if (8
!castType->isObjCIdType()8
) {
4054
6
          S.Diag(castExpr->getBeginLoc(),
4055
6
                 diag::err_objc_cf_bridged_not_interface)
4056
6
              << castExpr->getType() << Parm;
4057
6
          S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4058
6
        }
4059
8
        return true;
4060
157
      }
4061
0
      return false;
4062
171
    }
4063
223
    T = TDNDecl->getUnderlyingType();
4064
223
  }
4065
449
  return true;
4066
620
}
SemaExprObjC.cpp:bool CheckObjCBridgeNSCast<clang::ObjCBridgeMutableAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4007
490
                                  bool &HadTheAttribute, bool warn) {
4008
490
  QualType T = castExpr->getType();
4009
490
  HadTheAttribute = false;
4010
793
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4011
310
    TypedefNameDecl *TDNDecl = TD->getDecl();
4012
310
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4013
7
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4014
7
        HadTheAttribute = true;
4015
7
        if (Parm->isStr("id"))
4016
0
          return true;
4017
4018
        // Check for an existing type with this name.
4019
7
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4020
7
                       Sema::LookupOrdinaryName);
4021
7
        if (S.LookupName(R, S.TUScope)) {
4022
6
          NamedDecl *Target = R.getFoundDecl();
4023
6
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4024
6
            ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4025
6
            if (const ObjCObjectPointerType *InterfacePointerType =
4026
6
                  castType->getAsObjCInterfacePointerType()) {
4027
6
              ObjCInterfaceDecl *CastClass
4028
6
                = InterfacePointerType->getObjectType()->getInterface();
4029
6
              if ((CastClass == ExprClass) ||
4030
6
                  
(1
CastClass1
&&
CastClass->isSuperClassOf(ExprClass)1
))
4031
6
                return true;
4032
0
              if (warn)
4033
0
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4034
0
                    << T << Target->getName() << castType->getPointeeType();
4035
0
              return false;
4036
6
            } else 
if (0
castType->isObjCIdType()0
||
4037
0
                       (S.Context.ObjCObjectAdoptsQTypeProtocols(
4038
0
                          castType, ExprClass)))
4039
              // ok to cast to 'id'.
4040
              // casting to id<p-list> is ok if bridge type adopts all of
4041
              // p-list protocols.
4042
0
              return true;
4043
0
            else {
4044
0
              if (warn) {
4045
0
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4046
0
                    << T << Target->getName() << castType;
4047
0
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4048
0
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4049
0
              }
4050
0
              return false;
4051
0
           }
4052
6
          }
4053
6
        } else 
if (1
!castType->isObjCIdType()1
) {
4054
1
          S.Diag(castExpr->getBeginLoc(),
4055
1
                 diag::err_objc_cf_bridged_not_interface)
4056
1
              << castExpr->getType() << Parm;
4057
1
          S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4058
1
        }
4059
1
        return true;
4060
7
      }
4061
0
      return false;
4062
7
    }
4063
303
    T = TDNDecl->getUnderlyingType();
4064
303
  }
4065
483
  return true;
4066
490
}
4067
4068
template <typename TB>
4069
static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
4070
458
                                  bool &HadTheAttribute, bool warn) {
4071
458
  QualType T = castType;
4072
458
  HadTheAttribute = false;
4073
716
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4074
448
    TypedefNameDecl *TDNDecl = TD->getDecl();
4075
448
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4076
190
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4077
190
        HadTheAttribute = true;
4078
190
        if (Parm->isStr("id"))
4079
6
          return true;
4080
4081
184
        NamedDecl *Target = nullptr;
4082
        // Check for an existing type with this name.
4083
184
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4084
184
                       Sema::LookupOrdinaryName);
4085
184
        if (S.LookupName(R, S.TUScope)) {
4086
184
          Target = R.getFoundDecl();
4087
184
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4088
184
            ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4089
184
            if (const ObjCObjectPointerType *InterfacePointerType =
4090
184
                  castExpr->getType()->getAsObjCInterfacePointerType()) {
4091
103
              ObjCInterfaceDecl *ExprClass
4092
103
                = InterfacePointerType->getObjectType()->getInterface();
4093
103
              if ((CastClass == ExprClass) ||
4094
103
                  
(85
ExprClass85
&&
CastClass->isSuperClassOf(ExprClass)85
))
4095
81
                return true;
4096
22
              if (warn) {
4097
9
                S.Diag(castExpr->getBeginLoc(),
4098
9
                       diag::warn_objc_invalid_bridge_to_cf)
4099
9
                    << castExpr->getType()->getPointeeType() << T;
4100
9
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4101
9
              }
4102
22
              return false;
4103
103
            } else 
if (81
castExpr->getType()->isObjCIdType()81
||
4104
81
                       (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4105
68
                          castExpr->getType(), CastClass)))
4106
              // ok to cast an 'id' expression to a CFtype.
4107
              // ok to cast an 'id<plist>' expression to CFtype provided plist
4108
              // adopts all of CFtype's ObjetiveC's class plist.
4109
65
              return true;
4110
16
            else {
4111
16
              if (warn) {
4112
8
                S.Diag(castExpr->getBeginLoc(),
4113
8
                       diag::warn_objc_invalid_bridge_to_cf)
4114
8
                    << castExpr->getType() << castType;
4115
8
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4116
8
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4117
8
              }
4118
16
              return false;
4119
16
            }
4120
184
          }
4121
184
        }
4122
0
        S.Diag(castExpr->getBeginLoc(),
4123
0
               diag::err_objc_ns_bridged_invalid_cfobject)
4124
0
            << castExpr->getType() << castType;
4125
0
        S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4126
0
        if (Target)
4127
0
          S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4128
0
        return true;
4129
184
      }
4130
0
      return false;
4131
190
    }
4132
258
    T = TDNDecl->getUnderlyingType();
4133
258
  }
4134
268
  return true;
4135
458
}
SemaExprObjC.cpp:bool CheckObjCBridgeCFCast<clang::ObjCBridgeAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4070
310
                                  bool &HadTheAttribute, bool warn) {
4071
310
  QualType T = castType;
4072
310
  HadTheAttribute = false;
4073
432
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4074
305
    TypedefNameDecl *TDNDecl = TD->getDecl();
4075
305
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4076
183
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4077
183
        HadTheAttribute = true;
4078
183
        if (Parm->isStr("id"))
4079
6
          return true;
4080
4081
177
        NamedDecl *Target = nullptr;
4082
        // Check for an existing type with this name.
4083
177
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4084
177
                       Sema::LookupOrdinaryName);
4085
177
        if (S.LookupName(R, S.TUScope)) {
4086
177
          Target = R.getFoundDecl();
4087
177
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4088
177
            ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4089
177
            if (const ObjCObjectPointerType *InterfacePointerType =
4090
177
                  castExpr->getType()->getAsObjCInterfacePointerType()) {
4091
96
              ObjCInterfaceDecl *ExprClass
4092
96
                = InterfacePointerType->getObjectType()->getInterface();
4093
96
              if ((CastClass == ExprClass) ||
4094
96
                  
(83
ExprClass83
&&
CastClass->isSuperClassOf(ExprClass)83
))
4095
76
                return true;
4096
20
              if (warn) {
4097
8
                S.Diag(castExpr->getBeginLoc(),
4098
8
                       diag::warn_objc_invalid_bridge_to_cf)
4099
8
                    << castExpr->getType()->getPointeeType() << T;
4100
8
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4101
8
              }
4102
20
              return false;
4103
96
            } else 
if (81
castExpr->getType()->isObjCIdType()81
||
4104
81
                       (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4105
68
                          castExpr->getType(), CastClass)))
4106
              // ok to cast an 'id' expression to a CFtype.
4107
              // ok to cast an 'id<plist>' expression to CFtype provided plist
4108
              // adopts all of CFtype's ObjetiveC's class plist.
4109
65
              return true;
4110
16
            else {
4111
16
              if (warn) {
4112
8
                S.Diag(castExpr->getBeginLoc(),
4113
8
                       diag::warn_objc_invalid_bridge_to_cf)
4114
8
                    << castExpr->getType() << castType;
4115
8
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4116
8
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4117
8
              }
4118
16
              return false;
4119
16
            }
4120
177
          }
4121
177
        }
4122
0
        S.Diag(castExpr->getBeginLoc(),
4123
0
               diag::err_objc_ns_bridged_invalid_cfobject)
4124
0
            << castExpr->getType() << castType;
4125
0
        S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4126
0
        if (Target)
4127
0
          S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4128
0
        return true;
4129
177
      }
4130
0
      return false;
4131
183
    }
4132
122
    T = TDNDecl->getUnderlyingType();
4133
122
  }
4134
127
  return true;
4135
310
}
SemaExprObjC.cpp:bool CheckObjCBridgeCFCast<clang::ObjCBridgeMutableAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4070
148
                                  bool &HadTheAttribute, bool warn) {
4071
148
  QualType T = castType;
4072
148
  HadTheAttribute = false;
4073
284
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4074
143
    TypedefNameDecl *TDNDecl = TD->getDecl();
4075
143
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4076
7
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4077
7
        HadTheAttribute = true;
4078
7
        if (Parm->isStr("id"))
4079
0
          return true;
4080
4081
7
        NamedDecl *Target = nullptr;
4082
        // Check for an existing type with this name.
4083
7
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4084
7
                       Sema::LookupOrdinaryName);
4085
7
        if (S.LookupName(R, S.TUScope)) {
4086
7
          Target = R.getFoundDecl();
4087
7
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4088
7
            ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4089
7
            if (const ObjCObjectPointerType *InterfacePointerType =
4090
7
                  castExpr->getType()->getAsObjCInterfacePointerType()) {
4091
7
              ObjCInterfaceDecl *ExprClass
4092
7
                = InterfacePointerType->getObjectType()->getInterface();
4093
7
              if ((CastClass == ExprClass) ||
4094
7
                  
(2
ExprClass2
&&
CastClass->isSuperClassOf(ExprClass)2
))
4095
5
                return true;
4096
2
              if (warn) {
4097
1
                S.Diag(castExpr->getBeginLoc(),
4098
1
                       diag::warn_objc_invalid_bridge_to_cf)
4099
1
                    << castExpr->getType()->getPointeeType() << T;
4100
1
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4101
1
              }
4102
2
              return false;
4103
7
            } else 
if (0
castExpr->getType()->isObjCIdType()0
||
4104
0
                       (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4105
0
                          castExpr->getType(), CastClass)))
4106
              // ok to cast an 'id' expression to a CFtype.
4107
              // ok to cast an 'id<plist>' expression to CFtype provided plist
4108
              // adopts all of CFtype's ObjetiveC's class plist.
4109
0
              return true;
4110
0
            else {
4111
0
              if (warn) {
4112
0
                S.Diag(castExpr->getBeginLoc(),
4113
0
                       diag::warn_objc_invalid_bridge_to_cf)
4114
0
                    << castExpr->getType() << castType;
4115
0
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4116
0
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4117
0
              }
4118
0
              return false;
4119
0
            }
4120
7
          }
4121
7
        }
4122
0
        S.Diag(castExpr->getBeginLoc(),
4123
0
               diag::err_objc_ns_bridged_invalid_cfobject)
4124
0
            << castExpr->getType() << castType;
4125
0
        S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4126
0
        if (Target)
4127
0
          S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4128
0
        return true;
4129
7
      }
4130
0
      return false;
4131
7
    }
4132
136
    T = TDNDecl->getUnderlyingType();
4133
136
  }
4134
141
  return true;
4135
148
}
4136
4137
4.50M
void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
4138
4.50M
  if (!getLangOpts().ObjC)
4139
4.14M
    return;
4140
  // warn in presence of __bridge casting to or from a toll free bridge cast.
4141
361k
  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
4142
361k
  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4143
361k
  if (castACTC == ACTC_retainable && 
exprACTC == ACTC_coreFoundation7.18k
) {
4144
583
    bool HasObjCBridgeAttr;
4145
583
    bool ObjCBridgeAttrWillNotWarn =
4146
583
      CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4147
583
                                            false);
4148
583
    if (ObjCBridgeAttrWillNotWarn && 
HasObjCBridgeAttr542
)
4149
93
      return;
4150
490
    bool HasObjCBridgeMutableAttr;
4151
490
    bool ObjCBridgeMutableAttrWillNotWarn =
4152
490
      CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4153
490
                                                   HasObjCBridgeMutableAttr, false);
4154
490
    if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
4155
7
      return;
4156
4157
483
    if (HasObjCBridgeAttr)
4158
37
      CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4159
37
                                            true);
4160
446
    else if (HasObjCBridgeMutableAttr)
4161
0
      CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4162
0
                                                   HasObjCBridgeMutableAttr, true);
4163
483
  }
4164
360k
  else if (castACTC == ACTC_coreFoundation && 
exprACTC == ACTC_retainable27.5k
) {
4165
294
    bool HasObjCBridgeAttr;
4166
294
    bool ObjCBridgeAttrWillNotWarn =
4167
294
      CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4168
294
                                            false);
4169
294
    if (ObjCBridgeAttrWillNotWarn && 
HasObjCBridgeAttr274
)
4170
147
      return;
4171
147
    bool HasObjCBridgeMutableAttr;
4172
147
    bool ObjCBridgeMutableAttrWillNotWarn =
4173
147
      CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4174
147
                                                   HasObjCBridgeMutableAttr, false);
4175
147
    if (ObjCBridgeMutableAttrWillNotWarn && 
HasObjCBridgeMutableAttr146
)
4176
5
      return;
4177
4178
142
    if (HasObjCBridgeAttr)
4179
16
      CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4180
16
                                            true);
4181
126
    else if (HasObjCBridgeMutableAttr)
4182
1
      CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4183
1
                                                   HasObjCBridgeMutableAttr, true);
4184
142
  }
4185
361k
}
4186
4187
4.50M
void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
4188
4.50M
  QualType SrcType = castExpr->getType();
4189
4.50M
  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
4190
96
    if (PRE->isExplicitProperty()) {
4191
32
      if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
4192
32
        SrcType = PDecl->getType();
4193
32
    }
4194
64
    else if (PRE->isImplicitProperty()) {
4195
64
      if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
4196
64
        SrcType = Getter->getReturnType();
4197
64
    }
4198
96
  }
4199
4200
4.50M
  ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
4201
4.50M
  ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
4202
4.50M
  if (srcExprACTC != ACTC_retainable || 
castExprACTC != ACTC_coreFoundation1.83k
)
4203
4.50M
    return;
4204
244
  CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
4205
244
                                    castExpr);
4206
244
}
4207
4208
bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
4209
143
                                         CastKind &Kind) {
4210
143
  if (!getLangOpts().ObjC)
4211
114
    return false;
4212
29
  ARCConversionTypeClass exprACTC =
4213
29
    classifyTypeForARCConversion(castExpr->getType());
4214
29
  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4215
29
  if ((castACTC == ACTC_retainable && 
exprACTC == ACTC_coreFoundation15
) ||
4216
29
      
(15
castACTC == ACTC_coreFoundation15
&&
exprACTC == ACTC_retainable8
)) {
4217
22
    CheckTollFreeBridgeCast(castType, castExpr);
4218
22
    Kind = (castACTC == ACTC_coreFoundation) ? 
CK_BitCast8
4219
22
                                             : 
CK_CPointerToObjCPointerCast14
;
4220
22
    return true;
4221
22
  }
4222
7
  return false;
4223
29
}
4224
4225
bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4226
                                            QualType DestType, QualType SrcType,
4227
                                            ObjCInterfaceDecl *&RelatedClass,
4228
                                            ObjCMethodDecl *&ClassMethod,
4229
                                            ObjCMethodDecl *&InstanceMethod,
4230
                                            TypedefNameDecl *&TDNDecl,
4231
995
                                            bool CfToNs, bool Diagnose) {
4232
995
  QualType T = CfToNs ? 
SrcType201
:
DestType794
;
4233
995
  ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4234
995
  if (!ObjCBAttr)
4235
928
    return false;
4236
4237
67
  IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4238
67
  IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4239
67
  IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4240
67
  if (!RCId)
4241
0
    return false;
4242
67
  NamedDecl *Target = nullptr;
4243
  // Check for an existing type with this name.
4244
67
  LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4245
67
                 Sema::LookupOrdinaryName);
4246
67
  if (!LookupName(R, TUScope)) {
4247
2
    if (Diagnose) {
4248
2
      Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4249
2
            << SrcType << DestType;
4250
2
      Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4251
2
    }
4252
2
    return false;
4253
2
  }
4254
65
  Target = R.getFoundDecl();
4255
65
  if (Target && isa<ObjCInterfaceDecl>(Target))
4256
63
    RelatedClass = cast<ObjCInterfaceDecl>(Target);
4257
2
  else {
4258
2
    if (Diagnose) {
4259
2
      Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4260
2
            << SrcType << DestType;
4261
2
      Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4262
2
      if (Target)
4263
2
        Diag(Target->getBeginLoc(), diag::note_declared_at);
4264
2
    }
4265
2
    return false;
4266
2
  }
4267
4268
  // Check for an existing class method with the given selector name.
4269
63
  if (CfToNs && 
CMId26
) {
4270
16
    Selector Sel = Context.Selectors.getUnarySelector(CMId);
4271
16
    ClassMethod = RelatedClass->lookupMethod(Sel, false);
4272
16
    if (!ClassMethod) {
4273
1
      if (Diagnose) {
4274
1
        Diag(Loc, diag::err_objc_bridged_related_known_method)
4275
1
              << SrcType << DestType << Sel << false;
4276
1
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4277
1
      }
4278
1
      return false;
4279
1
    }
4280
16
  }
4281
4282
  // Check for an existing instance method with the given selector name.
4283
62
  if (!CfToNs && 
IMId37
) {
4284
31
    Selector Sel = Context.Selectors.getNullarySelector(IMId);
4285
31
    InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4286
31
    if (!InstanceMethod) {
4287
1
      if (Diagnose) {
4288
1
        Diag(Loc, diag::err_objc_bridged_related_known_method)
4289
1
              << SrcType << DestType << Sel << true;
4290
1
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4291
1
      }
4292
1
      return false;
4293
1
    }
4294
31
  }
4295
61
  return true;
4296
62
}
4297
4298
bool
4299
Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4300
                                        QualType DestType, QualType SrcType,
4301
1.16M
                                        Expr *&SrcExpr, bool Diagnose) {
4302
1.16M
  ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4303
1.16M
  ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4304
1.16M
  bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && 
lhsExprACTC == ACTC_retainable41.8k
);
4305
1.16M
  bool NsToCf = (rhsExprACTC == ACTC_retainable && 
lhsExprACTC == ACTC_coreFoundation57.9k
);
4306
1.16M
  if (!CfToNs && 
!NsToCf1.15M
)
4307
1.15M
    return false;
4308
4309
995
  ObjCInterfaceDecl *RelatedClass;
4310
995
  ObjCMethodDecl *ClassMethod = nullptr;
4311
995
  ObjCMethodDecl *InstanceMethod = nullptr;
4312
995
  TypedefNameDecl *TDNDecl = nullptr;
4313
995
  if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4314
995
                                        ClassMethod, InstanceMethod, TDNDecl,
4315
995
                                        CfToNs, Diagnose))
4316
934
    return false;
4317
4318
61
  if (CfToNs) {
4319
    // Implicit conversion from CF to ObjC object is needed.
4320
25
    if (ClassMethod) {
4321
15
      if (Diagnose) {
4322
15
        std::string ExpressionString = "[";
4323
15
        ExpressionString += RelatedClass->getNameAsString();
4324
15
        ExpressionString += " ";
4325
15
        ExpressionString += ClassMethod->getSelector().getAsString();
4326
15
        SourceLocation SrcExprEndLoc =
4327
15
            getLocForEndOfToken(SrcExpr->getEndLoc());
4328
        // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4329
15
        Diag(Loc, diag::err_objc_bridged_related_known_method)
4330
15
            << SrcType << DestType << ClassMethod->getSelector() << false
4331
15
            << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4332
15
                                          ExpressionString)
4333
15
            << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4334
15
        Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4335
15
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4336
4337
15
        QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4338
        // Argument.
4339
15
        Expr *args[] = { SrcExpr };
4340
15
        ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4341
15
                                      ClassMethod->getLocation(),
4342
15
                                      ClassMethod->getSelector(), ClassMethod,
4343
15
                                      MultiExprArg(args, 1));
4344
15
        SrcExpr = msg.get();
4345
15
      }
4346
15
      return true;
4347
15
    }
4348
25
  }
4349
36
  else {
4350
    // Implicit conversion from ObjC type to CF object is needed.
4351
36
    if (InstanceMethod) {
4352
30
      if (Diagnose) {
4353
30
        std::string ExpressionString;
4354
30
        SourceLocation SrcExprEndLoc =
4355
30
            getLocForEndOfToken(SrcExpr->getEndLoc());
4356
30
        if (InstanceMethod->isPropertyAccessor())
4357
6
          if (const ObjCPropertyDecl *PDecl =
4358
6
                  InstanceMethod->findPropertyDecl()) {
4359
            // fixit: ObjectExpr.propertyname when it is  aproperty accessor.
4360
6
            ExpressionString = ".";
4361
6
            ExpressionString += PDecl->getNameAsString();
4362
6
            Diag(Loc, diag::err_objc_bridged_related_known_method)
4363
6
                << SrcType << DestType << InstanceMethod->getSelector() << true
4364
6
                << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4365
6
          }
4366
30
        if (ExpressionString.empty()) {
4367
          // Provide a fixit: [ObjectExpr InstanceMethod]
4368
24
          ExpressionString = " ";
4369
24
          ExpressionString += InstanceMethod->getSelector().getAsString();
4370
24
          ExpressionString += "]";
4371
4372
24
          Diag(Loc, diag::err_objc_bridged_related_known_method)
4373
24
              << SrcType << DestType << InstanceMethod->getSelector() << true
4374
24
              << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
4375
24
              << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4376
24
        }
4377
30
        Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4378
30
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4379
4380
30
        ExprResult msg =
4381
30
          BuildInstanceMessageImplicit(SrcExpr, SrcType,
4382
30
                                       InstanceMethod->getLocation(),
4383
30
                                       InstanceMethod->getSelector(),
4384
30
                                       InstanceMethod, None);
4385
30
        SrcExpr = msg.get();
4386
30
      }
4387
30
      return true;
4388
30
    }
4389
36
  }
4390
16
  return false;
4391
61
}
4392
4393
Sema::ARCConversionResult
4394
Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4395
                          Expr *&castExpr, CheckedConversionKind CCK,
4396
                          bool Diagnose, bool DiagnoseCFAudited,
4397
18.5k
                          BinaryOperatorKind Opc) {
4398
18.5k
  QualType castExprType = castExpr->getType();
4399
4400
  // For the purposes of the classification, we assume reference types
4401
  // will bind to temporaries.
4402
18.5k
  QualType effCastType = castType;
4403
18.5k
  if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4404
174
    effCastType = ref->getPointeeType();
4405
4406
18.5k
  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4407
18.5k
  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4408
18.5k
  if (exprACTC == castACTC) {
4409
    // Check for viability and report error if casting an rvalue to a
4410
    // life-time qualifier.
4411
16.9k
    if (castACTC == ACTC_retainable &&
4412
16.9k
        
(2.07k
CCK == CCK_CStyleCast2.07k
||
CCK == CCK_OtherCast1.97k
) &&
4413
16.9k
        
castType != castExprType109
) {
4414
59
      const Type *DT = castType.getTypePtr();
4415
59
      QualType QDT = castType;
4416
      // We desugar some types but not others. We ignore those
4417
      // that cannot happen in a cast; i.e. auto, and those which
4418
      // should not be de-sugared; i.e typedef.
4419
59
      if (const ParenType *PT = dyn_cast<ParenType>(DT))
4420
0
        QDT = PT->desugar();
4421
59
      else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4422
3
        QDT = TP->desugar();
4423
56
      else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4424
26
        QDT = AT->desugar();
4425
59
      if (QDT != castType &&
4426
59
          
QDT.getObjCLifetime() != Qualifiers::OCL_None29
) {
4427
23
        if (Diagnose) {
4428
23
          SourceLocation loc = (castRange.isValid() ? 
castRange.getBegin()16
4429
23
                                                    : 
castExpr->getExprLoc()7
);
4430
23
          Diag(loc, diag::err_arc_nolifetime_behavior);
4431
23
        }
4432
23
        return ACR_error;
4433
23
      }
4434
59
    }
4435
16.9k
    return ACR_okay;
4436
16.9k
  }
4437
4438
  // The life-time qualifier cast check above is all we need for ObjCWeak.
4439
  // ObjCAutoRefCount has more restrictions on what is legal.
4440
1.57k
  if (!getLangOpts().ObjCAutoRefCount)
4441
3
    return ACR_okay;
4442
4443
1.57k
  if (isAnyCLike(exprACTC) && 
isAnyCLike(castACTC)1.22k
)
return ACR_okay742
;
4444
4445
  // Allow all of these types to be cast to integer types (but not
4446
  // vice-versa).
4447
829
  if (castACTC == ACTC_none && 
castType->isIntegralType(Context)38
)
4448
30
    return ACR_okay;
4449
4450
  // Allow casts between pointers to lifetime types (e.g., __strong id*)
4451
  // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4452
  // must be explicit.
4453
  // Allow conversions between pointers to lifetime types and coreFoundation
4454
  // pointers too, but only when the conversions are explicit.
4455
799
  if (exprACTC == ACTC_indirectRetainable &&
4456
799
      
(107
castACTC == ACTC_voidPtr107
||
4457
107
       
(7
castACTC == ACTC_coreFoundation7
&&
isCast(CCK)2
)))
4458
101
    return ACR_okay;
4459
698
  if (castACTC == ACTC_indirectRetainable &&
4460
698
      
(69
exprACTC == ACTC_voidPtr69
||
exprACTC == ACTC_coreFoundation18
) &&
4461
698
      
isCast(CCK)53
)
4462
48
    return ACR_okay;
4463
4464
650
  switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4465
  // For invalid casts, fall through.
4466
363
  case ACC_invalid:
4467
363
    break;
4468
4469
  // Do nothing for both bottom and +0.
4470
207
  case ACC_bottom:
4471
275
  case ACC_plusZero:
4472
275
    return ACR_okay;
4473
4474
  // If the result is +1, consume it here.
4475
12
  case ACC_plusOne:
4476
12
    castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4477
12
                                        CK_ARCConsumeObject, castExpr, nullptr,
4478
12
                                        VK_PRValue, FPOptionsOverride());
4479
12
    Cleanup.setExprNeedsCleanups(true);
4480
12
    return ACR_okay;
4481
650
  }
4482
4483
  // If this is a non-implicit cast from id or block type to a
4484
  // CoreFoundation type, delay complaining in case the cast is used
4485
  // in an acceptable context.
4486
363
  if (exprACTC == ACTC_retainable && 
isAnyRetainable(castACTC)190
&&
isCast(CCK)175
)
4487
122
    return ACR_unbridged;
4488
4489
  // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4490
  // to 'NSString *', instead of falling through to report a "bridge cast"
4491
  // diagnostic.
4492
241
  if (castACTC == ACTC_retainable && 
exprACTC == ACTC_none165
&&
4493
241
      
CheckConversionToObjCLiteral(castType, castExpr, Diagnose)5
)
4494
2
    return ACR_error;
4495
4496
  // Do not issue "bridge cast" diagnostic when implicit casting
4497
  // a retainable object to a CF type parameter belonging to an audited
4498
  // CF API function. Let caller issue a normal type mismatched diagnostic
4499
  // instead.
4500
239
  if ((!DiagnoseCFAudited || 
exprACTC != ACTC_retainable1
||
4501
239
       
castACTC != ACTC_coreFoundation1
) &&
4502
239
      
!(238
exprACTC == ACTC_voidPtr238
&&
castACTC == ACTC_retainable33
&&
4503
238
        
(29
Opc == BO_NE29
||
Opc == BO_EQ27
))) {
4504
231
    if (Diagnose)
4505
227
      diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4506
227
                                castExpr, exprACTC, CCK);
4507
231
    return ACR_error;
4508
231
  }
4509
8
  return ACR_okay;
4510
239
}
4511
4512
/// Given that we saw an expression with the ARCUnbridgedCastTy
4513
/// placeholder type, complain bitterly.
4514
111
void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4515
  // We expect the spurious ImplicitCastExpr to already have been stripped.
4516
111
  assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4517
0
  CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4518
4519
111
  SourceRange castRange;
4520
111
  QualType castType;
4521
111
  CheckedConversionKind CCK;
4522
4523
111
  if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4524
100
    castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4525
100
    castType = cast->getTypeAsWritten();
4526
100
    CCK = CCK_CStyleCast;
4527
100
  } else 
if (ExplicitCastExpr *11
cast11
= dyn_cast<ExplicitCastExpr>(realCast)) {
4528
11
    castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4529
11
    castType = cast->getTypeAsWritten();
4530
11
    CCK = CCK_OtherCast;
4531
11
  } else {
4532
0
    llvm_unreachable("Unexpected ImplicitCastExpr");
4533
0
  }
4534
4535
111
  ARCConversionTypeClass castACTC =
4536
111
    classifyTypeForARCConversion(castType.getNonReferenceType());
4537
4538
111
  Expr *castExpr = realCast->getSubExpr();
4539
111
  assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4540
4541
0
  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4542
111
                            castExpr, realCast, ACTC_retainable, CCK);
4543
111
}
4544
4545
/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4546
/// type, remove the placeholder cast.
4547
135
Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4548
135
  assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4549
4550
135
  if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4551
7
    Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4552
7
    return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4553
128
  } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4554
0
    assert(uo->getOpcode() == UO_Extension);
4555
0
    Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4556
0
    return UnaryOperator::Create(Context, sub, UO_Extension, sub->getType(),
4557
0
                                 sub->getValueKind(), sub->getObjectKind(),
4558
0
                                 uo->getOperatorLoc(), false,
4559
0
                                 CurFPFeatureOverrides());
4560
128
  } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4561
0
    assert(!gse->isResultDependent());
4562
4563
0
    unsigned n = gse->getNumAssocs();
4564
0
    SmallVector<Expr *, 4> subExprs;
4565
0
    SmallVector<TypeSourceInfo *, 4> subTypes;
4566
0
    subExprs.reserve(n);
4567
0
    subTypes.reserve(n);
4568
0
    for (const GenericSelectionExpr::Association assoc : gse->associations()) {
4569
0
      subTypes.push_back(assoc.getTypeSourceInfo());
4570
0
      Expr *sub = assoc.getAssociationExpr();
4571
0
      if (assoc.isSelected())
4572
0
        sub = stripARCUnbridgedCast(sub);
4573
0
      subExprs.push_back(sub);
4574
0
    }
4575
4576
0
    return GenericSelectionExpr::Create(
4577
0
        Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4578
0
        subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4579
0
        gse->containsUnexpandedParameterPack(), gse->getResultIndex());
4580
128
  } else {
4581
128
    assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4582
0
    return cast<ImplicitCastExpr>(e)->getSubExpr();
4583
128
  }
4584
135
}
4585
4586
bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4587
2.63k
                                                 QualType exprType) {
4588
2.63k
  QualType canCastType =
4589
2.63k
    Context.getCanonicalType(castType).getUnqualifiedType();
4590
2.63k
  QualType canExprType =
4591
2.63k
    Context.getCanonicalType(exprType).getUnqualifiedType();
4592
2.63k
  if (isa<ObjCObjectPointerType>(canCastType) &&
4593
2.63k
      
castType.getObjCLifetime() == Qualifiers::OCL_Weak1.40k
&&
4594
2.63k
      
canExprType->isObjCObjectPointerType()108
) {
4595
106
    if (const ObjCObjectPointerType *ObjT =
4596
106
        canExprType->getAs<ObjCObjectPointerType>())
4597
106
      if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4598
60
        return !ObjI->isArcWeakrefUnavailable();
4599
106
  }
4600
2.57k
  return true;
4601
2.63k
}
4602
4603
/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4604
66
static Expr *maybeUndoReclaimObject(Expr *e) {
4605
66
  Expr *curExpr = e, *prevExpr = nullptr;
4606
4607
  // Walk down the expression until we hit an implicit cast of kind
4608
  // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4609
121
  while (true) {
4610
121
    if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4611
7
      prevExpr = curExpr;
4612
7
      curExpr = pe->getSubExpr();
4613
7
      continue;
4614
7
    }
4615
4616
114
    if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4617
84
      if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4618
63
        if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4619
36
          if (!prevExpr)
4620
20
            return ice->getSubExpr();
4621
16
          if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4622
4
            pe->setSubExpr(ice->getSubExpr());
4623
12
          else
4624
12
            cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4625
16
          return e;
4626
36
        }
4627
4628
48
      prevExpr = curExpr;
4629
48
      curExpr = ce->getSubExpr();
4630
48
      continue;
4631
84
    }
4632
4633
    // Break out of the loop if curExpr is neither a Paren nor a Cast.
4634
30
    break;
4635
114
  }
4636
4637
30
  return e;
4638
66
}
4639
4640
ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4641
                                      ObjCBridgeCastKind Kind,
4642
                                      SourceLocation BridgeKeywordLoc,
4643
                                      TypeSourceInfo *TSInfo,
4644
351
                                      Expr *SubExpr) {
4645
351
  ExprResult SubResult = UsualUnaryConversions(SubExpr);
4646
351
  if (SubResult.isInvalid()) 
return ExprError()0
;
4647
351
  SubExpr = SubResult.get();
4648
4649
351
  QualType T = TSInfo->getType();
4650
351
  QualType FromType = SubExpr->getType();
4651
4652
351
  CastKind CK;
4653
4654
351
  bool MustConsume = false;
4655
351
  if (T->isDependentType() || 
SubExpr->isTypeDependent()340
) {
4656
    // Okay: we'll build a dependent expression type.
4657
14
    CK = CK_Dependent;
4658
337
  } else if (T->isObjCARCBridgableType() && 
FromType->isCARCBridgableType()165
) {
4659
    // Casting CF -> id
4660
165
    CK = (T->isBlockPointerType() ? 
CK_AnyPointerToBlockPointerCast1
4661
165
                                  : 
CK_CPointerToObjCPointerCast164
);
4662
165
    switch (Kind) {
4663
59
    case OBC_Bridge:
4664
59
      break;
4665
4666
0
    case OBC_BridgeRetained: {
4667
0
      bool br = isKnownName("CFBridgingRelease");
4668
0
      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4669
0
        << 2
4670
0
        << FromType
4671
0
        << (T->isBlockPointerType()? 1 : 0)
4672
0
        << T
4673
0
        << SubExpr->getSourceRange()
4674
0
        << Kind;
4675
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4676
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4677
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4678
0
        << FromType << br
4679
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc,
4680
0
                                        br ? "CFBridgingRelease "
4681
0
                                           : "__bridge_transfer ");
4682
4683
0
      Kind = OBC_Bridge;
4684
0
      break;
4685
0
    }
4686
4687
106
    case OBC_BridgeTransfer:
4688
      // We must consume the Objective-C object produced by the cast.
4689
106
      MustConsume = true;
4690
106
      break;
4691
165
    }
4692
172
  } else if (T->isCARCBridgableType() && 
FromType->isObjCARCBridgableType()169
) {
4693
    // Okay: id -> CF
4694
169
    CK = CK_BitCast;
4695
169
    switch (Kind) {
4696
66
    case OBC_Bridge:
4697
      // Reclaiming a value that's going to be __bridge-casted to CF
4698
      // is very dangerous, so we don't do it.
4699
66
      SubExpr = maybeUndoReclaimObject(SubExpr);
4700
66
      break;
4701
4702
103
    case OBC_BridgeRetained:
4703
      // Produce the object before casting it.
4704
103
      SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject,
4705
103
                                         SubExpr, nullptr, VK_PRValue,
4706
103
                                         FPOptionsOverride());
4707
103
      break;
4708
4709
0
    case OBC_BridgeTransfer: {
4710
0
      bool br = isKnownName("CFBridgingRetain");
4711
0
      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4712
0
        << (FromType->isBlockPointerType()? 1 : 0)
4713
0
        << FromType
4714
0
        << 2
4715
0
        << T
4716
0
        << SubExpr->getSourceRange()
4717
0
        << Kind;
4718
4719
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4720
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4721
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4722
0
        << T << br
4723
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc,
4724
0
                          br ? "CFBridgingRetain " : "__bridge_retained");
4725
4726
0
      Kind = OBC_Bridge;
4727
0
      break;