Coverage Report

Created: 2021-01-26 06:56

/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.47k
                                        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.47k
  StringLiteral *S = cast<StringLiteral>(Strings[0]);
42
43
  // If we have a multi-part string, merge it all together.
44
6.47k
  if (Strings.size() != 1) {
45
    // Concatenate objc strings.
46
243
    SmallString<128> StrBuf;
47
243
    SmallVector<SourceLocation, 8> StrLocs;
48
49
2.46k
    for (Expr *E : Strings) {
50
2.46k
      S = cast<StringLiteral>(E);
51
52
      // ObjC strings can't be wide or UTF.
53
2.46k
      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.46k
      StrBuf += S->getString();
61
62
      // Get the locations of the string tokens.
63
2.46k
      StrLocs.append(S->tokloc_begin(), S->tokloc_end());
64
2.46k
    }
65
66
    // Create the aggregate string with the appropriate content and location
67
    // information.
68
243
    const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
69
243
    assert(CAT && "String literal not of constant array type!");
70
243
    QualType StrTy = Context.getConstantArrayType(
71
243
        CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), nullptr,
72
243
        CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
73
243
    S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
74
243
                              /*Pascal=*/false, StrTy, &StrLocs[0],
75
243
                              StrLocs.size());
76
243
  }
77
78
6.47k
  return BuildObjCStringLiteral(AtLocs[0], S);
79
6.47k
}
80
81
6.50k
ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
82
  // Verify that this composite string is acceptable for ObjC strings.
83
6.50k
  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.50k
  QualType Ty = Context.getObjCConstantStringInterface();
91
6.50k
  if (!Ty.isNull()) {
92
5.80k
    Ty = Context.getObjCObjectPointerType(Ty);
93
699
  } else if (getLangOpts().NoConstantCFStrings) {
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
0
    } 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
213
    } 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.50k
  return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
143
6.50k
}
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
704
                                 Selector Sel, const ObjCMethodDecl *Method) {
150
704
  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
701
  QualType ReturnType = Method->getReturnType();
158
701
  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
697
  return true;
167
697
}
168
169
/// Maps ObjCLiteralKind to NSClassIdKindKind
170
static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
171
607
                                            Sema::ObjCLiteralKind LiteralKind) {
172
607
  switch (LiteralKind) {
173
176
    case Sema::LK_Array:
174
176
      return NSAPI::ClassId_NSArray;
175
189
    case Sema::LK_Dictionary:
176
189
      return NSAPI::ClassId_NSDictionary;
177
183
    case Sema::LK_Numeric:
178
183
      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
0
  }
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
583
                                            Sema::ObjCLiteralKind LiteralKind) {
199
583
  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
559
  } 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
552
  return true;
213
552
}
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
583
                                            Sema::ObjCLiteralKind LiteralKind) {
221
583
  NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
222
583
  IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
223
583
  NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
224
583
                                     Sema::LookupOrdinaryName);
225
583
  ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
226
583
  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
583
  if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
234
31
    ID = nullptr;
235
31
  }
236
237
583
  return ID;
238
583
}
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
970
                                                SourceRange R = SourceRange()) {
246
970
  Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
247
970
      S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
248
249
970
  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
968
  if (S.NSNumberLiteralMethods[*Kind])
259
632
    return S.NSNumberLiteralMethods[*Kind];
260
261
336
  Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
262
336
                                                        /*Instance=*/false);
263
264
336
  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
336
  if (!S.NSNumberDecl) {
269
181
    S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
270
181
                                                       Sema::LK_Numeric);
271
181
    if (!S.NSNumberDecl) {
272
4
      return nullptr;
273
4
    }
274
332
  }
275
276
332
  if (S.NSNumberPointer.isNull()) {
277
    // generate the pointer to NSNumber type.
278
177
    QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
279
177
    S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
280
177
  }
281
282
  // Look for the appropriate method within NSNumber.
283
332
  ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
284
332
  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
332
  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
328
  S.NSNumberLiteralMethods[*Kind] = Method;
311
328
  return Method;
312
328
}
313
314
/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
315
/// numeric literal expression. Type of the expression will be "NSNumber *".
316
859
ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
317
  // Determine the type of the literal.
318
859
  QualType NumberType = Number->getType();
319
859
  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
22
    switch (Char->getKind()) {
323
22
    case CharacterLiteral::Ascii:
324
22
    case CharacterLiteral::UTF8:
325
22
      NumberType = Context.CharTy;
326
22
      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
859
    }
340
859
  }
341
342
  // Look for the appropriate method within NSNumber.
343
  // Construct the literal.
344
859
  SourceRange NR(Number->getSourceRange());
345
859
  ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
346
859
                                                    true, NR);
347
859
  if (!Method)
348
7
    return ExprError();
349
350
  // Convert the number to the type that the parameter expects.
351
852
  ParmVarDecl *ParamDecl = Method->parameters()[0];
352
852
  InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
353
852
                                                                    ParamDecl);
354
852
  ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
355
852
                                                         SourceLocation(),
356
852
                                                         Number);
357
852
  if (ConvertedNumber.isInvalid())
358
0
    return ExprError();
359
852
  Number = ConvertedNumber.get();
360
361
  // Use the effective source range of the literal, including the leading '@'.
362
852
  return MaybeBindToTemporary(
363
852
           new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
364
852
                                       SourceRange(AtLoc, NR.getEnd())));
365
852
}
366
367
ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
368
                                      SourceLocation ValueLoc,
369
51
                                      bool Value) {
370
51
  ExprResult Inner;
371
51
  if (getLangOpts().CPlusPlus) {
372
13
    Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : 
tok::kw_false7
);
373
31
  } 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
27
    Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 
04
);
377
31
    Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
378
31
                              CK_IntegralToBoolean);
379
31
  }
380
381
51
  return BuildObjCNumericLiteral(AtLoc, Inner.get());
382
51
}
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.15k
                                                    bool ArrayLiteral = false) {
389
  // If the expression is type-dependent, there's nothing for us to do.
390
1.15k
  if (Element->isTypeDependent())
391
16
    return Element;
392
393
1.14k
  ExprResult Result = S.CheckPlaceholderExpr(Element);
394
1.14k
  if (Result.isInvalid())
395
0
    return ExprError();
396
1.14k
  Element = Result.get();
397
398
  // In C++, check for an implicit conversion to an Objective-C object pointer
399
  // type.
400
1.14k
  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
1.12k
  }
410
411
1.12k
  Expr *OrigElement = Element;
412
413
  // Perform lvalue-to-rvalue conversion.
414
1.12k
  Result = S.DefaultLvalueConversion(Element);
415
1.12k
  if (Result.isInvalid())
416
0
    return ExprError();
417
1.12k
  Element = Result.get();
418
419
  // Make sure that we have an Objective-C pointer type or block.
420
1.12k
  if (!Element->getType()->isObjCObjectPointerType() &&
421
21
      !Element->getType()->isBlockPointerType()) {
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
18
        isa<CharacterLiteral>(OrigElement) ||
427
16
        isa<FloatingLiteral>(OrigElement) ||
428
16
        isa<ObjCBoolLiteralExpr>(OrigElement) ||
429
16
        isa<CXXBoolLiteralExpr>(OrigElement)) {
430
4
      if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
431
2
        int Which = isa<CharacterLiteral>(OrigElement) ? 1
432
2
                  : (isa<CXXBoolLiteralExpr>(OrigElement) ||
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
1.11k
  }
471
1.11k
  if (ArrayLiteral)
472
463
    if (ObjCStringLiteral *getString =
473
279
          dyn_cast<ObjCStringLiteral>(OrigElement)) {
474
279
      if (StringLiteral *SL = getString->getString()) {
475
279
        unsigned numConcat = SL->getNumConcatenated();
476
279
        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
279
      }
490
279
    }
491
492
  // Make sure that the element has the type that the container factory
493
  // function expects.
494
1.11k
  return S.PerformCopyInitialization(
495
1.11k
      InitializedEntity::InitializeParameter(S.Context, T,
496
1.11k
                                             /*Consumed=*/false),
497
1.11k
      Element->getBeginLoc(), Element);
498
1.11k
}
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
18
                  dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
536
18
            assert((SL->isAscii() || SL->isUTF8()) &&
537
18
                   "unexpected character encoding");
538
18
            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
4
        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
105
      }
630
105
    }
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
71
  } else if (const EnumType *ET = 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
295
  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
295
  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
298
ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
794
298
  SourceLocation Loc = SR.getBegin();
795
796
298
  if (!NSArrayDecl) {
797
174
    NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
798
174
                                                    Sema::LK_Array);
799
174
    if (!NSArrayDecl) {
800
4
      return ExprError();
801
4
    }
802
294
  }
803
804
  // Find the arrayWithObjects:count: method, if we haven't done so already.
805
294
  QualType IdT = Context.getObjCIdType();
806
294
  if (!ArrayWithObjectsMethod) {
807
171
    Selector
808
171
      Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
809
171
    ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
810
171
    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
171
    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
171
    QualType T = Method->parameters()[0]->getType();
844
171
    const PointerType *PtrT = T->getAs<PointerType>();
845
171
    if (!PtrT ||
846
171
        !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
169
    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
169
    ArrayWithObjectsMethod = Method;
870
169
  }
871
872
292
  QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
873
292
  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
292
  Expr **ElementsBuffer = Elements.data();
878
771
  for (unsigned I = 0, N = Elements.size(); I != N; 
++I479
) {
879
486
    ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
880
486
                                                             ElementsBuffer[I],
881
486
                                                             RequiredType, true);
882
486
    if (Converted.isInvalid())
883
7
      return ExprError();
884
885
479
    ElementsBuffer[I] = Converted.get();
886
479
  }
887
888
285
  QualType Ty
889
285
    = Context.getObjCObjectPointerType(
890
285
                                    Context.getObjCInterfaceType(NSArrayDecl));
891
892
285
  return MaybeBindToTemporary(
893
285
           ObjCArrayLiteral::Create(Context, Elements, Ty,
894
285
                                    ArrayWithObjectsMethod, SR));
895
292
}
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
213
                                        ObjCDictionaryLiteral *Literal) {
902
213
  if (Literal->isValueDependent() || 
Literal->isTypeDependent()208
)
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
208
  struct APSIntCompare {
909
156
    bool operator()(const llvm::APSInt &LHS, const llvm::APSInt &RHS) const {
910
156
      return llvm::APSInt::compareValues(LHS, RHS) < 0;
911
156
    }
912
208
  };
913
914
208
  llvm::DenseMap<StringRef, SourceLocation> StringKeys;
915
208
  std::map<llvm::APSInt, SourceLocation, APSIntCompare> IntegralKeys;
916
917
254
  auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
918
254
    auto Pair = Map.insert({Key, Loc});
919
254
    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
254
  };
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
182
  auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
918
182
    auto Pair = Map.insert({Key, Loc});
919
182
    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
182
  };
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
526
  for (unsigned Idx = 0, End = Literal->getNumElements(); Idx != End; 
++Idx318
) {
926
318
    Expr *Key = Literal->getKeyValueElement(Idx).Key->IgnoreParenImpCasts();
927
928
318
    if (auto *StrLit = dyn_cast<ObjCStringLiteral>(Key)) {
929
180
      StringRef Bytes = StrLit->getString()->getBytes();
930
180
      SourceLocation Loc = StrLit->getExprLoc();
931
180
      checkOneKey(StringKeys, Bytes, Loc);
932
180
    }
933
934
318
    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
72
                               Expr::SE_AllowSideEffects)) {
947
72
        checkOneKey(IntegralKeys, Result.Val.getInt(), Loc);
948
72
      }
949
74
    }
950
318
  }
951
208
}
952
953
ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
954
242
                              MutableArrayRef<ObjCDictionaryElement> Elements) {
955
242
  SourceLocation Loc = SR.getBegin();
956
957
242
  if (!NSDictionaryDecl) {
958
171
    NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
959
171
                                                         Sema::LK_Dictionary);
960
171
    if (!NSDictionaryDecl) {
961
21
      return ExprError();
962
21
    }
963
221
  }
964
965
  // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
966
  // so already.
967
221
  QualType IdT = Context.getObjCIdType();
968
221
  if (!DictionaryWithObjectsMethod) {
969
151
    Selector Sel = NSAPIObj->getNSDictionarySelector(
970
151
                               NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
971
151
    ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
972
151
    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
151
    if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
1010
151
                              Method))
1011
0
       return ExprError();
1012
1013
    // Dig out the type that all values should be converted to.
1014
151
    QualType ValueT = Method->parameters()[0]->getType();
1015
151
    const PointerType *PtrValue = ValueT->getAs<PointerType>();
1016
151
    if (!PtrValue ||
1017
151
        !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
151
    QualType KeyT = Method->parameters()[1]->getType();
1029
151
    const PointerType *PtrKey = KeyT->getAs<PointerType>();
1030
151
    if (!PtrKey ||
1031
151
        !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1032
100
                                        IdT)) {
1033
100
      bool err = true;
1034
100
      if (PtrKey) {
1035
100
        if (QIDNSCopying.isNull()) {
1036
          // key argument of selector is id<NSCopying>?
1037
100
          if (ObjCProtocolDecl *NSCopyingPDecl =
1038
98
              LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
1039
98
            ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
1040
98
            QIDNSCopying =
1041
98
              Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
1042
98
                                        llvm::makeArrayRef(
1043
98
                                          (ObjCProtocolDecl**) PQ,
1044
98
                                          1),
1045
98
                                        false);
1046
98
            QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
1047
98
          }
1048
100
        }
1049
100
        if (!QIDNSCopying.isNull())
1050
98
          err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1051
98
                                                QIDNSCopying);
1052
100
      }
1053
1054
100
      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
149
    }
1064
1065
    // Check that the 'count' parameter is integral.
1066
149
    QualType CountType = Method->parameters()[2]->getType();
1067
149
    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
149
    DictionaryWithObjectsMethod = Method;
1079
149
  }
1080
1081
219
  QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1082
219
  QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1083
219
  QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1084
219
  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
219
  bool HasPackExpansions = false;
1089
337
  for (ObjCDictionaryElement &Element : Elements) {
1090
    // Check the key.
1091
337
    ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1092
337
                                                       KeyT);
1093
337
    if (Key.isInvalid())
1094
3
      return ExprError();
1095
1096
    // Check the value.
1097
334
    ExprResult Value
1098
334
      = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1099
334
    if (Value.isInvalid())
1100
3
      return ExprError();
1101
1102
331
    Element.Key = Key.get();
1103
331
    Element.Value = Value.get();
1104
1105
331
    if (Element.EllipsisLoc.isInvalid())
1106
325
      continue;
1107
1108
6
    if (!Element.Key->containsUnexpandedParameterPack() &&
1109
2
        !Element.Value->containsUnexpandedParameterPack()) {
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
213
  QualType Ty = Context.getObjCObjectPointerType(
1121
213
      Context.getObjCInterfaceType(NSDictionaryDecl));
1122
1123
213
  auto *Literal =
1124
213
      ObjCDictionaryLiteral::Create(Context, Elements, HasPackExpansions, Ty,
1125
213
                                    DictionaryWithObjectsMethod, SR);
1126
213
  CheckObjCDictionaryLiteralDuplicateKeys(*this, Literal);
1127
213
  return MaybeBindToTemporary(Literal);
1128
219
}
1129
1130
ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1131
                                      TypeSourceInfo *EncodedTypeInfo,
1132
146
                                      SourceLocation RParenLoc) {
1133
146
  QualType EncodedType = EncodedTypeInfo->getType();
1134
146
  QualType StrTy;
1135
146
  if (EncodedType->isDependentType())
1136
1
    StrTy = Context.DependentTy;
1137
145
  else {
1138
145
    if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1139
143
        !EncodedType->isVoidType()) // void is handled too.
1140
142
      if (RequireCompleteType(AtLoc, EncodedType,
1141
142
                              diag::err_incomplete_type_objc_at_encode,
1142
142
                              EncodedTypeInfo->getTypeLoc()))
1143
2
        return ExprError();
1144
1145
143
    std::string Str;
1146
143
    QualType NotEncodedT;
1147
143
    Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1148
143
    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
143
    StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
1155
143
  }
1156
1157
144
  return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1158
146
}
1159
1160
ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1161
                                           SourceLocation EncodeLoc,
1162
                                           SourceLocation LParenLoc,
1163
                                           ParsedType ty,
1164
143
                                           SourceLocation RParenLoc) {
1165
  // FIXME: Preserve type source info ?
1166
143
  TypeSourceInfo *TInfo;
1167
143
  QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1168
143
  if (!TInfo)
1169
0
    TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1170
0
                                             getLocForEndOfToken(LParenLoc));
1171
1172
143
  return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1173
143
}
1174
1175
static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1176
                                               SourceLocation AtLoc,
1177
                                               SourceLocation LParenLoc,
1178
                                               SourceLocation RParenLoc,
1179
                                               ObjCMethodDecl *Method,
1180
420
                                               ObjCMethodList &MethList) {
1181
420
  ObjCMethodList *M = &MethList;
1182
420
  bool Warned = false;
1183
532
  for (M = M->getNext(); M; 
M=M->getNext()112
) {
1184
112
    ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1185
112
    if (MatchingMethodDecl == Method ||
1186
112
        isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1187
103
        MatchingMethodDecl->getSelector() != Method->getSelector())
1188
101
      continue;
1189
11
    if (!S.MatchTwoMethodDeclarations(Method,
1190
9
                                      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
420
  return Warned;
1204
420
}
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
268
      S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1213
245
    return;
1214
29
  bool Warned = false;
1215
29
  for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1216
230
       e = S.MethodPool.end(); b != e; 
b++201
) {
1217
    // first, instance methods
1218
210
    ObjCMethodList &InstMethList = b->second.first;
1219
210
    if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1220
210
                                                      Method, InstMethList))
1221
9
      Warned = true;
1222
1223
    // second, class methods
1224
210
    ObjCMethodList &ClsMethList = b->second.second;
1225
210
    if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1226
210
                                                      Method, ClsMethList) || Warned)
1227
9
      return;
1228
210
  }
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.45k
  for (; M; 
M = M->getNext()902
) {
1239
902
    ObjCMethodDecl *Method = M->getMethod();
1240
902
    if (!Method)
1241
270
      continue;
1242
632
    assert(Method->getSelector() == Sel && "Method with wrong selector in method list");
1243
632
    if (Method->isDirectMethod()) {
1244
112
      anyDirect = true;
1245
112
      DirectMethod = Method;
1246
112
    } else
1247
520
      onlyDirect = false;
1248
632
  }
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
192
  return DirectInstance ? 
DirectInstance82
: DirectClass;
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
405
                                             bool WarnMultipleSelectors) {
1299
405
  ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1300
405
                             SourceRange(LParenLoc, RParenLoc));
1301
405
  if (!Method)
1302
180
    Method = LookupFactoryMethodInGlobalPool(Sel,
1303
180
                                          SourceRange(LParenLoc, RParenLoc));
1304
405
  if (!Method) {
1305
131
    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
126
        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
405
  if (Method &&
1352
274
      Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1353
273
      !getSourceManager().isInSystemHeader(Method->getLocation()))
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
405
  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
405
    }
1381
405
  }
1382
405
  QualType Ty = Context.getObjCSelType();
1383
405
  return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1384
405
}
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.26k
ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1416
1.26k
  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.26k
  ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1422
1.26k
  if (!method)
1423
0
    return nullptr;
1424
1425
1.26k
  tryCaptureVariable(method->getSelfDecl(), Loc);
1426
1427
1.26k
  return method;
1428
1.26k
}
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
0
  }
1442
1443
81
  if (T == Context.getObjCInstanceType())
1444
33
    return Context.getObjCIdType();
1445
1446
48
  return origType;
1447
48
}
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.8k
                                             bool isSuperMessage) {
1459
24.8k
  assert(Method && "Must have a method");
1460
24.8k
  if (!Method->hasRelatedResultType())
1461
16.1k
    return Method->getSendResultType(ReceiverType);
1462
1463
8.64k
  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.55k
  auto transferNullability = [&](QualType type) -> QualType {
1468
    // If the method's result type has nullability, extract it.
1469
8.55k
    if (auto nullability = Method->getSendResultType(ReceiverType)
1470
2.96k
                             ->getNullability(Context)){
1471
      // Strip off any outer nullability sugar from the provided type.
1472
2.96k
      (void)AttributedType::stripOuterNullability(type);
1473
1474
      // Form a new attributed type using the method result type's nullability.
1475
2.96k
      return Context.getAttributedType(
1476
2.96k
               AttributedType::getNullabilityAttrKind(*nullability),
1477
2.96k
               type,
1478
2.96k
               type);
1479
2.96k
    }
1480
1481
5.59k
    return type;
1482
5.59k
  };
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.64k
  if (Method->isInstanceMethod() && 
isClassMessage3.64k
)
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.61k
  if (isSuperMessage) {
1495
486
    if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1496
486
      if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1497
486
        return transferNullability(
1498
486
                 Context.getObjCObjectPointerType(
1499
486
                   Context.getObjCInterfaceType(Class)));
1500
486
      }
1501
8.13k
  }
1502
1503
  //   - if the receiver is the name of a class U, T is a pointer to U
1504
8.13k
  if (ReceiverType->getAsObjCInterfaceType())
1505
4.90k
    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.22k
  if (ReceiverType->isObjCClassType() ||
1509
3.17k
      ReceiverType->isObjCQualifiedClassType())
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.16k
  return transferNullability(ReceiverType);
1517
3.16k
}
1518
1519
QualType Sema::getMessageSendResultType(const Expr *Receiver,
1520
                                        QualType ReceiverType,
1521
                                        ObjCMethodDecl *Method,
1522
                                        bool isClassMessage,
1523
24.8k
                                        bool isSuperMessage) {
1524
  // Produce the result type.
1525
24.8k
  QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1526
24.8k
                                                     Method,
1527
24.8k
                                                     isClassMessage,
1528
24.8k
                                                     isSuperMessage);
1529
1530
  // If this is a class message, ignore the nullability of the receiver.
1531
24.8k
  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
8.22k
    if (Receiver && 
Receiver->isObjCSelfExpr()246
) {
1538
83
      assert(ReceiverType->isObjCClassType() && "expected a Class self");
1539
83
      QualType T = Method->getSendResultType(ReceiverType);
1540
83
      AttributedType::stripOuterNullability(T);
1541
83
      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
25
        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
8.19k
    }
1556
8.19k
    return resultType;
1557
8.19k
  }
1558
1559
  // There is nothing left to do if the result type cannot have a nullability
1560
  // specifier.
1561
16.6k
  if (!resultType->canHaveNullability())
1562
9.23k
    return resultType;
1563
1564
  // Map the nullability of the result into a table index.
1565
7.36k
  unsigned receiverNullabilityIdx = 0;
1566
7.36k
  if (Optional<NullabilityKind> nullability =
1567
89
          ReceiverType->getNullability(Context)) {
1568
89
    if (*nullability == NullabilityKind::NullableResult)
1569
5
      nullability = NullabilityKind::Nullable;
1570
89
    receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1571
89
  }
1572
1573
7.36k
  unsigned resultNullabilityIdx = 0;
1574
7.36k
  if (Optional<NullabilityKind> nullability =
1575
1.94k
          resultType->getNullability(Context)) {
1576
1.94k
    if (*nullability == NullabilityKind::NullableResult)
1577
1
      nullability = NullabilityKind::Nullable;
1578
1.94k
    resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1579
1.94k
  }
1580
1581
  // The table of nullability mappings, indexed by the receiver's nullability
1582
  // and then the result type's nullability.
1583
7.36k
  static const uint8_t None = 0;
1584
7.36k
  static const uint8_t NonNull = 1;
1585
7.36k
  static const uint8_t Nullable = 2;
1586
7.36k
  static const uint8_t Unspecified = 3;
1587
7.36k
  static const uint8_t nullabilityMap[4][4] = {
1588
    //                  None        NonNull       Nullable    Unspecified
1589
7.36k
    /* None */        { None,       None,         Nullable,   None },
1590
7.36k
    /* NonNull */     { None,       NonNull,      Nullable,   Unspecified },
1591
7.36k
    /* Nullable */    { Nullable,   Nullable,     Nullable,   Nullable },
1592
7.36k
    /* Unspecified */ { None,       Unspecified,  Nullable,   Unspecified }
1593
7.36k
  };
1594
1595
7.36k
  unsigned newResultNullabilityIdx
1596
7.36k
    = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1597
7.36k
  if (newResultNullabilityIdx == resultNullabilityIdx)
1598
5.79k
    return resultType;
1599
1600
  // Strip off the existing nullability. This removes as little type sugar as
1601
  // possible.
1602
1.57k
  do {
1603
1.57k
    if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1604
1.50k
      resultType = attributed->getModifiedType();
1605
69
    } else {
1606
69
      resultType = resultType.getDesugaredType(Context);
1607
69
    }
1608
1.57k
  } while (resultType->getNullability(Context));
1609
1610
  // Add nullability back if needed.
1611
1.57k
  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.56k
  return resultType;
1620
1.56k
}
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
20
        dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1633
20
    const ObjCContainerDecl *iface;
1634
20
    if (const ObjCCategoryImplDecl *catImpl =
1635
0
          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
18
  }
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
22
      Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
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
10
        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
26.0k
    ExprValueKind &VK) {
1718
26.0k
  SourceLocation SelLoc;
1719
26.0k
  if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1720
26.0k
    SelLoc = SelectorLocs.front();
1721
0
  else
1722
0
    SelLoc = lbrac;
1723
1724
26.0k
  if (!Method) {
1725
    // Apply default argument promotion as for (C99 6.5.2.2p6).
1726
2.08k
    for (unsigned i = 0, e = Args.size(); i != e; 
i++914
) {
1727
914
      if (Args[i]->isTypeDependent())
1728
1
        continue;
1729
1730
913
      ExprResult result;
1731
913
      if (getLangOpts().DebuggerSupport) {
1732
508
        QualType paramTy; // ignored
1733
508
        result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1734
405
      } else {
1735
405
        result = DefaultArgumentPromotion(Args[i]);
1736
405
      }
1737
913
      if (result.isInvalid())
1738
0
        return true;
1739
913
      Args[i] = result.get();
1740
913
    }
1741
1742
1.17k
    unsigned DiagID;
1743
1.17k
    if (getLangOpts().ObjCAutoRefCount)
1744
3
      DiagID = diag::err_arc_method_not_found;
1745
1.17k
    else
1746
1.17k
      DiagID = isClassMessage ? 
diag::warn_class_method_not_found116
1747
1.05k
                              : diag::warn_inst_method_not_found;
1748
1.17k
    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
34
                                  : diag::warn_instance_method_not_found_with_typo;
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.17k
    if (getLangOpts().DebuggerSupport) {
1785
543
      ReturnType = Context.UnknownAnyTy;
1786
632
    } else {
1787
632
      ReturnType = Context.getObjCIdType();
1788
632
    }
1789
1.17k
    VK = VK_RValue;
1790
1.17k
    return false;
1791
24.8k
  }
1792
1793
24.8k
  ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1794
24.8k
                                        isClassMessage, isSuperMessage);
1795
24.8k
  VK = Expr::getValueKindForType(Method->getReturnType());
1796
1797
24.8k
  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.8k
  if (Method->param_size() > Sel.getNumArgs())
1801
4
    NumNamedArgs = Method->param_size();
1802
  // FIXME. This need be cleaned up.
1803
24.8k
  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.8k
  Optional<ArrayRef<QualType>> typeArgs
1812
24.8k
    = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1813
24.8k
  bool IsError = false;
1814
41.0k
  for (unsigned i = 0; i < NumNamedArgs; 
i++16.2k
) {
1815
    // We can't do any type-checking on a type-dependent argument.
1816
16.2k
    if (Args[i]->isTypeDependent())
1817
10
      continue;
1818
1819
16.2k
    Expr *argExpr = Args[i];
1820
1821
16.2k
    ParmVarDecl *param = Method->parameters()[i];
1822
16.2k
    assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1823
1824
16.2k
    if (param->hasAttr<NoEscapeAttr>())
1825
5
      if (auto *BE = dyn_cast<BlockExpr>(
1826
2
              argExpr->IgnoreParenNoopCasts(Context)))
1827
2
        BE->getBlockDecl()->setDoesNotEscape();
1828
1829
    // Strip the unbridged-cast placeholder expression off unless it's
1830
    // a consumed argument.
1831
16.2k
    if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1832
4
        !param->hasAttr<CFConsumedAttr>())
1833
2
      argExpr = stripARCUnbridgedCast(argExpr);
1834
1835
    // If the parameter is __unknown_anytype, infer its type
1836
    // from the argument.
1837
16.2k
    if (param->getType() == Context.UnknownAnyTy) {
1838
4
      QualType paramType;
1839
4
      ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1840
4
      if (argE.isInvalid()) {
1841
0
        IsError = true;
1842
4
      } else {
1843
4
        Args[i] = argE.get();
1844
1845
        // Update the parameter type in-place.
1846
4
        param->setType(paramType);
1847
4
      }
1848
4
      continue;
1849
4
    }
1850
1851
16.2k
    QualType origParamType = param->getType();
1852
16.2k
    QualType paramType = param->getType();
1853
16.2k
    if (typeArgs)
1854
4.01k
      paramType = paramType.substObjCTypeArgs(
1855
4.01k
                    Context,
1856
4.01k
                    *typeArgs,
1857
4.01k
                    ObjCSubstitutionContext::Parameter);
1858
1859
16.2k
    if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1860
16.2k
                            paramType,
1861
16.2k
                            diag::err_call_incomplete_argument, argExpr))
1862
0
      return true;
1863
1864
16.2k
    InitializedEntity Entity
1865
16.2k
      = InitializedEntity::InitializeParameter(Context, param, paramType);
1866
16.2k
    ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1867
16.2k
    if (ArgE.isInvalid())
1868
32
      IsError = true;
1869
16.2k
    else {
1870
16.2k
      Args[i] = ArgE.getAs<Expr>();
1871
1872
      // If we are type-erasing a block to a block-compatible
1873
      // Objective-C pointer type, we may need to extend the lifetime
1874
      // of the block object.
1875
16.2k
      if (typeArgs && 
Args[i]->isRValue()3.99k
&&
paramType->isBlockPointerType()3.99k
&&
1876
2
          Args[i]->getType()->isBlockPointerType() &&
1877
2
          origParamType->isObjCObjectPointerType()) {
1878
2
        ExprResult arg = Args[i];
1879
2
        maybeExtendBlockObject(arg);
1880
2
        Args[i] = arg.get();
1881
2
      }
1882
16.2k
    }
1883
16.2k
  }
1884
1885
  // Promote additional arguments to variadic methods.
1886
24.8k
  if (Method->isVariadic()) {
1887
3.65k
    for (unsigned i = NumNamedArgs, e = Args.size(); i < e; 
++i2.49k
) {
1888
2.49k
      if (Args[i]->isTypeDependent())
1889
6
        continue;
1890
1891
2.48k
      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1892
2.48k
                                                        nullptr);
1893
2.48k
      IsError |= Arg.isInvalid();
1894
2.48k
      Args[i] = Arg.get();
1895
2.48k
    }
1896
23.6k
  } else {
1897
    // Check for extra arguments to non-variadic methods.
1898
23.6k
    if (Args.size() != NumNamedArgs) {
1899
2
      Diag(Args[NumNamedArgs]->getBeginLoc(),
1900
2
           diag::err_typecheck_call_too_many_args)
1901
2
          << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1902
2
          << Method->getSourceRange()
1903
2
          << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
1904
2
                         Args.back()->getEndLoc());
1905
2
    }
1906
23.6k
  }
1907
1908
24.8k
  DiagnoseSentinelCalls(Method, SelLoc, Args);
1909
1910
  // Do additional checkings on method.
1911
24.8k
  IsError |= CheckObjCMethodCall(
1912
24.8k
      Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1913
1914
24.8k
  return IsError;
1915
24.8k
}
1916
1917
19.0k
bool Sema::isSelfExpr(Expr *RExpr) {
1918
  // 'self' is objc 'self' in an objc method only.
1919
19.0k
  ObjCMethodDecl *Method =
1920
19.0k
      dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1921
19.0k
  return isSelfExpr(RExpr, Method);
1922
19.0k
}
1923
1924
19.0k
bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1925
19.0k
  if (!method) 
return false15.2k
;
1926
1927
3.81k
  receiver = receiver->IgnoreParenLValueCasts();
1928
3.81k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1929
1.61k
    if (DRE->getDecl() == method->getSelfDecl())
1930
997
      return true;
1931
2.82k
  return false;
1932
2.82k
}
1933
1934
/// LookupMethodInType - Look up a method in an ObjCObjectType.
1935
ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1936
18.3k
                                               bool isInstance) {
1937
18.3k
  const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1938
18.3k
  if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1939
    // Look it up in the main interface (and categories, etc.)
1940
18.2k
    if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1941
4.47k
      return method;
1942
1943
    // Okay, look for "private" methods declared in any
1944
    // @implementations we've seen.
1945
13.8k
    if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1946
14
      return method;
1947
13.8k
  }
1948
1949
  // Check qualifiers.
1950
13.8k
  for (const auto *I : objType->quals())
1951
26
    if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1952
22
      return method;
1953
1954
13.8k
  return nullptr;
1955
13.8k
}
1956
1957
/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1958
/// list of a qualified objective pointer type.
1959
ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1960
                                              const ObjCObjectPointerType *OPT,
1961
                                              bool Instance)
1962
3.66k
{
1963
3.66k
  ObjCMethodDecl *MD = nullptr;
1964
324
  for (const auto *PROTO : OPT->quals()) {
1965
324
    if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1966
228
      return MD;
1967
228
    }
1968
324
  }
1969
3.43k
  return nullptr;
1970
3.66k
}
1971
1972
/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1973
/// objective C interface.  This is a property reference expression.
1974
ExprResult Sema::
1975
HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1976
                          Expr *BaseExpr, SourceLocation OpLoc,
1977
                          DeclarationName MemberName,
1978
                          SourceLocation MemberLoc,
1979
                          SourceLocation SuperLoc, QualType SuperType,
1980
2.20k
                          bool Super) {
1981
2.20k
  const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1982
2.20k
  ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1983
1984
2.20k
  if (!MemberName.isIdentifier()) {
1985
1
    Diag(MemberLoc, diag::err_invalid_property_name)
1986
1
      << MemberName << QualType(OPT, 0);
1987
1
    return ExprError();
1988
1
  }
1989
1990
2.20k
  IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1991
1992
64
  SourceRange BaseRange = Super? SourceRange(SuperLoc)
1993
2.14k
                               : BaseExpr->getSourceRange();
1994
2.20k
  if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1995
2.20k
                          diag::err_property_not_found_forward_class,
1996
2.20k
                          MemberName, BaseRange))
1997
1
    return ExprError();
1998
1999
2.20k
  if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
2000
1.88k
          Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2001
    // Check whether we can reference this property.
2002
1.88k
    if (DiagnoseUseOfDecl(PD, MemberLoc))
2003
0
      return ExprError();
2004
1.88k
    if (Super)
2005
58
      return new (Context)
2006
58
          ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2007
58
                              OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
2008
1.82k
    else
2009
1.82k
      return new (Context)
2010
1.82k
          ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2011
1.82k
                              OK_ObjCProperty, MemberLoc, BaseExpr);
2012
317
  }
2013
  // Check protocols on qualified interfaces.
2014
317
  for (const auto *I : OPT->quals())
2015
11
    if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
2016
2
            Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2017
      // Check whether we can reference this property.
2018
2
      if (DiagnoseUseOfDecl(PD, MemberLoc))
2019
0
        return ExprError();
2020
2021
2
      if (Super)
2022
0
        return new (Context) ObjCPropertyRefExpr(
2023
0
            PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
2024
0
            SuperLoc, SuperType);
2025
2
      else
2026
2
        return new (Context)
2027
2
            ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2028
2
                                OK_ObjCProperty, MemberLoc, BaseExpr);
2029
2
    }
2030
  // If that failed, look for an "implicit" property by seeing if the nullary
2031
  // selector is implemented.
2032
2033
  // FIXME: The logic for looking up nullary and unary selectors should be
2034
  // shared with the code in ActOnInstanceMessage.
2035
2036
315
  Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2037
315
  ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2038
2039
  // May be found in property's qualified list.
2040
315
  if (!Getter)
2041
62
    Getter = LookupMethodInQualifiedType(Sel, OPT, true);
2042
2043
  // If this reference is in an @implementation, check for 'private' methods.
2044
315
  if (!Getter)
2045
61
    Getter = IFace->lookupPrivateMethod(Sel);
2046
2047
315
  if (Getter) {
2048
    // Check if we can reference this property.
2049
262
    if (DiagnoseUseOfDecl(Getter, MemberLoc))
2050
0
      return ExprError();
2051
315
  }
2052
  // If we found a getter then this may be a valid dot-reference, we
2053
  // will look for the matching setter, in case it is needed.
2054
315
  Selector SetterSel =
2055
315
    SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
2056
315
                                           PP.getSelectorTable(), Member);
2057
315
  ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2058
2059
  // May be found in property's qualified list.
2060
315
  if (!Setter)
2061
162
    Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
2062
2063
315
  if (!Setter) {
2064
    // If this reference is in an @implementation, also check for 'private'
2065
    // methods.
2066
162
    Setter = IFace->lookupPrivateMethod(SetterSel);
2067
162
  }
2068
2069
315
  if (Setter && 
DiagnoseUseOfDecl(Setter, MemberLoc)157
)
2070
0
    return ExprError();
2071
2072
  // Special warning if member name used in a property-dot for a setter accessor
2073
  // does not use a property with same name; e.g. obj.X = ... for a property with
2074
  // name 'x'.
2075
315
  if (Setter && 
Setter->isImplicit()157
&&
Setter->isPropertyAccessor()14
&&
2076
8
      !IFace->FindPropertyDeclaration(
2077
8
          Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2078
8
      if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
2079
        // Do not warn if user is using property-dot syntax to make call to
2080
        // user named setter.
2081
8
        if (!(PDecl->getPropertyAttributes() &
2082
8
              ObjCPropertyAttribute::kind_setter))
2083
5
          Diag(MemberLoc,
2084
5
               diag::warn_property_access_suggest)
2085
5
          << MemberName << QualType(OPT, 0) << PDecl->getName()
2086
5
          << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
2087
8
      }
2088
8
  }
2089
2090
315
  if (Getter || 
Setter53
) {
2091
290
    if (Super)
2092
6
      return new (Context)
2093
6
          ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2094
6
                              OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
2095
284
    else
2096
284
      return new (Context)
2097
284
          ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2098
284
                              OK_ObjCProperty, MemberLoc, BaseExpr);
2099
2100
25
  }
2101
2102
  // Attempt to correct for typos in property names.
2103
25
  DeclFilterCCC<ObjCPropertyDecl> CCC{};
2104
25
  if (TypoCorrection Corrected = CorrectTypo(
2105
12
          DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
2106
12
          nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
2107
12
    DeclarationName TypoResult = Corrected.getCorrection();
2108
12
    if (TypoResult.isIdentifier() &&
2109
12
        TypoResult.getAsIdentifierInfo() == Member) {
2110
      // There is no need to try the correction if it is the same.
2111
3
      NamedDecl *ChosenDecl =
2112
3
        Corrected.isKeyword() ? 
nullptr0
: Corrected.getFoundDecl();
2113
3
      if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
2114
3
        if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
2115
          // This is a class property, we should not use the instance to
2116
          // access it.
2117
3
          Diag(MemberLoc, diag::err_class_property_found) << MemberName
2118
3
          << OPT->getInterfaceDecl()->getName()
2119
3
          << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
2120
3
                                          OPT->getInterfaceDecl()->getName());
2121
3
          return ExprError();
2122
3
        }
2123
9
    } else {
2124
9
      diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
2125
9
                                << MemberName << QualType(OPT, 0));
2126
9
      return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
2127
9
                                       TypoResult, MemberLoc,
2128
9
                                       SuperLoc, SuperType, Super);
2129
9
    }
2130
13
  }
2131
13
  ObjCInterfaceDecl *ClassDeclared;
2132
13
  if (ObjCIvarDecl *Ivar =
2133
3
      IFace->lookupInstanceVariable(Member, ClassDeclared)) {
2134
3
    QualType T = Ivar->getType();
2135
3
    if (const ObjCObjectPointerType * OBJPT =
2136
1
        T->getAsObjCInterfacePointerType()) {
2137
1
      if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
2138
1
                              diag::err_property_not_as_forward_class,
2139
1
                              MemberName, BaseExpr))
2140
1
        return ExprError();
2141
2
    }
2142
2
    Diag(MemberLoc,
2143
2
         diag::err_ivar_access_using_property_syntax_suggest)
2144
2
    << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
2145
2
    << FixItHint::CreateReplacement(OpLoc, "->");
2146
2
    return ExprError();
2147
2
  }
2148
2149
10
  Diag(MemberLoc, diag::err_property_not_found)
2150
10
    << MemberName << QualType(OPT, 0);
2151
10
  if (Setter)
2152
0
    Diag(Setter->getLocation(), diag::note_getter_unavailable)
2153
0
          << MemberName << BaseExpr->getSourceRange();
2154
10
  return ExprError();
2155
10
}
2156
2157
ExprResult Sema::
2158
ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
2159
                          IdentifierInfo &propertyName,
2160
                          SourceLocation receiverNameLoc,
2161
262
                          SourceLocation propertyNameLoc) {
2162
2163
262
  IdentifierInfo *receiverNamePtr = &receiverName;
2164
262
  ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
2165
262
                                                  receiverNameLoc);
2166
2167
262
  QualType SuperType;
2168
262
  if (!IFace) {
2169
    // If the "receiver" is 'super' in a method, handle it as an expression-like
2170
    // property reference.
2171
77
    if (receiverNamePtr->isStr("super")) {
2172
77
      if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
2173
77
        if (auto classDecl = CurMethod->getClassInterface()) {
2174
76
          SuperType = QualType(classDecl->getSuperClassType(), 0);
2175
76
          if (CurMethod->isInstanceMethod()) {
2176
65
            if (SuperType.isNull()) {
2177
              // The current class does not have a superclass.
2178
1
              Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
2179
1
                << CurMethod->getClassInterface()->getIdentifier();
2180
1
              return ExprError();
2181
1
            }
2182
64
            QualType T = Context.getObjCObjectPointerType(SuperType);
2183
2184
64
            return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
2185
64
                                             /*BaseExpr*/nullptr,
2186
64
                                             SourceLocation()/*OpLoc*/,
2187
64
                                             &propertyName,
2188
64
                                             propertyNameLoc,
2189
64
                                             receiverNameLoc, T, true);
2190
64
          }
2191
2192
          // Otherwise, if this is a class method, try dispatching to our
2193
          // superclass.
2194
11
          IFace = CurMethod->getClassInterface()->getSuperClass();
2195
11
        }
2196
77
      }
2197
77
    }
2198
2199
12
    if (!IFace) {
2200
1
      Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2201
1
                                                       << tok::l_paren;
2202
1
      return ExprError();
2203
1
    }
2204
196
  }
2205
2206
196
  Selector GetterSel;
2207
196
  Selector SetterSel;
2208
196
  if (auto PD = IFace->FindPropertyDeclaration(
2209
91
          &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2210
91
    GetterSel = PD->getGetterName();
2211
91
    SetterSel = PD->getSetterName();
2212
105
  } else {
2213
105
    GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2214
105
    SetterSel = SelectorTable::constructSetterSelector(
2215
105
        PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2216
105
  }
2217
2218
  // Search for a declared property first.
2219
196
  ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2220
2221
  // If this reference is in an @implementation, check for 'private' methods.
2222
196
  if (!Getter)
2223
20
    Getter = IFace->lookupPrivateClassMethod(GetterSel);
2224
2225
196
  if (Getter) {
2226
    // FIXME: refactor/share with ActOnMemberReference().
2227
    // Check if we can reference this property.
2228
188
    if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2229
0
      return ExprError();
2230
196
  }
2231
2232
  // Look for the matching setter, in case it is needed.
2233
196
  ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2234
196
  if (!Setter) {
2235
    // If this reference is in an @implementation, also check for 'private'
2236
    // methods.
2237
61
    Setter = IFace->lookupPrivateClassMethod(SetterSel);
2238
61
  }
2239
  // Look through local category implementations associated with the class.
2240
196
  if (!Setter)
2241
47
    Setter = IFace->getCategoryClassMethod(SetterSel);
2242
2243
196
  if (Setter && 
DiagnoseUseOfDecl(Setter, propertyNameLoc)149
)
2244
0
    return ExprError();
2245
2246
196
  if (Getter || 
Setter8
) {
2247
195
    if (!SuperType.isNull())
2248
11
      return new (Context)
2249
11
          ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2250
11
                              OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2251
11
                              SuperType);
2252
2253
184
    return new (Context) ObjCPropertyRefExpr(
2254
184
        Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2255
184
        propertyNameLoc, receiverNameLoc, IFace);
2256
184
  }
2257
1
  return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2258
1
                     << &propertyName << Context.getObjCInterfaceType(IFace));
2259
1
}
2260
2261
namespace {
2262
2263
class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
2264
 public:
2265
13
  ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2266
    // Determine whether "super" is acceptable in the current context.
2267
13
    if (Method && 
Method->getClassInterface()7
)
2268
7
      WantObjCSuper = Method->getClassInterface()->getSuperClass();
2269
13
  }
2270
2271
16
  bool ValidateCandidate(const TypoCorrection &candidate) override {
2272
16
    return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2273
8
        candidate.isKeyword("super");
2274
16
  }
2275
2276
13
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
2277
13
    return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
2278
13
  }
2279
};
2280
2281
} // end anonymous namespace
2282
2283
Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2284
                                               IdentifierInfo *Name,
2285
                                               SourceLocation NameLoc,
2286
                                               bool IsSuper,
2287
                                               bool HasTrailingDot,
2288
16.6k
                                               ParsedType &ReceiverType) {
2289
16.6k
  ReceiverType = nullptr;
2290
2291
  // If the identifier is "super" and there is no trailing dot, we're
2292
  // messaging super. If the identifier is "super" and there is a
2293
  // trailing dot, it's an instance message.
2294
16.6k
  if (IsSuper && 
S->isInObjcMethodScope()1.13k
)
2295
1.05k
    return HasTrailingDot? 
ObjCInstanceMessage4
:
ObjCSuperMessage1.05k
;
2296
2297
15.5k
  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2298
15.5k
  LookupName(Result, S);
2299
2300
15.5k
  switch (Result.getResultKind()) {
2301
416
  case LookupResult::NotFound:
2302
    // Normal name lookup didn't find anything. If we're in an
2303
    // Objective-C method, look for ivars. If we find one, we're done!
2304
    // FIXME: This is a hack. Ivar lookup should be part of normal
2305
    // lookup.
2306
416
    if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2307
410
      if (!Method->getClassInterface()) {
2308
        // Fall back: let the parser try to parse it as an instance message.
2309
1
        return ObjCInstanceMessage;
2310
1
      }
2311
2312
409
      ObjCInterfaceDecl *ClassDeclared;
2313
409
      if (Method->getClassInterface()->lookupInstanceVariable(Name,
2314
409
                                                              ClassDeclared))
2315
402
        return ObjCInstanceMessage;
2316
13
    }
2317
2318
    // Break out; we'll perform typo correction below.
2319
13
    break;
2320
2321
0
  case LookupResult::NotFoundInCurrentInstantiation:
2322
0
  case LookupResult::FoundOverloaded:
2323
0
  case LookupResult::FoundUnresolvedValue:
2324
0
  case LookupResult::Ambiguous:
2325
0
    Result.suppressDiagnostics();
2326
0
    return ObjCInstanceMessage;
2327
2328
15.1k
  case LookupResult::Found: {
2329
    // If the identifier is a class or not, and there is a trailing dot,
2330
    // it's an instance message.
2331
15.1k
    if (HasTrailingDot)
2332
69
      return ObjCInstanceMessage;
2333
    // We found something. If it's a type, then we have a class
2334
    // message. Otherwise, it's an instance message.
2335
15.0k
    NamedDecl *ND = Result.getFoundDecl();
2336
15.0k
    QualType T;
2337
15.0k
    if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2338
6.18k
      T = Context.getObjCInterfaceType(Class);
2339
8.91k
    else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2340
87
      T = Context.getTypeDeclType(Type);
2341
87
      DiagnoseUseOfDecl(Type, NameLoc);
2342
87
    }
2343
8.82k
    else
2344
8.82k
      return ObjCInstanceMessage;
2345
2346
    //  We have a class message, and T is the type we're
2347
    //  messaging. Build source-location information for it.
2348
6.26k
    TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2349
6.26k
    ReceiverType = CreateParsedType(T, TSInfo);
2350
6.26k
    return ObjCClassMessage;
2351
6.26k
  }
2352
13
  }
2353
2354
13
  ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
2355
13
  if (TypoCorrection Corrected = CorrectTypo(
2356
8
          Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
2357
8
          CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2358
8
    if (Corrected.isKeyword()) {
2359
      // If we've found the keyword "super" (the only keyword that would be
2360
      // returned by CorrectTypo), this is a send to super.
2361
4
      diagnoseTypo(Corrected,
2362
4
                   PDiag(diag::err_unknown_receiver_suggest) << Name);
2363
4
      return ObjCSuperMessage;
2364
4
    } else if (ObjCInterfaceDecl *Class =
2365
4
                   Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2366
      // If we found a declaration, correct when it refers to an Objective-C
2367
      // class.
2368
4
      diagnoseTypo(Corrected,
2369
4
                   PDiag(diag::err_unknown_receiver_suggest) << Name);
2370
4
      QualType T = Context.getObjCInterfaceType(Class);
2371
4
      TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2372
4
      ReceiverType = CreateParsedType(T, TSInfo);
2373
4
      return ObjCClassMessage;
2374
4
    }
2375
5
  }
2376
2377
  // Fall back: let the parser try to parse it as an instance message.
2378
5
  return ObjCInstanceMessage;
2379
5
}
2380
2381
ExprResult Sema::ActOnSuperMessage(Scope *S,
2382
                                   SourceLocation SuperLoc,
2383
                                   Selector Sel,
2384
                                   SourceLocation LBracLoc,
2385
                                   ArrayRef<SourceLocation> SelectorLocs,
2386
                                   SourceLocation RBracLoc,
2387
1.18k
                                   MultiExprArg Args) {
2388
  // Determine whether we are inside a method or not.
2389
1.18k
  ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2390
1.18k
  if (!Method) {
2391
0
    Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2392
0
    return ExprError();
2393
0
  }
2394
2395
1.18k
  ObjCInterfaceDecl *Class = Method->getClassInterface();
2396
1.18k
  if (!Class) {
2397
1
    Diag(SuperLoc, diag::err_no_super_class_message)
2398
1
      << Method->getDeclName();
2399
1
    return ExprError();
2400
1
  }
2401
2402
1.18k
  QualType SuperTy(Class->getSuperClassType(), 0);
2403
1.18k
  if (SuperTy.isNull()) {
2404
    // The current class does not have a superclass.
2405
2
    Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2406
2
      << Class->getIdentifier();
2407
2
    return ExprError();
2408
2
  }
2409
2410
  // We are in a method whose class has a superclass, so 'super'
2411
  // is acting as a keyword.
2412
1.18k
  if (Method->getSelector() == Sel)
2413
591
    getCurFunction()->ObjCShouldCallSuper = false;
2414
2415
1.18k
  if (Method->isInstanceMethod()) {
2416
    // Since we are in an instance method, this is an instance
2417
    // message to the superclass instance.
2418
973
    SuperTy = Context.getObjCObjectPointerType(SuperTy);
2419
973
    return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2420
973
                                Sel, /*Method=*/nullptr,
2421
973
                                LBracLoc, SelectorLocs, RBracLoc, Args);
2422
973
  }
2423
2424
  // Since we are in a class method, this is a class message to
2425
  // the superclass.
2426
208
  return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2427
208
                           SuperTy,
2428
208
                           SuperLoc, Sel, /*Method=*/nullptr,
2429
208
                           LBracLoc, SelectorLocs, RBracLoc, Args);
2430
208
}
2431
2432
ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2433
                                           bool isSuperReceiver,
2434
                                           SourceLocation Loc,
2435
                                           Selector Sel,
2436
                                           ObjCMethodDecl *Method,
2437
209
                                           MultiExprArg Args) {
2438
209
  TypeSourceInfo *receiverTypeInfo = nullptr;
2439
209
  if (!ReceiverType.isNull())
2440
209
    receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2441
2442
209
  return BuildClassMessage(receiverTypeInfo, ReceiverType,
2443
198
                          /*SuperLoc=*/isSuperReceiver ? 
Loc11
: SourceLocation(),
2444
209
                           Sel, Method, Loc, Loc, Loc, Args,
2445
209
                           /*isImplicit=*/true);
2446
209
}
2447
2448
static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2449
                               unsigned DiagID,
2450
                               bool (*refactor)(const ObjCMessageExpr *,
2451
22.0k
                                              const NSAPI &, edit::Commit &)) {
2452
22.0k
  SourceLocation MsgLoc = Msg->getExprLoc();
2453
22.0k
  if (S.Diags.isIgnored(DiagID, MsgLoc))
2454
10.3k
    return;
2455
2456
11.7k
  SourceManager &SM = S.SourceMgr;
2457
11.7k
  edit::Commit ECommit(SM, S.LangOpts);
2458
11.7k
  if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2459
12
    auto Builder = S.Diag(MsgLoc, DiagID)
2460
12
                   << Msg->getSelector() << Msg->getSourceRange();
2461
    // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2462
12
    if (!ECommit.isCommitable())
2463
0
      return;
2464
12
    for (edit::Commit::edit_iterator
2465
36
           I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; 
++I24
) {
2466
24
      const edit::Commit::Edit &Edit = *I;
2467
24
      switch (Edit.Kind) {
2468
0
      case edit::Commit::Act_Insert:
2469
0
        Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2470
0
                                                        Edit.Text,
2471
0
                                                        Edit.BeforePrev));
2472
0
        break;
2473
0
      case edit::Commit::Act_InsertFromRange:
2474
0
        Builder.AddFixItHint(
2475
0
            FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2476
0
                                                Edit.getInsertFromRange(SM),
2477
0
                                                Edit.BeforePrev));
2478
0
        break;
2479
24
      case edit::Commit::Act_Remove:
2480
24
        Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2481
24
        break;
2482
24
      }
2483
24
    }
2484
12
  }
2485
11.7k
}
2486
2487
22.0k
static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2488
22.0k
  applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2489
22.0k
                     edit::rewriteObjCRedundantCallWithLiteral);
2490
22.0k
}
2491
2492
static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2493
                               const ObjCMethodDecl *Method,
2494
                               ArrayRef<Expr *> Args, QualType ReceiverType,
2495
24.7k
                               bool IsClassObjectCall) {
2496
  // Check if this is a performSelector method that uses a selector that returns
2497
  // a record or a vector type.
2498
24.7k
  if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2499
44
      Args.empty())
2500
24.7k
    return;
2501
44
  const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2502
44
  if (!SE)
2503
2
    return;
2504
42
  ObjCMethodDecl *ImpliedMethod;
2505
42
  if (!IsClassObjectCall) {
2506
35
    const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2507
35
    if (!OPT || !OPT->getInterfaceDecl())
2508
10
      return;
2509
25
    ImpliedMethod =
2510
25
        OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2511
25
    if (!ImpliedMethod)
2512
5
      ImpliedMethod =
2513
5
          OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2514
7
  } else {
2515
7
    const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2516
7
    if (!IT)
2517
1
      return;
2518
6
    ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2519
6
    if (!ImpliedMethod)
2520
1
      ImpliedMethod =
2521
1
          IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2522
6
  }
2523
31
  if (!ImpliedMethod)
2524
4
    return;
2525
27
  QualType Ret = ImpliedMethod->getReturnType();
2526
27
  if (Ret->isRecordType() || 
Ret->isVectorType()15
||
Ret->isExtVectorType()13
) {
2527
14
    S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2528
14
        << Method->getSelector()
2529
14
        << (!Ret->isRecordType()
2530
2
                ? /*Vector*/ 2
2531
12
                : Ret->isUnionType() ? /*Union*/ 
12
: /*Struct*/
010
);
2532
14
    S.Diag(ImpliedMethod->getBeginLoc(),
2533
14
           diag::note_objc_unsafe_perform_selector_method_declared_here)
2534
14
        << ImpliedMethod->getSelector() << Ret;
2535
14
  }
2536
27
}
2537
2538
/// Diagnose use of %s directive in an NSString which is being passed
2539
/// as formatting string to formatting method.
2540
static void
2541
DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2542
                                        ObjCMethodDecl *Method,
2543
                                        Selector Sel,
2544
25.9k
                                        Expr **Args, unsigned NumArgs) {
2545
25.9k
  unsigned Idx = 0;
2546
25.9k
  bool Format = false;
2547
25.9k
  ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2548
25.9k
  if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2549
744
    Idx = 0;
2550
744
    Format = true;
2551
744
  }
2552
25.2k
  else if (Method) {
2553
15
    for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2554
15
      if (S.GetFormatNSStringIdx(I, Idx)) {
2555
14
        Format = true;
2556
14
        break;
2557
14
      }
2558
15
    }
2559
24.0k
  }
2560
25.9k
  if (!Format || 
NumArgs <= Idx758
)
2561
25.2k
    return;
2562
2563
755
  Expr *FormatExpr = Args[Idx];
2564
755
  if (ObjCStringLiteral *OSL =
2565
734
      dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2566
734
    StringLiteral *FormatString = OSL->getString();
2567
734
    if (S.FormatStringHasSArg(FormatString)) {
2568
92
      S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2569
92
        << "%s" << 0 << 0;
2570
92
      if (Method)
2571
92
        S.Diag(Method->getLocation(), diag::note_method_declared_at)
2572
92
          << Method->getDeclName();
2573
92
    }
2574
734
  }
2575
755
}
2576
2577
/// Build an Objective-C class message expression.
2578
///
2579
/// This routine takes care of both normal class messages and
2580
/// class messages to the superclass.
2581
///
2582
/// \param ReceiverTypeInfo Type source information that describes the
2583
/// receiver of this message. This may be NULL, in which case we are
2584
/// sending to the superclass and \p SuperLoc must be a valid source
2585
/// location.
2586
2587
/// \param ReceiverType The type of the object receiving the
2588
/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2589
/// type as that refers to. For a superclass send, this is the type of
2590
/// the superclass.
2591
///
2592
/// \param SuperLoc The location of the "super" keyword in a
2593
/// superclass message.
2594
///
2595
/// \param Sel The selector to which the message is being sent.
2596
///
2597
/// \param Method The method that this class message is invoking, if
2598
/// already known.
2599
///
2600
/// \param LBracLoc The location of the opening square bracket ']'.
2601
///
2602
/// \param RBracLoc The location of the closing square bracket ']'.
2603
///
2604
/// \param ArgsIn The message arguments.
2605
ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2606
                                   QualType ReceiverType,
2607
                                   SourceLocation SuperLoc,
2608
                                   Selector Sel,
2609
                                   ObjCMethodDecl *Method,
2610
                                   SourceLocation LBracLoc,
2611
                                   ArrayRef<SourceLocation> SelectorLocs,
2612
                                   SourceLocation RBracLoc,
2613
                                   MultiExprArg ArgsIn,
2614
8.10k
                                   bool isImplicit) {
2615
220
  SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2616
7.88k
    : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2617
8.10k
  if (LBracLoc.isInvalid()) {
2618
247
    Diag(Loc, diag::err_missing_open_square_message_send)
2619
247
      << FixItHint::CreateInsertion(Loc, "[");
2620
247
    LBracLoc = Loc;
2621
247
  }
2622
8.10k
  ArrayRef<SourceLocation> SelectorSlotLocs;
2623
8.10k
  if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2624
8.10k
    SelectorSlotLocs = SelectorLocs;
2625
0
  else
2626
0
    SelectorSlotLocs = Loc;
2627
8.10k
  SourceLocation SelLoc = SelectorSlotLocs.front();
2628
2629
8.10k
  if (ReceiverType->isDependentType()) {
2630
    // If the receiver type is dependent, we can't type-check anything
2631
    // at this point. Build a dependent expression.
2632
2
    unsigned NumArgs = ArgsIn.size();
2633
2
    Expr **Args = ArgsIn.data();
2634
2
    assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2635
2
    return ObjCMessageExpr::Create(
2636
2
        Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2637
2
        SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2638
2
        isImplicit);
2639
2
  }
2640
2641
  // Find the class to which we are sending this message.
2642
8.09k
  ObjCInterfaceDecl *Class = nullptr;
2643
8.09k
  const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2644
8.09k
  if (!ClassType || 
!(Class = ClassType->getInterface())8.08k
) {
2645
12
    Diag(Loc, diag::err_invalid_receiver_class_message)
2646
12
      << ReceiverType;
2647
12
    return ExprError();
2648
12
  }
2649
8.08k
  assert(Class && "We don't know which class we're messaging?");
2650
  // objc++ diagnoses during typename annotation.
2651
8.08k
  if (!getLangOpts().CPlusPlus)
2652
6.67k
    (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
2653
  // Find the method we are messaging.
2654
8.08k
  if (!Method) {
2655
7.86k
    SourceRange TypeRange
2656
208
      = SuperLoc.isValid()? SourceRange(SuperLoc)
2657
7.66k
                          : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2658
7.86k
    if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2659
7.86k
                            (getLangOpts().ObjCAutoRefCount
2660
349
                               ? diag::err_arc_receiver_forward_class
2661
7.51k
                               : diag::warn_receiver_forward_class),
2662
38
                            TypeRange)) {
2663
      // A forward class used in messaging is treated as a 'Class'
2664
38
      Method = LookupFactoryMethodInGlobalPool(Sel,
2665
38
                                               SourceRange(LBracLoc, RBracLoc));
2666
38
      if (Method && 
!getLangOpts().ObjCAutoRefCount35
)
2667
33
        Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2668
33
          << Method->getDeclName();
2669
38
    }
2670
7.86k
    if (!Method)
2671
7.83k
      Method = Class->lookupClassMethod(Sel);
2672
2673
    // If we have an implementation in scope, check "private" methods.
2674
7.86k
    if (!Method)
2675
309
      Method = Class->lookupPrivateClassMethod(Sel);
2676
2677
7.86k
    if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2678
7.75k
                                    nullptr, false, false, Class))
2679
0
      return ExprError();
2680
8.08k
  }
2681
2682
  // Check the argument types and determine the result type.
2683
8.08k
  QualType ReturnType;
2684
8.08k
  ExprValueKind VK = VK_RValue;
2685
2686
8.08k
  unsigned NumArgs = ArgsIn.size();
2687
8.08k
  Expr **Args = ArgsIn.data();
2688
8.08k
  if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2689
8.08k
                                MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2690
8.08k
                                Method, true, SuperLoc.isValid(), LBracLoc,
2691
8.08k
                                RBracLoc, SourceRange(), ReturnType, VK))
2692
4
    return ExprError();
2693
2694
8.08k
  if (Method && 
!Method->getReturnType()->isVoidType()7.97k
&&
2695
7.52k
      RequireCompleteType(LBracLoc, Method->getReturnType(),
2696
7.52k
                          diag::err_illegal_message_expr_incomplete_type))
2697
3
    return ExprError();
2698
2699
8.08k
  if (Method && 
Method->isDirectMethod()7.97k
&&
SuperLoc.isValid()4
) {
2700
3
    Diag(SuperLoc, diag::err_messaging_super_with_direct_method)
2701
3
        << FixItHint::CreateReplacement(
2702
3
               SuperLoc, getLangOpts().ObjCAutoRefCount
2703
1
                             ? "self"
2704
2
                             : Method->getClassInterface()->getName());
2705
3
    Diag(Method->getLocation(), diag::note_direct_method_declared_at)
2706
3
        << Method->getDeclName();
2707
3
  }
2708
2709
  // Warn about explicit call of +initialize on its own class. But not on 'super'.
2710
8.08k
  if (Method && 
Method->getMethodFamily() == OMF_initialize7.97k
) {
2711
7
    if (!SuperLoc.isValid()) {
2712
5
      const ObjCInterfaceDecl *ID =
2713
5
        dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2714
5
      if (ID == Class) {
2715
2
        Diag(Loc, diag::warn_direct_initialize_call);
2716
2
        Diag(Method->getLocation(), diag::note_method_declared_at)
2717
2
          << Method->getDeclName();
2718
2
      }
2719
5
    }
2720
2
    else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2721
      // [super initialize] is allowed only within an +initialize implementation
2722
2
      if (CurMeth->getMethodFamily() != OMF_initialize) {
2723
1
        Diag(Loc, diag::warn_direct_super_initialize_call);
2724
1
        Diag(Method->getLocation(), diag::note_method_declared_at)
2725
1
          << Method->getDeclName();
2726
1
        Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2727
1
        << CurMeth->getDeclName();
2728
1
      }
2729
2
    }
2730
7
  }
2731
2732
8.08k
  DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2733
2734
  // Construct the appropriate ObjCMessageExpr.
2735
8.08k
  ObjCMessageExpr *Result;
2736
8.08k
  if (SuperLoc.isValid())
2737
220
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2738
220
                                     SuperLoc, /*IsInstanceSuper=*/false,
2739
220
                                     ReceiverType, Sel, SelectorLocs,
2740
220
                                     Method, makeArrayRef(Args, NumArgs),
2741
220
                                     RBracLoc, isImplicit);
2742
7.86k
  else {
2743
7.86k
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2744
7.86k
                                     ReceiverTypeInfo, Sel, SelectorLocs,
2745
7.86k
                                     Method, makeArrayRef(Args, NumArgs),
2746
7.86k
                                     RBracLoc, isImplicit);
2747
7.86k
    if (!isImplicit)
2748
7.66k
      checkCocoaAPI(*this, Result);
2749
7.86k
  }
2750
8.08k
  if (Method)
2751
7.97k
    checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2752
7.97k
                       ReceiverType, /*IsClassObjectCall=*/true);
2753
8.08k
  return MaybeBindToTemporary(Result);
2754
8.08k
}
2755
2756
// ActOnClassMessage - used for both unary and keyword messages.
2757
// ArgExprs is optional - if it is present, the number of expressions
2758
// is obtained from Sel.getNumArgs().
2759
ExprResult Sema::ActOnClassMessage(Scope *S,
2760
                                   ParsedType Receiver,
2761
                                   Selector Sel,
2762
                                   SourceLocation LBracLoc,
2763
                                   ArrayRef<SourceLocation> SelectorLocs,
2764
                                   SourceLocation RBracLoc,
2765
7.66k
                                   MultiExprArg Args) {
2766
7.66k
  TypeSourceInfo *ReceiverTypeInfo;
2767
7.66k
  QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2768
7.66k
  if (ReceiverType.isNull())
2769
0
    return ExprError();
2770
2771
7.66k
  if (!ReceiverTypeInfo)
2772
0
    ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2773
2774
7.66k
  return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2775
7.66k
                           /*SuperLoc=*/SourceLocation(), Sel,
2776
7.66k
                           /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2777
7.66k
                           Args);
2778
7.66k
}
2779
2780
ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2781
                                              QualType ReceiverType,
2782
                                              SourceLocation Loc,
2783
                                              Selector Sel,
2784
                                              ObjCMethodDecl *Method,
2785
2.50k
                                              MultiExprArg Args) {
2786
2.50k
  return BuildInstanceMessage(Receiver, ReceiverType,
2787
2.44k
                              /*SuperLoc=*/!Receiver ? 
Loc63
: SourceLocation(),
2788
2.50k
                              Sel, Method, Loc, Loc, Loc, Args,
2789
2.50k
                              /*isImplicit=*/true);
2790
2.50k
}
2791
2792
4
static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2793
4
  if (!S.NSAPIObj)
2794
0
    return false;
2795
4
  const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2796
4
  if (!Protocol)
2797
0
    return false;
2798
4
  const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2799
4
  if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2800
2
          S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
2801
2
                             Sema::LookupOrdinaryName))) {
2802
2
    for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2803
2
      if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2804
1
        return true;
2805
2
    }
2806
2
  }
2807
3
  return false;
2808
4
}
2809
2810
/// Build an Objective-C instance message expression.
2811
///
2812
/// This routine takes care of both normal instance messages and
2813
/// instance messages to the superclass instance.
2814
///
2815
/// \param Receiver The expression that computes the object that will
2816
/// receive this message. This may be empty, in which case we are
2817
/// sending to the superclass instance and \p SuperLoc must be a valid
2818
/// source location.
2819
///
2820
/// \param ReceiverType The (static) type of the object receiving the
2821
/// message. When a \p Receiver expression is provided, this is the
2822
/// same type as that expression. For a superclass instance send, this
2823
/// is a pointer to the type of the superclass.
2824
///
2825
/// \param SuperLoc The location of the "super" keyword in a
2826
/// superclass instance message.
2827
///
2828
/// \param Sel The selector to which the message is being sent.
2829
///
2830
/// \param Method The method that this instance message is invoking, if
2831
/// already known.
2832
///
2833
/// \param LBracLoc The location of the opening square bracket ']'.
2834
///
2835
/// \param RBracLoc The location of the closing square bracket ']'.
2836
///
2837
/// \param ArgsIn The message arguments.
2838
ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2839
                                      QualType ReceiverType,
2840
                                      SourceLocation SuperLoc,
2841
                                      Selector Sel,
2842
                                      ObjCMethodDecl *Method,
2843
                                      SourceLocation LBracLoc,
2844
                                      ArrayRef<SourceLocation> SelectorLocs,
2845
                                      SourceLocation RBracLoc,
2846
                                      MultiExprArg ArgsIn,
2847
17.9k
                                      bool isImplicit) {
2848
17.9k
  assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2849
17.9k
                                             "SuperLoc must be valid so we can "
2850
17.9k
                                             "use it instead.");
2851
2852
  // The location of the receiver.
2853
16.8k
  SourceLocation Loc = SuperLoc.isValid() ? 
SuperLoc1.03k
: Receiver->getBeginLoc();
2854
17.9k
  SourceRange RecRange =
2855
16.8k
      SuperLoc.isValid()? 
SuperLoc1.03k
: Receiver->getSourceRange();
2856
17.9k
  ArrayRef<SourceLocation> SelectorSlotLocs;
2857
17.9k
  if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2858
17.9k
    SelectorSlotLocs = SelectorLocs;
2859
0
  else
2860
0
    SelectorSlotLocs = Loc;
2861
17.9k
  SourceLocation SelLoc = SelectorSlotLocs.front();
2862
2863
17.9k
  if (LBracLoc.isInvalid()) {
2864
175
    Diag(Loc, diag::err_missing_open_square_message_send)
2865
175
      << FixItHint::CreateInsertion(Loc, "[");
2866
175
    LBracLoc = Loc;
2867
175
  }
2868
2869
  // If we have a receiver expression, perform appropriate promotions
2870
  // and determine receiver type.
2871
17.9k
  if (Receiver) {
2872
16.8k
    if (Receiver->hasPlaceholderType()) {
2873
110
      ExprResult Result;
2874
110
      if (Receiver->getType() == Context.UnknownAnyTy)
2875
12
        Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2876
98
      else
2877
98
        Result = CheckPlaceholderExpr(Receiver);
2878
110
      if (Result.isInvalid()) 
return ExprError()0
;
2879
110
      Receiver = Result.get();
2880
110
    }
2881
2882
16.8k
    if (Receiver->isTypeDependent()) {
2883
      // If the receiver is type-dependent, we can't type-check anything
2884
      // at this point. Build a dependent expression.
2885
4
      unsigned NumArgs = ArgsIn.size();
2886
4
      Expr **Args = ArgsIn.data();
2887
4
      assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2888
4
      return ObjCMessageExpr::Create(
2889
4
          Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2890
4
          SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2891
4
          RBracLoc, isImplicit);
2892
4
    }
2893
2894
    // If necessary, apply function/array conversion to the receiver.
2895
    // C99 6.7.5.3p[7,8].
2896
16.8k
    ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2897
16.8k
    if (Result.isInvalid())
2898
0
      return ExprError();
2899
16.8k
    Receiver = Result.get();
2900
16.8k
    ReceiverType = Receiver->getType();
2901
2902
    // If the receiver is an ObjC pointer, a block pointer, or an
2903
    // __attribute__((NSObject)) pointer, we don't need to do any
2904
    // special conversion in order to look up a receiver.
2905
16.8k
    if (ReceiverType->isObjCRetainableType()) {
2906
      // do nothing
2907
55
    } else if (!getLangOpts().ObjCAutoRefCount &&
2908
54
               !Context.getObjCIdType().isNull() &&
2909
54
               (ReceiverType->isPointerType() ||
2910
43
                
ReceiverType->isIntegerType()17
)) {
2911
      // Implicitly convert integers and pointers to 'id' but emit a warning.
2912
      // But not in ARC.
2913
43
      Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << RecRange;
2914
43
      if (ReceiverType->isPointerType()) {
2915
37
        Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2916
37
                                     CK_CPointerToObjCPointerCast).get();
2917
6
      } else {
2918
        // TODO: specialized warning on null receivers?
2919
6
        bool IsNull = Receiver->isNullPointerConstant(Context,
2920
6
                                              Expr::NPC_ValueDependentIsNull);
2921
6
        CastKind Kind = IsNull ? 
CK_NullToPointer0
: CK_IntegralToPointer;
2922
6
        Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2923
6
                                     Kind).get();
2924
6
      }
2925
43
      ReceiverType = Receiver->getType();
2926
12
    } else if (getLangOpts().CPlusPlus) {
2927
      // The receiver must be a complete type.
2928
10
      if (RequireCompleteType(Loc, Receiver->getType(),
2929
10
                              diag::err_incomplete_receiver_type))
2930
1
        return ExprError();
2931
2932
9
      ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2933
9
      if (result.isUsable()) {
2934
9
        Receiver = result.get();
2935
9
        ReceiverType = Receiver->getType();
2936
9
      }
2937
9
    }
2938
16.8k
  }
2939
2940
  // There's a somewhat weird interaction here where we assume that we
2941
  // won't actually have a method unless we also don't need to do some
2942
  // of the more detailed type-checking on the receiver.
2943
2944
17.9k
  if (!Method) {
2945
    // Handle messages to id and __kindof types (where we use the
2946
    // global method pool).
2947
15.4k
    const ObjCObjectType *typeBound = nullptr;
2948
15.4k
    bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2949
15.4k
                                                                     typeBound);
2950
15.4k
    if (receiverIsIdLike || 
ReceiverType->isBlockPointerType()13.4k
||
2951
13.4k
        (Receiver && 
Context.isObjCNSObjectType(Receiver->getType())12.4k
)) {
2952
1.99k
      SmallVector<ObjCMethodDecl*, 4> Methods;
2953
      // If we have a type bound, further filter the methods.
2954
1.99k
      CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2955
1.99k
                                         true/*CheckTheOther*/, typeBound);
2956
1.99k
      if (!Methods.empty()) {
2957
        // We choose the first method as the initial candidate, then try to
2958
        // select a better one.
2959
1.31k
        Method = Methods[0];
2960
2961
1.31k
        if (ObjCMethodDecl *BestMethod =
2962
130
            SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2963
130
          Method = BestMethod;
2964
2965
1.31k
        if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2966
1.31k
                                            SourceRange(LBracLoc, RBracLoc),
2967
1.31k
                                            receiverIsIdLike, Methods))
2968
1.17k
          DiagnoseUseOfDecl(Method, SelectorSlotLocs);
2969
1.31k
      }
2970
13.4k
    } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2971
13.1k
               ReceiverType->isObjCQualifiedClassType()) {
2972
      // Handle messages to Class.
2973
      // We allow sending a message to a qualified Class ("Class<foo>"), which
2974
      // is ok as long as one of the protocols implements the selector (if not,
2975
      // warn).
2976
249
      if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2977
10
        const ObjCObjectPointerType *QClassTy
2978
10
          = ReceiverType->getAsObjCQualifiedClassType();
2979
        // Search protocols for class methods.
2980
10
        Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2981
10
        if (!Method) {
2982
6
          Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2983
          // warn if instance method found for a Class message.
2984
6
          if (Method && 
!isMethodDeclaredInRootProtocol(*this, Method)4
) {
2985
3
            Diag(SelLoc, diag::warn_instance_method_on_class_found)
2986
3
              << Method->getSelector() << Sel;
2987
3
            Diag(Method->getLocation(), diag::note_method_declared_at)
2988
3
              << Method->getDeclName();
2989
3
          }
2990
6
        }
2991
239
      } else {
2992
239
        if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2993
196
          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2994
            // As a guess, try looking for the method in the current interface.
2995
            // This very well may not produce the "right" method.
2996
2997
            // First check the public methods in the class interface.
2998
196
            Method = ClassDecl->lookupClassMethod(Sel);
2999
3000
196
            if (!Method)
3001
30
              Method = ClassDecl->lookupPrivateClassMethod(Sel);
3002
3003
196
            if (Method && 
DiagnoseUseOfDecl(Method, SelectorSlotLocs)190
)
3004
0
              return ExprError();
3005
239
          }
3006
196
        }
3007
239
        if (!Method) {
3008
          // If not messaging 'self', look for any factory method named 'Sel'.
3009
49
          if (!Receiver || !isSelfExpr(Receiver)) {
3010
            // If no class (factory) method was found, check if an _instance_
3011
            // method of the same name exists in the root class only.
3012
44
            SmallVector<ObjCMethodDecl*, 4> Methods;
3013
44
            CollectMultipleMethodsInGlobalPool(Sel, Methods,
3014
44
                                               false/*InstanceFirst*/,
3015
44
                                               true/*CheckTheOther*/);
3016
44
            if (!Methods.empty()) {
3017
              // We choose the first method as the initial candidate, then try
3018
              // to select a better one.
3019
43
              Method = Methods[0];
3020
3021
              // If we find an instance method, emit warning.
3022
43
              if (Method->isInstanceMethod()) {
3023
3
                if (const ObjCInterfaceDecl *ID =
3024
2
                    dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
3025
2
                  if (ID->getSuperClass())
3026
1
                    Diag(SelLoc, diag::warn_root_inst_method_not_found)
3027
1
                        << Sel << SourceRange(LBracLoc, RBracLoc);
3028
2
                }
3029
3
              }
3030
3031
43
             if (ObjCMethodDecl *BestMethod =
3032
3
                 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3033
3
                                  Methods))
3034
3
               Method = BestMethod;
3035
43
            }
3036
44
          }
3037
49
        }
3038
239
      }
3039
13.1k
    } else {
3040
13.1k
      ObjCInterfaceDecl *ClassDecl = nullptr;
3041
3042
      // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
3043
      // long as one of the protocols implements the selector (if not, warn).
3044
      // And as long as message is not deprecated/unavailable (warn if it is).
3045
13.1k
      if (const ObjCObjectPointerType *QIdTy
3046
222
                                   = ReceiverType->getAsObjCQualifiedIdType()) {
3047
        // Search protocols for instance methods.
3048
222
        Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
3049
222
        if (!Method)
3050
32
          Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
3051
222
        if (Method && 
DiagnoseUseOfDecl(Method, SelectorSlotLocs)192
)
3052
0
          return ExprError();
3053
12.9k
      } else if (const ObjCObjectPointerType *OCIType
3054
12.9k
                   = ReceiverType->getAsObjCInterfacePointerType()) {
3055
        // We allow sending a message to a pointer to an interface (an object).
3056
12.9k
        ClassDecl = OCIType->getInterfaceDecl();
3057
3058
        // Try to complete the type. Under ARC, this is a hard error from which
3059
        // we don't try to recover.
3060
        // FIXME: In the non-ARC case, this will still be a hard error if the
3061
        // definition is found in a module that's not visible.
3062
12.9k
        const ObjCInterfaceDecl *forwardClass = nullptr;
3063
12.9k
        if (RequireCompleteType(Loc, OCIType->getPointeeType(),
3064
12.9k
                                getLangOpts().ObjCAutoRefCount
3065
950
                                    ? diag::err_arc_receiver_forward_instance
3066
11.9k
                                    : diag::warn_receiver_forward_instance,
3067
68
                                RecRange)) {
3068
68
          if (getLangOpts().ObjCAutoRefCount)
3069
4
            return ExprError();
3070
3071
64
          forwardClass = OCIType->getInterfaceDecl();
3072
64
          Diag(Receiver ? Receiver->getBeginLoc() : 
SuperLoc0
,
3073
64
               diag::note_receiver_is_id);
3074
64
          Method = nullptr;
3075
12.8k
        } else {
3076
12.8k
          Method = ClassDecl->lookupInstanceMethod(Sel);
3077
12.8k
        }
3078
3079
12.9k
        if (!Method)
3080
          // Search protocol qualifiers.
3081
3.14k
          Method = LookupMethodInQualifiedType(Sel, OCIType, true);
3082
3083
12.9k
        if (!Method) {
3084
          // If we have implementations in scope, check "private" methods.
3085
3.12k
          Method = ClassDecl->lookupPrivateMethod(Sel);
3086
3087
3.12k
          if (!Method && 
getLangOpts().ObjCAutoRefCount2.88k
) {
3088
3
            Diag(SelLoc, diag::err_arc_may_not_respond)
3089
3
              << OCIType->getPointeeType() << Sel << RecRange
3090
3
              << SourceRange(SelectorLocs.front(), SelectorLocs.back());
3091
3
            return ExprError();
3092
3
          }
3093
3094
3.11k
          if (!Method && 
(2.88k
!Receiver2.88k
||
!isSelfExpr(Receiver)2.85k
)) {
3095
            // If we still haven't found a method, look in the global pool. This
3096
            // behavior isn't very desirable, however we need it for GCC
3097
            // compatibility. FIXME: should we deviate??
3098
2.86k
            if (OCIType->qual_empty()) {
3099
2.84k
              SmallVector<ObjCMethodDecl*, 4> Methods;
3100
2.84k
              CollectMultipleMethodsInGlobalPool(Sel, Methods,
3101
2.84k
                                                 true/*InstanceFirst*/,
3102
2.84k
                                                 false/*CheckTheOther*/);
3103
2.84k
              if (!Methods.empty()) {
3104
                // We choose the first method as the initial candidate, then try
3105
                // to select a better one.
3106
2.53k
                Method = Methods[0];
3107
3108
2.53k
                if (ObjCMethodDecl *BestMethod =
3109
2.39k
                    SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3110
2.39k
                                     Methods))
3111
2.39k
                  Method = BestMethod;
3112
3113
2.53k
                AreMultipleMethodsInGlobalPool(Sel, Method,
3114
2.53k
                                               SourceRange(LBracLoc, RBracLoc),
3115
2.53k
                                               true/*receiverIdOrClass*/,
3116
2.53k
                                               Methods);
3117
2.53k
              }
3118
2.84k
              if (Method && 
!forwardClass2.53k
)
3119
2.47k
                Diag(SelLoc, diag::warn_maynot_respond)
3120
2.47k
                  << OCIType->getInterfaceDecl()->getIdentifier()
3121
2.47k
                  << Sel << RecRange;
3122
2.84k
            }
3123
2.86k
          }
3124
3.11k
        }
3125
12.9k
        if (Method && 
DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass)12.5k
)
3126
0
          return ExprError();
3127
2
      } else {
3128
        // Reject other random receiver types (e.g. structs).
3129
2
        Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << RecRange;
3130
2
        return ExprError();
3131
2
      }
3132
17.9k
    }
3133
15.4k
  }
3134
3135
17.9k
  FunctionScopeInfo *DIFunctionScopeInfo =
3136
17.9k
    (Method && 
Method->getMethodFamily() == OMF_init16.8k
)
3137
15.1k
      ? 
getEnclosingFunction()2.72k
: nullptr;
3138
3139
17.9k
  if (Method && 
Method->isDirectMethod()16.8k
) {
3140
81
    if (ReceiverType->isObjCIdType() && 
!isImplicit1
) {
3141
1
      Diag(Receiver->getExprLoc(),
3142
1
           diag::err_messaging_unqualified_id_with_direct_method);
3143
1
      Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3144
1
          << Method->getDeclName();
3145
1
    }
3146
3147
    // Under ARC, self can't be assigned, and doing a direct call to `self`
3148
    // when it's a Class is hence safe.  For other cases, we can't trust `self`
3149
    // is what we think it is, so we reject it.
3150
81
    if (ReceiverType->isObjCClassType() && 
!isImplicit9
&&
3151
9
        !(Receiver->isObjCSelfExpr() && 
getLangOpts().ObjCAutoRefCount7
)) {
3152
4
      {
3153
4
        auto Builder = Diag(Receiver->getExprLoc(),
3154
4
                            diag::err_messaging_class_with_direct_method);
3155
4
        if (Receiver->isObjCSelfExpr()) {
3156
2
          Builder.AddFixItHint(FixItHint::CreateReplacement(
3157
2
              RecRange, Method->getClassInterface()->getName()));
3158
2
        }
3159
4
      }
3160
4
      Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3161
4
          << Method->getDeclName();
3162
4
    }
3163
3164
81
    if (SuperLoc.isValid()) {
3165
3
      {
3166
3
        auto Builder =
3167
3
            Diag(SuperLoc, diag::err_messaging_super_with_direct_method);
3168
3
        if (ReceiverType->isObjCClassType()) {
3169
0
          Builder.AddFixItHint(FixItHint::CreateReplacement(
3170
0
              SuperLoc, Method->getClassInterface()->getName()));
3171
3
        } else {
3172
3
          Builder.AddFixItHint(FixItHint::CreateReplacement(SuperLoc, "self"));
3173
3
        }
3174
3
      }
3175
3
      Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3176
3
          << Method->getDeclName();
3177
3
    }
3178
17.8k
  } else if (ReceiverType->isObjCIdType() && 
!isImplicit1.96k
) {
3179
1.95k
    Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
3180
1.95k
  }
3181
3182
17.9k
  if (DIFunctionScopeInfo &&
3183
2.72k
      DIFunctionScopeInfo->ObjCIsDesignatedInit &&
3184
157
      (SuperLoc.isValid() || 
isSelfExpr(Receiver)24
)) {
3185
136
    bool isDesignatedInitChain = false;
3186
136
    if (SuperLoc.isValid()) {
3187
133
      if (const ObjCObjectPointerType *
3188
133
            OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
3189
133
        if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
3190
          // Either we know this is a designated initializer or we
3191
          // conservatively assume it because we don't know for sure.
3192
133
          if (!ID->declaresOrInheritsDesignatedInitializers() ||
3193
130
              ID->isDesignatedInitializer(Sel)) {
3194
129
            isDesignatedInitChain = true;
3195
129
            DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
3196
129
          }
3197
133
        }
3198
133
      }
3199
133
    }
3200
136
    if (!isDesignatedInitChain) {
3201
7
      const ObjCMethodDecl *InitMethod = nullptr;
3202
7
      bool isDesignated =
3203
7
        getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
3204
7
      assert(isDesignated && InitMethod);
3205
7
      (void)isDesignated;
3206
7
      Diag(SelLoc, SuperLoc.isValid() ?
3207
4
             diag::warn_objc_designated_init_non_designated_init_call :
3208
3
             diag::warn_objc_designated_init_non_super_designated_init_call);
3209
7
      Diag(InitMethod->getLocation(),
3210
7
           diag::note_objc_designated_init_marked_here);
3211
7
    }
3212
136
  }
3213
3214
17.9k
  if (DIFunctionScopeInfo &&
3215
2.72k
      DIFunctionScopeInfo->ObjCIsSecondaryInit &&
3216
10
      (SuperLoc.isValid() || 
isSelfExpr(Receiver)7
)) {
3217
9
    if (SuperLoc.isValid()) {
3218
3
      Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
3219
6
    } else {
3220
6
      DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
3221
6
    }
3222
9
  }
3223
3224
  // Check the message arguments.
3225
17.9k
  unsigned NumArgs = ArgsIn.size();
3226
17.9k
  Expr **Args = ArgsIn.data();
3227
17.9k
  QualType ReturnType;
3228
17.9k
  ExprValueKind VK = VK_RValue;
3229
17.9k
  bool ClassMessage = (ReceiverType->isObjCClassType() ||
3230
17.6k
                       ReceiverType->isObjCQualifiedClassType());
3231
17.9k
  if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3232
17.9k
                                MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3233
17.9k
                                Method, ClassMessage, SuperLoc.isValid(),
3234
17.9k
                                LBracLoc, RBracLoc, RecRange, ReturnType, VK))
3235
31
    return ExprError();
3236
3237
17.8k
  if (Method && 
!Method->getReturnType()->isVoidType()16.8k
&&
3238
9.67k
      RequireCompleteType(LBracLoc, Method->getReturnType(),
3239
9.67k
                          diag::err_illegal_message_expr_incomplete_type))
3240
0
    return ExprError();
3241
3242
  // In ARC, forbid the user from sending messages to
3243
  // retain/release/autorelease/dealloc/retainCount explicitly.
3244
17.8k
  if (getLangOpts().ObjCAutoRefCount) {
3245
1.62k
    ObjCMethodFamily family =
3246
1.62k
      (Method ? Method->getMethodFamily() : 
Sel.getMethodFamily()3
);
3247
1.62k
    switch (family) {
3248
201
    case OMF_init:
3249
201
      if (Method)
3250
201
        checkInitMethod(Method, ReceiverType);
3251
201
      break;
3252
3253
1.12k
    case OMF_None:
3254
1.12k
    case OMF_alloc:
3255
1.14k
    case OMF_copy:
3256
1.14k
    case OMF_finalize:
3257
1.14k
    case OMF_mutableCopy:
3258
1.15k
    case OMF_new:
3259
1.15k
    case OMF_self:
3260
1.15k
    case OMF_initialize:
3261
1.15k
      break;
3262
3263
12
    case OMF_dealloc:
3264
89
    case OMF_retain:
3265
209
    case OMF_release:
3266
236
    case OMF_autorelease:
3267
240
    case OMF_retainCount:
3268
240
      Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3269
240
        << Sel << RecRange;
3270
240
      break;
3271
3272
31
    case OMF_performSelector:
3273
31
      if (Method && NumArgs >= 1) {
3274
31
        if (const auto *SelExp =
3275
30
                dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
3276
30
          Selector ArgSel = SelExp->getSelector();
3277
30
          ObjCMethodDecl *SelMethod =
3278
30
            LookupInstanceMethodInGlobalPool(ArgSel,
3279
30
                                             SelExp->getSourceRange());
3280
30
          if (!SelMethod)
3281
3
            SelMethod =
3282
3
              LookupFactoryMethodInGlobalPool(ArgSel,
3283
3
                                              SelExp->getSourceRange());
3284
30
          if (SelMethod) {
3285
29
            ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3286
29
            switch (SelFamily) {
3287
0
              case OMF_alloc:
3288
1
              case OMF_copy:
3289
1
              case OMF_mutableCopy:
3290
2
              case OMF_new:
3291
3
              case OMF_init:
3292
                // Issue error, unless ns_returns_not_retained.
3293
3
                if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3294
                  // selector names a +1 method
3295
2
                  Diag(SelLoc,
3296
2
                       diag::err_arc_perform_selector_retains);
3297
2
                  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3298
2
                    << SelMethod->getDeclName();
3299
2
                }
3300
3
                break;
3301
26
              default:
3302
                // +0 call. OK. unless ns_returns_retained.
3303
26
                if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3304
                  // selector names a +1 method
3305
2
                  Diag(SelLoc,
3306
2
                       diag::err_arc_perform_selector_retains);
3307
2
                  Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3308
2
                    << SelMethod->getDeclName();
3309
2
                }
3310
26
                break;
3311
1
            }
3312
1
          }
3313
1
        } else {
3314
          // error (may leak).
3315
1
          Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3316
1
          Diag(Args[0]->getExprLoc(), diag::note_used_here);
3317
1
        }
3318
31
      }
3319
31
      break;
3320
17.8k
    }
3321
17.8k
  }
3322
3323
17.8k
  DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3324
3325
  // Construct the appropriate ObjCMessageExpr instance.
3326
17.8k
  ObjCMessageExpr *Result;
3327
17.8k
  if (SuperLoc.isValid())
3328
1.03k
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3329
1.03k
                                     SuperLoc,  /*IsInstanceSuper=*/true,
3330
1.03k
                                     ReceiverType, Sel, SelectorLocs, Method,
3331
1.03k
                                     makeArrayRef(Args, NumArgs), RBracLoc,
3332
1.03k
                                     isImplicit);
3333
16.8k
  else {
3334
16.8k
    Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3335
16.8k
                                     Receiver, Sel, SelectorLocs, Method,
3336
16.8k
                                     makeArrayRef(Args, NumArgs), RBracLoc,
3337
16.8k
                                     isImplicit);
3338
16.8k
    if (!isImplicit)
3339
14.4k
      checkCocoaAPI(*this, Result);
3340
16.8k
  }
3341
17.8k
  if (Method) {
3342
16.8k
    bool IsClassObjectCall = ClassMessage;
3343
    // 'self' message receivers in class methods should be treated as message
3344
    // sends to the class object in order for the semantic checks to be
3345
    // performed correctly. Messages to 'super' already count as class messages,
3346
    // so they don't need to be handled here.
3347
16.8k
    if (Receiver && 
isSelfExpr(Receiver)15.7k
) {
3348
832
      if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3349
832
        if (OPT->getObjectType()->isObjCClass()) {
3350
83
          if (const auto *CurMeth = getCurMethodDecl()) {
3351
83
            IsClassObjectCall = true;
3352
83
            ReceiverType =
3353
83
                Context.getObjCInterfaceType(CurMeth->getClassInterface());
3354
83
          }
3355
83
        }
3356
832
      }
3357
832
    }
3358
16.8k
    checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3359
16.8k
                       ReceiverType, IsClassObjectCall);
3360
16.8k
  }
3361
3362
17.8k
  if (getLangOpts().ObjCAutoRefCount) {
3363
    // In ARC, annotate delegate init calls.
3364
1.62k
    if (Result->getMethodFamily() == OMF_init &&
3365
201
        (SuperLoc.isValid() || 
isSelfExpr(Receiver)169
)) {
3366
      // Only consider init calls *directly* in init implementations,
3367
      // not within blocks.
3368
46
      ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3369
46
      if (method && method->getMethodFamily() == OMF_init) {
3370
        // The implicit assignment to self means we also don't want to
3371
        // consume the result.
3372
38
        Result->setDelegateInitCall(true);
3373
38
        return Result;
3374
38
      }
3375
1.58k
    }
3376
3377
    // In ARC, check for message sends which are likely to introduce
3378
    // retain cycles.
3379
1.58k
    checkRetainCycles(Result);
3380
1.58k
  }
3381
3382
17.8k
  if (getLangOpts().ObjCWeak) {
3383
777
    if (!isImplicit && 
Method412
) {
3384
410
      if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3385
80
        bool IsWeak =
3386
80
            Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak;
3387
80
        if (!IsWeak && 
Sel.isUnarySelector()52
)
3388
27
          IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3389
80
        if (IsWeak && 
!isUnevaluatedContext()28
&&
3390
26
            !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3391
26
          getCurFunction()->recordUseOfWeak(Result, Prop);
3392
80
      }
3393
410
    }
3394
777
  }
3395
3396
17.8k
  CheckObjCCircularContainer(Result);
3397
3398
17.8k
  return MaybeBindToTemporary(Result);
3399
17.8k
}
3400
3401
509
static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3402
509
  if (ObjCSelectorExpr *OSE =
3403
8
      dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3404
8
    Selector Sel = OSE->getSelector();
3405
8
    SourceLocation Loc = OSE->getAtLoc();
3406
8
    auto Pos = S.ReferencedSelectors.find(Sel);
3407
8
    if (Pos != S.ReferencedSelectors.end() && 
Pos->second == Loc1
)
3408
1
      S.ReferencedSelectors.erase(Pos);
3409
8
  }
3410
509
}
3411
3412
// ActOnInstanceMessage - used for both unary and keyword messages.
3413
// ArgExprs is optional - if it is present, the number of expressions
3414
// is obtained from Sel.getNumArgs().
3415
ExprResult Sema::ActOnInstanceMessage(Scope *S,
3416
                                      Expr *Receiver,
3417
                                      Selector Sel,
3418
                                      SourceLocation LBracLoc,
3419
                                      ArrayRef<SourceLocation> SelectorLocs,
3420
                                      SourceLocation RBracLoc,
3421
14.4k
                                      MultiExprArg Args) {
3422
14.4k
  if (!Receiver)
3423
0
    return ExprError();
3424
3425
  // A ParenListExpr can show up while doing error recovery with invalid code.
3426
14.4k
  if (isa<ParenListExpr>(Receiver)) {
3427
1
    ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3428
1
    if (Result.isInvalid()) 
return ExprError()0
;
3429
1
    Receiver = Result.get();
3430
1
  }
3431
3432
14.4k
  if (RespondsToSelectorSel.isNull()) {
3433
2.05k
    IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3434
2.05k
    RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3435
2.05k
  }
3436
14.4k
  if (Sel == RespondsToSelectorSel)
3437
509
    RemoveSelectorFromWarningCache(*this, Args[0]);
3438
3439
14.4k
  return BuildInstanceMessage(Receiver, Receiver->getType(),
3440
14.4k
                              /*SuperLoc=*/SourceLocation(), Sel,
3441
14.4k
                              /*Method=*/nullptr, LBracLoc, SelectorLocs,
3442
14.4k
                              RBracLoc, Args);
3443
14.4k
}
3444
3445
enum ARCConversionTypeClass {
3446
  /// int, void, struct A
3447
  ACTC_none,
3448
3449
  /// id, void (^)()
3450
  ACTC_retainable,
3451
3452
  /// id*, id***, void (^*)(),
3453
  ACTC_indirectRetainable,
3454
3455
  /// void* might be a normal C type, or it might a CF type.
3456
  ACTC_voidPtr,
3457
3458
  /// struct A*
3459
  ACTC_coreFoundation
3460
};
3461
3462
1.70k
static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3463
1.70k
  return (ACTC == ACTC_retainable ||
3464
1.04k
          ACTC == ACTC_coreFoundation ||
3465
243
          ACTC == ACTC_voidPtr);
3466
1.70k
}
3467
3468
2.68k
static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3469
2.68k
  return ACTC == ACTC_none ||
3470
1.94k
         ACTC == ACTC_voidPtr ||
3471
1.23k
         ACTC == ACTC_coreFoundation;
3472
2.68k
}
3473
3474
11.9M
static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3475
11.9M
  bool isIndirect = false;
3476
3477
  // Ignore an outermost reference type.
3478
11.9M
  if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3479
18.3k
    type = ref->getPointeeType();
3480
18.3k
    isIndirect = true;
3481
18.3k
  }
3482
3483
  // Drill through pointers and arrays recursively.
3484
12.3M
  while (true) {
3485
12.3M
    if (const PointerType *ptr = type->getAs<PointerType>()) {
3486
739k
      type = ptr->getPointeeType();
3487
3488
      // The first level of pointer may be the innermost pointer on a CF type.
3489
739k
      if (!isIndirect) {
3490
725k
        if (type->isVoidType()) 
return ACTC_voidPtr194k
;
3491
530k
        if (type->isRecordType()) 
return ACTC_coreFoundation162k
;
3492
11.5M
      }
3493
11.5M
    } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3494
39.3k
      type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3495
11.5M
    } else {
3496
11.5M
      break;
3497
11.5M
    }
3498
421k
    isIndirect = true;
3499
421k
  }
3500
3501
11.5M
  if (isIndirect) {
3502
424k
    if (type->isObjCARCBridgableType())
3503
3.36k
      return ACTC_indirectRetainable;
3504
420k
    return ACTC_none;
3505
420k
  }
3506
3507
11.1M
  if (type->isObjCARCBridgableType())
3508
120k
    return ACTC_retainable;
3509
3510
11.0M
  return ACTC_none;
3511
11.0M
}
3512
3513
namespace {
3514
  /// A result from the cast checker.
3515
  enum ACCResult {
3516
    /// Cannot be casted.
3517
    ACC_invalid,
3518
3519
    /// Can be safely retained or not retained.
3520
    ACC_bottom,
3521
3522
    /// Can be casted at +0.
3523
    ACC_plusZero,
3524
3525
    /// Can be casted at +1.
3526
    ACC_plusOne
3527
  };
3528
82
  ACCResult merge(ACCResult left, ACCResult right) {
3529
82
    if (left == right) 
return left17
;
3530
65
    if (left == ACC_bottom) 
return right41
;
3531
24
    if (right == ACC_bottom) 
return left14
;
3532
10
    return ACC_invalid;
3533
10
  }
3534
3535
  /// A checker which white-lists certain expressions whose conversion
3536
  /// to or from retainable type would otherwise be forbidden in ARC.
3537
  class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3538
    typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3539
3540
    ASTContext &Context;
3541
    ARCConversionTypeClass SourceClass;
3542
    ARCConversionTypeClass TargetClass;
3543
    bool Diagnose;
3544
3545
149
    static bool isCFType(QualType type) {
3546
      // Someday this can use ns_bridged.  For now, it has to do this.
3547
149
      return type->isCARCBridgableType();
3548
149
    }
3549
3550
  public:
3551
    ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3552
                   ARCConversionTypeClass target, bool diagnose)
3553
      : Context(Context), SourceClass(source), TargetClass(target),
3554
941
        Diagnose(diagnose) {}
3555
3556
    using super::Visit;
3557
1.77k
    ACCResult Visit(Expr *e) {
3558
1.77k
      return super::Visit(e->IgnoreParens());
3559
1.77k
    }
3560
3561
0
    ACCResult VisitStmt(Stmt *s) {
3562
0
      return ACC_invalid;
3563
0
    }
3564
3565
    /// Null pointer constants can be casted however you please.
3566
259
    ACCResult VisitExpr(Expr *e) {
3567
259
      if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3568
156
        return ACC_bottom;
3569
103
      return ACC_invalid;
3570
103
    }
3571
3572
    /// Objective-C string literals can be safely casted.
3573
46
    ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3574
      // If we're casting to any retainable type, go ahead.  Global
3575
      // strings are immune to retains, so this is bottom.
3576
46
      if (isAnyRetainable(TargetClass)) return ACC_bottom;
3577
3578
0
      return ACC_invalid;
3579
0
    }
3580
3581
    /// Look through certain implicit and explicit casts.
3582
757
    ACCResult VisitCastExpr(CastExpr *e) {
3583
757
      switch (e->getCastKind()) {
3584
60
        case CK_NullToPointer:
3585
60
          return ACC_bottom;
3586
3587
41
        case CK_NoOp:
3588
579
        case CK_LValueToRValue:
3589
625
        case CK_BitCast:
3590
628
        case CK_CPointerToObjCPointerCast:
3591
628
        case CK_BlockPointerToObjCPointerCast:
3592
628
        case CK_AnyPointerToBlockPointerCast:
3593
628
          return Visit(e->getSubExpr());
3594
3595
69
        default:
3596
69
          return ACC_invalid;
3597
757
      }
3598
757
    }
3599
3600
    /// Look through unary extension.
3601
0
    ACCResult VisitUnaryExtension(UnaryOperator *e) {
3602
0
      return Visit(e->getSubExpr());
3603
0
    }
3604
3605
    /// Ignore the LHS of a comma operator.
3606
3
    ACCResult VisitBinComma(BinaryOperator *e) {
3607
3
      return Visit(e->getRHS());
3608
3
    }
3609
3610
    /// Conditional operators are okay if both sides are okay.
3611
90
    ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3612
90
      ACCResult left = Visit(e->getTrueExpr());
3613
90
      if (left == ACC_invalid) 
return ACC_invalid8
;
3614
82
      return merge(left, Visit(e->getFalseExpr()));
3615
82
    }
3616
3617
    /// Look through pseudo-objects.
3618
30
    ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3619
      // If we're getting here, we should always have a result.
3620
30
      return Visit(e->getResultExpr());
3621
30
    }
3622
3623
    /// Statement expressions are okay if their result expression is okay.
3624
0
    ACCResult VisitStmtExpr(StmtExpr *e) {
3625
0
      return Visit(e->getSubStmt()->body_back());
3626
0
    }
3627
3628
    /// Some declaration references are okay.
3629
512
    ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3630
512
      VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3631
      // References to global constants are okay.
3632
512
      if (isAnyRetainable(TargetClass) &&
3633
491
          isAnyRetainable(SourceClass) &&
3634
489
          var &&
3635
489
          !var->hasDefinition(Context) &&
3636
62
          var->getType().isConstQualified()) {
3637
3638
        // In system headers, they can also be assumed to be immune to retains.
3639
        // These are things like 'kCFStringTransformToLatin'.
3640
46
        if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3641
5
          return ACC_bottom;
3642
3643
41
        return ACC_plusZero;
3644
41
      }
3645
3646
      // Nothing else.
3647
466
      return ACC_invalid;
3648
466
    }
3649
3650
    /// Some calls are okay.
3651
98
    ACCResult VisitCallExpr(CallExpr *e) {
3652
98
      if (FunctionDecl *fn = e->getDirectCallee())
3653
98
        if (ACCResult result = checkCallToFunction(fn))
3654
26
          return result;
3655
3656
72
      return super::VisitCallExpr(e);
3657
72
    }
3658
3659
98
    ACCResult checkCallToFunction(FunctionDecl *fn) {
3660
      // Require a CF*Ref return type.
3661
98
      if (!isCFType(fn->getReturnType()))
3662
0
        return ACC_invalid;
3663
3664
98
      if (!isAnyRetainable(TargetClass))
3665
0
        return ACC_invalid;
3666
3667
      // Honor an explicit 'not retained' attribute.
3668
98
      if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3669
2
        return ACC_plusZero;
3670
3671
      // Honor an explicit 'retained' attribute, except that for
3672
      // now we're not going to permit implicit handling of +1 results,
3673
      // because it's a bit frightening.
3674
96
      if (fn->hasAttr<CFReturnsRetainedAttr>())
3675
4
        return Diagnose ? 
ACC_plusOne2
3676
2
                        : ACC_invalid; // ACC_plusOne if we start accepting this
3677
3678
      // Recognize this specific builtin function, which is used by CFSTR.
3679
92
      unsigned builtinID = fn->getBuiltinID();
3680
92
      if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3681
1
        return ACC_bottom;
3682
3683
      // Otherwise, don't do anything implicit with an unaudited function.
3684
91
      if (!fn->hasAttr<CFAuditedTransferAttr>())
3685
58
        return ACC_invalid;
3686
3687
      // Otherwise, it's +0 unless it follows the create convention.
3688
33
      if (ento::coreFoundation::followsCreateRule(fn))
3689
24
        return Diagnose ? 
ACC_plusOne12
3690
12
                        : ACC_invalid; // ACC_plusOne if we start accepting this
3691
3692
9
      return ACC_plusZero;
3693
9
    }
3694
3695
51
    ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3696
51
      return checkCallToMethod(e->getMethodDecl());
3697
51
    }
3698
3699
0
    ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3700
0
      ObjCMethodDecl *method;
3701
0
      if (e->isExplicitProperty())
3702
0
        method = e->getExplicitProperty()->getGetterMethodDecl();
3703
0
      else
3704
0
        method = e->getImplicitPropertyGetter();
3705
0
      return checkCallToMethod(method);
3706
0
    }
3707
3708
51
    ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3709
51
      if (!method) 
return ACC_invalid0
;
3710
3711
      // Check for message sends to functions returning CF types.  We
3712
      // just obey the Cocoa conventions with these, even though the
3713
      // return type is CF.
3714
51
      if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3715
0
        return ACC_invalid;
3716
3717
      // If the method is explicitly marked not-retained, it's +0.
3718
51
      if (method->hasAttr<CFReturnsNotRetainedAttr>())
3719
0
        return ACC_plusZero;
3720
3721
      // If the method is explicitly marked as returning retained, or its
3722
      // selector follows a +1 Cocoa convention, treat it as +1.
3723
51
      if (method->hasAttr<CFReturnsRetainedAttr>())
3724
3
        return ACC_plusOne;
3725
3726
48
      switch (method->getSelector().getMethodFamily()) {
3727
0
      case OMF_alloc:
3728
0
      case OMF_copy:
3729
0
      case OMF_mutableCopy:
3730
11
      case OMF_new:
3731
11
        return ACC_plusOne;
3732
3733
37
      default:
3734
        // Otherwise, treat it as +0.
3735
37
        return ACC_plusZero;
3736
48
      }
3737
48
    }
3738
  };
3739
} // end anonymous namespace
3740
3741
303
bool Sema::isKnownName(StringRef name) {
3742
303
  if (name.empty())
3743
0
    return false;
3744
303
  LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3745
303
                 Sema::LookupOrdinaryName);
3746
303
  return LookupName(R, TUScope, false);
3747
303
}
3748
3749
template <typename DiagBuilderT>
3750
static void addFixitForObjCARCConversion(
3751
    Sema &S, DiagBuilderT &DiagB, Sema::CheckedConversionKind CCK,
3752
    SourceLocation afterLParen, QualType castType, Expr *castExpr,
3753
572
    Expr *realCast, const char *bridgeKeyword, const char *CFBridgeName) {
3754
  // We handle C-style and implicit casts here.
3755
572
  switch (CCK) {
3756
108
  case Sema::CCK_ImplicitConversion:
3757
108
  case Sema::CCK_ForBuiltinOverloadedOp:
3758
522
  case Sema::CCK_CStyleCast:
3759
572
  case Sema::CCK_OtherCast:
3760
572
    break;
3761
0
  case Sema::CCK_FunctionalCast:
3762
0
    return;
3763
572
  }
3764
3765
572
  if (CFBridgeName) {
3766
146
    if (CCK == Sema::CCK_OtherCast) {
3767
2
      if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3768
2
        SourceRange range(NCE->getOperatorLoc(),
3769
2
                          NCE->getAngleBrackets().getEnd());
3770
2
        SmallString<32> BridgeCall;
3771
3772
2
        SourceManager &SM = S.getSourceManager();
3773
2
        char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3774
2
        if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3775
0
          BridgeCall += ' ';
3776
3777
2
        BridgeCall += CFBridgeName;
3778
2
        DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3779
2
      }
3780
2
      return;
3781
2
    }
3782
144
    Expr *castedE = castExpr;
3783
144
    if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3784
4
      castedE = CCE->getSubExpr();
3785
144
    castedE = castedE->IgnoreImpCasts();
3786
144
    SourceRange range = castedE->getSourceRange();
3787
3788
144
    SmallString<32> BridgeCall;
3789
3790
144
    SourceManager &SM = S.getSourceManager();
3791
144
    char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3792
144
    if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3793
2
      BridgeCall += ' ';
3794
3795
144
    BridgeCall += CFBridgeName;
3796
3797
144
    if (isa<ParenExpr>(castedE)) {
3798
32
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3799
32
                         BridgeCall));
3800
112
    } else {
3801
112
      BridgeCall += '(';
3802
112
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3803
112
                                                    BridgeCall));
3804
112
      DiagB.AddFixItHint(FixItHint::CreateInsertion(
3805
112
                                       S.getLocForEndOfToken(range.getEnd()),
3806
112
                                       ")"));
3807
112
    }
3808
144
    return;
3809
144
  }
3810
3811
426
  if (CCK == Sema::CCK_CStyleCast) {
3812
319
    DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3813
107
  } else if (CCK == Sema::CCK_OtherCast) {
3814
48
    if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3815
20
      std::string castCode = "(";
3816
20
      castCode += bridgeKeyword;
3817
20
      castCode += castType.getAsString();
3818
20
      castCode += ")";
3819
20
      SourceRange Range(NCE->getOperatorLoc(),
3820
20
                        NCE->getAngleBrackets().getEnd());
3821
20
      DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3822
20
    }
3823
59
  } else {
3824
59
    std::string castCode = "(";
3825
59
    castCode += bridgeKeyword;
3826
59
    castCode += castType.getAsString();
3827
59
    castCode += ")";
3828
59
    Expr *castedE = castExpr->IgnoreImpCasts();
3829
59
    SourceRange range = castedE->getSourceRange();
3830
59
    if (isa<ParenExpr>(castedE)) {
3831
4
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3832
4
                         castCode));
3833
55
    } else {
3834
55
      castCode += "(";
3835
55
      DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3836
55
                                                    castCode));
3837
55
      DiagB.AddFixItHint(FixItHint::CreateInsertion(
3838
55
                                       S.getLocForEndOfToken(range.getEnd()),
3839
55
                                       ")"));
3840
55
    }
3841
59
  }
3842
426
}
3843
3844
template <typename T>
3845
2.46k
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3846
2.46k
  TypedefNameDecl *TDNDecl = TD->getDecl();
3847
2.46k
  QualType QT = TDNDecl->getUnderlyingType();
3848
2.46k
  if (QT->isPointerType()) {
3849
2.46k
    QT = QT->getPointeeType();
3850
2.46k
    if (const RecordType *RT = QT->getAs<RecordType>())
3851
2.46k
      if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3852
2.46k
        return RD->getAttr<T>();
3853
0
  }
3854
0
  return nullptr;
3855
0
}
SemaExprObjC.cpp:clang::ObjCBridgeRelatedAttr* getObjCBridgeAttr<clang::ObjCBridgeRelatedAttr>(clang::TypedefType const*)
Line
Count
Source
3845
1.30k
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3846
1.30k
  TypedefNameDecl *TDNDecl = TD->getDecl();
3847
1.30k
  QualType QT = TDNDecl->getUnderlyingType();
3848
1.30k
  if (QT->isPointerType()) {
3849
1.30k
    QT = QT->getPointeeType();
3850
1.30k
    if (const RecordType *RT = QT->getAs<RecordType>())
3851
1.30k
      if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3852
1.30k
        return RD->getAttr<T>();
3853
0
  }
3854
0
  return nullptr;
3855
0
}
SemaExprObjC.cpp:clang::ObjCBridgeAttr* getObjCBridgeAttr<clang::ObjCBridgeAttr>(clang::TypedefType const*)
Line
Count
Source
3845
704
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3846
704
  TypedefNameDecl *TDNDecl = TD->getDecl();
3847
704
  QualType QT = TDNDecl->getUnderlyingType();
3848
704
  if (QT->isPointerType()) {
3849
704
    QT = QT->getPointeeType();
3850
704
    if (const RecordType *RT = QT->getAs<RecordType>())
3851
704
      if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3852
704
        return RD->getAttr<T>();
3853
0
  }
3854
0
  return nullptr;
3855
0
}
SemaExprObjC.cpp:clang::ObjCBridgeMutableAttr* getObjCBridgeAttr<clang::ObjCBridgeMutableAttr>(clang::TypedefType const*)
Line
Count
Source
3845
453
static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3846
453
  TypedefNameDecl *TDNDecl = TD->getDecl();
3847
453
  QualType QT = TDNDecl->getUnderlyingType();
3848
453
  if (QT->isPointerType()) {
3849
453
    QT = QT->getPointeeType();
3850
453
    if (const RecordType *RT = QT->getAs<RecordType>())
3851
453
      if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3852
453
        return RD->getAttr<T>();
3853
0
  }
3854
0
  return nullptr;
3855
0
}
3856
3857
static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3858
1.29k
                                                            TypedefNameDecl *&TDNDecl) {
3859
2.52k
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3860
1.30k
    TDNDecl = TD->getDecl();
3861
1.30k
    if (ObjCBridgeRelatedAttr *ObjCBAttr =
3862
81
        getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3863
81
      return ObjCBAttr;
3864
1.22k
    T = TDNDecl->getUnderlyingType();
3865
1.22k
  }
3866
1.21k
  return nullptr;
3867
1.29k
}
3868
3869
static void
3870
diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3871
                          QualType castType, ARCConversionTypeClass castACTC,
3872
                          Expr *castExpr, Expr *realCast,
3873
                          ARCConversionTypeClass exprACTC,
3874
336
                          Sema::CheckedConversionKind CCK) {
3875
336
  SourceLocation loc =
3876
264
    (castRange.isValid() ? castRange.getBegin() : 
castExpr->getExprLoc()72
);
3877
3878
336
  if (S.makeUnavailableInSystemHeader(loc,
3879
336
                                 UnavailableAttr::IR_ARCForbiddenConversion))
3880
4
    return;
3881
3882
332
  QualType castExprType = castExpr->getType();
3883
  // Defer emitting a diagnostic for bridge-related casts; that will be
3884
  // handled by CheckObjCBridgeRelatedConversions.
3885
332
  TypedefNameDecl *TDNDecl = nullptr;
3886
332
  if ((castACTC == ACTC_coreFoundation &&  
exprACTC == ACTC_retainable119
&&
3887
119
       ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3888
323
      (exprACTC == ACTC_coreFoundation && 
castACTC == ACTC_retainable128
&&
3889
128
       ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3890
14
    return;
3891
3892
318
  unsigned srcKind = 0;
3893
318
  switch (exprACTC) {
3894
3
  case ACTC_none:
3895
126
  case ACTC_coreFoundation:
3896
152
  case ACTC_voidPtr:
3897
149
    srcKind = (castExprType->isPointerType() ? 1 : 
03
);
3898
152
    break;
3899
163
  case ACTC_retainable:
3900
159
    srcKind = (castExprType->isBlockPointerType() ? 
24
: 3);
3901
163
    break;
3902
3
  case ACTC_indirectRetainable:
3903
3
    srcKind = 4;
3904
3
    break;
3905
318
  }
3906
3907
  // Check whether this could be fixed with a bridge cast.
3908
318
  SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3909
247
  SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : 
loc71
;
3910
3911
257
  unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 
161
;
3912
3913
  // Bridge from an ARC type to a CF type.
3914
318
  if (castACTC == ACTC_retainable && 
isAnyRetainable(exprACTC)151
) {
3915
3916
145
    S.Diag(loc, diag::err_arc_cast_requires_bridge)
3917
145
      << convKindForDiag
3918
145
      << 2 // of C pointer type
3919
145
      << castExprType
3920
145
      << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3921
145
      << castType
3922
145
      << castRange
3923
145
      << castExpr->getSourceRange();
3924
145
    bool br = S.isKnownName("CFBridgingRelease");
3925
145
    ACCResult CreateRule =
3926
145
      ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3927
145
    assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3928
145
    if (CreateRule != ACC_plusOne)
3929
131
    {
3930
131
      auto DiagB = (CCK != Sema::CCK_OtherCast)
3931
117
                       ? S.Diag(noteLoc, diag::note_arc_bridge)
3932
14
                       : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3933
3934
131
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3935
131
                                   castType, castExpr, realCast, "__bridge ",
3936
131
                                   nullptr);
3937
131
    }
3938
145
    if (CreateRule != ACC_plusZero)
3939
145
    {
3940
145
      auto DiagB = (CCK == Sema::CCK_OtherCast && 
!br14
)
3941
14
                       ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer)
3942
14
                             << castExprType
3943
131
                       : S.Diag(br ? 
castExpr->getExprLoc()67
:
noteLoc64
,
3944
131
                                diag::note_arc_bridge_transfer)
3945
131
                             << castExprType << br;
3946
3947
145
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3948
145
                                   castType, castExpr, realCast, "__bridge_transfer ",
3949
78
                                   br ? 
"CFBridgingRelease"67
: nullptr);
3950
145
    }
3951
3952
145
    return;
3953
145
  }
3954
3955
  // Bridge from a CF type to an ARC type.
3956
173
  if (exprACTC == ACTC_retainable && 
isAnyRetainable(castACTC)163
) {
3957
148
    bool br = S.isKnownName("CFBridgingRetain");
3958
148
    S.Diag(loc, diag::err_arc_cast_requires_bridge)
3959
148
      << convKindForDiag
3960
148
      << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3961
148
      << castExprType
3962
148
      << 2 // to C pointer type
3963
148
      << castType
3964
148
      << castRange
3965
148
      << castExpr->getSourceRange();
3966
148
    ACCResult CreateRule =
3967
148
      ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3968
148
    assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3969
148
    if (CreateRule != ACC_plusOne)
3970
148
    {
3971
148
      auto DiagB = (CCK != Sema::CCK_OtherCast)
3972
137
                       ? S.Diag(noteLoc, diag::note_arc_bridge)
3973
11
                       : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3974
148
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3975
148
                                   castType, castExpr, realCast, "__bridge ",
3976
148
                                   nullptr);
3977
148
    }
3978
148
    if (CreateRule != ACC_plusZero)
3979
148
    {
3980
148
      auto DiagB = (CCK == Sema::CCK_OtherCast && 
!br11
)
3981
9
                       ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained)
3982
9
                             << castType
3983
139
                       : S.Diag(br ? 
castExpr->getExprLoc()79
:
noteLoc60
,
3984
139
                                diag::note_arc_bridge_retained)
3985
139
                             << castType << br;
3986
3987
148
      addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3988
148
                                   castType, castExpr, realCast, "__bridge_retained ",
3989
79
                                   br ? "CFBridgingRetain" : 
nullptr69
);
3990
148
    }
3991
3992
148
    return;
3993
148
  }
3994
3995
25
  S.Diag(loc, diag::err_arc_mismatched_cast)
3996
25
    << !convKindForDiag
3997
25
    << srcKind << castExprType << castType
3998
25
    << castRange << castExpr->getSourceRange();
3999
25
}
4000
4001
template <typename TB>
4002
static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
4003
1.25k
                                  bool &HadTheAttribute, bool warn) {
4004
1.25k
  QualType T = castExpr->getType();
4005
1.25k
  HadTheAttribute = false;
4006
1.78k
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4007
704
    TypedefNameDecl *TDNDecl = TD->getDecl();
4008
704
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4009
178
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4010
178
        HadTheAttribute = true;
4011
178
        if (Parm->isStr("id"))
4012
14
          return true;
4013
4014
164
        NamedDecl *Target = nullptr;
4015
        // Check for an existing type with this name.
4016
164
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4017
164
                       Sema::LookupOrdinaryName);
4018
164
        if (S.LookupName(R, S.TUScope)) {
4019
155
          Target = R.getFoundDecl();
4020
155
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4021
155
            ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4022
155
            if (const ObjCObjectPointerType *InterfacePointerType =
4023
61
                  castType->getAsObjCInterfacePointerType()) {
4024
61
              ObjCInterfaceDecl *CastClass
4025
61
                = InterfacePointerType->getObjectType()->getInterface();
4026
61
              if ((CastClass == ExprClass) ||
4027
36
                  (CastClass && CastClass->isSuperClassOf(ExprClass)))
4028
27
                return true;
4029
34
              if (warn)
4030
15
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4031
15
                    << T << Target->getName() << castType->getPointeeType();
4032
34
              return false;
4033
94
            } else if (castType->isObjCIdType() ||
4034
80
                       (S.Context.ObjCObjectAdoptsQTypeProtocols(
4035
80
                          castType, ExprClass)))
4036
              // ok to cast to 'id'.
4037
              // casting to id<p-list> is ok if bridge type adopts all of
4038
              // p-list protocols.
4039
50
              return true;
4040
44
            else {
4041
44
              if (warn) {
4042
22
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4043
22
                    << T << Target->getName() << castType;
4044
22
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4045
22
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4046
22
              }
4047
44
              return false;
4048
44
           }
4049
9
          }
4050
9
        } else if (!castType->isObjCIdType()) {
4051
7
          S.Diag(castExpr->getBeginLoc(),
4052
7
                 diag::err_objc_cf_bridged_not_interface)
4053
7
              << castExpr->getType() << Parm;
4054
7
          S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4055
7
          if (Target)
4056
0
            S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4057
7
        }
4058
9
        return true;
4059
0
      }
4060
0
      return false;
4061
0
    }
4062
526
    T = TDNDecl->getUnderlyingType();
4063
526
  }
4064
1.08k
  return true;
4065
1.25k
}
SemaExprObjC.cpp:bool CheckObjCBridgeNSCast<clang::ObjCBridgeAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4003
694
                                  bool &HadTheAttribute, bool warn) {
4004
694
  QualType T = castExpr->getType();
4005
694
  HadTheAttribute = false;
4006
917
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4007
394
    TypedefNameDecl *TDNDecl = TD->getDecl();
4008
394
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4009
171
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4010
171
        HadTheAttribute = true;
4011
171
        if (Parm->isStr("id"))
4012
14
          return true;
4013
4014
157
        NamedDecl *Target = nullptr;
4015
        // Check for an existing type with this name.
4016
157
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4017
157
                       Sema::LookupOrdinaryName);
4018
157
        if (S.LookupName(R, S.TUScope)) {
4019
149
          Target = R.getFoundDecl();
4020
149
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4021
149
            ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4022
149
            if (const ObjCObjectPointerType *InterfacePointerType =
4023
55
                  castType->getAsObjCInterfacePointerType()) {
4024
55
              ObjCInterfaceDecl *CastClass
4025
55
                = InterfacePointerType->getObjectType()->getInterface();
4026
55
              if ((CastClass == ExprClass) ||
4027
35
                  (CastClass && CastClass->isSuperClassOf(ExprClass)))
4028
21
                return true;
4029
34
              if (warn)
4030
15
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4031
15
                    << T << Target->getName() << castType->getPointeeType();
4032
34
              return false;
4033
94
            } else if (castType->isObjCIdType() ||
4034
80
                       (S.Context.ObjCObjectAdoptsQTypeProtocols(
4035
80
                          castType, ExprClass)))
4036
              // ok to cast to 'id'.
4037
              // casting to id<p-list> is ok if bridge type adopts all of
4038
              // p-list protocols.
4039
50
              return true;
4040
44
            else {
4041
44
              if (warn) {
4042
22
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4043
22
                    << T << Target->getName() << castType;
4044
22
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4045
22
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4046
22
              }
4047
44
              return false;
4048
44
           }
4049
8
          }
4050
8
        } else if (!castType->isObjCIdType()) {
4051
6
          S.Diag(castExpr->getBeginLoc(),
4052
6
                 diag::err_objc_cf_bridged_not_interface)
4053
6
              << castExpr->getType() << Parm;
4054
6
          S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4055
6
          if (Target)
4056
0
            S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4057
6
        }
4058
8
        return true;
4059
0
      }
4060
0
      return false;
4061
0
    }
4062
223
    T = TDNDecl->getUnderlyingType();
4063
223
  }
4064
523
  return true;
4065
694
}
SemaExprObjC.cpp:bool CheckObjCBridgeNSCast<clang::ObjCBridgeMutableAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4003
564
                                  bool &HadTheAttribute, bool warn) {
4004
564
  QualType T = castExpr->getType();
4005
564
  HadTheAttribute = false;
4006
867
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4007
310
    TypedefNameDecl *TDNDecl = TD->getDecl();
4008
310
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4009
7
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4010
7
        HadTheAttribute = true;
4011
7
        if (Parm->isStr("id"))
4012
0
          return true;
4013
4014
7
        NamedDecl *Target = nullptr;
4015
        // Check for an existing type with this name.
4016
7
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4017
7
                       Sema::LookupOrdinaryName);
4018
7
        if (S.LookupName(R, S.TUScope)) {
4019
6
          Target = R.getFoundDecl();
4020
6
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4021
6
            ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4022
6
            if (const ObjCObjectPointerType *InterfacePointerType =
4023
6
                  castType->getAsObjCInterfacePointerType()) {
4024
6
              ObjCInterfaceDecl *CastClass
4025
6
                = InterfacePointerType->getObjectType()->getInterface();
4026
6
              if ((CastClass == ExprClass) ||
4027
1
                  (CastClass && CastClass->isSuperClassOf(ExprClass)))
4028
6
                return true;
4029
0
              if (warn)
4030
0
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4031
0
                    << T << Target->getName() << castType->getPointeeType();
4032
0
              return false;
4033
0
            } else if (castType->isObjCIdType() ||
4034
0
                       (S.Context.ObjCObjectAdoptsQTypeProtocols(
4035
0
                          castType, ExprClass)))
4036
              // ok to cast to 'id'.
4037
              // casting to id<p-list> is ok if bridge type adopts all of
4038
              // p-list protocols.
4039
0
              return true;
4040
0
            else {
4041
0
              if (warn) {
4042
0
                S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4043
0
                    << T << Target->getName() << castType;
4044
0
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4045
0
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4046
0
              }
4047
0
              return false;
4048
0
           }
4049
1
          }
4050
1
        } else if (!castType->isObjCIdType()) {
4051
1
          S.Diag(castExpr->getBeginLoc(),
4052
1
                 diag::err_objc_cf_bridged_not_interface)
4053
1
              << castExpr->getType() << Parm;
4054
1
          S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4055
1
          if (Target)
4056
0
            S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4057
1
        }
4058
1
        return true;
4059
0
      }
4060
0
      return false;
4061
0
    }
4062
303
    T = TDNDecl->getUnderlyingType();
4063
303
  }
4064
557
  return true;
4065
564
}
4066
4067
template <typename TB>
4068
static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
4069
463
                                  bool &HadTheAttribute, bool warn) {
4070
463
  QualType T = castType;
4071
463
  HadTheAttribute = false;
4072
721
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4073
453
    TypedefNameDecl *TDNDecl = TD->getDecl();
4074
453
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4075
195
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4076
195
        HadTheAttribute = true;
4077
195
        if (Parm->isStr("id"))
4078
6
          return true;
4079
4080
189
        NamedDecl *Target = nullptr;
4081
        // Check for an existing type with this name.
4082
189
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4083
189
                       Sema::LookupOrdinaryName);
4084
189
        if (S.LookupName(R, S.TUScope)) {
4085
189
          Target = R.getFoundDecl();
4086
189
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4087
189
            ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4088
189
            if (const ObjCObjectPointerType *InterfacePointerType =
4089
108
                  castExpr->getType()->getAsObjCInterfacePointerType()) {
4090
108
              ObjCInterfaceDecl *ExprClass
4091
108
                = InterfacePointerType->getObjectType()->getInterface();
4092
108
              if ((CastClass == ExprClass) ||
4093
91
                  (ExprClass && CastClass->isSuperClassOf(ExprClass)))
4094
86
                return true;
4095
22
              if (warn) {
4096
9
                S.Diag(castExpr->getBeginLoc(),
4097
9
                       diag::warn_objc_invalid_bridge_to_cf)
4098
9
                    << castExpr->getType()->getPointeeType() << T;
4099
9
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4100
9
              }
4101
22
              return false;
4102
81
            } else if (castExpr->getType()->isObjCIdType() ||
4103
68
                       (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4104
68
                          castExpr->getType(), CastClass)))
4105
              // ok to cast an 'id' expression to a CFtype.
4106
              // ok to cast an 'id<plist>' expression to CFtype provided plist
4107
              // adopts all of CFtype's ObjetiveC's class plist.
4108
65
              return true;
4109
16
            else {
4110
16
              if (warn) {
4111
8
                S.Diag(castExpr->getBeginLoc(),
4112
8
                       diag::warn_objc_invalid_bridge_to_cf)
4113
8
                    << castExpr->getType() << castType;
4114
8
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4115
8
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4116
8
              }
4117
16
              return false;
4118
16
            }
4119
0
          }
4120
189
        }
4121
0
        S.Diag(castExpr->getBeginLoc(),
4122
0
               diag::err_objc_ns_bridged_invalid_cfobject)
4123
0
            << castExpr->getType() << castType;
4124
0
        S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4125
0
        if (Target)
4126
0
          S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4127
0
        return true;
4128
0
      }
4129
0
      return false;
4130
0
    }
4131
258
    T = TDNDecl->getUnderlyingType();
4132
258
  }
4133
268
  return true;
4134
463
}
SemaExprObjC.cpp:bool CheckObjCBridgeCFCast<clang::ObjCBridgeAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4069
315
                                  bool &HadTheAttribute, bool warn) {
4070
315
  QualType T = castType;
4071
315
  HadTheAttribute = false;
4072
437
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4073
310
    TypedefNameDecl *TDNDecl = TD->getDecl();
4074
310
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4075
188
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4076
188
        HadTheAttribute = true;
4077
188
        if (Parm->isStr("id"))
4078
6
          return true;
4079
4080
182
        NamedDecl *Target = nullptr;
4081
        // Check for an existing type with this name.
4082
182
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4083
182
                       Sema::LookupOrdinaryName);
4084
182
        if (S.LookupName(R, S.TUScope)) {
4085
182
          Target = R.getFoundDecl();
4086
182
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4087
182
            ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4088
182
            if (const ObjCObjectPointerType *InterfacePointerType =
4089
101
                  castExpr->getType()->getAsObjCInterfacePointerType()) {
4090
101
              ObjCInterfaceDecl *ExprClass
4091
101
                = InterfacePointerType->getObjectType()->getInterface();
4092
101
              if ((CastClass == ExprClass) ||
4093
89
                  (ExprClass && CastClass->isSuperClassOf(ExprClass)))
4094
81
                return true;
4095
20
              if (warn) {
4096
8
                S.Diag(castExpr->getBeginLoc(),
4097
8
                       diag::warn_objc_invalid_bridge_to_cf)
4098
8
                    << castExpr->getType()->getPointeeType() << T;
4099
8
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4100
8
              }
4101
20
              return false;
4102
81
            } else if (castExpr->getType()->isObjCIdType() ||
4103
68
                       (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4104
68
                          castExpr->getType(), CastClass)))
4105
              // ok to cast an 'id' expression to a CFtype.
4106
              // ok to cast an 'id<plist>' expression to CFtype provided plist
4107
              // adopts all of CFtype's ObjetiveC's class plist.
4108
65
              return true;
4109
16
            else {
4110
16
              if (warn) {
4111
8
                S.Diag(castExpr->getBeginLoc(),
4112
8
                       diag::warn_objc_invalid_bridge_to_cf)
4113
8
                    << castExpr->getType() << castType;
4114
8
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4115
8
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4116
8
              }
4117
16
              return false;
4118
16
            }
4119
0
          }
4120
182
        }
4121
0
        S.Diag(castExpr->getBeginLoc(),
4122
0
               diag::err_objc_ns_bridged_invalid_cfobject)
4123
0
            << castExpr->getType() << castType;
4124
0
        S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4125
0
        if (Target)
4126
0
          S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4127
0
        return true;
4128
0
      }
4129
0
      return false;
4130
0
    }
4131
122
    T = TDNDecl->getUnderlyingType();
4132
122
  }
4133
127
  return true;
4134
315
}
SemaExprObjC.cpp:bool CheckObjCBridgeCFCast<clang::ObjCBridgeMutableAttr>(clang::Sema&, clang::QualType, clang::Expr*, bool&, bool)
Line
Count
Source
4069
148
                                  bool &HadTheAttribute, bool warn) {
4070
148
  QualType T = castType;
4071
148
  HadTheAttribute = false;
4072
284
  while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4073
143
    TypedefNameDecl *TDNDecl = TD->getDecl();
4074
143
    if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4075
7
      if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4076
7
        HadTheAttribute = true;
4077
7
        if (Parm->isStr("id"))
4078
0
          return true;
4079
4080
7
        NamedDecl *Target = nullptr;
4081
        // Check for an existing type with this name.
4082
7
        LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4083
7
                       Sema::LookupOrdinaryName);
4084
7
        if (S.LookupName(R, S.TUScope)) {
4085
7
          Target = R.getFoundDecl();
4086
7
          if (Target && isa<ObjCInterfaceDecl>(Target)) {
4087
7
            ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4088
7
            if (const ObjCObjectPointerType *InterfacePointerType =
4089
7
                  castExpr->getType()->getAsObjCInterfacePointerType()) {
4090
7
              ObjCInterfaceDecl *ExprClass
4091
7
                = InterfacePointerType->getObjectType()->getInterface();
4092
7
              if ((CastClass == ExprClass) ||
4093
2
                  (ExprClass && CastClass->isSuperClassOf(ExprClass)))
4094
5
                return true;
4095
2
              if (warn) {
4096
1
                S.Diag(castExpr->getBeginLoc(),
4097
1
                       diag::warn_objc_invalid_bridge_to_cf)
4098
1
                    << castExpr->getType()->getPointeeType() << T;
4099
1
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4100
1
              }
4101
2
              return false;
4102
0
            } else if (castExpr->getType()->isObjCIdType() ||
4103
0
                       (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4104
0
                          castExpr->getType(), CastClass)))
4105
              // ok to cast an 'id' expression to a CFtype.
4106
              // ok to cast an 'id<plist>' expression to CFtype provided plist
4107
              // adopts all of CFtype's ObjetiveC's class plist.
4108
0
              return true;
4109
0
            else {
4110
0
              if (warn) {
4111
0
                S.Diag(castExpr->getBeginLoc(),
4112
0
                       diag::warn_objc_invalid_bridge_to_cf)
4113
0
                    << castExpr->getType() << castType;
4114
0
                S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4115
0
                S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4116
0
              }
4117
0
              return false;
4118
0
            }
4119
0
          }
4120
7
        }
4121
0
        S.Diag(castExpr->getBeginLoc(),
4122
0
               diag::err_objc_ns_bridged_invalid_cfobject)
4123
0
            << castExpr->getType() << castType;
4124
0
        S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4125
0
        if (Target)
4126
0
          S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4127
0
        return true;
4128
0
      }
4129
0
      return false;
4130
0
    }
4131
136
    T = TDNDecl->getUnderlyingType();
4132
136
  }
4133
141
  return true;
4134
148
}
4135
4136
4.21M
void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
4137
4.21M
  if (!getLangOpts().ObjC)
4138
3.77M
    return;
4139
  // warn in presence of __bridge casting to or from a toll free bridge cast.
4140
445k
  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
4141
445k
  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4142
445k
  if (castACTC == ACTC_retainable && 
exprACTC == ACTC_coreFoundation4.84k
) {
4143
657
    bool HasObjCBridgeAttr;
4144
657
    bool ObjCBridgeAttrWillNotWarn =
4145
657
      CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4146
657
                                            false);
4147
657
    if (ObjCBridgeAttrWillNotWarn && 
HasObjCBridgeAttr616
)
4148
93
      return;
4149
564
    bool HasObjCBridgeMutableAttr;
4150
564
    bool ObjCBridgeMutableAttrWillNotWarn =
4151
564
      CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4152
564
                                                   HasObjCBridgeMutableAttr, false);
4153
564
    if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
4154
7
      return;
4155
4156
557
    if (HasObjCBridgeAttr)
4157
37
      CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4158
37
                                            true);
4159
520
    else if (HasObjCBridgeMutableAttr)
4160
0
      CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4161
0
                                                   HasObjCBridgeMutableAttr, true);
4162
557
  }
4163
444k
  else if (castACTC == ACTC_coreFoundation && 
exprACTC == ACTC_retainable22.6k
) {
4164
299
    bool HasObjCBridgeAttr;
4165
299
    bool ObjCBridgeAttrWillNotWarn =
4166
299
      CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4167
299
                                            false);
4168
299
    if (ObjCBridgeAttrWillNotWarn && 
HasObjCBridgeAttr279
)
4169
152
      return;
4170
147
    bool HasObjCBridgeMutableAttr;
4171
147
    bool ObjCBridgeMutableAttrWillNotWarn =
4172
147
      CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4173
147
                                                   HasObjCBridgeMutableAttr, false);
4174
147
    if (ObjCBridgeMutableAttrWillNotWarn && 
HasObjCBridgeMutableAttr146
)
4175
5
      return;
4176
4177
142
    if (HasObjCBridgeAttr)
4178
16
      CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4179
16
                                            true);
4180
126
    else if (HasObjCBridgeMutableAttr)
4181
1
      CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4182
1
                                                   HasObjCBridgeMutableAttr, true);
4183
142
  }
4184
445k
}
4185
4186
4.21M
void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
4187
4.21M
  QualType SrcType = castExpr->getType();
4188
4.21M
  if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
4189
96
    if (PRE->isExplicitProperty()) {
4190
32
      if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
4191
32
        SrcType = PDecl->getType();
4192
32
    }
4193
64
    else if (PRE->isImplicitProperty()) {
4194
64
      if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
4195
64
        SrcType = Getter->getReturnType();
4196
64
    }
4197
96
  }
4198
4199
4.21M
  ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
4200
4.21M
  ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
4201
4.21M
  if (srcExprACTC != ACTC_retainable || 
castExprACTC != ACTC_coreFoundation1.99k
)
4202
4.21M
    return;
4203
249
  CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
4204
249
                                    castExpr);
4205
249
}
4206
4207
bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
4208
111
                                         CastKind &Kind) {
4209
111
  if (!getLangOpts().ObjC)
4210
82
    return false;
4211
29
  ARCConversionTypeClass exprACTC =
4212
29
    classifyTypeForARCConversion(castExpr->getType());
4213
29
  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4214
29
  if ((castACTC == ACTC_retainable && 
exprACTC == ACTC_coreFoundation15
) ||
4215
22
      
(15
castACTC == ACTC_coreFoundation15
&&
exprACTC == ACTC_retainable8
)) {
4216
22
    CheckTollFreeBridgeCast(castType, castExpr);
4217
8
    Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
4218
14
                                             : CK_CPointerToObjCPointerCast;
4219
22
    return true;
4220
22
  }
4221
7
  return false;
4222
7
}
4223
4224
bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4225
                                            QualType DestType, QualType SrcType,
4226
                                            ObjCInterfaceDecl *&RelatedClass,
4227
                                            ObjCMethodDecl *&ClassMethod,
4228
                                            ObjCMethodDecl *&InstanceMethod,
4229
                                            TypedefNameDecl *&TDNDecl,
4230
1.04k
                                            bool CfToNs, bool Diagnose) {
4231
840
  QualType T = CfToNs ? 
SrcType206
: DestType;
4232
1.04k
  ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4233
1.04k
  if (!ObjCBAttr)
4234
979
    return false;
4235
4236
67
  IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4237
67
  IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4238
67
  IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4239
67
  if (!RCId)
4240
0
    return false;
4241
67
  NamedDecl *Target = nullptr;
4242
  // Check for an existing type with this name.
4243
67
  LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4244
67
                 Sema::LookupOrdinaryName);
4245
67
  if (!LookupName(R, TUScope)) {
4246
2
    if (Diagnose) {
4247
2
      Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4248
2
            << SrcType << DestType;
4249
2
      Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4250
2
    }
4251
2
    return false;
4252
2
  }
4253
65
  Target = R.getFoundDecl();
4254
65
  if (Target && isa<ObjCInterfaceDecl>(Target))
4255
63
    RelatedClass = cast<ObjCInterfaceDecl>(Target);
4256
2
  else {
4257
2
    if (Diagnose) {
4258
2
      Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4259
2
            << SrcType << DestType;
4260
2
      Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4261
2
      if (Target)
4262
2
        Diag(Target->getBeginLoc(), diag::note_declared_at);
4263
2
    }
4264
2
    return false;
4265
2
  }
4266
4267
  // Check for an existing class method with the given selector name.
4268
63
  if (CfToNs && 
CMId26
) {
4269
16
    Selector Sel = Context.Selectors.getUnarySelector(CMId);
4270
16
    ClassMethod = RelatedClass->lookupMethod(Sel, false);
4271
16
    if (!ClassMethod) {
4272
1
      if (Diagnose) {
4273
1
        Diag(Loc, diag::err_objc_bridged_related_known_method)
4274
1
              << SrcType << DestType << Sel << false;
4275
1
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4276
1
      }
4277
1
      return false;
4278
1
    }
4279
62
  }
4280
4281
  // Check for an existing instance method with the given selector name.
4282
62
  if (!CfToNs && 
IMId37
) {
4283
31
    Selector Sel = Context.Selectors.getNullarySelector(IMId);
4284
31
    InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4285
31
    if (!InstanceMethod) {
4286
1
      if (Diagnose) {
4287
1
        Diag(Loc, diag::err_objc_bridged_related_known_method)
4288
1
              << SrcType << DestType << Sel << true;
4289
1
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4290
1
      }
4291
1
      return false;
4292
1
    }
4293
61
  }
4294
61
  return true;
4295
61
}
4296
4297
bool
4298
Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4299
                                        QualType DestType, QualType SrcType,
4300
1.27M
                                        Expr *&SrcExpr, bool Diagnose) {
4301
1.27M
  ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4302
1.27M
  ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4303
1.27M
  bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && 
lhsExprACTC == ACTC_retainable32.0k
);
4304
1.27M
  bool NsToCf = (rhsExprACTC == ACTC_retainable && 
lhsExprACTC == ACTC_coreFoundation51.6k
);
4305
1.27M
  if (!CfToNs && 
!NsToCf1.27M
)
4306
1.27M
    return false;
4307
4308
1.04k
  ObjCInterfaceDecl *RelatedClass;
4309
1.04k
  ObjCMethodDecl *ClassMethod = nullptr;
4310
1.04k
  ObjCMethodDecl *InstanceMethod = nullptr;
4311
1.04k
  TypedefNameDecl *TDNDecl = nullptr;
4312
1.04k
  if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4313
1.04k
                                        ClassMethod, InstanceMethod, TDNDecl,
4314
1.04k
                                        CfToNs, Diagnose))
4315
985
    return false;
4316
4317
61
  if (CfToNs) {
4318
    // Implicit conversion from CF to ObjC object is needed.
4319
25
    if (ClassMethod) {
4320
15
      if (Diagnose) {
4321
15
        std::string ExpressionString = "[";
4322
15
        ExpressionString += RelatedClass->getNameAsString();
4323
15
        ExpressionString += " ";
4324
15
        ExpressionString += ClassMethod->getSelector().getAsString();
4325
15
        SourceLocation SrcExprEndLoc =
4326
15
            getLocForEndOfToken(SrcExpr->getEndLoc());
4327
        // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4328
15
        Diag(Loc, diag::err_objc_bridged_related_known_method)
4329
15
            << SrcType << DestType << ClassMethod->getSelector() << false
4330
15
            << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4331
15
                                          ExpressionString)
4332
15
            << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4333
15
        Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4334
15
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4335
4336
15
        QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4337
        // Argument.
4338
15
        Expr *args[] = { SrcExpr };
4339
15
        ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4340
15
                                      ClassMethod->getLocation(),
4341
15
                                      ClassMethod->getSelector(), ClassMethod,
4342
15
                                      MultiExprArg(args, 1));
4343
15
        SrcExpr = msg.get();
4344
15
      }
4345
15
      return true;
4346
15
    }
4347
36
  }
4348
36
  else {
4349
    // Implicit conversion from ObjC type to CF object is needed.
4350
36
    if (InstanceMethod) {
4351
30
      if (Diagnose) {
4352
30
        std::string ExpressionString;
4353
30
        SourceLocation SrcExprEndLoc =
4354
30
            getLocForEndOfToken(SrcExpr->getEndLoc());
4355
30
        if (InstanceMethod->isPropertyAccessor())
4356
6
          if (const ObjCPropertyDecl *PDecl =
4357
6
                  InstanceMethod->findPropertyDecl()) {
4358
            // fixit: ObjectExpr.propertyname when it is  aproperty accessor.
4359
6
            ExpressionString = ".";
4360
6
            ExpressionString += PDecl->getNameAsString();
4361
6
            Diag(Loc, diag::err_objc_bridged_related_known_method)
4362
6
                << SrcType << DestType << InstanceMethod->getSelector() << true
4363
6
                << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4364
6
          }
4365
30
        if (ExpressionString.empty()) {
4366
          // Provide a fixit: [ObjectExpr InstanceMethod]
4367
24
          ExpressionString = " ";
4368
24
          ExpressionString += InstanceMethod->getSelector().getAsString();
4369
24
          ExpressionString += "]";
4370
4371
24
          Diag(Loc, diag::err_objc_bridged_related_known_method)
4372
24
              << SrcType << DestType << InstanceMethod->getSelector() << true
4373
24
              << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
4374
24
              << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4375
24
        }
4376
30
        Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4377
30
        Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4378
4379
30
        ExprResult msg =
4380
30
          BuildInstanceMessageImplicit(SrcExpr, SrcType,
4381
30
                                       InstanceMethod->getLocation(),
4382
30
                                       InstanceMethod->getSelector(),
4383
30
                                       InstanceMethod, None);
4384
30
        SrcExpr = msg.get();
4385
30
      }
4386
30
      return true;
4387
30
    }
4388
16
  }
4389
16
  return false;
4390
16
}
4391
4392
Sema::ARCConversionResult
4393
Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4394
                          Expr *&castExpr, CheckedConversionKind CCK,
4395
                          bool Diagnose, bool DiagnoseCFAudited,
4396
17.6k
                          BinaryOperatorKind Opc) {
4397
17.6k
  QualType castExprType = castExpr->getType();
4398
4399
  // For the purposes of the classification, we assume reference types
4400
  // will bind to temporaries.
4401
17.6k
  QualType effCastType = castType;
4402
17.6k
  if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4403
174
    effCastType = ref->getPointeeType();
4404
4405
17.6k
  ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4406
17.6k
  ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4407
17.6k
  if (exprACTC == castACTC) {
4408
    // Check for viability and report error if casting an rvalue to a
4409
    // life-time qualifier.
4410
16.1k
    if (castACTC == ACTC_retainable &&
4411
2.03k
        (CCK == CCK_CStyleCast || 
CCK == CCK_OtherCast1.94k
) &&
4412
105
        castType != castExprType) {
4413
57
      const Type *DT = castType.getTypePtr();
4414
57
      QualType QDT = castType;
4415
      // We desugar some types but not others. We ignore those
4416
      // that cannot happen in a cast; i.e. auto, and those which
4417
      // should not be de-sugared; i.e typedef.
4418
57
      if (const ParenType *PT = dyn_cast<ParenType>(DT))
4419
0
        QDT = PT->desugar();
4420
57
      else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4421
3
        QDT = TP->desugar();
4422
54
      else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4423
26
        QDT = AT->desugar();
4424
57
      if (QDT != castType &&
4425
29
          QDT.getObjCLifetime() !=  Qualifiers::OCL_None) {
4426
23
        if (Diagnose) {
4427
16
          SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4428
7
                                                    : castExpr->getExprLoc());
4429
23
          Diag(loc, diag::err_arc_nolifetime_behavior);
4430
23
        }
4431
23
        return ACR_error;
4432
23
      }
4433
16.1k
    }
4434
16.1k
    return ACR_okay;
4435
16.1k
  }
4436
4437
  // The life-time qualifier cast check above is all we need for ObjCWeak.
4438
  // ObjCAutoRefCount has more restrictions on what is legal.
4439
1.51k
  if (!getLangOpts().ObjCAutoRefCount)
4440
3
    return ACR_okay;
4441
4442
1.51k
  if (isAnyCLike(exprACTC) && 
isAnyCLike(castACTC)1.16k
)
return ACR_okay690
;
4443
4444
  // Allow all of these types to be cast to integer types (but not
4445
  // vice-versa).
4446
825
  if (castACTC == ACTC_none && 
castType->isIntegralType(Context)38
)
4447
30
    return ACR_okay;
4448
4449
  // Allow casts between pointers to lifetime types (e.g., __strong id*)
4450
  // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4451
  // must be explicit.
4452
795
  if (exprACTC == ACTC_indirectRetainable && 
castACTC == ACTC_voidPtr105
)
4453
100
    return ACR_okay;
4454
695
  if (castACTC == ACTC_indirectRetainable && 
exprACTC == ACTC_voidPtr67
&&
4455
51
      isCast(CCK))
4456
47
    return ACR_okay;
4457
4458
648
  switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4459
  // For invalid casts, fall through.
4460
361
  case ACC_invalid:
4461
361
    break;
4462
4463
  // Do nothing for both bottom and +0.
4464
207
  case ACC_bottom:
4465
275
  case ACC_plusZero:
4466
275
    return ACR_okay;
4467
4468
  // If the result is +1, consume it here.
4469
12
  case ACC_plusOne:
4470
12
    castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4471
12
                                        CK_ARCConsumeObject, castExpr, nullptr,
4472
12
                                        VK_RValue, FPOptionsOverride());
4473
12
    Cleanup.setExprNeedsCleanups(true);
4474
12
    return ACR_okay;
4475
361
  }
4476
4477
  // If this is a non-implicit cast from id or block type to a
4478
  // CoreFoundation type, delay complaining in case the cast is used
4479
  // in an acceptable context.
4480
361
  if (exprACTC == ACTC_retainable && 
isAnyRetainable(castACTC)190
&&
isCast(CCK)175
)
4481
122
    return ACR_unbridged;
4482
4483
  // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4484
  // to 'NSString *', instead of falling through to report a "bridge cast"
4485
  // diagnostic.
4486
239
  if (castACTC == ACTC_retainable && 
exprACTC == ACTC_none165
&&
4487
5
      CheckConversionToObjCLiteral(castType, castExpr, Diagnose))
4488
2
    return ACR_error;
4489
4490
  // Do not issue "bridge cast" diagnostic when implicit casting
4491
  // a retainable object to a CF type parameter belonging to an audited
4492
  // CF API function. Let caller issue a normal type mismatched diagnostic
4493
  // instead.
4494
237
  if ((!DiagnoseCFAudited || 
exprACTC != ACTC_retainable1
||
4495
1
       castACTC != ACTC_coreFoundation) &&
4496
236
      !(exprACTC == ACTC_voidPtr && 
castACTC == ACTC_retainable33
&&
4497
229
        
(29
Opc == BO_NE29
||
Opc == BO_EQ27
))) {
4498
229
    if (Diagnose)
4499
225
      diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4500
225
                                castExpr, exprACTC, CCK);
4501
229
    return ACR_error;
4502
229
  }
4503
8
  return ACR_okay;
4504
8
}
4505
4506
/// Given that we saw an expression with the ARCUnbridgedCastTy
4507
/// placeholder type, complain bitterly.
4508
111
void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4509
  // We expect the spurious ImplicitCastExpr to already have been stripped.
4510
111
  assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4511
111
  CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4512
4513
111
  SourceRange castRange;
4514
111
  QualType castType;
4515
111
  CheckedConversionKind CCK;
4516
4517
111
  if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4518
100
    castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4519
100
    castType = cast->getTypeAsWritten();
4520
100
    CCK = CCK_CStyleCast;
4521
11
  } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4522
11
    castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4523
11
    castType = cast->getTypeAsWritten();
4524
11
    CCK = CCK_OtherCast;
4525
0
  } else {
4526
0
    llvm_unreachable("Unexpected ImplicitCastExpr");
4527
0
  }
4528
4529
111
  ARCConversionTypeClass castACTC =
4530
111
    classifyTypeForARCConversion(castType.getNonReferenceType());
4531
4532
111
  Expr *castExpr = realCast->getSubExpr();
4533
111
  assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4534
4535
111
  diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4536
111
                            castExpr, realCast, ACTC_retainable, CCK);
4537
111
}
4538
4539
/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4540
/// type, remove the placeholder cast.
4541
135
Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4542
135
  assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4543
4544
135
  if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4545
7
    Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4546
7
    return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4547
128
  } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4548
0
    assert(uo->getOpcode() == UO_Extension);
4549
0
    Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4550
0
    return UnaryOperator::Create(Context, sub, UO_Extension, sub->getType(),
4551
0
                                 sub->getValueKind(), sub->getObjectKind(),
4552
0
                                 uo->getOperatorLoc(), false,
4553
0
                                 CurFPFeatureOverrides());
4554
128
  } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4555
0
    assert(!gse->isResultDependent());
4556
4557
0
    unsigned n = gse->getNumAssocs();
4558
0
    SmallVector<Expr *, 4> subExprs;
4559
0
    SmallVector<TypeSourceInfo *, 4> subTypes;
4560
0
    subExprs.reserve(n);
4561
0
    subTypes.reserve(n);
4562
0
    for (const GenericSelectionExpr::Association assoc : gse->associations()) {
4563
0
      subTypes.push_back(assoc.getTypeSourceInfo());
4564
0
      Expr *sub = assoc.getAssociationExpr();
4565
0
      if (assoc.isSelected())
4566
0
        sub = stripARCUnbridgedCast(sub);
4567
0
      subExprs.push_back(sub);
4568
0
    }
4569
4570
0
    return GenericSelectionExpr::Create(
4571
0
        Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4572
0
        subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4573
0
        gse->containsUnexpandedParameterPack(), gse->getResultIndex());
4574
128
  } else {
4575
128
    assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4576
128
    return cast<ImplicitCastExpr>(e)->getSubExpr();
4577
128
  }
4578
135
}
4579
4580
bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4581
2.39k
                                                 QualType exprType) {
4582
2.39k
  QualType canCastType =
4583
2.39k
    Context.getCanonicalType(castType).getUnqualifiedType();
4584
2.39k
  QualType canExprType =
4585
2.39k
    Context.getCanonicalType(exprType).getUnqualifiedType();
4586
2.39k
  if (isa<ObjCObjectPointerType>(canCastType) &&
4587
1.39k
      castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4588
108
      canExprType->isObjCObjectPointerType()) {
4589
106
    if (const ObjCObjectPointerType *ObjT =
4590
106
        canExprType->getAs<ObjCObjectPointerType>())
4591
106
      if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4592
60
        return !ObjI->isArcWeakrefUnavailable();
4593
2.33k
  }
4594
2.33k
  return true;
4595
2.33k
}
4596
4597
/// Look for an ObjCReclaimReturnedObject cast and destroy it.
4598
64
static Expr *maybeUndoReclaimObject(Expr *e) {
4599
64
  Expr *curExpr = e, *prevExpr = nullptr;
4600
4601
  // Walk down the expression until we hit an implicit cast of kind
4602
  // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4603
117
  while (true) {
4604
117
    if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4605
7
      prevExpr = curExpr;
4606
7
      curExpr = pe->getSubExpr();
4607
7
      continue;
4608
7
    }
4609
4610
110
    if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4611
82
      if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4612
61
        if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4613
36
          if (!prevExpr)
4614
20
            return ice->getSubExpr();
4615
16
          if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4616
4
            pe->setSubExpr(ice->getSubExpr());
4617
12
          else
4618
12
            cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4619
16
          return e;
4620
16
        }
4621
4622
46
      prevExpr = curExpr;
4623
46
      curExpr = ce->getSubExpr();
4624
46
      continue;
4625
46
    }
4626
4627
    // Break out of the loop if curExpr is neither a Paren nor a Cast.
4628
28
    break;
4629
28
  }
4630
4631
28
  return e;
4632
64
}
4633
4634
ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4635
                                      ObjCBridgeCastKind Kind,
4636
                                      SourceLocation BridgeKeywordLoc,
4637
                                      TypeSourceInfo *TSInfo,
4638
346
                                      Expr *SubExpr) {
4639
346
  ExprResult SubResult = UsualUnaryConversions(SubExpr);
4640
346
  if (SubResult.isInvalid()) 
return ExprError()0
;
4641
346
  SubExpr = SubResult.get();
4642
4643
346
  QualType T = TSInfo->getType();
4644
346
  QualType FromType = SubExpr->getType();
4645
4646
346
  CastKind CK;
4647
4648
346
  bool MustConsume = false;
4649
346
  if (T->isDependentType() || 
SubExpr->isTypeDependent()335
) {
4650
    // Okay: we'll build a dependent expression type.
4651
14
    CK = CK_Dependent;
4652
332
  } else if (T->isObjCARCBridgableType() && 
FromType->isCARCBridgableType()163
) {
4653
    // Casting CF -> id
4654
1
    CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4655
162
                                  : CK_CPointerToObjCPointerCast);
4656
163
    switch (Kind) {
4657
58
    case OBC_Bridge:
4658
58
      break;
4659
4660
0
    case OBC_BridgeRetained: {
4661
0
      bool br = isKnownName("CFBridgingRelease");
4662
0
      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4663
0
        << 2
4664
0
        << FromType
4665
0
        << (T->isBlockPointerType()? 1 : 0)
4666
0
        << T
4667
0
        << SubExpr->getSourceRange()
4668
0
        << Kind;
4669
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4670
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4671
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4672
0
        << FromType << br
4673
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc,
4674
0
                                        br ? "CFBridgingRelease "
4675
0
                                           : "__bridge_transfer ");
4676
4677
0
      Kind = OBC_Bridge;
4678
0
      break;
4679
0
    }
4680
4681
105
    case OBC_BridgeTransfer:
4682
      // We must consume the Objective-C object produced by the cast.
4683
105
      MustConsume = true;
4684
105
      break;
4685
169
    }
4686
169
  } else if (T->isCARCBridgableType() && 
FromType->isObjCARCBridgableType()166
) {
4687
    // Okay: id -> CF
4688
166
    CK = CK_BitCast;
4689
166
    switch (Kind) {
4690
64
    case OBC_Bridge:
4691
      // Reclaiming a value that's going to be __bridge-casted to CF
4692
      // is very dangerous, so we don't do it.
4693
64
      SubExpr = maybeUndoReclaimObject(SubExpr);
4694
64
      break;
4695
4696
102
    case OBC_BridgeRetained:
4697
      // Produce the object before casting it.
4698
102
      SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject,
4699
102
                                         SubExpr, nullptr, VK_RValue,
4700
102
                                         FPOptionsOverride());
4701
102
      break;
4702
4703
0
    case OBC_BridgeTransfer: {
4704
0
      bool br = isKnownName("CFBridgingRetain");
4705
0
      Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4706
0
        << (FromType->isBlockPointerType()? 1 : 0)
4707
0
        << FromType
4708
0
        << 2
4709
0
        << T
4710
0
        << SubExpr->getSourceRange()
4711
0
        << Kind;
4712
4713
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4714
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4715
0
      Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4716
0
        << T << br
4717
0
        << FixItHint::CreateReplacement(BridgeKeywordLoc,
4718
0
                          br ? "CFBridgingRetain " : "__bridge_retained");
4719
4720
0
      Kind = OBC_Bridge;
4721
0
      break;
4722
3
    }
4723
3
    }
4724
3
  } else {
4725
3
    Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4726
3
      << FromType << T << Kind
4727
3
      << SubExpr->getSourceRange()
4728
3
      << TSInfo->getTypeLoc().getSourceRange();
4729
3
    return ExprError();
4730
3
  }
4731
4732
343
  Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4733
343
                                                   BridgeKeywordLoc,
4734
343
                                                   TSInfo, SubExpr);
4735
4736
343
  if (MustConsume) {
4737
105
    Cleanup.setExprNeedsCleanups(true);
4738
105
    Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4739
105
                                      nullptr, VK_RValue, FPOptionsOverride());
4740
105
  }
4741
4742
343
  return Result;
4743
343
}
4744
4745
ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4746
                                      SourceLocation LParenLoc,
4747
                                      ObjCBridgeCastKind Kind,
4748
                                      SourceLocation BridgeKeywordLoc,
4749
                                      ParsedType Type,
4750
                                      SourceLocation RParenLoc,
4751
329
                                      Expr *SubExpr) {
4752
329
  TypeSourceInfo *TSInfo = nullptr;
4753
329
  QualType T = GetTypeFromParser(Type, &TSInfo);
4754
329
  if (Kind == OBC_Bridge)
4755
122
    CheckTollFreeBridgeCast(T, SubExpr);
4756
329
  if (!TSInfo)
4757
0
    TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4758
329
  return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4759
329
                              SubExpr);
4760
329
}