1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective-C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21 #include "clang/Edit/Commit.h"
22 #include "clang/Edit/Rewriters.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/Initialization.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/SmallString.h"
30 using namespace clang;
32 using llvm::makeArrayRef;
34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 ArrayRef<Expr *> Strings) {
36 // Most ObjC strings are formed out of a single piece. However, we *can*
37 // have strings formed out of multiple @ strings with multiple pptokens in
38 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
39 // StringLiteral for ObjCStringLiteral to hold onto.
40 StringLiteral *S = cast<StringLiteral>(Strings[0]);
42 // If we have a multi-part string, merge it all together.
43 if (Strings.size() != 1) {
44 // Concatenate objc strings.
45 SmallString<128> StrBuf;
46 SmallVector<SourceLocation, 8> StrLocs;
48 for (Expr *E : Strings) {
49 S = cast<StringLiteral>(E);
51 // ObjC strings can't be wide or UTF.
53 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
54 << S->getSourceRange();
59 StrBuf += S->getString();
61 // Get the locations of the string tokens.
62 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
65 // Create the aggregate string with the appropriate content and location
67 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
68 assert(CAT && "String literal not of constant array type!");
69 QualType StrTy = Context.getConstantArrayType(
70 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
71 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
72 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
73 /*Pascal=*/false, StrTy, &StrLocs[0],
77 return BuildObjCStringLiteral(AtLocs[0], S);
80 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
81 // Verify that this composite string is acceptable for ObjC strings.
82 if (CheckObjCString(S))
85 // Initialize the constant string interface lazily. This assumes
86 // the NSString interface is seen in this translation unit. Note: We
87 // don't use NSConstantString, since the runtime team considers this
88 // interface private (even though it appears in the header files).
89 QualType Ty = Context.getObjCConstantStringInterface();
91 Ty = Context.getObjCObjectPointerType(Ty);
92 } else if (getLangOpts().NoConstantCFStrings) {
93 IdentifierInfo *NSIdent=nullptr;
94 std::string StringClass(getLangOpts().ObjCConstantStringClass);
96 if (StringClass.empty())
97 NSIdent = &Context.Idents.get("NSConstantString");
99 NSIdent = &Context.Idents.get(StringClass);
101 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
103 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
104 Context.setObjCConstantStringInterface(StrIF);
105 Ty = Context.getObjCConstantStringInterface();
106 Ty = Context.getObjCObjectPointerType(Ty);
108 // If there is no NSConstantString interface defined then treat this
109 // as error and recover from it.
110 Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
111 << NSIdent << S->getSourceRange();
112 Ty = Context.getObjCIdType();
115 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
116 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
118 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
119 Context.setObjCConstantStringInterface(StrIF);
120 Ty = Context.getObjCConstantStringInterface();
121 Ty = Context.getObjCObjectPointerType(Ty);
123 // If there is no NSString interface defined, implicitly declare
124 // a @class NSString; and use that instead. This is to make sure
125 // type of an NSString literal is represented correctly, instead of
126 // being an 'id' type.
127 Ty = Context.getObjCNSStringType();
129 ObjCInterfaceDecl *NSStringIDecl =
130 ObjCInterfaceDecl::Create (Context,
131 Context.getTranslationUnitDecl(),
132 SourceLocation(), NSIdent,
133 nullptr, nullptr, SourceLocation());
134 Ty = Context.getObjCInterfaceType(NSStringIDecl);
135 Context.setObjCNSStringType(Ty);
137 Ty = Context.getObjCObjectPointerType(Ty);
141 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
144 /// Emits an error if the given method does not exist, or if the return
145 /// type is not an Objective-C object.
146 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
147 const ObjCInterfaceDecl *Class,
148 Selector Sel, const ObjCMethodDecl *Method) {
150 // FIXME: Is there a better way to avoid quotes than using getName()?
151 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 // Make sure the return type is reasonable.
156 QualType ReturnType = Method->getReturnType();
157 if (!ReturnType->isObjCObjectPointerType()) {
158 S.Diag(Loc, diag::err_objc_literal_method_sig)
160 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
168 /// Maps ObjCLiteralKind to NSClassIdKindKind
169 static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
170 Sema::ObjCLiteralKind LiteralKind) {
171 switch (LiteralKind) {
173 return NSAPI::ClassId_NSArray;
174 case Sema::LK_Dictionary:
175 return NSAPI::ClassId_NSDictionary;
176 case Sema::LK_Numeric:
177 return NSAPI::ClassId_NSNumber;
178 case Sema::LK_String:
179 return NSAPI::ClassId_NSString;
181 return NSAPI::ClassId_NSValue;
183 // there is no corresponding matching
184 // between LK_None/LK_Block and NSClassIdKindKind
189 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
192 /// Validates ObjCInterfaceDecl availability.
193 /// ObjCInterfaceDecl, used to create ObjC literals, should be defined
194 /// if clang not in a debugger mode.
195 static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
197 Sema::ObjCLiteralKind LiteralKind) {
199 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
200 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
201 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
202 << II->getName() << LiteralKind;
204 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
205 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
206 << Decl->getName() << LiteralKind;
207 S.Diag(Decl->getLocation(), diag::note_forward_class);
214 /// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
215 /// Used to create ObjC literals, such as NSDictionary (@{}),
216 /// NSArray (@[]) and Boxed Expressions (@())
217 static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
219 Sema::ObjCLiteralKind LiteralKind) {
220 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
221 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
222 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
223 Sema::LookupOrdinaryName);
224 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
225 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
226 ASTContext &Context = S.Context;
227 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
228 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
229 nullptr, nullptr, SourceLocation());
232 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
239 /// Retrieve the NSNumber factory method that should be used to create
240 /// an Objective-C literal for the given type.
241 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
243 bool isLiteral = false,
244 SourceRange R = SourceRange()) {
245 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
246 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
250 S.Diag(Loc, diag::err_invalid_nsnumber_type)
256 // If we already looked up this method, we're done.
257 if (S.NSNumberLiteralMethods[*Kind])
258 return S.NSNumberLiteralMethods[*Kind];
260 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
263 ASTContext &CX = S.Context;
265 // Look up the NSNumber class, if we haven't done so already. It's cached
266 // in the Sema instance.
267 if (!S.NSNumberDecl) {
268 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
270 if (!S.NSNumberDecl) {
275 if (S.NSNumberPointer.isNull()) {
276 // generate the pointer to NSNumber type.
277 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
278 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
281 // Look for the appropriate method within NSNumber.
282 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
283 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
284 // create a stub definition this NSNumber factory method.
285 TypeSourceInfo *ReturnTInfo = nullptr;
287 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
288 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
289 /*isInstance=*/false, /*isVariadic=*/false,
290 /*isPropertyAccessor=*/false,
291 /*isImplicitlyDeclared=*/true,
292 /*isDefined=*/false, ObjCMethodDecl::Required,
293 /*HasRelatedResultType=*/false);
294 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
295 SourceLocation(), SourceLocation(),
296 &CX.Idents.get("value"),
297 NumberType, /*TInfo=*/nullptr,
299 Method->setMethodParams(S.Context, value, None);
302 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
305 // Note: if the parameter type is out-of-line, we'll catch it later in the
306 // implicit conversion.
308 S.NSNumberLiteralMethods[*Kind] = Method;
312 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
313 /// numeric literal expression. Type of the expression will be "NSNumber *".
314 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
315 // Determine the type of the literal.
316 QualType NumberType = Number->getType();
317 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
318 // In C, character literals have type 'int'. That's not the type we want
319 // to use to determine the Objective-c literal kind.
320 switch (Char->getKind()) {
321 case CharacterLiteral::Ascii:
322 case CharacterLiteral::UTF8:
323 NumberType = Context.CharTy;
326 case CharacterLiteral::Wide:
327 NumberType = Context.getWideCharType();
330 case CharacterLiteral::UTF16:
331 NumberType = Context.Char16Ty;
334 case CharacterLiteral::UTF32:
335 NumberType = Context.Char32Ty;
340 // Look for the appropriate method within NSNumber.
341 // Construct the literal.
342 SourceRange NR(Number->getSourceRange());
343 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
348 // Convert the number to the type that the parameter expects.
349 ParmVarDecl *ParamDecl = Method->parameters()[0];
350 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
352 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
355 if (ConvertedNumber.isInvalid())
357 Number = ConvertedNumber.get();
359 // Use the effective source range of the literal, including the leading '@'.
360 return MaybeBindToTemporary(
361 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
362 SourceRange(AtLoc, NR.getEnd())));
365 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
366 SourceLocation ValueLoc,
369 if (getLangOpts().CPlusPlus) {
370 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
372 // C doesn't actually have a way to represent literal values of type
373 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
374 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
375 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
376 CK_IntegralToBoolean);
379 return BuildObjCNumericLiteral(AtLoc, Inner.get());
382 /// Check that the given expression is a valid element of an Objective-C
383 /// collection literal.
384 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
386 bool ArrayLiteral = false) {
387 // If the expression is type-dependent, there's nothing for us to do.
388 if (Element->isTypeDependent())
391 ExprResult Result = S.CheckPlaceholderExpr(Element);
392 if (Result.isInvalid())
394 Element = Result.get();
396 // In C++, check for an implicit conversion to an Objective-C object pointer
398 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
399 InitializedEntity Entity
400 = InitializedEntity::InitializeParameter(S.Context, T,
402 InitializationKind Kind = InitializationKind::CreateCopy(
403 Element->getBeginLoc(), SourceLocation());
404 InitializationSequence Seq(S, Entity, Kind, Element);
406 return Seq.Perform(S, Entity, Kind, Element);
409 Expr *OrigElement = Element;
411 // Perform lvalue-to-rvalue conversion.
412 Result = S.DefaultLvalueConversion(Element);
413 if (Result.isInvalid())
415 Element = Result.get();
417 // Make sure that we have an Objective-C pointer type or block.
418 if (!Element->getType()->isObjCObjectPointerType() &&
419 !Element->getType()->isBlockPointerType()) {
420 bool Recovered = false;
422 // If this is potentially an Objective-C numeric literal, add the '@'.
423 if (isa<IntegerLiteral>(OrigElement) ||
424 isa<CharacterLiteral>(OrigElement) ||
425 isa<FloatingLiteral>(OrigElement) ||
426 isa<ObjCBoolLiteralExpr>(OrigElement) ||
427 isa<CXXBoolLiteralExpr>(OrigElement)) {
428 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
429 int Which = isa<CharacterLiteral>(OrigElement) ? 1
430 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
431 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
434 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
435 << Which << OrigElement->getSourceRange()
436 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
439 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
440 if (Result.isInvalid())
443 Element = Result.get();
447 // If this is potentially an Objective-C string literal, add the '@'.
448 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
449 if (String->isAscii()) {
450 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
451 << 0 << OrigElement->getSourceRange()
452 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
454 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
455 if (Result.isInvalid())
458 Element = Result.get();
464 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
465 << Element->getType();
470 if (ObjCStringLiteral *getString =
471 dyn_cast<ObjCStringLiteral>(OrigElement)) {
472 if (StringLiteral *SL = getString->getString()) {
473 unsigned numConcat = SL->getNumConcatenated();
475 // Only warn if the concatenated string doesn't come from a macro.
476 bool hasMacro = false;
477 for (unsigned i = 0; i < numConcat ; ++i)
478 if (SL->getStrTokenLoc(i).isMacroID()) {
483 S.Diag(Element->getBeginLoc(),
484 diag::warn_concatenated_nsarray_literal)
485 << Element->getType();
490 // Make sure that the element has the type that the container factory
492 return S.PerformCopyInitialization(
493 InitializedEntity::InitializeParameter(S.Context, T,
495 Element->getBeginLoc(), Element);
498 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
499 if (ValueExpr->isTypeDependent()) {
500 ObjCBoxedExpr *BoxedExpr =
501 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
504 ObjCMethodDecl *BoxingMethod = nullptr;
506 // Convert the expression to an RValue, so we can check for pointer types...
507 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
508 if (RValue.isInvalid()) {
511 SourceLocation Loc = SR.getBegin();
512 ValueExpr = RValue.get();
513 QualType ValueType(ValueExpr->getType());
514 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
515 QualType PointeeType = PT->getPointeeType();
516 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
519 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
524 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
525 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
528 if (!StringWithUTF8StringMethod) {
529 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
530 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
532 // Look for the appropriate method within NSString.
533 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
534 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
535 // Debugger needs to work even if NSString hasn't been defined.
536 TypeSourceInfo *ReturnTInfo = nullptr;
537 ObjCMethodDecl *M = ObjCMethodDecl::Create(
538 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
539 NSStringPointer, ReturnTInfo, NSStringDecl,
540 /*isInstance=*/false, /*isVariadic=*/false,
541 /*isPropertyAccessor=*/false,
542 /*isImplicitlyDeclared=*/true,
543 /*isDefined=*/false, ObjCMethodDecl::Required,
544 /*HasRelatedResultType=*/false);
545 QualType ConstCharType = Context.CharTy.withConst();
547 ParmVarDecl::Create(Context, M,
548 SourceLocation(), SourceLocation(),
549 &Context.Idents.get("value"),
550 Context.getPointerType(ConstCharType),
553 M->setMethodParams(Context, value, None);
557 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
558 stringWithUTF8String, BoxingMethod))
561 StringWithUTF8StringMethod = BoxingMethod;
564 BoxingMethod = StringWithUTF8StringMethod;
565 BoxedType = NSStringPointer;
566 // Transfer the nullability from method's return type.
567 Optional<NullabilityKind> Nullability =
568 BoxingMethod->getReturnType()->getNullability(Context);
570 BoxedType = Context.getAttributedType(
571 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
574 } else if (ValueType->isBuiltinType()) {
575 // The other types we support are numeric, char and BOOL/bool. We could also
576 // provide limited support for structure types, such as NSRange, NSRect, and
577 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
580 // Check for a top-level character literal.
581 if (const CharacterLiteral *Char =
582 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
583 // In C, character literals have type 'int'. That's not the type we want
584 // to use to determine the Objective-c literal kind.
585 switch (Char->getKind()) {
586 case CharacterLiteral::Ascii:
587 case CharacterLiteral::UTF8:
588 ValueType = Context.CharTy;
591 case CharacterLiteral::Wide:
592 ValueType = Context.getWideCharType();
595 case CharacterLiteral::UTF16:
596 ValueType = Context.Char16Ty;
599 case CharacterLiteral::UTF32:
600 ValueType = Context.Char32Ty;
604 // FIXME: Do I need to do anything special with BoolTy expressions?
606 // Look for the appropriate method within NSNumber.
607 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
608 BoxedType = NSNumberPointer;
609 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
610 if (!ET->getDecl()->isComplete()) {
611 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
612 << ValueType << ValueExpr->getSourceRange();
616 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
617 ET->getDecl()->getIntegerType());
618 BoxedType = NSNumberPointer;
619 } else if (ValueType->isObjCBoxableRecordType()) {
620 // Support for structure types, that marked as objc_boxable
621 // struct __attribute__((objc_boxable)) s { ... };
623 // Look up the NSValue class, if we haven't done so already. It's cached
624 // in the Sema instance.
626 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
632 // generate the pointer to NSValue type.
633 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
634 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
637 if (!ValueWithBytesObjCTypeMethod) {
638 IdentifierInfo *II[] = {
639 &Context.Idents.get("valueWithBytes"),
640 &Context.Idents.get("objCType")
642 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
644 // Look for the appropriate method within NSValue.
645 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
646 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
647 // Debugger needs to work even if NSValue hasn't been defined.
648 TypeSourceInfo *ReturnTInfo = nullptr;
649 ObjCMethodDecl *M = ObjCMethodDecl::Create(
653 ValueWithBytesObjCType,
657 /*isInstance=*/false,
658 /*isVariadic=*/false,
659 /*isPropertyAccessor=*/false,
660 /*isImplicitlyDeclared=*/true,
662 ObjCMethodDecl::Required,
663 /*HasRelatedResultType=*/false);
665 SmallVector<ParmVarDecl *, 2> Params;
668 ParmVarDecl::Create(Context, M,
669 SourceLocation(), SourceLocation(),
670 &Context.Idents.get("bytes"),
671 Context.VoidPtrTy.withConst(),
674 Params.push_back(bytes);
676 QualType ConstCharType = Context.CharTy.withConst();
678 ParmVarDecl::Create(Context, M,
679 SourceLocation(), SourceLocation(),
680 &Context.Idents.get("type"),
681 Context.getPointerType(ConstCharType),
684 Params.push_back(type);
686 M->setMethodParams(Context, Params, None);
690 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
691 ValueWithBytesObjCType, BoxingMethod))
694 ValueWithBytesObjCTypeMethod = BoxingMethod;
697 if (!ValueType.isTriviallyCopyableType(Context)) {
698 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
699 << ValueType << ValueExpr->getSourceRange();
703 BoxingMethod = ValueWithBytesObjCTypeMethod;
704 BoxedType = NSValuePointer;
708 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
709 << ValueType << ValueExpr->getSourceRange();
713 DiagnoseUseOfDecl(BoxingMethod, Loc);
715 ExprResult ConvertedValueExpr;
716 if (ValueType->isObjCBoxableRecordType()) {
717 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
718 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
721 // Convert the expression to the type that the parameter requires.
722 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
723 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
725 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
729 if (ConvertedValueExpr.isInvalid())
731 ValueExpr = ConvertedValueExpr.get();
733 ObjCBoxedExpr *BoxedExpr =
734 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
736 return MaybeBindToTemporary(BoxedExpr);
739 /// Build an ObjC subscript pseudo-object expression, given that
740 /// that's supported by the runtime.
741 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
743 ObjCMethodDecl *getterMethod,
744 ObjCMethodDecl *setterMethod) {
745 assert(!LangOpts.isSubscriptPointerArithmetic());
747 // We can't get dependent types here; our callers should have
748 // filtered them out.
749 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
750 "base or index cannot have dependent type here");
752 // Filter out placeholders in the index. In theory, overloads could
753 // be preserved here, although that might not actually work correctly.
754 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
755 if (Result.isInvalid())
757 IndexExpr = Result.get();
759 // Perform lvalue-to-rvalue conversion on the base.
760 Result = DefaultLvalueConversion(BaseExpr);
761 if (Result.isInvalid())
763 BaseExpr = Result.get();
765 // Build the pseudo-object expression.
766 return new (Context) ObjCSubscriptRefExpr(
767 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
768 getterMethod, setterMethod, RB);
771 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
772 SourceLocation Loc = SR.getBegin();
775 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
782 // Find the arrayWithObjects:count: method, if we haven't done so already.
783 QualType IdT = Context.getObjCIdType();
784 if (!ArrayWithObjectsMethod) {
786 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
787 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
788 if (!Method && getLangOpts().DebuggerObjCLiteral) {
789 TypeSourceInfo *ReturnTInfo = nullptr;
790 Method = ObjCMethodDecl::Create(
791 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
792 Context.getTranslationUnitDecl(), false /*Instance*/,
793 false /*isVariadic*/,
794 /*isPropertyAccessor=*/false,
795 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
796 ObjCMethodDecl::Required, false);
797 SmallVector<ParmVarDecl *, 2> Params;
798 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
801 &Context.Idents.get("objects"),
802 Context.getPointerType(IdT),
805 Params.push_back(objects);
806 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
809 &Context.Idents.get("cnt"),
810 Context.UnsignedLongTy,
811 /*TInfo=*/nullptr, SC_None,
813 Params.push_back(cnt);
814 Method->setMethodParams(Context, Params, None);
817 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
820 // Dig out the type that all elements should be converted to.
821 QualType T = Method->parameters()[0]->getType();
822 const PointerType *PtrT = T->getAs<PointerType>();
824 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
825 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
827 Diag(Method->parameters()[0]->getLocation(),
828 diag::note_objc_literal_method_param)
830 << Context.getPointerType(IdT.withConst());
834 // Check that the 'count' parameter is integral.
835 if (!Method->parameters()[1]->getType()->isIntegerType()) {
836 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
838 Diag(Method->parameters()[1]->getLocation(),
839 diag::note_objc_literal_method_param)
841 << Method->parameters()[1]->getType()
846 // We've found a good +arrayWithObjects:count: method. Save it!
847 ArrayWithObjectsMethod = Method;
850 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
851 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
853 // Check that each of the elements provided is valid in a collection literal,
854 // performing conversions as necessary.
855 Expr **ElementsBuffer = Elements.data();
856 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
857 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
860 if (Converted.isInvalid())
863 ElementsBuffer[I] = Converted.get();
867 = Context.getObjCObjectPointerType(
868 Context.getObjCInterfaceType(NSArrayDecl));
870 return MaybeBindToTemporary(
871 ObjCArrayLiteral::Create(Context, Elements, Ty,
872 ArrayWithObjectsMethod, SR));
875 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
876 MutableArrayRef<ObjCDictionaryElement> Elements) {
877 SourceLocation Loc = SR.getBegin();
879 if (!NSDictionaryDecl) {
880 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
881 Sema::LK_Dictionary);
882 if (!NSDictionaryDecl) {
887 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
889 QualType IdT = Context.getObjCIdType();
890 if (!DictionaryWithObjectsMethod) {
891 Selector Sel = NSAPIObj->getNSDictionarySelector(
892 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
893 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
894 if (!Method && getLangOpts().DebuggerObjCLiteral) {
895 Method = ObjCMethodDecl::Create(Context,
896 SourceLocation(), SourceLocation(), Sel,
898 nullptr /*TypeSourceInfo */,
899 Context.getTranslationUnitDecl(),
900 false /*Instance*/, false/*isVariadic*/,
901 /*isPropertyAccessor=*/false,
902 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
903 ObjCMethodDecl::Required,
905 SmallVector<ParmVarDecl *, 3> Params;
906 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
909 &Context.Idents.get("objects"),
910 Context.getPointerType(IdT),
911 /*TInfo=*/nullptr, SC_None,
913 Params.push_back(objects);
914 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
917 &Context.Idents.get("keys"),
918 Context.getPointerType(IdT),
919 /*TInfo=*/nullptr, SC_None,
921 Params.push_back(keys);
922 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
925 &Context.Idents.get("cnt"),
926 Context.UnsignedLongTy,
927 /*TInfo=*/nullptr, SC_None,
929 Params.push_back(cnt);
930 Method->setMethodParams(Context, Params, None);
933 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
937 // Dig out the type that all values should be converted to.
938 QualType ValueT = Method->parameters()[0]->getType();
939 const PointerType *PtrValue = ValueT->getAs<PointerType>();
941 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
942 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
944 Diag(Method->parameters()[0]->getLocation(),
945 diag::note_objc_literal_method_param)
947 << Context.getPointerType(IdT.withConst());
951 // Dig out the type that all keys should be converted to.
952 QualType KeyT = Method->parameters()[1]->getType();
953 const PointerType *PtrKey = KeyT->getAs<PointerType>();
955 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
959 if (QIDNSCopying.isNull()) {
960 // key argument of selector is id<NSCopying>?
961 if (ObjCProtocolDecl *NSCopyingPDecl =
962 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
963 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
965 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
967 (ObjCProtocolDecl**) PQ,
970 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
973 if (!QIDNSCopying.isNull())
974 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
979 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
981 Diag(Method->parameters()[1]->getLocation(),
982 diag::note_objc_literal_method_param)
984 << Context.getPointerType(IdT.withConst());
989 // Check that the 'count' parameter is integral.
990 QualType CountType = Method->parameters()[2]->getType();
991 if (!CountType->isIntegerType()) {
992 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
994 Diag(Method->parameters()[2]->getLocation(),
995 diag::note_objc_literal_method_param)
1001 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1002 DictionaryWithObjectsMethod = Method;
1005 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1006 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1007 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1008 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1010 // Check that each of the keys and values provided is valid in a collection
1011 // literal, performing conversions as necessary.
1012 bool HasPackExpansions = false;
1013 for (ObjCDictionaryElement &Element : Elements) {
1015 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1017 if (Key.isInvalid())
1022 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1023 if (Value.isInvalid())
1026 Element.Key = Key.get();
1027 Element.Value = Value.get();
1029 if (Element.EllipsisLoc.isInvalid())
1032 if (!Element.Key->containsUnexpandedParameterPack() &&
1033 !Element.Value->containsUnexpandedParameterPack()) {
1034 Diag(Element.EllipsisLoc,
1035 diag::err_pack_expansion_without_parameter_packs)
1036 << SourceRange(Element.Key->getBeginLoc(),
1037 Element.Value->getEndLoc());
1041 HasPackExpansions = true;
1045 = Context.getObjCObjectPointerType(
1046 Context.getObjCInterfaceType(NSDictionaryDecl));
1047 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1048 Context, Elements, HasPackExpansions, Ty,
1049 DictionaryWithObjectsMethod, SR));
1052 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1053 TypeSourceInfo *EncodedTypeInfo,
1054 SourceLocation RParenLoc) {
1055 QualType EncodedType = EncodedTypeInfo->getType();
1057 if (EncodedType->isDependentType())
1058 StrTy = Context.DependentTy;
1060 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1061 !EncodedType->isVoidType()) // void is handled too.
1062 if (RequireCompleteType(AtLoc, EncodedType,
1063 diag::err_incomplete_type_objc_at_encode,
1064 EncodedTypeInfo->getTypeLoc()))
1068 QualType NotEncodedT;
1069 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1070 if (!NotEncodedT.isNull())
1071 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1072 << EncodedType << NotEncodedT;
1074 // The type of @encode is the same as the type of the corresponding string,
1075 // which is an array type.
1076 StrTy = Context.CharTy;
1077 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1078 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1080 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1081 ArrayType::Normal, 0);
1084 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1087 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1088 SourceLocation EncodeLoc,
1089 SourceLocation LParenLoc,
1091 SourceLocation RParenLoc) {
1092 // FIXME: Preserve type source info ?
1093 TypeSourceInfo *TInfo;
1094 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1096 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1097 getLocForEndOfToken(LParenLoc));
1099 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1102 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1103 SourceLocation AtLoc,
1104 SourceLocation LParenLoc,
1105 SourceLocation RParenLoc,
1106 ObjCMethodDecl *Method,
1107 ObjCMethodList &MethList) {
1108 ObjCMethodList *M = &MethList;
1109 bool Warned = false;
1110 for (M = M->getNext(); M; M=M->getNext()) {
1111 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1112 if (MatchingMethodDecl == Method ||
1113 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1114 MatchingMethodDecl->getSelector() != Method->getSelector())
1116 if (!S.MatchTwoMethodDeclarations(Method,
1117 MatchingMethodDecl, Sema::MMS_loose)) {
1120 S.Diag(AtLoc, diag::warn_multiple_selectors)
1121 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1122 << FixItHint::CreateInsertion(RParenLoc, ")");
1123 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1124 << Method->getDeclName();
1126 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1127 << MatchingMethodDecl->getDeclName();
1133 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1134 ObjCMethodDecl *Method,
1135 SourceLocation LParenLoc,
1136 SourceLocation RParenLoc,
1137 bool WarnMultipleSelectors) {
1138 if (!WarnMultipleSelectors ||
1139 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1141 bool Warned = false;
1142 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1143 e = S.MethodPool.end(); b != e; b++) {
1144 // first, instance methods
1145 ObjCMethodList &InstMethList = b->second.first;
1146 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1147 Method, InstMethList))
1150 // second, class methods
1151 ObjCMethodList &ClsMethList = b->second.second;
1152 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1153 Method, ClsMethList) || Warned)
1158 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1159 SourceLocation AtLoc,
1160 SourceLocation SelLoc,
1161 SourceLocation LParenLoc,
1162 SourceLocation RParenLoc,
1163 bool WarnMultipleSelectors) {
1164 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1165 SourceRange(LParenLoc, RParenLoc));
1167 Method = LookupFactoryMethodInGlobalPool(Sel,
1168 SourceRange(LParenLoc, RParenLoc));
1170 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1171 Selector MatchedSel = OM->getSelector();
1172 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1173 RParenLoc.getLocWithOffset(-1));
1174 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1175 << Sel << MatchedSel
1176 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1179 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1181 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1182 WarnMultipleSelectors);
1185 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1186 !getSourceManager().isInSystemHeader(Method->getLocation()))
1187 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1189 // In ARC, forbid the user from using @selector for
1190 // retain/release/autorelease/dealloc/retainCount.
1191 if (getLangOpts().ObjCAutoRefCount) {
1192 switch (Sel.getMethodFamily()) {
1195 case OMF_autorelease:
1196 case OMF_retainCount:
1198 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1199 Sel << SourceRange(LParenLoc, RParenLoc);
1207 case OMF_mutableCopy:
1210 case OMF_initialize:
1211 case OMF_performSelector:
1215 QualType Ty = Context.getObjCSelType();
1216 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1219 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1220 SourceLocation AtLoc,
1221 SourceLocation ProtoLoc,
1222 SourceLocation LParenLoc,
1223 SourceLocation ProtoIdLoc,
1224 SourceLocation RParenLoc) {
1225 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1227 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1230 if (!PDecl->hasDefinition()) {
1231 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1232 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1234 PDecl = PDecl->getDefinition();
1237 QualType Ty = Context.getObjCProtoType();
1240 Ty = Context.getObjCObjectPointerType(Ty);
1241 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1244 /// Try to capture an implicit reference to 'self'.
1245 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1246 DeclContext *DC = getFunctionLevelDeclContext();
1248 // If we're not in an ObjC method, error out. Note that, unlike the
1249 // C++ case, we don't require an instance method --- class methods
1250 // still have a 'self', and we really do still need to capture it!
1251 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1255 tryCaptureVariable(method->getSelfDecl(), Loc);
1260 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1261 QualType origType = T;
1262 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1263 if (T == Context.getObjCInstanceType()) {
1264 return Context.getAttributedType(
1265 AttributedType::getNullabilityAttrKind(*nullability),
1266 Context.getObjCIdType(),
1267 Context.getObjCIdType());
1273 if (T == Context.getObjCInstanceType())
1274 return Context.getObjCIdType();
1279 /// Determine the result type of a message send based on the receiver type,
1280 /// method, and the kind of message send.
1282 /// This is the "base" result type, which will still need to be adjusted
1283 /// to account for nullability.
1284 static QualType getBaseMessageSendResultType(Sema &S,
1285 QualType ReceiverType,
1286 ObjCMethodDecl *Method,
1287 bool isClassMessage,
1288 bool isSuperMessage) {
1289 assert(Method && "Must have a method");
1290 if (!Method->hasRelatedResultType())
1291 return Method->getSendResultType(ReceiverType);
1293 ASTContext &Context = S.Context;
1295 // Local function that transfers the nullability of the method's
1296 // result type to the returned result.
1297 auto transferNullability = [&](QualType type) -> QualType {
1298 // If the method's result type has nullability, extract it.
1299 if (auto nullability = Method->getSendResultType(ReceiverType)
1300 ->getNullability(Context)){
1301 // Strip off any outer nullability sugar from the provided type.
1302 (void)AttributedType::stripOuterNullability(type);
1304 // Form a new attributed type using the method result type's nullability.
1305 return Context.getAttributedType(
1306 AttributedType::getNullabilityAttrKind(*nullability),
1314 // If a method has a related return type:
1315 // - if the method found is an instance method, but the message send
1316 // was a class message send, T is the declared return type of the method
1318 if (Method->isInstanceMethod() && isClassMessage)
1319 return stripObjCInstanceType(Context,
1320 Method->getSendResultType(ReceiverType));
1322 // - if the receiver is super, T is a pointer to the class of the
1323 // enclosing method definition
1324 if (isSuperMessage) {
1325 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1326 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1327 return transferNullability(
1328 Context.getObjCObjectPointerType(
1329 Context.getObjCInterfaceType(Class)));
1333 // - if the receiver is the name of a class U, T is a pointer to U
1334 if (ReceiverType->getAsObjCInterfaceType())
1335 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1336 // - if the receiver is of type Class or qualified Class type,
1337 // T is the declared return type of the method.
1338 if (ReceiverType->isObjCClassType() ||
1339 ReceiverType->isObjCQualifiedClassType())
1340 return stripObjCInstanceType(Context,
1341 Method->getSendResultType(ReceiverType));
1343 // - if the receiver is id, qualified id, Class, or qualified Class, T
1344 // is the receiver type, otherwise
1345 // - T is the type of the receiver expression.
1346 return transferNullability(ReceiverType);
1349 QualType Sema::getMessageSendResultType(const Expr *Receiver,
1350 QualType ReceiverType,
1351 ObjCMethodDecl *Method,
1352 bool isClassMessage,
1353 bool isSuperMessage) {
1354 // Produce the result type.
1355 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1360 // If this is a class message, ignore the nullability of the receiver.
1361 if (isClassMessage) {
1362 // In a class method, class messages to 'self' that return instancetype can
1363 // be typed as the current class. We can safely do this in ARC because self
1364 // can't be reassigned, and we do it unsafely outside of ARC because in
1365 // practice people never reassign self in class methods and there's some
1366 // virtue in not being aggressively pedantic.
1367 if (Receiver && Receiver->isObjCSelfExpr()) {
1368 assert(ReceiverType->isObjCClassType() && "expected a Class self");
1369 QualType T = Method->getSendResultType(ReceiverType);
1370 AttributedType::stripOuterNullability(T);
1371 if (T == Context.getObjCInstanceType()) {
1372 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1373 cast<ImplicitParamDecl>(
1374 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1375 ->getDeclContext());
1376 assert(MD->isClassMethod() && "expected a class method");
1377 QualType NewResultType = Context.getObjCObjectPointerType(
1378 Context.getObjCInterfaceType(MD->getClassInterface()));
1379 if (auto Nullability = resultType->getNullability(Context))
1380 NewResultType = Context.getAttributedType(
1381 AttributedType::getNullabilityAttrKind(*Nullability),
1382 NewResultType, NewResultType);
1383 return NewResultType;
1389 // There is nothing left to do if the result type cannot have a nullability
1391 if (!resultType->canHaveNullability())
1394 // Map the nullability of the result into a table index.
1395 unsigned receiverNullabilityIdx = 0;
1396 if (auto nullability = ReceiverType->getNullability(Context))
1397 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1399 unsigned resultNullabilityIdx = 0;
1400 if (auto nullability = resultType->getNullability(Context))
1401 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1403 // The table of nullability mappings, indexed by the receiver's nullability
1404 // and then the result type's nullability.
1405 static const uint8_t None = 0;
1406 static const uint8_t NonNull = 1;
1407 static const uint8_t Nullable = 2;
1408 static const uint8_t Unspecified = 3;
1409 static const uint8_t nullabilityMap[4][4] = {
1410 // None NonNull Nullable Unspecified
1411 /* None */ { None, None, Nullable, None },
1412 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1413 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1414 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1417 unsigned newResultNullabilityIdx
1418 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1419 if (newResultNullabilityIdx == resultNullabilityIdx)
1422 // Strip off the existing nullability. This removes as little type sugar as
1425 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1426 resultType = attributed->getModifiedType();
1428 resultType = resultType.getDesugaredType(Context);
1430 } while (resultType->getNullability(Context));
1432 // Add nullability back if needed.
1433 if (newResultNullabilityIdx > 0) {
1435 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1436 return Context.getAttributedType(
1437 AttributedType::getNullabilityAttrKind(newNullability),
1438 resultType, resultType);
1444 /// Look for an ObjC method whose result type exactly matches the given type.
1445 static const ObjCMethodDecl *
1446 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1447 QualType instancetype) {
1448 if (MD->getReturnType() == instancetype)
1451 // For these purposes, a method in an @implementation overrides a
1452 // declaration in the @interface.
1453 if (const ObjCImplDecl *impl =
1454 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1455 const ObjCContainerDecl *iface;
1456 if (const ObjCCategoryImplDecl *catImpl =
1457 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1458 iface = catImpl->getCategoryDecl();
1460 iface = impl->getClassInterface();
1463 const ObjCMethodDecl *ifaceMD =
1464 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1465 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1468 SmallVector<const ObjCMethodDecl *, 4> overrides;
1469 MD->getOverriddenMethods(overrides);
1470 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1471 if (const ObjCMethodDecl *result =
1472 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1479 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1480 // Only complain if we're in an ObjC method and the required return
1481 // type doesn't match the method's declared return type.
1482 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1483 if (!MD || !MD->hasRelatedResultType() ||
1484 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1487 // Look for a method overridden by this method which explicitly uses
1489 if (const ObjCMethodDecl *overridden =
1490 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1491 SourceRange range = overridden->getReturnTypeSourceRange();
1492 SourceLocation loc = range.getBegin();
1493 if (loc.isInvalid())
1494 loc = overridden->getLocation();
1495 Diag(loc, diag::note_related_result_type_explicit)
1496 << /*current method*/ 1 << range;
1500 // Otherwise, if we have an interesting method family, note that.
1501 // This should always trigger if the above didn't.
1502 if (ObjCMethodFamily family = MD->getMethodFamily())
1503 Diag(MD->getLocation(), diag::note_related_result_type_family)
1504 << /*current method*/ 1
1508 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1509 E = E->IgnoreParenImpCasts();
1510 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1514 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1518 if (!Method->hasRelatedResultType())
1521 if (Context.hasSameUnqualifiedType(
1522 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1525 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1526 Context.getObjCInstanceType()))
1529 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1530 << Method->isInstanceMethod() << Method->getSelector()
1531 << MsgSend->getType();
1534 bool Sema::CheckMessageArgumentTypes(
1535 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1536 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1537 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1538 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1539 ExprValueKind &VK) {
1540 SourceLocation SelLoc;
1541 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1542 SelLoc = SelectorLocs.front();
1547 // Apply default argument promotion as for (C99 6.5.2.2p6).
1548 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1549 if (Args[i]->isTypeDependent())
1553 if (getLangOpts().DebuggerSupport) {
1554 QualType paramTy; // ignored
1555 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1557 result = DefaultArgumentPromotion(Args[i]);
1559 if (result.isInvalid())
1561 Args[i] = result.get();
1565 if (getLangOpts().ObjCAutoRefCount)
1566 DiagID = diag::err_arc_method_not_found;
1568 DiagID = isClassMessage ? diag::warn_class_method_not_found
1569 : diag::warn_inst_method_not_found;
1570 if (!getLangOpts().DebuggerSupport) {
1571 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1572 if (OMD && !OMD->isInvalidDecl()) {
1573 if (getLangOpts().ObjCAutoRefCount)
1574 DiagID = diag::err_method_not_found_with_typo;
1576 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1577 : diag::warn_instance_method_not_found_with_typo;
1578 Selector MatchedSel = OMD->getSelector();
1579 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1580 if (MatchedSel.isUnarySelector())
1581 Diag(SelLoc, DiagID)
1582 << Sel<< isClassMessage << MatchedSel
1583 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1585 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1588 Diag(SelLoc, DiagID)
1589 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1590 SelectorLocs.back());
1591 // Find the class to which we are sending this message.
1592 if (ReceiverType->isObjCObjectPointerType()) {
1593 if (ObjCInterfaceDecl *ThisClass =
1594 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1595 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1596 if (!RecRange.isInvalid())
1597 if (ThisClass->lookupClassMethod(Sel))
1598 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1599 << FixItHint::CreateReplacement(RecRange,
1600 ThisClass->getNameAsString());
1605 // In debuggers, we want to use __unknown_anytype for these
1606 // results so that clients can cast them.
1607 if (getLangOpts().DebuggerSupport) {
1608 ReturnType = Context.UnknownAnyTy;
1610 ReturnType = Context.getObjCIdType();
1616 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1617 isClassMessage, isSuperMessage);
1618 VK = Expr::getValueKindForType(Method->getReturnType());
1620 unsigned NumNamedArgs = Sel.getNumArgs();
1621 // Method might have more arguments than selector indicates. This is due
1622 // to addition of c-style arguments in method.
1623 if (Method->param_size() > Sel.getNumArgs())
1624 NumNamedArgs = Method->param_size();
1625 // FIXME. This need be cleaned up.
1626 if (Args.size() < NumNamedArgs) {
1627 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1628 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1632 // Compute the set of type arguments to be substituted into each parameter
1634 Optional<ArrayRef<QualType>> typeArgs
1635 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1636 bool IsError = false;
1637 for (unsigned i = 0; i < NumNamedArgs; i++) {
1638 // We can't do any type-checking on a type-dependent argument.
1639 if (Args[i]->isTypeDependent())
1642 Expr *argExpr = Args[i];
1644 ParmVarDecl *param = Method->parameters()[i];
1645 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1647 if (param->hasAttr<NoEscapeAttr>())
1648 if (auto *BE = dyn_cast<BlockExpr>(
1649 argExpr->IgnoreParenNoopCasts(Context)))
1650 BE->getBlockDecl()->setDoesNotEscape();
1652 // Strip the unbridged-cast placeholder expression off unless it's
1653 // a consumed argument.
1654 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1655 !param->hasAttr<CFConsumedAttr>())
1656 argExpr = stripARCUnbridgedCast(argExpr);
1658 // If the parameter is __unknown_anytype, infer its type
1659 // from the argument.
1660 if (param->getType() == Context.UnknownAnyTy) {
1662 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1663 if (argE.isInvalid()) {
1666 Args[i] = argE.get();
1668 // Update the parameter type in-place.
1669 param->setType(paramType);
1674 QualType origParamType = param->getType();
1675 QualType paramType = param->getType();
1677 paramType = paramType.substObjCTypeArgs(
1680 ObjCSubstitutionContext::Parameter);
1682 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1684 diag::err_call_incomplete_argument, argExpr))
1687 InitializedEntity Entity
1688 = InitializedEntity::InitializeParameter(Context, param, paramType);
1689 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1690 if (ArgE.isInvalid())
1693 Args[i] = ArgE.getAs<Expr>();
1695 // If we are type-erasing a block to a block-compatible
1696 // Objective-C pointer type, we may need to extend the lifetime
1697 // of the block object.
1698 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1699 Args[i]->getType()->isBlockPointerType() &&
1700 origParamType->isObjCObjectPointerType()) {
1701 ExprResult arg = Args[i];
1702 maybeExtendBlockObject(arg);
1703 Args[i] = arg.get();
1708 // Promote additional arguments to variadic methods.
1709 if (Method->isVariadic()) {
1710 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1711 if (Args[i]->isTypeDependent())
1714 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1716 IsError |= Arg.isInvalid();
1717 Args[i] = Arg.get();
1720 // Check for extra arguments to non-variadic methods.
1721 if (Args.size() != NumNamedArgs) {
1722 Diag(Args[NumNamedArgs]->getBeginLoc(),
1723 diag::err_typecheck_call_too_many_args)
1724 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1725 << Method->getSourceRange()
1726 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
1727 Args.back()->getEndLoc());
1731 DiagnoseSentinelCalls(Method, SelLoc, Args);
1733 // Do additional checkings on method.
1734 IsError |= CheckObjCMethodCall(
1735 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1740 bool Sema::isSelfExpr(Expr *RExpr) {
1741 // 'self' is objc 'self' in an objc method only.
1742 ObjCMethodDecl *Method =
1743 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1744 return isSelfExpr(RExpr, Method);
1747 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1748 if (!method) return false;
1750 receiver = receiver->IgnoreParenLValueCasts();
1751 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1752 if (DRE->getDecl() == method->getSelfDecl())
1757 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1758 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1760 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1761 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1762 // Look it up in the main interface (and categories, etc.)
1763 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1766 // Okay, look for "private" methods declared in any
1767 // @implementations we've seen.
1768 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1772 // Check qualifiers.
1773 for (const auto *I : objType->quals())
1774 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1780 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1781 /// list of a qualified objective pointer type.
1782 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1783 const ObjCObjectPointerType *OPT,
1786 ObjCMethodDecl *MD = nullptr;
1787 for (const auto *PROTO : OPT->quals()) {
1788 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1795 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1796 /// objective C interface. This is a property reference expression.
1798 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1799 Expr *BaseExpr, SourceLocation OpLoc,
1800 DeclarationName MemberName,
1801 SourceLocation MemberLoc,
1802 SourceLocation SuperLoc, QualType SuperType,
1804 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1805 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1807 if (!MemberName.isIdentifier()) {
1808 Diag(MemberLoc, diag::err_invalid_property_name)
1809 << MemberName << QualType(OPT, 0);
1813 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1815 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1816 : BaseExpr->getSourceRange();
1817 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1818 diag::err_property_not_found_forward_class,
1819 MemberName, BaseRange))
1822 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1823 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1824 // Check whether we can reference this property.
1825 if (DiagnoseUseOfDecl(PD, MemberLoc))
1828 return new (Context)
1829 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1830 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1832 return new (Context)
1833 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1834 OK_ObjCProperty, MemberLoc, BaseExpr);
1836 // Check protocols on qualified interfaces.
1837 for (const auto *I : OPT->quals())
1838 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1839 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1840 // Check whether we can reference this property.
1841 if (DiagnoseUseOfDecl(PD, MemberLoc))
1845 return new (Context) ObjCPropertyRefExpr(
1846 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1847 SuperLoc, SuperType);
1849 return new (Context)
1850 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1851 OK_ObjCProperty, MemberLoc, BaseExpr);
1853 // If that failed, look for an "implicit" property by seeing if the nullary
1854 // selector is implemented.
1856 // FIXME: The logic for looking up nullary and unary selectors should be
1857 // shared with the code in ActOnInstanceMessage.
1859 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1860 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1862 // May be found in property's qualified list.
1864 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1866 // If this reference is in an @implementation, check for 'private' methods.
1868 Getter = IFace->lookupPrivateMethod(Sel);
1871 // Check if we can reference this property.
1872 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1875 // If we found a getter then this may be a valid dot-reference, we
1876 // will look for the matching setter, in case it is needed.
1877 Selector SetterSel =
1878 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1879 PP.getSelectorTable(), Member);
1880 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1882 // May be found in property's qualified list.
1884 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1887 // If this reference is in an @implementation, also check for 'private'
1889 Setter = IFace->lookupPrivateMethod(SetterSel);
1892 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1895 // Special warning if member name used in a property-dot for a setter accessor
1896 // does not use a property with same name; e.g. obj.X = ... for a property with
1898 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1899 !IFace->FindPropertyDeclaration(
1900 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1901 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1902 // Do not warn if user is using property-dot syntax to make call to
1903 // user named setter.
1904 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1906 diag::warn_property_access_suggest)
1907 << MemberName << QualType(OPT, 0) << PDecl->getName()
1908 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1912 if (Getter || Setter) {
1914 return new (Context)
1915 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1916 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1918 return new (Context)
1919 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1920 OK_ObjCProperty, MemberLoc, BaseExpr);
1924 // Attempt to correct for typos in property names.
1925 if (TypoCorrection Corrected =
1926 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1927 LookupOrdinaryName, nullptr, nullptr,
1928 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1929 CTK_ErrorRecovery, IFace, false, OPT)) {
1930 DeclarationName TypoResult = Corrected.getCorrection();
1931 if (TypoResult.isIdentifier() &&
1932 TypoResult.getAsIdentifierInfo() == Member) {
1933 // There is no need to try the correction if it is the same.
1934 NamedDecl *ChosenDecl =
1935 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1936 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1937 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1938 // This is a class property, we should not use the instance to
1940 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1941 << OPT->getInterfaceDecl()->getName()
1942 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1943 OPT->getInterfaceDecl()->getName());
1947 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1948 << MemberName << QualType(OPT, 0));
1949 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1950 TypoResult, MemberLoc,
1951 SuperLoc, SuperType, Super);
1954 ObjCInterfaceDecl *ClassDeclared;
1955 if (ObjCIvarDecl *Ivar =
1956 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1957 QualType T = Ivar->getType();
1958 if (const ObjCObjectPointerType * OBJPT =
1959 T->getAsObjCInterfacePointerType()) {
1960 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1961 diag::err_property_not_as_forward_class,
1962 MemberName, BaseExpr))
1966 diag::err_ivar_access_using_property_syntax_suggest)
1967 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1968 << FixItHint::CreateReplacement(OpLoc, "->");
1972 Diag(MemberLoc, diag::err_property_not_found)
1973 << MemberName << QualType(OPT, 0);
1975 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1976 << MemberName << BaseExpr->getSourceRange();
1981 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1982 IdentifierInfo &propertyName,
1983 SourceLocation receiverNameLoc,
1984 SourceLocation propertyNameLoc) {
1986 IdentifierInfo *receiverNamePtr = &receiverName;
1987 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1992 // If the "receiver" is 'super' in a method, handle it as an expression-like
1993 // property reference.
1994 if (receiverNamePtr->isStr("super")) {
1995 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1996 if (auto classDecl = CurMethod->getClassInterface()) {
1997 SuperType = QualType(classDecl->getSuperClassType(), 0);
1998 if (CurMethod->isInstanceMethod()) {
1999 if (SuperType.isNull()) {
2000 // The current class does not have a superclass.
2001 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
2002 << CurMethod->getClassInterface()->getIdentifier();
2005 QualType T = Context.getObjCObjectPointerType(SuperType);
2007 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
2008 /*BaseExpr*/nullptr,
2009 SourceLocation()/*OpLoc*/,
2012 receiverNameLoc, T, true);
2015 // Otherwise, if this is a class method, try dispatching to our
2017 IFace = CurMethod->getClassInterface()->getSuperClass();
2023 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2031 if (auto PD = IFace->FindPropertyDeclaration(
2032 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2033 GetterSel = PD->getGetterName();
2034 SetterSel = PD->getSetterName();
2036 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2037 SetterSel = SelectorTable::constructSetterSelector(
2038 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2041 // Search for a declared property first.
2042 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2044 // If this reference is in an @implementation, check for 'private' methods.
2046 Getter = IFace->lookupPrivateClassMethod(GetterSel);
2049 // FIXME: refactor/share with ActOnMemberReference().
2050 // Check if we can reference this property.
2051 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2055 // Look for the matching setter, in case it is needed.
2056 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2058 // If this reference is in an @implementation, also check for 'private'
2060 Setter = IFace->lookupPrivateClassMethod(SetterSel);
2062 // Look through local category implementations associated with the class.
2064 Setter = IFace->getCategoryClassMethod(SetterSel);
2066 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2069 if (Getter || Setter) {
2070 if (!SuperType.isNull())
2071 return new (Context)
2072 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2073 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2076 return new (Context) ObjCPropertyRefExpr(
2077 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2078 propertyNameLoc, receiverNameLoc, IFace);
2080 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2081 << &propertyName << Context.getObjCInterfaceType(IFace));
2086 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2088 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2089 // Determine whether "super" is acceptable in the current context.
2090 if (Method && Method->getClassInterface())
2091 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2094 bool ValidateCandidate(const TypoCorrection &candidate) override {
2095 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2096 candidate.isKeyword("super");
2100 } // end anonymous namespace
2102 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2103 IdentifierInfo *Name,
2104 SourceLocation NameLoc,
2106 bool HasTrailingDot,
2107 ParsedType &ReceiverType) {
2108 ReceiverType = nullptr;
2110 // If the identifier is "super" and there is no trailing dot, we're
2111 // messaging super. If the identifier is "super" and there is a
2112 // trailing dot, it's an instance message.
2113 if (IsSuper && S->isInObjcMethodScope())
2114 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2116 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2117 LookupName(Result, S);
2119 switch (Result.getResultKind()) {
2120 case LookupResult::NotFound:
2121 // Normal name lookup didn't find anything. If we're in an
2122 // Objective-C method, look for ivars. If we find one, we're done!
2123 // FIXME: This is a hack. Ivar lookup should be part of normal
2125 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2126 if (!Method->getClassInterface()) {
2127 // Fall back: let the parser try to parse it as an instance message.
2128 return ObjCInstanceMessage;
2131 ObjCInterfaceDecl *ClassDeclared;
2132 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2134 return ObjCInstanceMessage;
2137 // Break out; we'll perform typo correction below.
2140 case LookupResult::NotFoundInCurrentInstantiation:
2141 case LookupResult::FoundOverloaded:
2142 case LookupResult::FoundUnresolvedValue:
2143 case LookupResult::Ambiguous:
2144 Result.suppressDiagnostics();
2145 return ObjCInstanceMessage;
2147 case LookupResult::Found: {
2148 // If the identifier is a class or not, and there is a trailing dot,
2149 // it's an instance message.
2151 return ObjCInstanceMessage;
2152 // We found something. If it's a type, then we have a class
2153 // message. Otherwise, it's an instance message.
2154 NamedDecl *ND = Result.getFoundDecl();
2156 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2157 T = Context.getObjCInterfaceType(Class);
2158 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2159 T = Context.getTypeDeclType(Type);
2160 DiagnoseUseOfDecl(Type, NameLoc);
2163 return ObjCInstanceMessage;
2165 // We have a class message, and T is the type we're
2166 // messaging. Build source-location information for it.
2167 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2168 ReceiverType = CreateParsedType(T, TSInfo);
2169 return ObjCClassMessage;
2173 if (TypoCorrection Corrected = CorrectTypo(
2174 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2175 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2176 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2177 if (Corrected.isKeyword()) {
2178 // If we've found the keyword "super" (the only keyword that would be
2179 // returned by CorrectTypo), this is a send to super.
2180 diagnoseTypo(Corrected,
2181 PDiag(diag::err_unknown_receiver_suggest) << Name);
2182 return ObjCSuperMessage;
2183 } else if (ObjCInterfaceDecl *Class =
2184 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2185 // If we found a declaration, correct when it refers to an Objective-C
2187 diagnoseTypo(Corrected,
2188 PDiag(diag::err_unknown_receiver_suggest) << Name);
2189 QualType T = Context.getObjCInterfaceType(Class);
2190 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2191 ReceiverType = CreateParsedType(T, TSInfo);
2192 return ObjCClassMessage;
2196 // Fall back: let the parser try to parse it as an instance message.
2197 return ObjCInstanceMessage;
2200 ExprResult Sema::ActOnSuperMessage(Scope *S,
2201 SourceLocation SuperLoc,
2203 SourceLocation LBracLoc,
2204 ArrayRef<SourceLocation> SelectorLocs,
2205 SourceLocation RBracLoc,
2206 MultiExprArg Args) {
2207 // Determine whether we are inside a method or not.
2208 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2210 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2214 ObjCInterfaceDecl *Class = Method->getClassInterface();
2216 Diag(SuperLoc, diag::err_no_super_class_message)
2217 << Method->getDeclName();
2221 QualType SuperTy(Class->getSuperClassType(), 0);
2222 if (SuperTy.isNull()) {
2223 // The current class does not have a superclass.
2224 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2225 << Class->getIdentifier();
2229 // We are in a method whose class has a superclass, so 'super'
2230 // is acting as a keyword.
2231 if (Method->getSelector() == Sel)
2232 getCurFunction()->ObjCShouldCallSuper = false;
2234 if (Method->isInstanceMethod()) {
2235 // Since we are in an instance method, this is an instance
2236 // message to the superclass instance.
2237 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2238 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2239 Sel, /*Method=*/nullptr,
2240 LBracLoc, SelectorLocs, RBracLoc, Args);
2243 // Since we are in a class method, this is a class message to
2245 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2247 SuperLoc, Sel, /*Method=*/nullptr,
2248 LBracLoc, SelectorLocs, RBracLoc, Args);
2251 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2252 bool isSuperReceiver,
2255 ObjCMethodDecl *Method,
2256 MultiExprArg Args) {
2257 TypeSourceInfo *receiverTypeInfo = nullptr;
2258 if (!ReceiverType.isNull())
2259 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2261 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2262 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2263 Sel, Method, Loc, Loc, Loc, Args,
2264 /*isImplicit=*/true);
2267 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2269 bool (*refactor)(const ObjCMessageExpr *,
2270 const NSAPI &, edit::Commit &)) {
2271 SourceLocation MsgLoc = Msg->getExprLoc();
2272 if (S.Diags.isIgnored(DiagID, MsgLoc))
2275 SourceManager &SM = S.SourceMgr;
2276 edit::Commit ECommit(SM, S.LangOpts);
2277 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2278 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2279 << Msg->getSelector() << Msg->getSourceRange();
2280 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2281 if (!ECommit.isCommitable())
2283 for (edit::Commit::edit_iterator
2284 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2285 const edit::Commit::Edit &Edit = *I;
2286 switch (Edit.Kind) {
2287 case edit::Commit::Act_Insert:
2288 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2292 case edit::Commit::Act_InsertFromRange:
2293 Builder.AddFixItHint(
2294 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2295 Edit.getInsertFromRange(SM),
2298 case edit::Commit::Act_Remove:
2299 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2306 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2307 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2308 edit::rewriteObjCRedundantCallWithLiteral);
2311 static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2312 const ObjCMethodDecl *Method,
2313 ArrayRef<Expr *> Args, QualType ReceiverType,
2314 bool IsClassObjectCall) {
2315 // Check if this is a performSelector method that uses a selector that returns
2316 // a record or a vector type.
2317 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2320 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2323 ObjCMethodDecl *ImpliedMethod;
2324 if (!IsClassObjectCall) {
2325 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2326 if (!OPT || !OPT->getInterfaceDecl())
2329 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2332 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2334 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2337 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2340 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2344 QualType Ret = ImpliedMethod->getReturnType();
2345 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2346 QualType Ret = ImpliedMethod->getReturnType();
2347 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2348 << Method->getSelector()
2349 << (!Ret->isRecordType()
2351 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2352 S.Diag(ImpliedMethod->getBeginLoc(),
2353 diag::note_objc_unsafe_perform_selector_method_declared_here)
2354 << ImpliedMethod->getSelector() << Ret;
2358 /// Diagnose use of %s directive in an NSString which is being passed
2359 /// as formatting string to formatting method.
2361 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2362 ObjCMethodDecl *Method,
2364 Expr **Args, unsigned NumArgs) {
2366 bool Format = false;
2367 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2368 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2373 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2374 if (S.GetFormatNSStringIdx(I, Idx)) {
2380 if (!Format || NumArgs <= Idx)
2383 Expr *FormatExpr = Args[Idx];
2384 if (ObjCStringLiteral *OSL =
2385 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2386 StringLiteral *FormatString = OSL->getString();
2387 if (S.FormatStringHasSArg(FormatString)) {
2388 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2391 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2392 << Method->getDeclName();
2397 /// Build an Objective-C class message expression.
2399 /// This routine takes care of both normal class messages and
2400 /// class messages to the superclass.
2402 /// \param ReceiverTypeInfo Type source information that describes the
2403 /// receiver of this message. This may be NULL, in which case we are
2404 /// sending to the superclass and \p SuperLoc must be a valid source
2407 /// \param ReceiverType The type of the object receiving the
2408 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2409 /// type as that refers to. For a superclass send, this is the type of
2412 /// \param SuperLoc The location of the "super" keyword in a
2413 /// superclass message.
2415 /// \param Sel The selector to which the message is being sent.
2417 /// \param Method The method that this class message is invoking, if
2420 /// \param LBracLoc The location of the opening square bracket ']'.
2422 /// \param RBracLoc The location of the closing square bracket ']'.
2424 /// \param ArgsIn The message arguments.
2425 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2426 QualType ReceiverType,
2427 SourceLocation SuperLoc,
2429 ObjCMethodDecl *Method,
2430 SourceLocation LBracLoc,
2431 ArrayRef<SourceLocation> SelectorLocs,
2432 SourceLocation RBracLoc,
2433 MultiExprArg ArgsIn,
2435 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2436 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2437 if (LBracLoc.isInvalid()) {
2438 Diag(Loc, diag::err_missing_open_square_message_send)
2439 << FixItHint::CreateInsertion(Loc, "[");
2442 ArrayRef<SourceLocation> SelectorSlotLocs;
2443 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2444 SelectorSlotLocs = SelectorLocs;
2446 SelectorSlotLocs = Loc;
2447 SourceLocation SelLoc = SelectorSlotLocs.front();
2449 if (ReceiverType->isDependentType()) {
2450 // If the receiver type is dependent, we can't type-check anything
2451 // at this point. Build a dependent expression.
2452 unsigned NumArgs = ArgsIn.size();
2453 Expr **Args = ArgsIn.data();
2454 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2455 return ObjCMessageExpr::Create(
2456 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2457 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2461 // Find the class to which we are sending this message.
2462 ObjCInterfaceDecl *Class = nullptr;
2463 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2464 if (!ClassType || !(Class = ClassType->getInterface())) {
2465 Diag(Loc, diag::err_invalid_receiver_class_message)
2469 assert(Class && "We don't know which class we're messaging?");
2470 // objc++ diagnoses during typename annotation.
2471 if (!getLangOpts().CPlusPlus)
2472 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
2473 // Find the method we are messaging.
2475 SourceRange TypeRange
2476 = SuperLoc.isValid()? SourceRange(SuperLoc)
2477 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2478 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2479 (getLangOpts().ObjCAutoRefCount
2480 ? diag::err_arc_receiver_forward_class
2481 : diag::warn_receiver_forward_class),
2483 // A forward class used in messaging is treated as a 'Class'
2484 Method = LookupFactoryMethodInGlobalPool(Sel,
2485 SourceRange(LBracLoc, RBracLoc));
2486 if (Method && !getLangOpts().ObjCAutoRefCount)
2487 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2488 << Method->getDeclName();
2491 Method = Class->lookupClassMethod(Sel);
2493 // If we have an implementation in scope, check "private" methods.
2495 Method = Class->lookupPrivateClassMethod(Sel);
2497 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2498 nullptr, false, false, Class))
2502 // Check the argument types and determine the result type.
2503 QualType ReturnType;
2504 ExprValueKind VK = VK_RValue;
2506 unsigned NumArgs = ArgsIn.size();
2507 Expr **Args = ArgsIn.data();
2508 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2509 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2510 Method, true, SuperLoc.isValid(), LBracLoc,
2511 RBracLoc, SourceRange(), ReturnType, VK))
2514 if (Method && !Method->getReturnType()->isVoidType() &&
2515 RequireCompleteType(LBracLoc, Method->getReturnType(),
2516 diag::err_illegal_message_expr_incomplete_type))
2519 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2520 if (Method && Method->getMethodFamily() == OMF_initialize) {
2521 if (!SuperLoc.isValid()) {
2522 const ObjCInterfaceDecl *ID =
2523 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2525 Diag(Loc, diag::warn_direct_initialize_call);
2526 Diag(Method->getLocation(), diag::note_method_declared_at)
2527 << Method->getDeclName();
2530 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2531 // [super initialize] is allowed only within an +initialize implementation
2532 if (CurMeth->getMethodFamily() != OMF_initialize) {
2533 Diag(Loc, diag::warn_direct_super_initialize_call);
2534 Diag(Method->getLocation(), diag::note_method_declared_at)
2535 << Method->getDeclName();
2536 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2537 << CurMeth->getDeclName();
2542 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2544 // Construct the appropriate ObjCMessageExpr.
2545 ObjCMessageExpr *Result;
2546 if (SuperLoc.isValid())
2547 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2548 SuperLoc, /*IsInstanceSuper=*/false,
2549 ReceiverType, Sel, SelectorLocs,
2550 Method, makeArrayRef(Args, NumArgs),
2551 RBracLoc, isImplicit);
2553 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2554 ReceiverTypeInfo, Sel, SelectorLocs,
2555 Method, makeArrayRef(Args, NumArgs),
2556 RBracLoc, isImplicit);
2558 checkCocoaAPI(*this, Result);
2561 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2562 ReceiverType, /*IsClassObjectCall=*/true);
2563 return MaybeBindToTemporary(Result);
2566 // ActOnClassMessage - used for both unary and keyword messages.
2567 // ArgExprs is optional - if it is present, the number of expressions
2568 // is obtained from Sel.getNumArgs().
2569 ExprResult Sema::ActOnClassMessage(Scope *S,
2570 ParsedType Receiver,
2572 SourceLocation LBracLoc,
2573 ArrayRef<SourceLocation> SelectorLocs,
2574 SourceLocation RBracLoc,
2575 MultiExprArg Args) {
2576 TypeSourceInfo *ReceiverTypeInfo;
2577 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2578 if (ReceiverType.isNull())
2581 if (!ReceiverTypeInfo)
2582 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2584 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2585 /*SuperLoc=*/SourceLocation(), Sel,
2586 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2590 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2591 QualType ReceiverType,
2594 ObjCMethodDecl *Method,
2595 MultiExprArg Args) {
2596 return BuildInstanceMessage(Receiver, ReceiverType,
2597 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2598 Sel, Method, Loc, Loc, Loc, Args,
2599 /*isImplicit=*/true);
2602 static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2605 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2608 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2609 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2610 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
2611 Sema::LookupOrdinaryName))) {
2612 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2613 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2620 /// Build an Objective-C instance message expression.
2622 /// This routine takes care of both normal instance messages and
2623 /// instance messages to the superclass instance.
2625 /// \param Receiver The expression that computes the object that will
2626 /// receive this message. This may be empty, in which case we are
2627 /// sending to the superclass instance and \p SuperLoc must be a valid
2628 /// source location.
2630 /// \param ReceiverType The (static) type of the object receiving the
2631 /// message. When a \p Receiver expression is provided, this is the
2632 /// same type as that expression. For a superclass instance send, this
2633 /// is a pointer to the type of the superclass.
2635 /// \param SuperLoc The location of the "super" keyword in a
2636 /// superclass instance message.
2638 /// \param Sel The selector to which the message is being sent.
2640 /// \param Method The method that this instance message is invoking, if
2643 /// \param LBracLoc The location of the opening square bracket ']'.
2645 /// \param RBracLoc The location of the closing square bracket ']'.
2647 /// \param ArgsIn The message arguments.
2648 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2649 QualType ReceiverType,
2650 SourceLocation SuperLoc,
2652 ObjCMethodDecl *Method,
2653 SourceLocation LBracLoc,
2654 ArrayRef<SourceLocation> SelectorLocs,
2655 SourceLocation RBracLoc,
2656 MultiExprArg ArgsIn,
2658 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2659 "SuperLoc must be valid so we can "
2662 // The location of the receiver.
2663 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
2664 SourceRange RecRange =
2665 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2666 ArrayRef<SourceLocation> SelectorSlotLocs;
2667 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2668 SelectorSlotLocs = SelectorLocs;
2670 SelectorSlotLocs = Loc;
2671 SourceLocation SelLoc = SelectorSlotLocs.front();
2673 if (LBracLoc.isInvalid()) {
2674 Diag(Loc, diag::err_missing_open_square_message_send)
2675 << FixItHint::CreateInsertion(Loc, "[");
2679 // If we have a receiver expression, perform appropriate promotions
2680 // and determine receiver type.
2682 if (Receiver->hasPlaceholderType()) {
2684 if (Receiver->getType() == Context.UnknownAnyTy)
2685 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2687 Result = CheckPlaceholderExpr(Receiver);
2688 if (Result.isInvalid()) return ExprError();
2689 Receiver = Result.get();
2692 if (Receiver->isTypeDependent()) {
2693 // If the receiver is type-dependent, we can't type-check anything
2694 // at this point. Build a dependent expression.
2695 unsigned NumArgs = ArgsIn.size();
2696 Expr **Args = ArgsIn.data();
2697 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2698 return ObjCMessageExpr::Create(
2699 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2700 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2701 RBracLoc, isImplicit);
2704 // If necessary, apply function/array conversion to the receiver.
2705 // C99 6.7.5.3p[7,8].
2706 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2707 if (Result.isInvalid())
2709 Receiver = Result.get();
2710 ReceiverType = Receiver->getType();
2712 // If the receiver is an ObjC pointer, a block pointer, or an
2713 // __attribute__((NSObject)) pointer, we don't need to do any
2714 // special conversion in order to look up a receiver.
2715 if (ReceiverType->isObjCRetainableType()) {
2717 } else if (!getLangOpts().ObjCAutoRefCount &&
2718 !Context.getObjCIdType().isNull() &&
2719 (ReceiverType->isPointerType() ||
2720 ReceiverType->isIntegerType())) {
2721 // Implicitly convert integers and pointers to 'id' but emit a warning.
2723 Diag(Loc, diag::warn_bad_receiver_type)
2725 << Receiver->getSourceRange();
2726 if (ReceiverType->isPointerType()) {
2727 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2728 CK_CPointerToObjCPointerCast).get();
2730 // TODO: specialized warning on null receivers?
2731 bool IsNull = Receiver->isNullPointerConstant(Context,
2732 Expr::NPC_ValueDependentIsNull);
2733 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2734 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2737 ReceiverType = Receiver->getType();
2738 } else if (getLangOpts().CPlusPlus) {
2739 // The receiver must be a complete type.
2740 if (RequireCompleteType(Loc, Receiver->getType(),
2741 diag::err_incomplete_receiver_type))
2744 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2745 if (result.isUsable()) {
2746 Receiver = result.get();
2747 ReceiverType = Receiver->getType();
2752 if (ReceiverType->isObjCIdType() && !isImplicit)
2753 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
2755 // There's a somewhat weird interaction here where we assume that we
2756 // won't actually have a method unless we also don't need to do some
2757 // of the more detailed type-checking on the receiver.
2760 // Handle messages to id and __kindof types (where we use the
2761 // global method pool).
2762 const ObjCObjectType *typeBound = nullptr;
2763 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2765 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2766 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2767 SmallVector<ObjCMethodDecl*, 4> Methods;
2768 // If we have a type bound, further filter the methods.
2769 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2770 true/*CheckTheOther*/, typeBound);
2771 if (!Methods.empty()) {
2772 // We choose the first method as the initial candidate, then try to
2773 // select a better one.
2774 Method = Methods[0];
2776 if (ObjCMethodDecl *BestMethod =
2777 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2778 Method = BestMethod;
2780 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2781 SourceRange(LBracLoc, RBracLoc),
2782 receiverIsIdLike, Methods))
2783 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
2785 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2786 ReceiverType->isObjCQualifiedClassType()) {
2787 // Handle messages to Class.
2788 // We allow sending a message to a qualified Class ("Class<foo>"), which
2789 // is ok as long as one of the protocols implements the selector (if not,
2791 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2792 const ObjCObjectPointerType *QClassTy
2793 = ReceiverType->getAsObjCQualifiedClassType();
2794 // Search protocols for class methods.
2795 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2797 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2798 // warn if instance method found for a Class message.
2799 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2800 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2801 << Method->getSelector() << Sel;
2802 Diag(Method->getLocation(), diag::note_method_declared_at)
2803 << Method->getDeclName();
2807 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2808 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2809 // FIXME: Is this correct? Why are we assuming that a message to
2810 // Class will call a method in the current interface?
2812 // First check the public methods in the class interface.
2813 Method = ClassDecl->lookupClassMethod(Sel);
2816 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2818 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, nullptr,
2819 false, false, ClassDecl))
2824 // If not messaging 'self', look for any factory method named 'Sel'.
2825 if (!Receiver || !isSelfExpr(Receiver)) {
2826 // If no class (factory) method was found, check if an _instance_
2827 // method of the same name exists in the root class only.
2828 SmallVector<ObjCMethodDecl*, 4> Methods;
2829 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2830 false/*InstanceFirst*/,
2831 true/*CheckTheOther*/);
2832 if (!Methods.empty()) {
2833 // We choose the first method as the initial candidate, then try
2834 // to select a better one.
2835 Method = Methods[0];
2837 // If we find an instance method, emit warning.
2838 if (Method->isInstanceMethod()) {
2839 if (const ObjCInterfaceDecl *ID =
2840 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2841 if (ID->getSuperClass())
2842 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2843 << Sel << SourceRange(LBracLoc, RBracLoc);
2847 if (ObjCMethodDecl *BestMethod =
2848 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2850 Method = BestMethod;
2856 ObjCInterfaceDecl *ClassDecl = nullptr;
2858 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2859 // long as one of the protocols implements the selector (if not, warn).
2860 // And as long as message is not deprecated/unavailable (warn if it is).
2861 if (const ObjCObjectPointerType *QIdTy
2862 = ReceiverType->getAsObjCQualifiedIdType()) {
2863 // Search protocols for instance methods.
2864 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2866 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2867 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
2869 } else if (const ObjCObjectPointerType *OCIType
2870 = ReceiverType->getAsObjCInterfacePointerType()) {
2871 // We allow sending a message to a pointer to an interface (an object).
2872 ClassDecl = OCIType->getInterfaceDecl();
2874 // Try to complete the type. Under ARC, this is a hard error from which
2875 // we don't try to recover.
2876 // FIXME: In the non-ARC case, this will still be a hard error if the
2877 // definition is found in a module that's not visible.
2878 const ObjCInterfaceDecl *forwardClass = nullptr;
2879 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2880 getLangOpts().ObjCAutoRefCount
2881 ? diag::err_arc_receiver_forward_instance
2882 : diag::warn_receiver_forward_instance,
2883 Receiver? Receiver->getSourceRange()
2884 : SourceRange(SuperLoc))) {
2885 if (getLangOpts().ObjCAutoRefCount)
2888 forwardClass = OCIType->getInterfaceDecl();
2889 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
2890 diag::note_receiver_is_id);
2893 Method = ClassDecl->lookupInstanceMethod(Sel);
2897 // Search protocol qualifiers.
2898 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2901 // If we have implementations in scope, check "private" methods.
2902 Method = ClassDecl->lookupPrivateMethod(Sel);
2904 if (!Method && getLangOpts().ObjCAutoRefCount) {
2905 Diag(SelLoc, diag::err_arc_may_not_respond)
2906 << OCIType->getPointeeType() << Sel << RecRange
2907 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2911 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2912 // If we still haven't found a method, look in the global pool. This
2913 // behavior isn't very desirable, however we need it for GCC
2914 // compatibility. FIXME: should we deviate??
2915 if (OCIType->qual_empty()) {
2916 SmallVector<ObjCMethodDecl*, 4> Methods;
2917 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2918 true/*InstanceFirst*/,
2919 false/*CheckTheOther*/);
2920 if (!Methods.empty()) {
2921 // We choose the first method as the initial candidate, then try
2922 // to select a better one.
2923 Method = Methods[0];
2925 if (ObjCMethodDecl *BestMethod =
2926 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2928 Method = BestMethod;
2930 AreMultipleMethodsInGlobalPool(Sel, Method,
2931 SourceRange(LBracLoc, RBracLoc),
2932 true/*receiverIdOrClass*/,
2935 if (Method && !forwardClass)
2936 Diag(SelLoc, diag::warn_maynot_respond)
2937 << OCIType->getInterfaceDecl()->getIdentifier()
2942 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
2945 // Reject other random receiver types (e.g. structs).
2946 Diag(Loc, diag::err_bad_receiver_type)
2947 << ReceiverType << Receiver->getSourceRange();
2953 FunctionScopeInfo *DIFunctionScopeInfo =
2954 (Method && Method->getMethodFamily() == OMF_init)
2955 ? getEnclosingFunction() : nullptr;
2957 if (DIFunctionScopeInfo &&
2958 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2959 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2960 bool isDesignatedInitChain = false;
2961 if (SuperLoc.isValid()) {
2962 if (const ObjCObjectPointerType *
2963 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2964 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2965 // Either we know this is a designated initializer or we
2966 // conservatively assume it because we don't know for sure.
2967 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2968 ID->isDesignatedInitializer(Sel)) {
2969 isDesignatedInitChain = true;
2970 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2975 if (!isDesignatedInitChain) {
2976 const ObjCMethodDecl *InitMethod = nullptr;
2978 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2979 assert(isDesignated && InitMethod);
2981 Diag(SelLoc, SuperLoc.isValid() ?
2982 diag::warn_objc_designated_init_non_designated_init_call :
2983 diag::warn_objc_designated_init_non_super_designated_init_call);
2984 Diag(InitMethod->getLocation(),
2985 diag::note_objc_designated_init_marked_here);
2989 if (DIFunctionScopeInfo &&
2990 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2991 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2992 if (SuperLoc.isValid()) {
2993 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2995 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2999 // Check the message arguments.
3000 unsigned NumArgs = ArgsIn.size();
3001 Expr **Args = ArgsIn.data();
3002 QualType ReturnType;
3003 ExprValueKind VK = VK_RValue;
3004 bool ClassMessage = (ReceiverType->isObjCClassType() ||
3005 ReceiverType->isObjCQualifiedClassType());
3006 if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3007 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3008 Method, ClassMessage, SuperLoc.isValid(),
3009 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
3012 if (Method && !Method->getReturnType()->isVoidType() &&
3013 RequireCompleteType(LBracLoc, Method->getReturnType(),
3014 diag::err_illegal_message_expr_incomplete_type))
3017 // In ARC, forbid the user from sending messages to
3018 // retain/release/autorelease/dealloc/retainCount explicitly.
3019 if (getLangOpts().ObjCAutoRefCount) {
3020 ObjCMethodFamily family =
3021 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
3025 checkInitMethod(Method, ReceiverType);
3032 case OMF_mutableCopy:
3035 case OMF_initialize:
3041 case OMF_autorelease:
3042 case OMF_retainCount:
3043 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3047 case OMF_performSelector:
3048 if (Method && NumArgs >= 1) {
3049 if (const auto *SelExp =
3050 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
3051 Selector ArgSel = SelExp->getSelector();
3052 ObjCMethodDecl *SelMethod =
3053 LookupInstanceMethodInGlobalPool(ArgSel,
3054 SelExp->getSourceRange());
3057 LookupFactoryMethodInGlobalPool(ArgSel,
3058 SelExp->getSourceRange());
3060 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3061 switch (SelFamily) {
3064 case OMF_mutableCopy:
3067 // Issue error, unless ns_returns_not_retained.
3068 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3069 // selector names a +1 method
3071 diag::err_arc_perform_selector_retains);
3072 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3073 << SelMethod->getDeclName();
3077 // +0 call. OK. unless ns_returns_retained.
3078 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3079 // selector names a +1 method
3081 diag::err_arc_perform_selector_retains);
3082 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3083 << SelMethod->getDeclName();
3089 // error (may leak).
3090 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3091 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3098 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3100 // Construct the appropriate ObjCMessageExpr instance.
3101 ObjCMessageExpr *Result;
3102 if (SuperLoc.isValid())
3103 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3104 SuperLoc, /*IsInstanceSuper=*/true,
3105 ReceiverType, Sel, SelectorLocs, Method,
3106 makeArrayRef(Args, NumArgs), RBracLoc,
3109 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3110 Receiver, Sel, SelectorLocs, Method,
3111 makeArrayRef(Args, NumArgs), RBracLoc,
3114 checkCocoaAPI(*this, Result);
3117 bool IsClassObjectCall = ClassMessage;
3118 // 'self' message receivers in class methods should be treated as message
3119 // sends to the class object in order for the semantic checks to be
3120 // performed correctly. Messages to 'super' already count as class messages,
3121 // so they don't need to be handled here.
3122 if (Receiver && isSelfExpr(Receiver)) {
3123 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3124 if (OPT->getObjectType()->isObjCClass()) {
3125 if (const auto *CurMeth = getCurMethodDecl()) {
3126 IsClassObjectCall = true;
3128 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3133 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3134 ReceiverType, IsClassObjectCall);
3137 if (getLangOpts().ObjCAutoRefCount) {
3138 // In ARC, annotate delegate init calls.
3139 if (Result->getMethodFamily() == OMF_init &&
3140 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3141 // Only consider init calls *directly* in init implementations,
3142 // not within blocks.
3143 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3144 if (method && method->getMethodFamily() == OMF_init) {
3145 // The implicit assignment to self means we also don't want to
3146 // consume the result.
3147 Result->setDelegateInitCall(true);
3152 // In ARC, check for message sends which are likely to introduce
3154 checkRetainCycles(Result);
3157 if (getLangOpts().ObjCWeak) {
3158 if (!isImplicit && Method) {
3159 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3161 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3162 if (!IsWeak && Sel.isUnarySelector())
3163 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3164 if (IsWeak && !isUnevaluatedContext() &&
3165 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3166 getCurFunction()->recordUseOfWeak(Result, Prop);
3171 CheckObjCCircularContainer(Result);
3173 return MaybeBindToTemporary(Result);
3176 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3177 if (ObjCSelectorExpr *OSE =
3178 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3179 Selector Sel = OSE->getSelector();
3180 SourceLocation Loc = OSE->getAtLoc();
3181 auto Pos = S.ReferencedSelectors.find(Sel);
3182 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3183 S.ReferencedSelectors.erase(Pos);
3187 // ActOnInstanceMessage - used for both unary and keyword messages.
3188 // ArgExprs is optional - if it is present, the number of expressions
3189 // is obtained from Sel.getNumArgs().
3190 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3193 SourceLocation LBracLoc,
3194 ArrayRef<SourceLocation> SelectorLocs,
3195 SourceLocation RBracLoc,
3196 MultiExprArg Args) {
3200 // A ParenListExpr can show up while doing error recovery with invalid code.
3201 if (isa<ParenListExpr>(Receiver)) {
3202 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3203 if (Result.isInvalid()) return ExprError();
3204 Receiver = Result.get();
3207 if (RespondsToSelectorSel.isNull()) {
3208 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3209 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3211 if (Sel == RespondsToSelectorSel)
3212 RemoveSelectorFromWarningCache(*this, Args[0]);
3214 return BuildInstanceMessage(Receiver, Receiver->getType(),
3215 /*SuperLoc=*/SourceLocation(), Sel,
3216 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3220 enum ARCConversionTypeClass {
3221 /// int, void, struct A
3227 /// id*, id***, void (^*)(),
3228 ACTC_indirectRetainable,
3230 /// void* might be a normal C type, or it might a CF type.
3237 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3238 return (ACTC == ACTC_retainable ||
3239 ACTC == ACTC_coreFoundation ||
3240 ACTC == ACTC_voidPtr);
3243 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3244 return ACTC == ACTC_none ||
3245 ACTC == ACTC_voidPtr ||
3246 ACTC == ACTC_coreFoundation;
3249 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3250 bool isIndirect = false;
3252 // Ignore an outermost reference type.
3253 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3254 type = ref->getPointeeType();
3258 // Drill through pointers and arrays recursively.
3260 if (const PointerType *ptr = type->getAs<PointerType>()) {
3261 type = ptr->getPointeeType();
3263 // The first level of pointer may be the innermost pointer on a CF type.
3265 if (type->isVoidType()) return ACTC_voidPtr;
3266 if (type->isRecordType()) return ACTC_coreFoundation;
3268 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3269 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3277 if (type->isObjCARCBridgableType())
3278 return ACTC_indirectRetainable;
3282 if (type->isObjCARCBridgableType())
3283 return ACTC_retainable;
3289 /// A result from the cast checker.
3291 /// Cannot be casted.
3294 /// Can be safely retained or not retained.
3297 /// Can be casted at +0.
3300 /// Can be casted at +1.
3303 ACCResult merge(ACCResult left, ACCResult right) {
3304 if (left == right) return left;
3305 if (left == ACC_bottom) return right;
3306 if (right == ACC_bottom) return left;
3310 /// A checker which white-lists certain expressions whose conversion
3311 /// to or from retainable type would otherwise be forbidden in ARC.
3312 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3313 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3315 ASTContext &Context;
3316 ARCConversionTypeClass SourceClass;
3317 ARCConversionTypeClass TargetClass;
3320 static bool isCFType(QualType type) {
3321 // Someday this can use ns_bridged. For now, it has to do this.
3322 return type->isCARCBridgableType();
3326 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3327 ARCConversionTypeClass target, bool diagnose)
3328 : Context(Context), SourceClass(source), TargetClass(target),
3329 Diagnose(diagnose) {}
3332 ACCResult Visit(Expr *e) {
3333 return super::Visit(e->IgnoreParens());
3336 ACCResult VisitStmt(Stmt *s) {
3340 /// Null pointer constants can be casted however you please.
3341 ACCResult VisitExpr(Expr *e) {
3342 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3347 /// Objective-C string literals can be safely casted.
3348 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3349 // If we're casting to any retainable type, go ahead. Global
3350 // strings are immune to retains, so this is bottom.
3351 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3356 /// Look through certain implicit and explicit casts.
3357 ACCResult VisitCastExpr(CastExpr *e) {
3358 switch (e->getCastKind()) {
3359 case CK_NullToPointer:
3363 case CK_LValueToRValue:
3365 case CK_CPointerToObjCPointerCast:
3366 case CK_BlockPointerToObjCPointerCast:
3367 case CK_AnyPointerToBlockPointerCast:
3368 return Visit(e->getSubExpr());
3375 /// Look through unary extension.
3376 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3377 return Visit(e->getSubExpr());
3380 /// Ignore the LHS of a comma operator.
3381 ACCResult VisitBinComma(BinaryOperator *e) {
3382 return Visit(e->getRHS());
3385 /// Conditional operators are okay if both sides are okay.
3386 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3387 ACCResult left = Visit(e->getTrueExpr());
3388 if (left == ACC_invalid) return ACC_invalid;
3389 return merge(left, Visit(e->getFalseExpr()));
3392 /// Look through pseudo-objects.
3393 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3394 // If we're getting here, we should always have a result.
3395 return Visit(e->getResultExpr());
3398 /// Statement expressions are okay if their result expression is okay.
3399 ACCResult VisitStmtExpr(StmtExpr *e) {
3400 return Visit(e->getSubStmt()->body_back());
3403 /// Some declaration references are okay.
3404 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3405 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3406 // References to global constants are okay.
3407 if (isAnyRetainable(TargetClass) &&
3408 isAnyRetainable(SourceClass) &&
3410 !var->hasDefinition(Context) &&
3411 var->getType().isConstQualified()) {
3413 // In system headers, they can also be assumed to be immune to retains.
3414 // These are things like 'kCFStringTransformToLatin'.
3415 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3418 return ACC_plusZero;
3425 /// Some calls are okay.
3426 ACCResult VisitCallExpr(CallExpr *e) {
3427 if (FunctionDecl *fn = e->getDirectCallee())
3428 if (ACCResult result = checkCallToFunction(fn))
3431 return super::VisitCallExpr(e);
3434 ACCResult checkCallToFunction(FunctionDecl *fn) {
3435 // Require a CF*Ref return type.
3436 if (!isCFType(fn->getReturnType()))
3439 if (!isAnyRetainable(TargetClass))
3442 // Honor an explicit 'not retained' attribute.
3443 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3444 return ACC_plusZero;
3446 // Honor an explicit 'retained' attribute, except that for
3447 // now we're not going to permit implicit handling of +1 results,
3448 // because it's a bit frightening.
3449 if (fn->hasAttr<CFReturnsRetainedAttr>())
3450 return Diagnose ? ACC_plusOne
3451 : ACC_invalid; // ACC_plusOne if we start accepting this
3453 // Recognize this specific builtin function, which is used by CFSTR.
3454 unsigned builtinID = fn->getBuiltinID();
3455 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3458 // Otherwise, don't do anything implicit with an unaudited function.
3459 if (!fn->hasAttr<CFAuditedTransferAttr>())
3462 // Otherwise, it's +0 unless it follows the create convention.
3463 if (ento::coreFoundation::followsCreateRule(fn))
3464 return Diagnose ? ACC_plusOne
3465 : ACC_invalid; // ACC_plusOne if we start accepting this
3467 return ACC_plusZero;
3470 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3471 return checkCallToMethod(e->getMethodDecl());
3474 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3475 ObjCMethodDecl *method;
3476 if (e->isExplicitProperty())
3477 method = e->getExplicitProperty()->getGetterMethodDecl();
3479 method = e->getImplicitPropertyGetter();
3480 return checkCallToMethod(method);
3483 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3484 if (!method) return ACC_invalid;
3486 // Check for message sends to functions returning CF types. We
3487 // just obey the Cocoa conventions with these, even though the
3488 // return type is CF.
3489 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3492 // If the method is explicitly marked not-retained, it's +0.
3493 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3494 return ACC_plusZero;
3496 // If the method is explicitly marked as returning retained, or its
3497 // selector follows a +1 Cocoa convention, treat it as +1.
3498 if (method->hasAttr<CFReturnsRetainedAttr>())
3501 switch (method->getSelector().getMethodFamily()) {
3504 case OMF_mutableCopy:
3509 // Otherwise, treat it as +0.
3510 return ACC_plusZero;
3514 } // end anonymous namespace
3516 bool Sema::isKnownName(StringRef name) {
3519 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3520 Sema::LookupOrdinaryName);
3521 return LookupName(R, TUScope, false);
3524 static void addFixitForObjCARCConversion(Sema &S,
3525 DiagnosticBuilder &DiagB,
3526 Sema::CheckedConversionKind CCK,
3527 SourceLocation afterLParen,
3531 const char *bridgeKeyword,
3532 const char *CFBridgeName) {
3533 // We handle C-style and implicit casts here.
3535 case Sema::CCK_ImplicitConversion:
3536 case Sema::CCK_ForBuiltinOverloadedOp:
3537 case Sema::CCK_CStyleCast:
3538 case Sema::CCK_OtherCast:
3540 case Sema::CCK_FunctionalCast:
3545 if (CCK == Sema::CCK_OtherCast) {
3546 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3547 SourceRange range(NCE->getOperatorLoc(),
3548 NCE->getAngleBrackets().getEnd());
3549 SmallString<32> BridgeCall;
3551 SourceManager &SM = S.getSourceManager();
3552 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3553 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3556 BridgeCall += CFBridgeName;
3557 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3561 Expr *castedE = castExpr;
3562 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3563 castedE = CCE->getSubExpr();
3564 castedE = castedE->IgnoreImpCasts();
3565 SourceRange range = castedE->getSourceRange();
3567 SmallString<32> BridgeCall;
3569 SourceManager &SM = S.getSourceManager();
3570 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3571 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3574 BridgeCall += CFBridgeName;
3576 if (isa<ParenExpr>(castedE)) {
3577 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3581 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3583 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3584 S.getLocForEndOfToken(range.getEnd()),
3590 if (CCK == Sema::CCK_CStyleCast) {
3591 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3592 } else if (CCK == Sema::CCK_OtherCast) {
3593 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3594 std::string castCode = "(";
3595 castCode += bridgeKeyword;
3596 castCode += castType.getAsString();
3598 SourceRange Range(NCE->getOperatorLoc(),
3599 NCE->getAngleBrackets().getEnd());
3600 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3603 std::string castCode = "(";
3604 castCode += bridgeKeyword;
3605 castCode += castType.getAsString();
3607 Expr *castedE = castExpr->IgnoreImpCasts();
3608 SourceRange range = castedE->getSourceRange();
3609 if (isa<ParenExpr>(castedE)) {
3610 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3614 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3616 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3617 S.getLocForEndOfToken(range.getEnd()),
3623 template <typename T>
3624 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3625 TypedefNameDecl *TDNDecl = TD->getDecl();
3626 QualType QT = TDNDecl->getUnderlyingType();
3627 if (QT->isPointerType()) {
3628 QT = QT->getPointeeType();
3629 if (const RecordType *RT = QT->getAs<RecordType>())
3630 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3631 return RD->getAttr<T>();
3636 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3637 TypedefNameDecl *&TDNDecl) {
3638 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3639 TDNDecl = TD->getDecl();
3640 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3641 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3643 T = TDNDecl->getUnderlyingType();
3649 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3650 QualType castType, ARCConversionTypeClass castACTC,
3651 Expr *castExpr, Expr *realCast,
3652 ARCConversionTypeClass exprACTC,
3653 Sema::CheckedConversionKind CCK) {
3654 SourceLocation loc =
3655 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3657 if (S.makeUnavailableInSystemHeader(loc,
3658 UnavailableAttr::IR_ARCForbiddenConversion))
3661 QualType castExprType = castExpr->getType();
3662 // Defer emitting a diagnostic for bridge-related casts; that will be
3663 // handled by CheckObjCBridgeRelatedConversions.
3664 TypedefNameDecl *TDNDecl = nullptr;
3665 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3666 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3667 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3668 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3671 unsigned srcKind = 0;
3674 case ACTC_coreFoundation:
3676 srcKind = (castExprType->isPointerType() ? 1 : 0);
3678 case ACTC_retainable:
3679 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3681 case ACTC_indirectRetainable:
3686 // Check whether this could be fixed with a bridge cast.
3687 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3688 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3690 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3692 // Bridge from an ARC type to a CF type.
3693 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3695 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3697 << 2 // of C pointer type
3699 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3702 << castExpr->getSourceRange();
3703 bool br = S.isKnownName("CFBridgingRelease");
3704 ACCResult CreateRule =
3705 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3706 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3707 if (CreateRule != ACC_plusOne)
3709 DiagnosticBuilder DiagB =
3710 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3711 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3713 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3714 castType, castExpr, realCast, "__bridge ",
3717 if (CreateRule != ACC_plusZero)
3719 DiagnosticBuilder DiagB =
3720 (CCK == Sema::CCK_OtherCast && !br) ?
3721 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3722 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3723 diag::note_arc_bridge_transfer)
3724 << castExprType << br;
3726 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3727 castType, castExpr, realCast, "__bridge_transfer ",
3728 br ? "CFBridgingRelease" : nullptr);
3734 // Bridge from a CF type to an ARC type.
3735 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3736 bool br = S.isKnownName("CFBridgingRetain");
3737 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3739 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3741 << 2 // to C pointer type
3744 << castExpr->getSourceRange();
3745 ACCResult CreateRule =
3746 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3747 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3748 if (CreateRule != ACC_plusOne)
3750 DiagnosticBuilder DiagB =
3751 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3752 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3753 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3754 castType, castExpr, realCast, "__bridge ",
3757 if (CreateRule != ACC_plusZero)
3759 DiagnosticBuilder DiagB =
3760 (CCK == Sema::CCK_OtherCast && !br) ?
3761 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3762 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3763 diag::note_arc_bridge_retained)
3766 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3767 castType, castExpr, realCast, "__bridge_retained ",
3768 br ? "CFBridgingRetain" : nullptr);
3774 S.Diag(loc, diag::err_arc_mismatched_cast)
3776 << srcKind << castExprType << castType
3777 << castRange << castExpr->getSourceRange();
3780 template <typename TB>
3781 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3782 bool &HadTheAttribute, bool warn) {
3783 QualType T = castExpr->getType();
3784 HadTheAttribute = false;
3785 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3786 TypedefNameDecl *TDNDecl = TD->getDecl();
3787 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3788 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3789 HadTheAttribute = true;
3790 if (Parm->isStr("id"))
3793 NamedDecl *Target = nullptr;
3794 // Check for an existing type with this name.
3795 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3796 Sema::LookupOrdinaryName);
3797 if (S.LookupName(R, S.TUScope)) {
3798 Target = R.getFoundDecl();
3799 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3800 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3801 if (const ObjCObjectPointerType *InterfacePointerType =
3802 castType->getAsObjCInterfacePointerType()) {
3803 ObjCInterfaceDecl *CastClass
3804 = InterfacePointerType->getObjectType()->getInterface();
3805 if ((CastClass == ExprClass) ||
3806 (CastClass && CastClass->isSuperClassOf(ExprClass)))
3809 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3810 << T << Target->getName() << castType->getPointeeType();
3812 } else if (castType->isObjCIdType() ||
3813 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3814 castType, ExprClass)))
3815 // ok to cast to 'id'.
3816 // casting to id<p-list> is ok if bridge type adopts all of
3817 // p-list protocols.
3821 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
3822 << T << Target->getName() << castType;
3823 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3824 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3829 } else if (!castType->isObjCIdType()) {
3830 S.Diag(castExpr->getBeginLoc(),
3831 diag::err_objc_cf_bridged_not_interface)
3832 << castExpr->getType() << Parm;
3833 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3835 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3841 T = TDNDecl->getUnderlyingType();
3846 template <typename TB>
3847 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3848 bool &HadTheAttribute, bool warn) {
3849 QualType T = castType;
3850 HadTheAttribute = false;
3851 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3852 TypedefNameDecl *TDNDecl = TD->getDecl();
3853 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3854 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3855 HadTheAttribute = true;
3856 if (Parm->isStr("id"))
3859 NamedDecl *Target = nullptr;
3860 // Check for an existing type with this name.
3861 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3862 Sema::LookupOrdinaryName);
3863 if (S.LookupName(R, S.TUScope)) {
3864 Target = R.getFoundDecl();
3865 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3866 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3867 if (const ObjCObjectPointerType *InterfacePointerType =
3868 castExpr->getType()->getAsObjCInterfacePointerType()) {
3869 ObjCInterfaceDecl *ExprClass
3870 = InterfacePointerType->getObjectType()->getInterface();
3871 if ((CastClass == ExprClass) ||
3872 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3875 S.Diag(castExpr->getBeginLoc(),
3876 diag::warn_objc_invalid_bridge_to_cf)
3877 << castExpr->getType()->getPointeeType() << T;
3878 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3881 } else if (castExpr->getType()->isObjCIdType() ||
3882 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3883 castExpr->getType(), CastClass)))
3884 // ok to cast an 'id' expression to a CFtype.
3885 // ok to cast an 'id<plist>' expression to CFtype provided plist
3886 // adopts all of CFtype's ObjetiveC's class plist.
3890 S.Diag(castExpr->getBeginLoc(),
3891 diag::warn_objc_invalid_bridge_to_cf)
3892 << castExpr->getType() << castType;
3893 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3894 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3900 S.Diag(castExpr->getBeginLoc(),
3901 diag::err_objc_ns_bridged_invalid_cfobject)
3902 << castExpr->getType() << castType;
3903 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
3905 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
3910 T = TDNDecl->getUnderlyingType();
3915 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3916 if (!getLangOpts().ObjC)
3918 // warn in presence of __bridge casting to or from a toll free bridge cast.
3919 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3920 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3921 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3922 bool HasObjCBridgeAttr;
3923 bool ObjCBridgeAttrWillNotWarn =
3924 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3926 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3928 bool HasObjCBridgeMutableAttr;
3929 bool ObjCBridgeMutableAttrWillNotWarn =
3930 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3931 HasObjCBridgeMutableAttr, false);
3932 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3935 if (HasObjCBridgeAttr)
3936 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3938 else if (HasObjCBridgeMutableAttr)
3939 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3940 HasObjCBridgeMutableAttr, true);
3942 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3943 bool HasObjCBridgeAttr;
3944 bool ObjCBridgeAttrWillNotWarn =
3945 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3947 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3949 bool HasObjCBridgeMutableAttr;
3950 bool ObjCBridgeMutableAttrWillNotWarn =
3951 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3952 HasObjCBridgeMutableAttr, false);
3953 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3956 if (HasObjCBridgeAttr)
3957 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3959 else if (HasObjCBridgeMutableAttr)
3960 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3961 HasObjCBridgeMutableAttr, true);
3965 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3966 QualType SrcType = castExpr->getType();
3967 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3968 if (PRE->isExplicitProperty()) {
3969 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3970 SrcType = PDecl->getType();
3972 else if (PRE->isImplicitProperty()) {
3973 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3974 SrcType = Getter->getReturnType();
3978 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3979 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3980 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3982 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
3986 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3988 if (!getLangOpts().ObjC)
3990 ARCConversionTypeClass exprACTC =
3991 classifyTypeForARCConversion(castExpr->getType());
3992 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3993 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3994 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3995 CheckTollFreeBridgeCast(castType, castExpr);
3996 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3997 : CK_CPointerToObjCPointerCast;
4003 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4004 QualType DestType, QualType SrcType,
4005 ObjCInterfaceDecl *&RelatedClass,
4006 ObjCMethodDecl *&ClassMethod,
4007 ObjCMethodDecl *&InstanceMethod,
4008 TypedefNameDecl *&TDNDecl,
4009 bool CfToNs, bool Diagnose) {
4010 QualType T = CfToNs ? SrcType : DestType;
4011 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4015 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4016 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4017 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4020 NamedDecl *Target = nullptr;
4021 // Check for an existing type with this name.
4022 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4023 Sema::LookupOrdinaryName);
4024 if (!LookupName(R, TUScope)) {
4026 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4027 << SrcType << DestType;
4028 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4032 Target = R.getFoundDecl();
4033 if (Target && isa<ObjCInterfaceDecl>(Target))
4034 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4037 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4038 << SrcType << DestType;
4039 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4041 Diag(Target->getBeginLoc(), diag::note_declared_at);
4046 // Check for an existing class method with the given selector name.
4047 if (CfToNs && CMId) {
4048 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4049 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4052 Diag(Loc, diag::err_objc_bridged_related_known_method)
4053 << SrcType << DestType << Sel << false;
4054 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4060 // Check for an existing instance method with the given selector name.
4061 if (!CfToNs && IMId) {
4062 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4063 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4064 if (!InstanceMethod) {
4066 Diag(Loc, diag::err_objc_bridged_related_known_method)
4067 << SrcType << DestType << Sel << true;
4068 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4077 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4078 QualType DestType, QualType SrcType,
4079 Expr *&SrcExpr, bool Diagnose) {
4080 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4081 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4082 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4083 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4084 if (!CfToNs && !NsToCf)
4087 ObjCInterfaceDecl *RelatedClass;
4088 ObjCMethodDecl *ClassMethod = nullptr;
4089 ObjCMethodDecl *InstanceMethod = nullptr;
4090 TypedefNameDecl *TDNDecl = nullptr;
4091 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4092 ClassMethod, InstanceMethod, TDNDecl,
4097 // Implicit conversion from CF to ObjC object is needed.
4100 std::string ExpressionString = "[";
4101 ExpressionString += RelatedClass->getNameAsString();
4102 ExpressionString += " ";
4103 ExpressionString += ClassMethod->getSelector().getAsString();
4104 SourceLocation SrcExprEndLoc =
4105 getLocForEndOfToken(SrcExpr->getEndLoc());
4106 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4107 Diag(Loc, diag::err_objc_bridged_related_known_method)
4108 << SrcType << DestType << ClassMethod->getSelector() << false
4109 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4111 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4112 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4113 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4115 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4117 Expr *args[] = { SrcExpr };
4118 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4119 ClassMethod->getLocation(),
4120 ClassMethod->getSelector(), ClassMethod,
4121 MultiExprArg(args, 1));
4122 SrcExpr = msg.get();
4128 // Implicit conversion from ObjC type to CF object is needed.
4129 if (InstanceMethod) {
4131 std::string ExpressionString;
4132 SourceLocation SrcExprEndLoc =
4133 getLocForEndOfToken(SrcExpr->getEndLoc());
4134 if (InstanceMethod->isPropertyAccessor())
4135 if (const ObjCPropertyDecl *PDecl =
4136 InstanceMethod->findPropertyDecl()) {
4137 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4138 ExpressionString = ".";
4139 ExpressionString += PDecl->getNameAsString();
4140 Diag(Loc, diag::err_objc_bridged_related_known_method)
4141 << SrcType << DestType << InstanceMethod->getSelector() << true
4142 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4144 if (ExpressionString.empty()) {
4145 // Provide a fixit: [ObjectExpr InstanceMethod]
4146 ExpressionString = " ";
4147 ExpressionString += InstanceMethod->getSelector().getAsString();
4148 ExpressionString += "]";
4150 Diag(Loc, diag::err_objc_bridged_related_known_method)
4151 << SrcType << DestType << InstanceMethod->getSelector() << true
4152 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
4153 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4155 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4156 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4159 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4160 InstanceMethod->getLocation(),
4161 InstanceMethod->getSelector(),
4162 InstanceMethod, None);
4163 SrcExpr = msg.get();
4171 Sema::ARCConversionResult
4172 Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4173 Expr *&castExpr, CheckedConversionKind CCK,
4174 bool Diagnose, bool DiagnoseCFAudited,
4175 BinaryOperatorKind Opc) {
4176 QualType castExprType = castExpr->getType();
4178 // For the purposes of the classification, we assume reference types
4179 // will bind to temporaries.
4180 QualType effCastType = castType;
4181 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4182 effCastType = ref->getPointeeType();
4184 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4185 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4186 if (exprACTC == castACTC) {
4187 // Check for viability and report error if casting an rvalue to a
4188 // life-time qualifier.
4189 if (castACTC == ACTC_retainable &&
4190 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4191 castType != castExprType) {
4192 const Type *DT = castType.getTypePtr();
4193 QualType QDT = castType;
4194 // We desugar some types but not others. We ignore those
4195 // that cannot happen in a cast; i.e. auto, and those which
4196 // should not be de-sugared; i.e typedef.
4197 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4198 QDT = PT->desugar();
4199 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4200 QDT = TP->desugar();
4201 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4202 QDT = AT->desugar();
4203 if (QDT != castType &&
4204 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
4206 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4207 : castExpr->getExprLoc());
4208 Diag(loc, diag::err_arc_nolifetime_behavior);
4216 // The life-time qualifier cast check above is all we need for ObjCWeak.
4217 // ObjCAutoRefCount has more restrictions on what is legal.
4218 if (!getLangOpts().ObjCAutoRefCount)
4221 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4223 // Allow all of these types to be cast to integer types (but not
4225 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4228 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4229 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4230 // must be explicit.
4231 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4233 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4237 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4238 // For invalid casts, fall through.
4242 // Do nothing for both bottom and +0.
4247 // If the result is +1, consume it here.
4249 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4250 CK_ARCConsumeObject, castExpr,
4251 nullptr, VK_RValue);
4252 Cleanup.setExprNeedsCleanups(true);
4256 // If this is a non-implicit cast from id or block type to a
4257 // CoreFoundation type, delay complaining in case the cast is used
4258 // in an acceptable context.
4259 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
4260 return ACR_unbridged;
4262 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4263 // to 'NSString *', instead of falling through to report a "bridge cast"
4265 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4266 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
4269 // Do not issue "bridge cast" diagnostic when implicit casting
4270 // a retainable object to a CF type parameter belonging to an audited
4271 // CF API function. Let caller issue a normal type mismatched diagnostic
4273 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4274 castACTC != ACTC_coreFoundation) &&
4275 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4276 (Opc == BO_NE || Opc == BO_EQ))) {
4278 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4279 castExpr, exprACTC, CCK);
4285 /// Given that we saw an expression with the ARCUnbridgedCastTy
4286 /// placeholder type, complain bitterly.
4287 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4288 // We expect the spurious ImplicitCastExpr to already have been stripped.
4289 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4290 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4292 SourceRange castRange;
4294 CheckedConversionKind CCK;
4296 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4297 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4298 castType = cast->getTypeAsWritten();
4299 CCK = CCK_CStyleCast;
4300 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4301 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4302 castType = cast->getTypeAsWritten();
4303 CCK = CCK_OtherCast;
4305 llvm_unreachable("Unexpected ImplicitCastExpr");
4308 ARCConversionTypeClass castACTC =
4309 classifyTypeForARCConversion(castType.getNonReferenceType());
4311 Expr *castExpr = realCast->getSubExpr();
4312 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4314 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4315 castExpr, realCast, ACTC_retainable, CCK);
4318 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4319 /// type, remove the placeholder cast.
4320 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4321 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4323 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4324 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4325 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4326 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4327 assert(uo->getOpcode() == UO_Extension);
4328 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4329 return new (Context)
4330 UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(),
4331 sub->getObjectKind(), uo->getOperatorLoc(), false);
4332 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4333 assert(!gse->isResultDependent());
4335 unsigned n = gse->getNumAssocs();
4336 SmallVector<Expr*, 4> subExprs(n);
4337 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4338 for (unsigned i = 0; i != n; ++i) {
4339 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4340 Expr *sub = gse->getAssocExpr(i);
4341 if (i == gse->getResultIndex())
4342 sub = stripARCUnbridgedCast(sub);
4346 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4347 gse->getControllingExpr(),
4349 gse->getDefaultLoc(),
4350 gse->getRParenLoc(),
4351 gse->containsUnexpandedParameterPack(),
4352 gse->getResultIndex());
4354 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4355 return cast<ImplicitCastExpr>(e)->getSubExpr();
4359 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4360 QualType exprType) {
4361 QualType canCastType =
4362 Context.getCanonicalType(castType).getUnqualifiedType();
4363 QualType canExprType =
4364 Context.getCanonicalType(exprType).getUnqualifiedType();
4365 if (isa<ObjCObjectPointerType>(canCastType) &&
4366 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4367 canExprType->isObjCObjectPointerType()) {
4368 if (const ObjCObjectPointerType *ObjT =
4369 canExprType->getAs<ObjCObjectPointerType>())
4370 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4371 return !ObjI->isArcWeakrefUnavailable();
4376 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4377 static Expr *maybeUndoReclaimObject(Expr *e) {
4378 Expr *curExpr = e, *prevExpr = nullptr;
4380 // Walk down the expression until we hit an implicit cast of kind
4381 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4383 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4385 curExpr = pe->getSubExpr();
4389 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4390 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4391 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4393 return ice->getSubExpr();
4394 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4395 pe->setSubExpr(ice->getSubExpr());
4397 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4402 curExpr = ce->getSubExpr();
4406 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4413 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4414 ObjCBridgeCastKind Kind,
4415 SourceLocation BridgeKeywordLoc,
4416 TypeSourceInfo *TSInfo,
4418 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4419 if (SubResult.isInvalid()) return ExprError();
4420 SubExpr = SubResult.get();
4422 QualType T = TSInfo->getType();
4423 QualType FromType = SubExpr->getType();
4427 bool MustConsume = false;
4428 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4429 // Okay: we'll build a dependent expression type.
4431 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4433 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4434 : CK_CPointerToObjCPointerCast);
4439 case OBC_BridgeRetained: {
4440 bool br = isKnownName("CFBridgingRelease");
4441 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4444 << (T->isBlockPointerType()? 1 : 0)
4446 << SubExpr->getSourceRange()
4448 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4449 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4450 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4452 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4453 br ? "CFBridgingRelease "
4454 : "__bridge_transfer ");
4460 case OBC_BridgeTransfer:
4461 // We must consume the Objective-C object produced by the cast.
4465 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4470 // Reclaiming a value that's going to be __bridge-casted to CF
4471 // is very dangerous, so we don't do it.
4472 SubExpr = maybeUndoReclaimObject(SubExpr);
4475 case OBC_BridgeRetained:
4476 // Produce the object before casting it.
4477 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4478 CK_ARCProduceObject,
4479 SubExpr, nullptr, VK_RValue);
4482 case OBC_BridgeTransfer: {
4483 bool br = isKnownName("CFBridgingRetain");
4484 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4485 << (FromType->isBlockPointerType()? 1 : 0)
4489 << SubExpr->getSourceRange()
4492 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4493 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4494 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4496 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4497 br ? "CFBridgingRetain " : "__bridge_retained");
4504 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4505 << FromType << T << Kind
4506 << SubExpr->getSourceRange()
4507 << TSInfo->getTypeLoc().getSourceRange();
4511 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4516 Cleanup.setExprNeedsCleanups(true);
4517 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4518 nullptr, VK_RValue);
4524 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4525 SourceLocation LParenLoc,
4526 ObjCBridgeCastKind Kind,
4527 SourceLocation BridgeKeywordLoc,
4529 SourceLocation RParenLoc,
4531 TypeSourceInfo *TSInfo = nullptr;
4532 QualType T = GetTypeFromParser(Type, &TSInfo);
4533 if (Kind == OBC_Bridge)
4534 CheckTollFreeBridgeCast(T, SubExpr);
4536 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4537 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,