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->getLocStart(), 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->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
111 << 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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 /// \brief 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
403 = InitializationKind::CreateCopy(Element->getLocStart(),
405 InitializationSequence Seq(S, Entity, Kind, Element);
407 return Seq.Perform(S, Entity, Kind, Element);
410 Expr *OrigElement = Element;
412 // Perform lvalue-to-rvalue conversion.
413 Result = S.DefaultLvalueConversion(Element);
414 if (Result.isInvalid())
416 Element = Result.get();
418 // Make sure that we have an Objective-C pointer type or block.
419 if (!Element->getType()->isObjCObjectPointerType() &&
420 !Element->getType()->isBlockPointerType()) {
421 bool Recovered = false;
423 // If this is potentially an Objective-C numeric literal, add the '@'.
424 if (isa<IntegerLiteral>(OrigElement) ||
425 isa<CharacterLiteral>(OrigElement) ||
426 isa<FloatingLiteral>(OrigElement) ||
427 isa<ObjCBoolLiteralExpr>(OrigElement) ||
428 isa<CXXBoolLiteralExpr>(OrigElement)) {
429 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
430 int Which = isa<CharacterLiteral>(OrigElement) ? 1
431 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
432 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
435 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
436 << Which << OrigElement->getSourceRange()
437 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
439 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
441 if (Result.isInvalid())
444 Element = Result.get();
448 // If this is potentially an Objective-C string literal, add the '@'.
449 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
450 if (String->isAscii()) {
451 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
452 << 0 << OrigElement->getSourceRange()
453 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
455 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
456 if (Result.isInvalid())
459 Element = Result.get();
465 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
466 << Element->getType();
471 if (ObjCStringLiteral *getString =
472 dyn_cast<ObjCStringLiteral>(OrigElement)) {
473 if (StringLiteral *SL = getString->getString()) {
474 unsigned numConcat = SL->getNumConcatenated();
476 // Only warn if the concatenated string doesn't come from a macro.
477 bool hasMacro = false;
478 for (unsigned i = 0; i < numConcat ; ++i)
479 if (SL->getStrTokenLoc(i).isMacroID()) {
484 S.Diag(Element->getLocStart(),
485 diag::warn_concatenated_nsarray_literal)
486 << Element->getType();
491 // Make sure that the element has the type that the container factory
493 return S.PerformCopyInitialization(
494 InitializedEntity::InitializeParameter(S.Context, T,
496 Element->getLocStart(), Element);
499 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
500 if (ValueExpr->isTypeDependent()) {
501 ObjCBoxedExpr *BoxedExpr =
502 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
505 ObjCMethodDecl *BoxingMethod = nullptr;
507 // Convert the expression to an RValue, so we can check for pointer types...
508 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
509 if (RValue.isInvalid()) {
512 SourceLocation Loc = SR.getBegin();
513 ValueExpr = RValue.get();
514 QualType ValueType(ValueExpr->getType());
515 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
516 QualType PointeeType = PT->getPointeeType();
517 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
520 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
525 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
526 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
529 if (!StringWithUTF8StringMethod) {
530 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
531 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
533 // Look for the appropriate method within NSString.
534 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
535 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
536 // Debugger needs to work even if NSString hasn't been defined.
537 TypeSourceInfo *ReturnTInfo = nullptr;
538 ObjCMethodDecl *M = ObjCMethodDecl::Create(
539 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
540 NSStringPointer, ReturnTInfo, NSStringDecl,
541 /*isInstance=*/false, /*isVariadic=*/false,
542 /*isPropertyAccessor=*/false,
543 /*isImplicitlyDeclared=*/true,
544 /*isDefined=*/false, ObjCMethodDecl::Required,
545 /*HasRelatedResultType=*/false);
546 QualType ConstCharType = Context.CharTy.withConst();
548 ParmVarDecl::Create(Context, M,
549 SourceLocation(), SourceLocation(),
550 &Context.Idents.get("value"),
551 Context.getPointerType(ConstCharType),
554 M->setMethodParams(Context, value, None);
558 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
559 stringWithUTF8String, BoxingMethod))
562 StringWithUTF8StringMethod = BoxingMethod;
565 BoxingMethod = StringWithUTF8StringMethod;
566 BoxedType = NSStringPointer;
568 } else if (ValueType->isBuiltinType()) {
569 // The other types we support are numeric, char and BOOL/bool. We could also
570 // provide limited support for structure types, such as NSRange, NSRect, and
571 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
574 // Check for a top-level character literal.
575 if (const CharacterLiteral *Char =
576 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
577 // In C, character literals have type 'int'. That's not the type we want
578 // to use to determine the Objective-c literal kind.
579 switch (Char->getKind()) {
580 case CharacterLiteral::Ascii:
581 case CharacterLiteral::UTF8:
582 ValueType = Context.CharTy;
585 case CharacterLiteral::Wide:
586 ValueType = Context.getWideCharType();
589 case CharacterLiteral::UTF16:
590 ValueType = Context.Char16Ty;
593 case CharacterLiteral::UTF32:
594 ValueType = Context.Char32Ty;
598 CheckForIntOverflow(ValueExpr);
599 // FIXME: Do I need to do anything special with BoolTy expressions?
601 // Look for the appropriate method within NSNumber.
602 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
603 BoxedType = NSNumberPointer;
604 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
605 if (!ET->getDecl()->isComplete()) {
606 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
607 << ValueType << ValueExpr->getSourceRange();
611 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
612 ET->getDecl()->getIntegerType());
613 BoxedType = NSNumberPointer;
614 } else if (ValueType->isObjCBoxableRecordType()) {
615 // Support for structure types, that marked as objc_boxable
616 // struct __attribute__((objc_boxable)) s { ... };
618 // Look up the NSValue class, if we haven't done so already. It's cached
619 // in the Sema instance.
621 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
627 // generate the pointer to NSValue type.
628 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
629 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
632 if (!ValueWithBytesObjCTypeMethod) {
633 IdentifierInfo *II[] = {
634 &Context.Idents.get("valueWithBytes"),
635 &Context.Idents.get("objCType")
637 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
639 // Look for the appropriate method within NSValue.
640 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
641 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
642 // Debugger needs to work even if NSValue hasn't been defined.
643 TypeSourceInfo *ReturnTInfo = nullptr;
644 ObjCMethodDecl *M = ObjCMethodDecl::Create(
648 ValueWithBytesObjCType,
652 /*isInstance=*/false,
653 /*isVariadic=*/false,
654 /*isPropertyAccessor=*/false,
655 /*isImplicitlyDeclared=*/true,
657 ObjCMethodDecl::Required,
658 /*HasRelatedResultType=*/false);
660 SmallVector<ParmVarDecl *, 2> Params;
663 ParmVarDecl::Create(Context, M,
664 SourceLocation(), SourceLocation(),
665 &Context.Idents.get("bytes"),
666 Context.VoidPtrTy.withConst(),
669 Params.push_back(bytes);
671 QualType ConstCharType = Context.CharTy.withConst();
673 ParmVarDecl::Create(Context, M,
674 SourceLocation(), SourceLocation(),
675 &Context.Idents.get("type"),
676 Context.getPointerType(ConstCharType),
679 Params.push_back(type);
681 M->setMethodParams(Context, Params, None);
685 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
686 ValueWithBytesObjCType, BoxingMethod))
689 ValueWithBytesObjCTypeMethod = BoxingMethod;
692 if (!ValueType.isTriviallyCopyableType(Context)) {
693 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
694 << ValueType << ValueExpr->getSourceRange();
698 BoxingMethod = ValueWithBytesObjCTypeMethod;
699 BoxedType = NSValuePointer;
703 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
704 << ValueType << ValueExpr->getSourceRange();
708 DiagnoseUseOfDecl(BoxingMethod, Loc);
710 ExprResult ConvertedValueExpr;
711 if (ValueType->isObjCBoxableRecordType()) {
712 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
713 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
716 // Convert the expression to the type that the parameter requires.
717 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
718 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
720 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
724 if (ConvertedValueExpr.isInvalid())
726 ValueExpr = ConvertedValueExpr.get();
728 ObjCBoxedExpr *BoxedExpr =
729 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
731 return MaybeBindToTemporary(BoxedExpr);
734 /// Build an ObjC subscript pseudo-object expression, given that
735 /// that's supported by the runtime.
736 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
738 ObjCMethodDecl *getterMethod,
739 ObjCMethodDecl *setterMethod) {
740 assert(!LangOpts.isSubscriptPointerArithmetic());
742 // We can't get dependent types here; our callers should have
743 // filtered them out.
744 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
745 "base or index cannot have dependent type here");
747 // Filter out placeholders in the index. In theory, overloads could
748 // be preserved here, although that might not actually work correctly.
749 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
750 if (Result.isInvalid())
752 IndexExpr = Result.get();
754 // Perform lvalue-to-rvalue conversion on the base.
755 Result = DefaultLvalueConversion(BaseExpr);
756 if (Result.isInvalid())
758 BaseExpr = Result.get();
760 // Build the pseudo-object expression.
761 return new (Context) ObjCSubscriptRefExpr(
762 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
763 getterMethod, setterMethod, RB);
766 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
767 SourceLocation Loc = SR.getBegin();
770 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
777 // Find the arrayWithObjects:count: method, if we haven't done so already.
778 QualType IdT = Context.getObjCIdType();
779 if (!ArrayWithObjectsMethod) {
781 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
782 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
783 if (!Method && getLangOpts().DebuggerObjCLiteral) {
784 TypeSourceInfo *ReturnTInfo = nullptr;
785 Method = ObjCMethodDecl::Create(
786 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
787 Context.getTranslationUnitDecl(), false /*Instance*/,
788 false /*isVariadic*/,
789 /*isPropertyAccessor=*/false,
790 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
791 ObjCMethodDecl::Required, false);
792 SmallVector<ParmVarDecl *, 2> Params;
793 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
796 &Context.Idents.get("objects"),
797 Context.getPointerType(IdT),
800 Params.push_back(objects);
801 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
804 &Context.Idents.get("cnt"),
805 Context.UnsignedLongTy,
806 /*TInfo=*/nullptr, SC_None,
808 Params.push_back(cnt);
809 Method->setMethodParams(Context, Params, None);
812 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
815 // Dig out the type that all elements should be converted to.
816 QualType T = Method->parameters()[0]->getType();
817 const PointerType *PtrT = T->getAs<PointerType>();
819 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
820 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
822 Diag(Method->parameters()[0]->getLocation(),
823 diag::note_objc_literal_method_param)
825 << Context.getPointerType(IdT.withConst());
829 // Check that the 'count' parameter is integral.
830 if (!Method->parameters()[1]->getType()->isIntegerType()) {
831 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
833 Diag(Method->parameters()[1]->getLocation(),
834 diag::note_objc_literal_method_param)
836 << Method->parameters()[1]->getType()
841 // We've found a good +arrayWithObjects:count: method. Save it!
842 ArrayWithObjectsMethod = Method;
845 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
846 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
848 // Check that each of the elements provided is valid in a collection literal,
849 // performing conversions as necessary.
850 Expr **ElementsBuffer = Elements.data();
851 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
852 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
855 if (Converted.isInvalid())
858 ElementsBuffer[I] = Converted.get();
862 = Context.getObjCObjectPointerType(
863 Context.getObjCInterfaceType(NSArrayDecl));
865 return MaybeBindToTemporary(
866 ObjCArrayLiteral::Create(Context, Elements, Ty,
867 ArrayWithObjectsMethod, SR));
870 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
871 MutableArrayRef<ObjCDictionaryElement> Elements) {
872 SourceLocation Loc = SR.getBegin();
874 if (!NSDictionaryDecl) {
875 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
876 Sema::LK_Dictionary);
877 if (!NSDictionaryDecl) {
882 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
884 QualType IdT = Context.getObjCIdType();
885 if (!DictionaryWithObjectsMethod) {
886 Selector Sel = NSAPIObj->getNSDictionarySelector(
887 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
888 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
889 if (!Method && getLangOpts().DebuggerObjCLiteral) {
890 Method = ObjCMethodDecl::Create(Context,
891 SourceLocation(), SourceLocation(), Sel,
893 nullptr /*TypeSourceInfo */,
894 Context.getTranslationUnitDecl(),
895 false /*Instance*/, false/*isVariadic*/,
896 /*isPropertyAccessor=*/false,
897 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
898 ObjCMethodDecl::Required,
900 SmallVector<ParmVarDecl *, 3> Params;
901 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
904 &Context.Idents.get("objects"),
905 Context.getPointerType(IdT),
906 /*TInfo=*/nullptr, SC_None,
908 Params.push_back(objects);
909 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
912 &Context.Idents.get("keys"),
913 Context.getPointerType(IdT),
914 /*TInfo=*/nullptr, SC_None,
916 Params.push_back(keys);
917 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
920 &Context.Idents.get("cnt"),
921 Context.UnsignedLongTy,
922 /*TInfo=*/nullptr, SC_None,
924 Params.push_back(cnt);
925 Method->setMethodParams(Context, Params, None);
928 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
932 // Dig out the type that all values should be converted to.
933 QualType ValueT = Method->parameters()[0]->getType();
934 const PointerType *PtrValue = ValueT->getAs<PointerType>();
936 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
937 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
939 Diag(Method->parameters()[0]->getLocation(),
940 diag::note_objc_literal_method_param)
942 << Context.getPointerType(IdT.withConst());
946 // Dig out the type that all keys should be converted to.
947 QualType KeyT = Method->parameters()[1]->getType();
948 const PointerType *PtrKey = KeyT->getAs<PointerType>();
950 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
954 if (QIDNSCopying.isNull()) {
955 // key argument of selector is id<NSCopying>?
956 if (ObjCProtocolDecl *NSCopyingPDecl =
957 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
958 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
960 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
962 (ObjCProtocolDecl**) PQ,
965 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
968 if (!QIDNSCopying.isNull())
969 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
974 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
976 Diag(Method->parameters()[1]->getLocation(),
977 diag::note_objc_literal_method_param)
979 << Context.getPointerType(IdT.withConst());
984 // Check that the 'count' parameter is integral.
985 QualType CountType = Method->parameters()[2]->getType();
986 if (!CountType->isIntegerType()) {
987 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
989 Diag(Method->parameters()[2]->getLocation(),
990 diag::note_objc_literal_method_param)
996 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
997 DictionaryWithObjectsMethod = Method;
1000 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1001 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1002 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1003 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1005 // Check that each of the keys and values provided is valid in a collection
1006 // literal, performing conversions as necessary.
1007 bool HasPackExpansions = false;
1008 for (ObjCDictionaryElement &Element : Elements) {
1010 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1012 if (Key.isInvalid())
1017 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1018 if (Value.isInvalid())
1021 Element.Key = Key.get();
1022 Element.Value = Value.get();
1024 if (Element.EllipsisLoc.isInvalid())
1027 if (!Element.Key->containsUnexpandedParameterPack() &&
1028 !Element.Value->containsUnexpandedParameterPack()) {
1029 Diag(Element.EllipsisLoc,
1030 diag::err_pack_expansion_without_parameter_packs)
1031 << SourceRange(Element.Key->getLocStart(),
1032 Element.Value->getLocEnd());
1036 HasPackExpansions = true;
1040 = Context.getObjCObjectPointerType(
1041 Context.getObjCInterfaceType(NSDictionaryDecl));
1042 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1043 Context, Elements, HasPackExpansions, Ty,
1044 DictionaryWithObjectsMethod, SR));
1047 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1048 TypeSourceInfo *EncodedTypeInfo,
1049 SourceLocation RParenLoc) {
1050 QualType EncodedType = EncodedTypeInfo->getType();
1052 if (EncodedType->isDependentType())
1053 StrTy = Context.DependentTy;
1055 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1056 !EncodedType->isVoidType()) // void is handled too.
1057 if (RequireCompleteType(AtLoc, EncodedType,
1058 diag::err_incomplete_type_objc_at_encode,
1059 EncodedTypeInfo->getTypeLoc()))
1063 QualType NotEncodedT;
1064 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1065 if (!NotEncodedT.isNull())
1066 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1067 << EncodedType << NotEncodedT;
1069 // The type of @encode is the same as the type of the corresponding string,
1070 // which is an array type.
1071 StrTy = Context.CharTy;
1072 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1073 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1075 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1076 ArrayType::Normal, 0);
1079 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1082 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1083 SourceLocation EncodeLoc,
1084 SourceLocation LParenLoc,
1086 SourceLocation RParenLoc) {
1087 // FIXME: Preserve type source info ?
1088 TypeSourceInfo *TInfo;
1089 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1091 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1092 getLocForEndOfToken(LParenLoc));
1094 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1097 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1098 SourceLocation AtLoc,
1099 SourceLocation LParenLoc,
1100 SourceLocation RParenLoc,
1101 ObjCMethodDecl *Method,
1102 ObjCMethodList &MethList) {
1103 ObjCMethodList *M = &MethList;
1104 bool Warned = false;
1105 for (M = M->getNext(); M; M=M->getNext()) {
1106 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1107 if (MatchingMethodDecl == Method ||
1108 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1109 MatchingMethodDecl->getSelector() != Method->getSelector())
1111 if (!S.MatchTwoMethodDeclarations(Method,
1112 MatchingMethodDecl, Sema::MMS_loose)) {
1115 S.Diag(AtLoc, diag::warn_multiple_selectors)
1116 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1117 << FixItHint::CreateInsertion(RParenLoc, ")");
1118 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1119 << Method->getDeclName();
1121 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1122 << MatchingMethodDecl->getDeclName();
1128 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1129 ObjCMethodDecl *Method,
1130 SourceLocation LParenLoc,
1131 SourceLocation RParenLoc,
1132 bool WarnMultipleSelectors) {
1133 if (!WarnMultipleSelectors ||
1134 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1136 bool Warned = false;
1137 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1138 e = S.MethodPool.end(); b != e; b++) {
1139 // first, instance methods
1140 ObjCMethodList &InstMethList = b->second.first;
1141 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1142 Method, InstMethList))
1145 // second, class methods
1146 ObjCMethodList &ClsMethList = b->second.second;
1147 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1148 Method, ClsMethList) || Warned)
1153 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1154 SourceLocation AtLoc,
1155 SourceLocation SelLoc,
1156 SourceLocation LParenLoc,
1157 SourceLocation RParenLoc,
1158 bool WarnMultipleSelectors) {
1159 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1160 SourceRange(LParenLoc, RParenLoc));
1162 Method = LookupFactoryMethodInGlobalPool(Sel,
1163 SourceRange(LParenLoc, RParenLoc));
1165 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1166 Selector MatchedSel = OM->getSelector();
1167 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1168 RParenLoc.getLocWithOffset(-1));
1169 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1170 << Sel << MatchedSel
1171 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1174 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1176 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1177 WarnMultipleSelectors);
1180 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1181 !getSourceManager().isInSystemHeader(Method->getLocation()))
1182 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1184 // In ARC, forbid the user from using @selector for
1185 // retain/release/autorelease/dealloc/retainCount.
1186 if (getLangOpts().ObjCAutoRefCount) {
1187 switch (Sel.getMethodFamily()) {
1190 case OMF_autorelease:
1191 case OMF_retainCount:
1193 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1194 Sel << SourceRange(LParenLoc, RParenLoc);
1202 case OMF_mutableCopy:
1205 case OMF_initialize:
1206 case OMF_performSelector:
1210 QualType Ty = Context.getObjCSelType();
1211 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1214 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1215 SourceLocation AtLoc,
1216 SourceLocation ProtoLoc,
1217 SourceLocation LParenLoc,
1218 SourceLocation ProtoIdLoc,
1219 SourceLocation RParenLoc) {
1220 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1222 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1225 if (PDecl->hasDefinition())
1226 PDecl = PDecl->getDefinition();
1228 QualType Ty = Context.getObjCProtoType();
1231 Ty = Context.getObjCObjectPointerType(Ty);
1232 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1235 /// Try to capture an implicit reference to 'self'.
1236 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1237 DeclContext *DC = getFunctionLevelDeclContext();
1239 // If we're not in an ObjC method, error out. Note that, unlike the
1240 // C++ case, we don't require an instance method --- class methods
1241 // still have a 'self', and we really do still need to capture it!
1242 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1246 tryCaptureVariable(method->getSelfDecl(), Loc);
1251 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1252 QualType origType = T;
1253 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1254 if (T == Context.getObjCInstanceType()) {
1255 return Context.getAttributedType(
1256 AttributedType::getNullabilityAttrKind(*nullability),
1257 Context.getObjCIdType(),
1258 Context.getObjCIdType());
1264 if (T == Context.getObjCInstanceType())
1265 return Context.getObjCIdType();
1270 /// Determine the result type of a message send based on the receiver type,
1271 /// method, and the kind of message send.
1273 /// This is the "base" result type, which will still need to be adjusted
1274 /// to account for nullability.
1275 static QualType getBaseMessageSendResultType(Sema &S,
1276 QualType ReceiverType,
1277 ObjCMethodDecl *Method,
1278 bool isClassMessage,
1279 bool isSuperMessage) {
1280 assert(Method && "Must have a method");
1281 if (!Method->hasRelatedResultType())
1282 return Method->getSendResultType(ReceiverType);
1284 ASTContext &Context = S.Context;
1286 // Local function that transfers the nullability of the method's
1287 // result type to the returned result.
1288 auto transferNullability = [&](QualType type) -> QualType {
1289 // If the method's result type has nullability, extract it.
1290 if (auto nullability = Method->getSendResultType(ReceiverType)
1291 ->getNullability(Context)){
1292 // Strip off any outer nullability sugar from the provided type.
1293 (void)AttributedType::stripOuterNullability(type);
1295 // Form a new attributed type using the method result type's nullability.
1296 return Context.getAttributedType(
1297 AttributedType::getNullabilityAttrKind(*nullability),
1305 // If a method has a related return type:
1306 // - if the method found is an instance method, but the message send
1307 // was a class message send, T is the declared return type of the method
1309 if (Method->isInstanceMethod() && isClassMessage)
1310 return stripObjCInstanceType(Context,
1311 Method->getSendResultType(ReceiverType));
1313 // - if the receiver is super, T is a pointer to the class of the
1314 // enclosing method definition
1315 if (isSuperMessage) {
1316 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1317 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1318 return transferNullability(
1319 Context.getObjCObjectPointerType(
1320 Context.getObjCInterfaceType(Class)));
1324 // - if the receiver is the name of a class U, T is a pointer to U
1325 if (ReceiverType->getAsObjCInterfaceType())
1326 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1327 // - if the receiver is of type Class or qualified Class type,
1328 // T is the declared return type of the method.
1329 if (ReceiverType->isObjCClassType() ||
1330 ReceiverType->isObjCQualifiedClassType())
1331 return stripObjCInstanceType(Context,
1332 Method->getSendResultType(ReceiverType));
1334 // - if the receiver is id, qualified id, Class, or qualified Class, T
1335 // is the receiver type, otherwise
1336 // - T is the type of the receiver expression.
1337 return transferNullability(ReceiverType);
1340 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1341 ObjCMethodDecl *Method,
1342 bool isClassMessage,
1343 bool isSuperMessage) {
1344 // Produce the result type.
1345 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1350 // If this is a class message, ignore the nullability of the receiver.
1354 // Map the nullability of the result into a table index.
1355 unsigned receiverNullabilityIdx = 0;
1356 if (auto nullability = ReceiverType->getNullability(Context))
1357 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1359 unsigned resultNullabilityIdx = 0;
1360 if (auto nullability = resultType->getNullability(Context))
1361 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1363 // The table of nullability mappings, indexed by the receiver's nullability
1364 // and then the result type's nullability.
1365 static const uint8_t None = 0;
1366 static const uint8_t NonNull = 1;
1367 static const uint8_t Nullable = 2;
1368 static const uint8_t Unspecified = 3;
1369 static const uint8_t nullabilityMap[4][4] = {
1370 // None NonNull Nullable Unspecified
1371 /* None */ { None, None, Nullable, None },
1372 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1373 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1374 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1377 unsigned newResultNullabilityIdx
1378 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1379 if (newResultNullabilityIdx == resultNullabilityIdx)
1382 // Strip off the existing nullability. This removes as little type sugar as
1385 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1386 resultType = attributed->getModifiedType();
1388 resultType = resultType.getDesugaredType(Context);
1390 } while (resultType->getNullability(Context));
1392 // Add nullability back if needed.
1393 if (newResultNullabilityIdx > 0) {
1395 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1396 return Context.getAttributedType(
1397 AttributedType::getNullabilityAttrKind(newNullability),
1398 resultType, resultType);
1404 /// Look for an ObjC method whose result type exactly matches the given type.
1405 static const ObjCMethodDecl *
1406 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1407 QualType instancetype) {
1408 if (MD->getReturnType() == instancetype)
1411 // For these purposes, a method in an @implementation overrides a
1412 // declaration in the @interface.
1413 if (const ObjCImplDecl *impl =
1414 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1415 const ObjCContainerDecl *iface;
1416 if (const ObjCCategoryImplDecl *catImpl =
1417 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1418 iface = catImpl->getCategoryDecl();
1420 iface = impl->getClassInterface();
1423 const ObjCMethodDecl *ifaceMD =
1424 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1425 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1428 SmallVector<const ObjCMethodDecl *, 4> overrides;
1429 MD->getOverriddenMethods(overrides);
1430 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1431 if (const ObjCMethodDecl *result =
1432 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1439 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1440 // Only complain if we're in an ObjC method and the required return
1441 // type doesn't match the method's declared return type.
1442 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1443 if (!MD || !MD->hasRelatedResultType() ||
1444 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1447 // Look for a method overridden by this method which explicitly uses
1449 if (const ObjCMethodDecl *overridden =
1450 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1451 SourceRange range = overridden->getReturnTypeSourceRange();
1452 SourceLocation loc = range.getBegin();
1453 if (loc.isInvalid())
1454 loc = overridden->getLocation();
1455 Diag(loc, diag::note_related_result_type_explicit)
1456 << /*current method*/ 1 << range;
1460 // Otherwise, if we have an interesting method family, note that.
1461 // This should always trigger if the above didn't.
1462 if (ObjCMethodFamily family = MD->getMethodFamily())
1463 Diag(MD->getLocation(), diag::note_related_result_type_family)
1464 << /*current method*/ 1
1468 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1469 E = E->IgnoreParenImpCasts();
1470 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1474 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1478 if (!Method->hasRelatedResultType())
1481 if (Context.hasSameUnqualifiedType(
1482 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1485 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1486 Context.getObjCInstanceType()))
1489 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1490 << Method->isInstanceMethod() << Method->getSelector()
1491 << MsgSend->getType();
1494 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1497 ArrayRef<SourceLocation> SelectorLocs,
1498 ObjCMethodDecl *Method,
1499 bool isClassMessage, bool isSuperMessage,
1500 SourceLocation lbrac, SourceLocation rbrac,
1501 SourceRange RecRange,
1502 QualType &ReturnType, ExprValueKind &VK) {
1503 SourceLocation SelLoc;
1504 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1505 SelLoc = SelectorLocs.front();
1510 // Apply default argument promotion as for (C99 6.5.2.2p6).
1511 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1512 if (Args[i]->isTypeDependent())
1516 if (getLangOpts().DebuggerSupport) {
1517 QualType paramTy; // ignored
1518 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1520 result = DefaultArgumentPromotion(Args[i]);
1522 if (result.isInvalid())
1524 Args[i] = result.get();
1528 if (getLangOpts().ObjCAutoRefCount)
1529 DiagID = diag::err_arc_method_not_found;
1531 DiagID = isClassMessage ? diag::warn_class_method_not_found
1532 : diag::warn_inst_method_not_found;
1533 if (!getLangOpts().DebuggerSupport) {
1534 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1535 if (OMD && !OMD->isInvalidDecl()) {
1536 if (getLangOpts().ObjCAutoRefCount)
1537 DiagID = diag::err_method_not_found_with_typo;
1539 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1540 : diag::warn_instance_method_not_found_with_typo;
1541 Selector MatchedSel = OMD->getSelector();
1542 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1543 if (MatchedSel.isUnarySelector())
1544 Diag(SelLoc, DiagID)
1545 << Sel<< isClassMessage << MatchedSel
1546 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1548 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1551 Diag(SelLoc, DiagID)
1552 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1553 SelectorLocs.back());
1554 // Find the class to which we are sending this message.
1555 if (ReceiverType->isObjCObjectPointerType()) {
1556 if (ObjCInterfaceDecl *ThisClass =
1557 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1558 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1559 if (!RecRange.isInvalid())
1560 if (ThisClass->lookupClassMethod(Sel))
1561 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1562 << FixItHint::CreateReplacement(RecRange,
1563 ThisClass->getNameAsString());
1568 // In debuggers, we want to use __unknown_anytype for these
1569 // results so that clients can cast them.
1570 if (getLangOpts().DebuggerSupport) {
1571 ReturnType = Context.UnknownAnyTy;
1573 ReturnType = Context.getObjCIdType();
1579 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1581 VK = Expr::getValueKindForType(Method->getReturnType());
1583 unsigned NumNamedArgs = Sel.getNumArgs();
1584 // Method might have more arguments than selector indicates. This is due
1585 // to addition of c-style arguments in method.
1586 if (Method->param_size() > Sel.getNumArgs())
1587 NumNamedArgs = Method->param_size();
1588 // FIXME. This need be cleaned up.
1589 if (Args.size() < NumNamedArgs) {
1590 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1591 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1595 // Compute the set of type arguments to be substituted into each parameter
1597 Optional<ArrayRef<QualType>> typeArgs
1598 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1599 bool IsError = false;
1600 for (unsigned i = 0; i < NumNamedArgs; i++) {
1601 // We can't do any type-checking on a type-dependent argument.
1602 if (Args[i]->isTypeDependent())
1605 Expr *argExpr = Args[i];
1607 ParmVarDecl *param = Method->parameters()[i];
1608 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1610 // Strip the unbridged-cast placeholder expression off unless it's
1611 // a consumed argument.
1612 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1613 !param->hasAttr<CFConsumedAttr>())
1614 argExpr = stripARCUnbridgedCast(argExpr);
1616 // If the parameter is __unknown_anytype, infer its type
1617 // from the argument.
1618 if (param->getType() == Context.UnknownAnyTy) {
1620 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1621 if (argE.isInvalid()) {
1624 Args[i] = argE.get();
1626 // Update the parameter type in-place.
1627 param->setType(paramType);
1632 QualType origParamType = param->getType();
1633 QualType paramType = param->getType();
1635 paramType = paramType.substObjCTypeArgs(
1638 ObjCSubstitutionContext::Parameter);
1640 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1642 diag::err_call_incomplete_argument, argExpr))
1645 InitializedEntity Entity
1646 = InitializedEntity::InitializeParameter(Context, param, paramType);
1647 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1648 if (ArgE.isInvalid())
1651 Args[i] = ArgE.getAs<Expr>();
1653 // If we are type-erasing a block to a block-compatible
1654 // Objective-C pointer type, we may need to extend the lifetime
1655 // of the block object.
1656 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1657 Args[i]->getType()->isBlockPointerType() &&
1658 origParamType->isObjCObjectPointerType()) {
1659 ExprResult arg = Args[i];
1660 maybeExtendBlockObject(arg);
1661 Args[i] = arg.get();
1666 // Promote additional arguments to variadic methods.
1667 if (Method->isVariadic()) {
1668 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1669 if (Args[i]->isTypeDependent())
1672 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1674 IsError |= Arg.isInvalid();
1675 Args[i] = Arg.get();
1678 // Check for extra arguments to non-variadic methods.
1679 if (Args.size() != NumNamedArgs) {
1680 Diag(Args[NumNamedArgs]->getLocStart(),
1681 diag::err_typecheck_call_too_many_args)
1682 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1683 << Method->getSourceRange()
1684 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1685 Args.back()->getLocEnd());
1689 DiagnoseSentinelCalls(Method, SelLoc, Args);
1691 // Do additional checkings on method.
1692 IsError |= CheckObjCMethodCall(
1693 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1698 bool Sema::isSelfExpr(Expr *RExpr) {
1699 // 'self' is objc 'self' in an objc method only.
1700 ObjCMethodDecl *Method =
1701 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1702 return isSelfExpr(RExpr, Method);
1705 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1706 if (!method) return false;
1708 receiver = receiver->IgnoreParenLValueCasts();
1709 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1710 if (DRE->getDecl() == method->getSelfDecl())
1715 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1716 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1718 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1719 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1720 // Look it up in the main interface (and categories, etc.)
1721 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1724 // Okay, look for "private" methods declared in any
1725 // @implementations we've seen.
1726 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1730 // Check qualifiers.
1731 for (const auto *I : objType->quals())
1732 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1738 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1739 /// list of a qualified objective pointer type.
1740 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1741 const ObjCObjectPointerType *OPT,
1744 ObjCMethodDecl *MD = nullptr;
1745 for (const auto *PROTO : OPT->quals()) {
1746 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1753 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1754 /// objective C interface. This is a property reference expression.
1756 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1757 Expr *BaseExpr, SourceLocation OpLoc,
1758 DeclarationName MemberName,
1759 SourceLocation MemberLoc,
1760 SourceLocation SuperLoc, QualType SuperType,
1762 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1763 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1765 if (!MemberName.isIdentifier()) {
1766 Diag(MemberLoc, diag::err_invalid_property_name)
1767 << MemberName << QualType(OPT, 0);
1771 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1773 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1774 : BaseExpr->getSourceRange();
1775 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1776 diag::err_property_not_found_forward_class,
1777 MemberName, BaseRange))
1780 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1781 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1782 // Check whether we can reference this property.
1783 if (DiagnoseUseOfDecl(PD, MemberLoc))
1786 return new (Context)
1787 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1788 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1790 return new (Context)
1791 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1792 OK_ObjCProperty, MemberLoc, BaseExpr);
1794 // Check protocols on qualified interfaces.
1795 for (const auto *I : OPT->quals())
1796 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
1797 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1798 // Check whether we can reference this property.
1799 if (DiagnoseUseOfDecl(PD, MemberLoc))
1803 return new (Context) ObjCPropertyRefExpr(
1804 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1805 SuperLoc, SuperType);
1807 return new (Context)
1808 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1809 OK_ObjCProperty, MemberLoc, BaseExpr);
1811 // If that failed, look for an "implicit" property by seeing if the nullary
1812 // selector is implemented.
1814 // FIXME: The logic for looking up nullary and unary selectors should be
1815 // shared with the code in ActOnInstanceMessage.
1817 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1818 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1820 // May be found in property's qualified list.
1822 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1824 // If this reference is in an @implementation, check for 'private' methods.
1826 Getter = IFace->lookupPrivateMethod(Sel);
1829 // Check if we can reference this property.
1830 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1833 // If we found a getter then this may be a valid dot-reference, we
1834 // will look for the matching setter, in case it is needed.
1835 Selector SetterSel =
1836 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1837 PP.getSelectorTable(), Member);
1838 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1840 // May be found in property's qualified list.
1842 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1845 // If this reference is in an @implementation, also check for 'private'
1847 Setter = IFace->lookupPrivateMethod(SetterSel);
1850 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1853 // Special warning if member name used in a property-dot for a setter accessor
1854 // does not use a property with same name; e.g. obj.X = ... for a property with
1856 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
1857 !IFace->FindPropertyDeclaration(
1858 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1859 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1860 // Do not warn if user is using property-dot syntax to make call to
1861 // user named setter.
1862 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1864 diag::warn_property_access_suggest)
1865 << MemberName << QualType(OPT, 0) << PDecl->getName()
1866 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1870 if (Getter || Setter) {
1872 return new (Context)
1873 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1874 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1876 return new (Context)
1877 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1878 OK_ObjCProperty, MemberLoc, BaseExpr);
1882 // Attempt to correct for typos in property names.
1883 if (TypoCorrection Corrected =
1884 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1885 LookupOrdinaryName, nullptr, nullptr,
1886 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1887 CTK_ErrorRecovery, IFace, false, OPT)) {
1888 DeclarationName TypoResult = Corrected.getCorrection();
1889 if (TypoResult.isIdentifier() &&
1890 TypoResult.getAsIdentifierInfo() == Member) {
1891 // There is no need to try the correction if it is the same.
1892 NamedDecl *ChosenDecl =
1893 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
1894 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
1895 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
1896 // This is a class property, we should not use the instance to
1898 Diag(MemberLoc, diag::err_class_property_found) << MemberName
1899 << OPT->getInterfaceDecl()->getName()
1900 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
1901 OPT->getInterfaceDecl()->getName());
1905 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1906 << MemberName << QualType(OPT, 0));
1907 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1908 TypoResult, MemberLoc,
1909 SuperLoc, SuperType, Super);
1912 ObjCInterfaceDecl *ClassDeclared;
1913 if (ObjCIvarDecl *Ivar =
1914 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1915 QualType T = Ivar->getType();
1916 if (const ObjCObjectPointerType * OBJPT =
1917 T->getAsObjCInterfacePointerType()) {
1918 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1919 diag::err_property_not_as_forward_class,
1920 MemberName, BaseExpr))
1924 diag::err_ivar_access_using_property_syntax_suggest)
1925 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1926 << FixItHint::CreateReplacement(OpLoc, "->");
1930 Diag(MemberLoc, diag::err_property_not_found)
1931 << MemberName << QualType(OPT, 0);
1933 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1934 << MemberName << BaseExpr->getSourceRange();
1939 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1940 IdentifierInfo &propertyName,
1941 SourceLocation receiverNameLoc,
1942 SourceLocation propertyNameLoc) {
1944 IdentifierInfo *receiverNamePtr = &receiverName;
1945 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1950 // If the "receiver" is 'super' in a method, handle it as an expression-like
1951 // property reference.
1952 if (receiverNamePtr->isStr("super")) {
1953 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1954 if (auto classDecl = CurMethod->getClassInterface()) {
1955 SuperType = QualType(classDecl->getSuperClassType(), 0);
1956 if (CurMethod->isInstanceMethod()) {
1957 if (SuperType.isNull()) {
1958 // The current class does not have a superclass.
1959 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
1960 << CurMethod->getClassInterface()->getIdentifier();
1963 QualType T = Context.getObjCObjectPointerType(SuperType);
1965 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
1966 /*BaseExpr*/nullptr,
1967 SourceLocation()/*OpLoc*/,
1970 receiverNameLoc, T, true);
1973 // Otherwise, if this is a class method, try dispatching to our
1975 IFace = CurMethod->getClassInterface()->getSuperClass();
1981 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1989 if (auto PD = IFace->FindPropertyDeclaration(
1990 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
1991 GetterSel = PD->getGetterName();
1992 SetterSel = PD->getSetterName();
1994 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
1995 SetterSel = SelectorTable::constructSetterSelector(
1996 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
1999 // Search for a declared property first.
2000 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2002 // If this reference is in an @implementation, check for 'private' methods.
2004 Getter = IFace->lookupPrivateClassMethod(GetterSel);
2007 // FIXME: refactor/share with ActOnMemberReference().
2008 // Check if we can reference this property.
2009 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2013 // Look for the matching setter, in case it is needed.
2014 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2016 // If this reference is in an @implementation, also check for 'private'
2018 Setter = IFace->lookupPrivateClassMethod(SetterSel);
2020 // Look through local category implementations associated with the class.
2022 Setter = IFace->getCategoryClassMethod(SetterSel);
2024 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2027 if (Getter || Setter) {
2028 if (!SuperType.isNull())
2029 return new (Context)
2030 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2031 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2034 return new (Context) ObjCPropertyRefExpr(
2035 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2036 propertyNameLoc, receiverNameLoc, IFace);
2038 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2039 << &propertyName << Context.getObjCInterfaceType(IFace));
2044 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2046 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2047 // Determine whether "super" is acceptable in the current context.
2048 if (Method && Method->getClassInterface())
2049 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2052 bool ValidateCandidate(const TypoCorrection &candidate) override {
2053 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2054 candidate.isKeyword("super");
2058 } // end anonymous namespace
2060 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2061 IdentifierInfo *Name,
2062 SourceLocation NameLoc,
2064 bool HasTrailingDot,
2065 ParsedType &ReceiverType) {
2066 ReceiverType = nullptr;
2068 // If the identifier is "super" and there is no trailing dot, we're
2069 // messaging super. If the identifier is "super" and there is a
2070 // trailing dot, it's an instance message.
2071 if (IsSuper && S->isInObjcMethodScope())
2072 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2074 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2075 LookupName(Result, S);
2077 switch (Result.getResultKind()) {
2078 case LookupResult::NotFound:
2079 // Normal name lookup didn't find anything. If we're in an
2080 // Objective-C method, look for ivars. If we find one, we're done!
2081 // FIXME: This is a hack. Ivar lookup should be part of normal
2083 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2084 if (!Method->getClassInterface()) {
2085 // Fall back: let the parser try to parse it as an instance message.
2086 return ObjCInstanceMessage;
2089 ObjCInterfaceDecl *ClassDeclared;
2090 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2092 return ObjCInstanceMessage;
2095 // Break out; we'll perform typo correction below.
2098 case LookupResult::NotFoundInCurrentInstantiation:
2099 case LookupResult::FoundOverloaded:
2100 case LookupResult::FoundUnresolvedValue:
2101 case LookupResult::Ambiguous:
2102 Result.suppressDiagnostics();
2103 return ObjCInstanceMessage;
2105 case LookupResult::Found: {
2106 // If the identifier is a class or not, and there is a trailing dot,
2107 // it's an instance message.
2109 return ObjCInstanceMessage;
2110 // We found something. If it's a type, then we have a class
2111 // message. Otherwise, it's an instance message.
2112 NamedDecl *ND = Result.getFoundDecl();
2114 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2115 T = Context.getObjCInterfaceType(Class);
2116 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2117 T = Context.getTypeDeclType(Type);
2118 DiagnoseUseOfDecl(Type, NameLoc);
2121 return ObjCInstanceMessage;
2123 // We have a class message, and T is the type we're
2124 // messaging. Build source-location information for it.
2125 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2126 ReceiverType = CreateParsedType(T, TSInfo);
2127 return ObjCClassMessage;
2131 if (TypoCorrection Corrected = CorrectTypo(
2132 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2133 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2134 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2135 if (Corrected.isKeyword()) {
2136 // If we've found the keyword "super" (the only keyword that would be
2137 // returned by CorrectTypo), this is a send to super.
2138 diagnoseTypo(Corrected,
2139 PDiag(diag::err_unknown_receiver_suggest) << Name);
2140 return ObjCSuperMessage;
2141 } else if (ObjCInterfaceDecl *Class =
2142 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2143 // If we found a declaration, correct when it refers to an Objective-C
2145 diagnoseTypo(Corrected,
2146 PDiag(diag::err_unknown_receiver_suggest) << Name);
2147 QualType T = Context.getObjCInterfaceType(Class);
2148 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2149 ReceiverType = CreateParsedType(T, TSInfo);
2150 return ObjCClassMessage;
2154 // Fall back: let the parser try to parse it as an instance message.
2155 return ObjCInstanceMessage;
2158 ExprResult Sema::ActOnSuperMessage(Scope *S,
2159 SourceLocation SuperLoc,
2161 SourceLocation LBracLoc,
2162 ArrayRef<SourceLocation> SelectorLocs,
2163 SourceLocation RBracLoc,
2164 MultiExprArg Args) {
2165 // Determine whether we are inside a method or not.
2166 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2168 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2172 ObjCInterfaceDecl *Class = Method->getClassInterface();
2174 Diag(SuperLoc, diag::err_no_super_class_message)
2175 << Method->getDeclName();
2179 QualType SuperTy(Class->getSuperClassType(), 0);
2180 if (SuperTy.isNull()) {
2181 // The current class does not have a superclass.
2182 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2183 << Class->getIdentifier();
2187 // We are in a method whose class has a superclass, so 'super'
2188 // is acting as a keyword.
2189 if (Method->getSelector() == Sel)
2190 getCurFunction()->ObjCShouldCallSuper = false;
2192 if (Method->isInstanceMethod()) {
2193 // Since we are in an instance method, this is an instance
2194 // message to the superclass instance.
2195 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2196 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2197 Sel, /*Method=*/nullptr,
2198 LBracLoc, SelectorLocs, RBracLoc, Args);
2201 // Since we are in a class method, this is a class message to
2203 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2205 SuperLoc, Sel, /*Method=*/nullptr,
2206 LBracLoc, SelectorLocs, RBracLoc, Args);
2209 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2210 bool isSuperReceiver,
2213 ObjCMethodDecl *Method,
2214 MultiExprArg Args) {
2215 TypeSourceInfo *receiverTypeInfo = nullptr;
2216 if (!ReceiverType.isNull())
2217 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2219 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2220 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2221 Sel, Method, Loc, Loc, Loc, Args,
2222 /*isImplicit=*/true);
2225 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2227 bool (*refactor)(const ObjCMessageExpr *,
2228 const NSAPI &, edit::Commit &)) {
2229 SourceLocation MsgLoc = Msg->getExprLoc();
2230 if (S.Diags.isIgnored(DiagID, MsgLoc))
2233 SourceManager &SM = S.SourceMgr;
2234 edit::Commit ECommit(SM, S.LangOpts);
2235 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2236 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2237 << Msg->getSelector() << Msg->getSourceRange();
2238 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2239 if (!ECommit.isCommitable())
2241 for (edit::Commit::edit_iterator
2242 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2243 const edit::Commit::Edit &Edit = *I;
2244 switch (Edit.Kind) {
2245 case edit::Commit::Act_Insert:
2246 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2250 case edit::Commit::Act_InsertFromRange:
2251 Builder.AddFixItHint(
2252 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2253 Edit.getInsertFromRange(SM),
2256 case edit::Commit::Act_Remove:
2257 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2264 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2265 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2266 edit::rewriteObjCRedundantCallWithLiteral);
2269 static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2270 const ObjCMethodDecl *Method,
2271 ArrayRef<Expr *> Args, QualType ReceiverType,
2272 bool IsClassObjectCall) {
2273 // Check if this is a performSelector method that uses a selector that returns
2274 // a record or a vector type.
2275 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2278 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2281 ObjCMethodDecl *ImpliedMethod;
2282 if (!IsClassObjectCall) {
2283 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2284 if (!OPT || !OPT->getInterfaceDecl())
2287 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2290 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2292 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2295 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2298 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2302 QualType Ret = ImpliedMethod->getReturnType();
2303 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2304 QualType Ret = ImpliedMethod->getReturnType();
2305 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2306 << Method->getSelector()
2307 << (!Ret->isRecordType()
2309 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2310 S.Diag(ImpliedMethod->getLocStart(),
2311 diag::note_objc_unsafe_perform_selector_method_declared_here)
2312 << ImpliedMethod->getSelector() << Ret;
2316 /// \brief Diagnose use of %s directive in an NSString which is being passed
2317 /// as formatting string to formatting method.
2319 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2320 ObjCMethodDecl *Method,
2322 Expr **Args, unsigned NumArgs) {
2324 bool Format = false;
2325 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2326 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2331 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2332 if (S.GetFormatNSStringIdx(I, Idx)) {
2338 if (!Format || NumArgs <= Idx)
2341 Expr *FormatExpr = Args[Idx];
2342 if (ObjCStringLiteral *OSL =
2343 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2344 StringLiteral *FormatString = OSL->getString();
2345 if (S.FormatStringHasSArg(FormatString)) {
2346 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2349 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2350 << Method->getDeclName();
2355 /// \brief Build an Objective-C class message expression.
2357 /// This routine takes care of both normal class messages and
2358 /// class messages to the superclass.
2360 /// \param ReceiverTypeInfo Type source information that describes the
2361 /// receiver of this message. This may be NULL, in which case we are
2362 /// sending to the superclass and \p SuperLoc must be a valid source
2365 /// \param ReceiverType The type of the object receiving the
2366 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2367 /// type as that refers to. For a superclass send, this is the type of
2370 /// \param SuperLoc The location of the "super" keyword in a
2371 /// superclass message.
2373 /// \param Sel The selector to which the message is being sent.
2375 /// \param Method The method that this class message is invoking, if
2378 /// \param LBracLoc The location of the opening square bracket ']'.
2380 /// \param RBracLoc The location of the closing square bracket ']'.
2382 /// \param ArgsIn The message arguments.
2383 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2384 QualType ReceiverType,
2385 SourceLocation SuperLoc,
2387 ObjCMethodDecl *Method,
2388 SourceLocation LBracLoc,
2389 ArrayRef<SourceLocation> SelectorLocs,
2390 SourceLocation RBracLoc,
2391 MultiExprArg ArgsIn,
2393 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2394 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2395 if (LBracLoc.isInvalid()) {
2396 Diag(Loc, diag::err_missing_open_square_message_send)
2397 << FixItHint::CreateInsertion(Loc, "[");
2400 SourceLocation SelLoc;
2401 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2402 SelLoc = SelectorLocs.front();
2406 if (ReceiverType->isDependentType()) {
2407 // If the receiver type is dependent, we can't type-check anything
2408 // at this point. Build a dependent expression.
2409 unsigned NumArgs = ArgsIn.size();
2410 Expr **Args = ArgsIn.data();
2411 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2412 return ObjCMessageExpr::Create(
2413 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2414 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2418 // Find the class to which we are sending this message.
2419 ObjCInterfaceDecl *Class = nullptr;
2420 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2421 if (!ClassType || !(Class = ClassType->getInterface())) {
2422 Diag(Loc, diag::err_invalid_receiver_class_message)
2426 assert(Class && "We don't know which class we're messaging?");
2427 // objc++ diagnoses during typename annotation.
2428 if (!getLangOpts().CPlusPlus)
2429 (void)DiagnoseUseOfDecl(Class, SelLoc);
2430 // Find the method we are messaging.
2432 SourceRange TypeRange
2433 = SuperLoc.isValid()? SourceRange(SuperLoc)
2434 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2435 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2436 (getLangOpts().ObjCAutoRefCount
2437 ? diag::err_arc_receiver_forward_class
2438 : diag::warn_receiver_forward_class),
2440 // A forward class used in messaging is treated as a 'Class'
2441 Method = LookupFactoryMethodInGlobalPool(Sel,
2442 SourceRange(LBracLoc, RBracLoc));
2443 if (Method && !getLangOpts().ObjCAutoRefCount)
2444 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2445 << Method->getDeclName();
2448 Method = Class->lookupClassMethod(Sel);
2450 // If we have an implementation in scope, check "private" methods.
2452 Method = Class->lookupPrivateClassMethod(Sel);
2454 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2458 // Check the argument types and determine the result type.
2459 QualType ReturnType;
2460 ExprValueKind VK = VK_RValue;
2462 unsigned NumArgs = ArgsIn.size();
2463 Expr **Args = ArgsIn.data();
2464 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2467 SuperLoc.isValid(), LBracLoc, RBracLoc,
2472 if (Method && !Method->getReturnType()->isVoidType() &&
2473 RequireCompleteType(LBracLoc, Method->getReturnType(),
2474 diag::err_illegal_message_expr_incomplete_type))
2477 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2478 if (Method && Method->getMethodFamily() == OMF_initialize) {
2479 if (!SuperLoc.isValid()) {
2480 const ObjCInterfaceDecl *ID =
2481 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2483 Diag(Loc, diag::warn_direct_initialize_call);
2484 Diag(Method->getLocation(), diag::note_method_declared_at)
2485 << Method->getDeclName();
2488 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2489 // [super initialize] is allowed only within an +initialize implementation
2490 if (CurMeth->getMethodFamily() != OMF_initialize) {
2491 Diag(Loc, diag::warn_direct_super_initialize_call);
2492 Diag(Method->getLocation(), diag::note_method_declared_at)
2493 << Method->getDeclName();
2494 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2495 << CurMeth->getDeclName();
2500 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2502 // Construct the appropriate ObjCMessageExpr.
2503 ObjCMessageExpr *Result;
2504 if (SuperLoc.isValid())
2505 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2506 SuperLoc, /*IsInstanceSuper=*/false,
2507 ReceiverType, Sel, SelectorLocs,
2508 Method, makeArrayRef(Args, NumArgs),
2509 RBracLoc, isImplicit);
2511 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2512 ReceiverTypeInfo, Sel, SelectorLocs,
2513 Method, makeArrayRef(Args, NumArgs),
2514 RBracLoc, isImplicit);
2516 checkCocoaAPI(*this, Result);
2519 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2520 ReceiverType, /*IsClassObjectCall=*/true);
2521 return MaybeBindToTemporary(Result);
2524 // ActOnClassMessage - used for both unary and keyword messages.
2525 // ArgExprs is optional - if it is present, the number of expressions
2526 // is obtained from Sel.getNumArgs().
2527 ExprResult Sema::ActOnClassMessage(Scope *S,
2528 ParsedType Receiver,
2530 SourceLocation LBracLoc,
2531 ArrayRef<SourceLocation> SelectorLocs,
2532 SourceLocation RBracLoc,
2533 MultiExprArg Args) {
2534 TypeSourceInfo *ReceiverTypeInfo;
2535 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2536 if (ReceiverType.isNull())
2539 if (!ReceiverTypeInfo)
2540 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2542 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2543 /*SuperLoc=*/SourceLocation(), Sel,
2544 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2548 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2549 QualType ReceiverType,
2552 ObjCMethodDecl *Method,
2553 MultiExprArg Args) {
2554 return BuildInstanceMessage(Receiver, ReceiverType,
2555 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2556 Sel, Method, Loc, Loc, Loc, Args,
2557 /*isImplicit=*/true);
2560 static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2563 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2566 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2567 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2568 S.LookupSingleName(S.TUScope, II, Protocol->getLocStart(),
2569 Sema::LookupOrdinaryName))) {
2570 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2571 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2578 /// \brief Build an Objective-C instance message expression.
2580 /// This routine takes care of both normal instance messages and
2581 /// instance messages to the superclass instance.
2583 /// \param Receiver The expression that computes the object that will
2584 /// receive this message. This may be empty, in which case we are
2585 /// sending to the superclass instance and \p SuperLoc must be a valid
2586 /// source location.
2588 /// \param ReceiverType The (static) type of the object receiving the
2589 /// message. When a \p Receiver expression is provided, this is the
2590 /// same type as that expression. For a superclass instance send, this
2591 /// is a pointer to the type of the superclass.
2593 /// \param SuperLoc The location of the "super" keyword in a
2594 /// superclass instance message.
2596 /// \param Sel The selector to which the message is being sent.
2598 /// \param Method The method that this instance message is invoking, if
2601 /// \param LBracLoc The location of the opening square bracket ']'.
2603 /// \param RBracLoc The location of the closing square bracket ']'.
2605 /// \param ArgsIn The message arguments.
2606 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2607 QualType ReceiverType,
2608 SourceLocation SuperLoc,
2610 ObjCMethodDecl *Method,
2611 SourceLocation LBracLoc,
2612 ArrayRef<SourceLocation> SelectorLocs,
2613 SourceLocation RBracLoc,
2614 MultiExprArg ArgsIn,
2616 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2617 "SuperLoc must be valid so we can "
2620 // The location of the receiver.
2621 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2622 SourceRange RecRange =
2623 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2624 SourceLocation SelLoc;
2625 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2626 SelLoc = SelectorLocs.front();
2630 if (LBracLoc.isInvalid()) {
2631 Diag(Loc, diag::err_missing_open_square_message_send)
2632 << FixItHint::CreateInsertion(Loc, "[");
2636 // If we have a receiver expression, perform appropriate promotions
2637 // and determine receiver type.
2639 if (Receiver->hasPlaceholderType()) {
2641 if (Receiver->getType() == Context.UnknownAnyTy)
2642 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2644 Result = CheckPlaceholderExpr(Receiver);
2645 if (Result.isInvalid()) return ExprError();
2646 Receiver = Result.get();
2649 if (Receiver->isTypeDependent()) {
2650 // If the receiver is type-dependent, we can't type-check anything
2651 // at this point. Build a dependent expression.
2652 unsigned NumArgs = ArgsIn.size();
2653 Expr **Args = ArgsIn.data();
2654 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2655 return ObjCMessageExpr::Create(
2656 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2657 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2658 RBracLoc, isImplicit);
2661 // If necessary, apply function/array conversion to the receiver.
2662 // C99 6.7.5.3p[7,8].
2663 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2664 if (Result.isInvalid())
2666 Receiver = Result.get();
2667 ReceiverType = Receiver->getType();
2669 // If the receiver is an ObjC pointer, a block pointer, or an
2670 // __attribute__((NSObject)) pointer, we don't need to do any
2671 // special conversion in order to look up a receiver.
2672 if (ReceiverType->isObjCRetainableType()) {
2674 } else if (!getLangOpts().ObjCAutoRefCount &&
2675 !Context.getObjCIdType().isNull() &&
2676 (ReceiverType->isPointerType() ||
2677 ReceiverType->isIntegerType())) {
2678 // Implicitly convert integers and pointers to 'id' but emit a warning.
2680 Diag(Loc, diag::warn_bad_receiver_type)
2682 << Receiver->getSourceRange();
2683 if (ReceiverType->isPointerType()) {
2684 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2685 CK_CPointerToObjCPointerCast).get();
2687 // TODO: specialized warning on null receivers?
2688 bool IsNull = Receiver->isNullPointerConstant(Context,
2689 Expr::NPC_ValueDependentIsNull);
2690 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2691 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2694 ReceiverType = Receiver->getType();
2695 } else if (getLangOpts().CPlusPlus) {
2696 // The receiver must be a complete type.
2697 if (RequireCompleteType(Loc, Receiver->getType(),
2698 diag::err_incomplete_receiver_type))
2701 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2702 if (result.isUsable()) {
2703 Receiver = result.get();
2704 ReceiverType = Receiver->getType();
2709 // There's a somewhat weird interaction here where we assume that we
2710 // won't actually have a method unless we also don't need to do some
2711 // of the more detailed type-checking on the receiver.
2714 // Handle messages to id and __kindof types (where we use the
2715 // global method pool).
2716 const ObjCObjectType *typeBound = nullptr;
2717 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2719 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2720 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2721 SmallVector<ObjCMethodDecl*, 4> Methods;
2722 // If we have a type bound, further filter the methods.
2723 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2724 true/*CheckTheOther*/, typeBound);
2725 if (!Methods.empty()) {
2726 // We choose the first method as the initial candidate, then try to
2727 // select a better one.
2728 Method = Methods[0];
2730 if (ObjCMethodDecl *BestMethod =
2731 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2732 Method = BestMethod;
2734 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2735 SourceRange(LBracLoc, RBracLoc),
2736 receiverIsIdLike, Methods))
2737 DiagnoseUseOfDecl(Method, SelLoc);
2739 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2740 ReceiverType->isObjCQualifiedClassType()) {
2741 // Handle messages to Class.
2742 // We allow sending a message to a qualified Class ("Class<foo>"), which
2743 // is ok as long as one of the protocols implements the selector (if not,
2745 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2746 const ObjCObjectPointerType *QClassTy
2747 = ReceiverType->getAsObjCQualifiedClassType();
2748 // Search protocols for class methods.
2749 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2751 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2752 // warn if instance method found for a Class message.
2753 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2754 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2755 << Method->getSelector() << Sel;
2756 Diag(Method->getLocation(), diag::note_method_declared_at)
2757 << Method->getDeclName();
2761 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2762 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2763 // First check the public methods in the class interface.
2764 Method = ClassDecl->lookupClassMethod(Sel);
2767 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2769 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2773 // If not messaging 'self', look for any factory method named 'Sel'.
2774 if (!Receiver || !isSelfExpr(Receiver)) {
2775 // If no class (factory) method was found, check if an _instance_
2776 // method of the same name exists in the root class only.
2777 SmallVector<ObjCMethodDecl*, 4> Methods;
2778 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2779 false/*InstanceFirst*/,
2780 true/*CheckTheOther*/);
2781 if (!Methods.empty()) {
2782 // We choose the first method as the initial candidate, then try
2783 // to select a better one.
2784 Method = Methods[0];
2786 // If we find an instance method, emit waring.
2787 if (Method->isInstanceMethod()) {
2788 if (const ObjCInterfaceDecl *ID =
2789 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2790 if (ID->getSuperClass())
2791 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2792 << Sel << SourceRange(LBracLoc, RBracLoc);
2796 if (ObjCMethodDecl *BestMethod =
2797 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2799 Method = BestMethod;
2805 ObjCInterfaceDecl *ClassDecl = nullptr;
2807 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2808 // long as one of the protocols implements the selector (if not, warn).
2809 // And as long as message is not deprecated/unavailable (warn if it is).
2810 if (const ObjCObjectPointerType *QIdTy
2811 = ReceiverType->getAsObjCQualifiedIdType()) {
2812 // Search protocols for instance methods.
2813 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2815 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2816 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2818 } else if (const ObjCObjectPointerType *OCIType
2819 = ReceiverType->getAsObjCInterfacePointerType()) {
2820 // We allow sending a message to a pointer to an interface (an object).
2821 ClassDecl = OCIType->getInterfaceDecl();
2823 // Try to complete the type. Under ARC, this is a hard error from which
2824 // we don't try to recover.
2825 // FIXME: In the non-ARC case, this will still be a hard error if the
2826 // definition is found in a module that's not visible.
2827 const ObjCInterfaceDecl *forwardClass = nullptr;
2828 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2829 getLangOpts().ObjCAutoRefCount
2830 ? diag::err_arc_receiver_forward_instance
2831 : diag::warn_receiver_forward_instance,
2832 Receiver? Receiver->getSourceRange()
2833 : SourceRange(SuperLoc))) {
2834 if (getLangOpts().ObjCAutoRefCount)
2837 forwardClass = OCIType->getInterfaceDecl();
2838 Diag(Receiver ? Receiver->getLocStart()
2839 : SuperLoc, diag::note_receiver_is_id);
2842 Method = ClassDecl->lookupInstanceMethod(Sel);
2846 // Search protocol qualifiers.
2847 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2850 // If we have implementations in scope, check "private" methods.
2851 Method = ClassDecl->lookupPrivateMethod(Sel);
2853 if (!Method && getLangOpts().ObjCAutoRefCount) {
2854 Diag(SelLoc, diag::err_arc_may_not_respond)
2855 << OCIType->getPointeeType() << Sel << RecRange
2856 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2860 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2861 // If we still haven't found a method, look in the global pool. This
2862 // behavior isn't very desirable, however we need it for GCC
2863 // compatibility. FIXME: should we deviate??
2864 if (OCIType->qual_empty()) {
2865 SmallVector<ObjCMethodDecl*, 4> Methods;
2866 CollectMultipleMethodsInGlobalPool(Sel, Methods,
2867 true/*InstanceFirst*/,
2868 false/*CheckTheOther*/);
2869 if (!Methods.empty()) {
2870 // We choose the first method as the initial candidate, then try
2871 // to select a better one.
2872 Method = Methods[0];
2874 if (ObjCMethodDecl *BestMethod =
2875 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
2877 Method = BestMethod;
2879 AreMultipleMethodsInGlobalPool(Sel, Method,
2880 SourceRange(LBracLoc, RBracLoc),
2881 true/*receiverIdOrClass*/,
2884 if (Method && !forwardClass)
2885 Diag(SelLoc, diag::warn_maynot_respond)
2886 << OCIType->getInterfaceDecl()->getIdentifier()
2891 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2894 // Reject other random receiver types (e.g. structs).
2895 Diag(Loc, diag::err_bad_receiver_type)
2896 << ReceiverType << Receiver->getSourceRange();
2902 FunctionScopeInfo *DIFunctionScopeInfo =
2903 (Method && Method->getMethodFamily() == OMF_init)
2904 ? getEnclosingFunction() : nullptr;
2906 if (DIFunctionScopeInfo &&
2907 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2908 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2909 bool isDesignatedInitChain = false;
2910 if (SuperLoc.isValid()) {
2911 if (const ObjCObjectPointerType *
2912 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2913 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2914 // Either we know this is a designated initializer or we
2915 // conservatively assume it because we don't know for sure.
2916 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2917 ID->isDesignatedInitializer(Sel)) {
2918 isDesignatedInitChain = true;
2919 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2924 if (!isDesignatedInitChain) {
2925 const ObjCMethodDecl *InitMethod = nullptr;
2927 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2928 assert(isDesignated && InitMethod);
2930 Diag(SelLoc, SuperLoc.isValid() ?
2931 diag::warn_objc_designated_init_non_designated_init_call :
2932 diag::warn_objc_designated_init_non_super_designated_init_call);
2933 Diag(InitMethod->getLocation(),
2934 diag::note_objc_designated_init_marked_here);
2938 if (DIFunctionScopeInfo &&
2939 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2940 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2941 if (SuperLoc.isValid()) {
2942 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2944 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2948 // Check the message arguments.
2949 unsigned NumArgs = ArgsIn.size();
2950 Expr **Args = ArgsIn.data();
2951 QualType ReturnType;
2952 ExprValueKind VK = VK_RValue;
2953 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2954 ReceiverType->isObjCQualifiedClassType());
2955 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2956 Sel, SelectorLocs, Method,
2957 ClassMessage, SuperLoc.isValid(),
2958 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
2961 if (Method && !Method->getReturnType()->isVoidType() &&
2962 RequireCompleteType(LBracLoc, Method->getReturnType(),
2963 diag::err_illegal_message_expr_incomplete_type))
2966 // In ARC, forbid the user from sending messages to
2967 // retain/release/autorelease/dealloc/retainCount explicitly.
2968 if (getLangOpts().ObjCAutoRefCount) {
2969 ObjCMethodFamily family =
2970 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2974 checkInitMethod(Method, ReceiverType);
2980 case OMF_mutableCopy:
2983 case OMF_initialize:
2989 case OMF_autorelease:
2990 case OMF_retainCount:
2991 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2995 case OMF_performSelector:
2996 if (Method && NumArgs >= 1) {
2997 if (const auto *SelExp =
2998 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
2999 Selector ArgSel = SelExp->getSelector();
3000 ObjCMethodDecl *SelMethod =
3001 LookupInstanceMethodInGlobalPool(ArgSel,
3002 SelExp->getSourceRange());
3005 LookupFactoryMethodInGlobalPool(ArgSel,
3006 SelExp->getSourceRange());
3008 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3009 switch (SelFamily) {
3012 case OMF_mutableCopy:
3015 // Issue error, unless ns_returns_not_retained.
3016 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3017 // selector names a +1 method
3019 diag::err_arc_perform_selector_retains);
3020 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3021 << SelMethod->getDeclName();
3025 // +0 call. OK. unless ns_returns_retained.
3026 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3027 // selector names a +1 method
3029 diag::err_arc_perform_selector_retains);
3030 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3031 << SelMethod->getDeclName();
3037 // error (may leak).
3038 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3039 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3046 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3048 // Construct the appropriate ObjCMessageExpr instance.
3049 ObjCMessageExpr *Result;
3050 if (SuperLoc.isValid())
3051 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3052 SuperLoc, /*IsInstanceSuper=*/true,
3053 ReceiverType, Sel, SelectorLocs, Method,
3054 makeArrayRef(Args, NumArgs), RBracLoc,
3057 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3058 Receiver, Sel, SelectorLocs, Method,
3059 makeArrayRef(Args, NumArgs), RBracLoc,
3062 checkCocoaAPI(*this, Result);
3065 bool IsClassObjectCall = ClassMessage;
3066 // 'self' message receivers in class methods should be treated as message
3067 // sends to the class object in order for the semantic checks to be
3068 // performed correctly. Messages to 'super' already count as class messages,
3069 // so they don't need to be handled here.
3070 if (Receiver && isSelfExpr(Receiver)) {
3071 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3072 if (OPT->getObjectType()->isObjCClass()) {
3073 if (const auto *CurMeth = getCurMethodDecl()) {
3074 IsClassObjectCall = true;
3076 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3081 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3082 ReceiverType, IsClassObjectCall);
3085 if (getLangOpts().ObjCAutoRefCount) {
3086 // In ARC, annotate delegate init calls.
3087 if (Result->getMethodFamily() == OMF_init &&
3088 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3089 // Only consider init calls *directly* in init implementations,
3090 // not within blocks.
3091 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3092 if (method && method->getMethodFamily() == OMF_init) {
3093 // The implicit assignment to self means we also don't want to
3094 // consume the result.
3095 Result->setDelegateInitCall(true);
3100 // In ARC, check for message sends which are likely to introduce
3102 checkRetainCycles(Result);
3105 if (getLangOpts().ObjCWeak) {
3106 if (!isImplicit && Method) {
3107 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3109 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
3110 if (!IsWeak && Sel.isUnarySelector())
3111 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3113 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3114 getCurFunction()->recordUseOfWeak(Result, Prop);
3119 CheckObjCCircularContainer(Result);
3121 return MaybeBindToTemporary(Result);
3124 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3125 if (ObjCSelectorExpr *OSE =
3126 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3127 Selector Sel = OSE->getSelector();
3128 SourceLocation Loc = OSE->getAtLoc();
3129 auto Pos = S.ReferencedSelectors.find(Sel);
3130 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3131 S.ReferencedSelectors.erase(Pos);
3135 // ActOnInstanceMessage - used for both unary and keyword messages.
3136 // ArgExprs is optional - if it is present, the number of expressions
3137 // is obtained from Sel.getNumArgs().
3138 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3141 SourceLocation LBracLoc,
3142 ArrayRef<SourceLocation> SelectorLocs,
3143 SourceLocation RBracLoc,
3144 MultiExprArg Args) {
3148 // A ParenListExpr can show up while doing error recovery with invalid code.
3149 if (isa<ParenListExpr>(Receiver)) {
3150 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3151 if (Result.isInvalid()) return ExprError();
3152 Receiver = Result.get();
3155 if (RespondsToSelectorSel.isNull()) {
3156 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3157 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3159 if (Sel == RespondsToSelectorSel)
3160 RemoveSelectorFromWarningCache(*this, Args[0]);
3162 return BuildInstanceMessage(Receiver, Receiver->getType(),
3163 /*SuperLoc=*/SourceLocation(), Sel,
3164 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3168 enum ARCConversionTypeClass {
3169 /// int, void, struct A
3175 /// id*, id***, void (^*)(),
3176 ACTC_indirectRetainable,
3178 /// void* might be a normal C type, or it might a CF type.
3185 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3186 return (ACTC == ACTC_retainable ||
3187 ACTC == ACTC_coreFoundation ||
3188 ACTC == ACTC_voidPtr);
3191 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3192 return ACTC == ACTC_none ||
3193 ACTC == ACTC_voidPtr ||
3194 ACTC == ACTC_coreFoundation;
3197 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3198 bool isIndirect = false;
3200 // Ignore an outermost reference type.
3201 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3202 type = ref->getPointeeType();
3206 // Drill through pointers and arrays recursively.
3208 if (const PointerType *ptr = type->getAs<PointerType>()) {
3209 type = ptr->getPointeeType();
3211 // The first level of pointer may be the innermost pointer on a CF type.
3213 if (type->isVoidType()) return ACTC_voidPtr;
3214 if (type->isRecordType()) return ACTC_coreFoundation;
3216 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3217 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3225 if (type->isObjCARCBridgableType())
3226 return ACTC_indirectRetainable;
3230 if (type->isObjCARCBridgableType())
3231 return ACTC_retainable;
3237 /// A result from the cast checker.
3239 /// Cannot be casted.
3242 /// Can be safely retained or not retained.
3245 /// Can be casted at +0.
3248 /// Can be casted at +1.
3251 ACCResult merge(ACCResult left, ACCResult right) {
3252 if (left == right) return left;
3253 if (left == ACC_bottom) return right;
3254 if (right == ACC_bottom) return left;
3258 /// A checker which white-lists certain expressions whose conversion
3259 /// to or from retainable type would otherwise be forbidden in ARC.
3260 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3261 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3263 ASTContext &Context;
3264 ARCConversionTypeClass SourceClass;
3265 ARCConversionTypeClass TargetClass;
3268 static bool isCFType(QualType type) {
3269 // Someday this can use ns_bridged. For now, it has to do this.
3270 return type->isCARCBridgableType();
3274 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3275 ARCConversionTypeClass target, bool diagnose)
3276 : Context(Context), SourceClass(source), TargetClass(target),
3277 Diagnose(diagnose) {}
3280 ACCResult Visit(Expr *e) {
3281 return super::Visit(e->IgnoreParens());
3284 ACCResult VisitStmt(Stmt *s) {
3288 /// Null pointer constants can be casted however you please.
3289 ACCResult VisitExpr(Expr *e) {
3290 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3295 /// Objective-C string literals can be safely casted.
3296 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3297 // If we're casting to any retainable type, go ahead. Global
3298 // strings are immune to retains, so this is bottom.
3299 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3304 /// Look through certain implicit and explicit casts.
3305 ACCResult VisitCastExpr(CastExpr *e) {
3306 switch (e->getCastKind()) {
3307 case CK_NullToPointer:
3311 case CK_LValueToRValue:
3313 case CK_CPointerToObjCPointerCast:
3314 case CK_BlockPointerToObjCPointerCast:
3315 case CK_AnyPointerToBlockPointerCast:
3316 return Visit(e->getSubExpr());
3323 /// Look through unary extension.
3324 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3325 return Visit(e->getSubExpr());
3328 /// Ignore the LHS of a comma operator.
3329 ACCResult VisitBinComma(BinaryOperator *e) {
3330 return Visit(e->getRHS());
3333 /// Conditional operators are okay if both sides are okay.
3334 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3335 ACCResult left = Visit(e->getTrueExpr());
3336 if (left == ACC_invalid) return ACC_invalid;
3337 return merge(left, Visit(e->getFalseExpr()));
3340 /// Look through pseudo-objects.
3341 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3342 // If we're getting here, we should always have a result.
3343 return Visit(e->getResultExpr());
3346 /// Statement expressions are okay if their result expression is okay.
3347 ACCResult VisitStmtExpr(StmtExpr *e) {
3348 return Visit(e->getSubStmt()->body_back());
3351 /// Some declaration references are okay.
3352 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3353 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3354 // References to global constants are okay.
3355 if (isAnyRetainable(TargetClass) &&
3356 isAnyRetainable(SourceClass) &&
3358 !var->hasDefinition(Context) &&
3359 var->getType().isConstQualified()) {
3361 // In system headers, they can also be assumed to be immune to retains.
3362 // These are things like 'kCFStringTransformToLatin'.
3363 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3366 return ACC_plusZero;
3373 /// Some calls are okay.
3374 ACCResult VisitCallExpr(CallExpr *e) {
3375 if (FunctionDecl *fn = e->getDirectCallee())
3376 if (ACCResult result = checkCallToFunction(fn))
3379 return super::VisitCallExpr(e);
3382 ACCResult checkCallToFunction(FunctionDecl *fn) {
3383 // Require a CF*Ref return type.
3384 if (!isCFType(fn->getReturnType()))
3387 if (!isAnyRetainable(TargetClass))
3390 // Honor an explicit 'not retained' attribute.
3391 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3392 return ACC_plusZero;
3394 // Honor an explicit 'retained' attribute, except that for
3395 // now we're not going to permit implicit handling of +1 results,
3396 // because it's a bit frightening.
3397 if (fn->hasAttr<CFReturnsRetainedAttr>())
3398 return Diagnose ? ACC_plusOne
3399 : ACC_invalid; // ACC_plusOne if we start accepting this
3401 // Recognize this specific builtin function, which is used by CFSTR.
3402 unsigned builtinID = fn->getBuiltinID();
3403 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3406 // Otherwise, don't do anything implicit with an unaudited function.
3407 if (!fn->hasAttr<CFAuditedTransferAttr>())
3410 // Otherwise, it's +0 unless it follows the create convention.
3411 if (ento::coreFoundation::followsCreateRule(fn))
3412 return Diagnose ? ACC_plusOne
3413 : ACC_invalid; // ACC_plusOne if we start accepting this
3415 return ACC_plusZero;
3418 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3419 return checkCallToMethod(e->getMethodDecl());
3422 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3423 ObjCMethodDecl *method;
3424 if (e->isExplicitProperty())
3425 method = e->getExplicitProperty()->getGetterMethodDecl();
3427 method = e->getImplicitPropertyGetter();
3428 return checkCallToMethod(method);
3431 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3432 if (!method) return ACC_invalid;
3434 // Check for message sends to functions returning CF types. We
3435 // just obey the Cocoa conventions with these, even though the
3436 // return type is CF.
3437 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3440 // If the method is explicitly marked not-retained, it's +0.
3441 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3442 return ACC_plusZero;
3444 // If the method is explicitly marked as returning retained, or its
3445 // selector follows a +1 Cocoa convention, treat it as +1.
3446 if (method->hasAttr<CFReturnsRetainedAttr>())
3449 switch (method->getSelector().getMethodFamily()) {
3452 case OMF_mutableCopy:
3457 // Otherwise, treat it as +0.
3458 return ACC_plusZero;
3462 } // end anonymous namespace
3464 bool Sema::isKnownName(StringRef name) {
3467 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3468 Sema::LookupOrdinaryName);
3469 return LookupName(R, TUScope, false);
3472 static void addFixitForObjCARCConversion(Sema &S,
3473 DiagnosticBuilder &DiagB,
3474 Sema::CheckedConversionKind CCK,
3475 SourceLocation afterLParen,
3479 const char *bridgeKeyword,
3480 const char *CFBridgeName) {
3481 // We handle C-style and implicit casts here.
3483 case Sema::CCK_ImplicitConversion:
3484 case Sema::CCK_CStyleCast:
3485 case Sema::CCK_OtherCast:
3487 case Sema::CCK_FunctionalCast:
3492 if (CCK == Sema::CCK_OtherCast) {
3493 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3494 SourceRange range(NCE->getOperatorLoc(),
3495 NCE->getAngleBrackets().getEnd());
3496 SmallString<32> BridgeCall;
3498 SourceManager &SM = S.getSourceManager();
3499 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3500 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3503 BridgeCall += CFBridgeName;
3504 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3508 Expr *castedE = castExpr;
3509 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3510 castedE = CCE->getSubExpr();
3511 castedE = castedE->IgnoreImpCasts();
3512 SourceRange range = castedE->getSourceRange();
3514 SmallString<32> BridgeCall;
3516 SourceManager &SM = S.getSourceManager();
3517 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3518 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3521 BridgeCall += CFBridgeName;
3523 if (isa<ParenExpr>(castedE)) {
3524 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3528 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3530 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3531 S.getLocForEndOfToken(range.getEnd()),
3537 if (CCK == Sema::CCK_CStyleCast) {
3538 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3539 } else if (CCK == Sema::CCK_OtherCast) {
3540 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3541 std::string castCode = "(";
3542 castCode += bridgeKeyword;
3543 castCode += castType.getAsString();
3545 SourceRange Range(NCE->getOperatorLoc(),
3546 NCE->getAngleBrackets().getEnd());
3547 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3550 std::string castCode = "(";
3551 castCode += bridgeKeyword;
3552 castCode += castType.getAsString();
3554 Expr *castedE = castExpr->IgnoreImpCasts();
3555 SourceRange range = castedE->getSourceRange();
3556 if (isa<ParenExpr>(castedE)) {
3557 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3561 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3563 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3564 S.getLocForEndOfToken(range.getEnd()),
3570 template <typename T>
3571 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3572 TypedefNameDecl *TDNDecl = TD->getDecl();
3573 QualType QT = TDNDecl->getUnderlyingType();
3574 if (QT->isPointerType()) {
3575 QT = QT->getPointeeType();
3576 if (const RecordType *RT = QT->getAs<RecordType>())
3577 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3578 return RD->getAttr<T>();
3583 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3584 TypedefNameDecl *&TDNDecl) {
3585 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3586 TDNDecl = TD->getDecl();
3587 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3588 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3590 T = TDNDecl->getUnderlyingType();
3596 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3597 QualType castType, ARCConversionTypeClass castACTC,
3598 Expr *castExpr, Expr *realCast,
3599 ARCConversionTypeClass exprACTC,
3600 Sema::CheckedConversionKind CCK) {
3601 SourceLocation loc =
3602 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3604 if (S.makeUnavailableInSystemHeader(loc,
3605 UnavailableAttr::IR_ARCForbiddenConversion))
3608 QualType castExprType = castExpr->getType();
3609 // Defer emitting a diagnostic for bridge-related casts; that will be
3610 // handled by CheckObjCBridgeRelatedConversions.
3611 TypedefNameDecl *TDNDecl = nullptr;
3612 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3613 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3614 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3615 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3618 unsigned srcKind = 0;
3621 case ACTC_coreFoundation:
3623 srcKind = (castExprType->isPointerType() ? 1 : 0);
3625 case ACTC_retainable:
3626 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3628 case ACTC_indirectRetainable:
3633 // Check whether this could be fixed with a bridge cast.
3634 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3635 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3637 // Bridge from an ARC type to a CF type.
3638 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3640 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3641 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3642 << 2 // of C pointer type
3644 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3647 << castExpr->getSourceRange();
3648 bool br = S.isKnownName("CFBridgingRelease");
3649 ACCResult CreateRule =
3650 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3651 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3652 if (CreateRule != ACC_plusOne)
3654 DiagnosticBuilder DiagB =
3655 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3656 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3658 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3659 castType, castExpr, realCast, "__bridge ",
3662 if (CreateRule != ACC_plusZero)
3664 DiagnosticBuilder DiagB =
3665 (CCK == Sema::CCK_OtherCast && !br) ?
3666 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3667 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3668 diag::note_arc_bridge_transfer)
3669 << castExprType << br;
3671 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3672 castType, castExpr, realCast, "__bridge_transfer ",
3673 br ? "CFBridgingRelease" : nullptr);
3679 // Bridge from a CF type to an ARC type.
3680 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3681 bool br = S.isKnownName("CFBridgingRetain");
3682 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3683 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3684 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3686 << 2 // to C pointer type
3689 << castExpr->getSourceRange();
3690 ACCResult CreateRule =
3691 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3692 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3693 if (CreateRule != ACC_plusOne)
3695 DiagnosticBuilder DiagB =
3696 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3697 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3698 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3699 castType, castExpr, realCast, "__bridge ",
3702 if (CreateRule != ACC_plusZero)
3704 DiagnosticBuilder DiagB =
3705 (CCK == Sema::CCK_OtherCast && !br) ?
3706 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3707 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3708 diag::note_arc_bridge_retained)
3711 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3712 castType, castExpr, realCast, "__bridge_retained ",
3713 br ? "CFBridgingRetain" : nullptr);
3719 S.Diag(loc, diag::err_arc_mismatched_cast)
3720 << (CCK != Sema::CCK_ImplicitConversion)
3721 << srcKind << castExprType << castType
3722 << castRange << castExpr->getSourceRange();
3725 template <typename TB>
3726 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3727 bool &HadTheAttribute, bool warn) {
3728 QualType T = castExpr->getType();
3729 HadTheAttribute = false;
3730 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3731 TypedefNameDecl *TDNDecl = TD->getDecl();
3732 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3733 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3734 HadTheAttribute = true;
3735 if (Parm->isStr("id"))
3738 NamedDecl *Target = nullptr;
3739 // Check for an existing type with this name.
3740 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3741 Sema::LookupOrdinaryName);
3742 if (S.LookupName(R, S.TUScope)) {
3743 Target = R.getFoundDecl();
3744 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3745 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3746 if (const ObjCObjectPointerType *InterfacePointerType =
3747 castType->getAsObjCInterfacePointerType()) {
3748 ObjCInterfaceDecl *CastClass
3749 = InterfacePointerType->getObjectType()->getInterface();
3750 if ((CastClass == ExprClass) ||
3751 (CastClass && CastClass->isSuperClassOf(ExprClass)))
3754 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3755 << T << Target->getName() << castType->getPointeeType();
3757 } else if (castType->isObjCIdType() ||
3758 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3759 castType, ExprClass)))
3760 // ok to cast to 'id'.
3761 // casting to id<p-list> is ok if bridge type adopts all of
3762 // p-list protocols.
3766 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3767 << T << Target->getName() << castType;
3768 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3769 S.Diag(Target->getLocStart(), diag::note_declared_at);
3774 } else if (!castType->isObjCIdType()) {
3775 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3776 << castExpr->getType() << Parm;
3777 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3779 S.Diag(Target->getLocStart(), diag::note_declared_at);
3785 T = TDNDecl->getUnderlyingType();
3790 template <typename TB>
3791 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3792 bool &HadTheAttribute, bool warn) {
3793 QualType T = castType;
3794 HadTheAttribute = false;
3795 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3796 TypedefNameDecl *TDNDecl = TD->getDecl();
3797 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3798 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3799 HadTheAttribute = true;
3800 if (Parm->isStr("id"))
3803 NamedDecl *Target = nullptr;
3804 // Check for an existing type with this name.
3805 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3806 Sema::LookupOrdinaryName);
3807 if (S.LookupName(R, S.TUScope)) {
3808 Target = R.getFoundDecl();
3809 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3810 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3811 if (const ObjCObjectPointerType *InterfacePointerType =
3812 castExpr->getType()->getAsObjCInterfacePointerType()) {
3813 ObjCInterfaceDecl *ExprClass
3814 = InterfacePointerType->getObjectType()->getInterface();
3815 if ((CastClass == ExprClass) ||
3816 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3819 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3820 << castExpr->getType()->getPointeeType() << T;
3821 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3824 } else if (castExpr->getType()->isObjCIdType() ||
3825 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3826 castExpr->getType(), CastClass)))
3827 // ok to cast an 'id' expression to a CFtype.
3828 // ok to cast an 'id<plist>' expression to CFtype provided plist
3829 // adopts all of CFtype's ObjetiveC's class plist.
3833 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3834 << castExpr->getType() << castType;
3835 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3836 S.Diag(Target->getLocStart(), diag::note_declared_at);
3842 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3843 << castExpr->getType() << castType;
3844 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3846 S.Diag(Target->getLocStart(), diag::note_declared_at);
3851 T = TDNDecl->getUnderlyingType();
3856 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3857 if (!getLangOpts().ObjC1)
3859 // warn in presence of __bridge casting to or from a toll free bridge cast.
3860 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3861 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3862 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3863 bool HasObjCBridgeAttr;
3864 bool ObjCBridgeAttrWillNotWarn =
3865 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3867 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3869 bool HasObjCBridgeMutableAttr;
3870 bool ObjCBridgeMutableAttrWillNotWarn =
3871 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3872 HasObjCBridgeMutableAttr, false);
3873 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3876 if (HasObjCBridgeAttr)
3877 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3879 else if (HasObjCBridgeMutableAttr)
3880 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3881 HasObjCBridgeMutableAttr, true);
3883 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3884 bool HasObjCBridgeAttr;
3885 bool ObjCBridgeAttrWillNotWarn =
3886 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3888 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3890 bool HasObjCBridgeMutableAttr;
3891 bool ObjCBridgeMutableAttrWillNotWarn =
3892 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3893 HasObjCBridgeMutableAttr, false);
3894 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3897 if (HasObjCBridgeAttr)
3898 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3900 else if (HasObjCBridgeMutableAttr)
3901 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3902 HasObjCBridgeMutableAttr, true);
3906 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3907 QualType SrcType = castExpr->getType();
3908 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3909 if (PRE->isExplicitProperty()) {
3910 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3911 SrcType = PDecl->getType();
3913 else if (PRE->isImplicitProperty()) {
3914 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3915 SrcType = Getter->getReturnType();
3919 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3920 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3921 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3923 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3924 castType, SrcType, castExpr);
3927 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3929 if (!getLangOpts().ObjC1)
3931 ARCConversionTypeClass exprACTC =
3932 classifyTypeForARCConversion(castExpr->getType());
3933 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3934 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3935 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3936 CheckTollFreeBridgeCast(castType, castExpr);
3937 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3938 : CK_CPointerToObjCPointerCast;
3944 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3945 QualType DestType, QualType SrcType,
3946 ObjCInterfaceDecl *&RelatedClass,
3947 ObjCMethodDecl *&ClassMethod,
3948 ObjCMethodDecl *&InstanceMethod,
3949 TypedefNameDecl *&TDNDecl,
3950 bool CfToNs, bool Diagnose) {
3951 QualType T = CfToNs ? SrcType : DestType;
3952 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3956 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3957 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3958 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3961 NamedDecl *Target = nullptr;
3962 // Check for an existing type with this name.
3963 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3964 Sema::LookupOrdinaryName);
3965 if (!LookupName(R, TUScope)) {
3967 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3968 << SrcType << DestType;
3969 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3973 Target = R.getFoundDecl();
3974 if (Target && isa<ObjCInterfaceDecl>(Target))
3975 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3978 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3979 << SrcType << DestType;
3980 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3982 Diag(Target->getLocStart(), diag::note_declared_at);
3987 // Check for an existing class method with the given selector name.
3988 if (CfToNs && CMId) {
3989 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3990 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3993 Diag(Loc, diag::err_objc_bridged_related_known_method)
3994 << SrcType << DestType << Sel << false;
3995 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4001 // Check for an existing instance method with the given selector name.
4002 if (!CfToNs && IMId) {
4003 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4004 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4005 if (!InstanceMethod) {
4007 Diag(Loc, diag::err_objc_bridged_related_known_method)
4008 << SrcType << DestType << Sel << true;
4009 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4018 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4019 QualType DestType, QualType SrcType,
4020 Expr *&SrcExpr, bool Diagnose) {
4021 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4022 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4023 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4024 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4025 if (!CfToNs && !NsToCf)
4028 ObjCInterfaceDecl *RelatedClass;
4029 ObjCMethodDecl *ClassMethod = nullptr;
4030 ObjCMethodDecl *InstanceMethod = nullptr;
4031 TypedefNameDecl *TDNDecl = nullptr;
4032 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4033 ClassMethod, InstanceMethod, TDNDecl,
4038 // Implicit conversion from CF to ObjC object is needed.
4041 std::string ExpressionString = "[";
4042 ExpressionString += RelatedClass->getNameAsString();
4043 ExpressionString += " ";
4044 ExpressionString += ClassMethod->getSelector().getAsString();
4045 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
4046 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4047 Diag(Loc, diag::err_objc_bridged_related_known_method)
4048 << SrcType << DestType << ClassMethod->getSelector() << false
4049 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
4050 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4051 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4052 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4054 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4056 Expr *args[] = { SrcExpr };
4057 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4058 ClassMethod->getLocation(),
4059 ClassMethod->getSelector(), ClassMethod,
4060 MultiExprArg(args, 1));
4061 SrcExpr = msg.get();
4067 // Implicit conversion from ObjC type to CF object is needed.
4068 if (InstanceMethod) {
4070 std::string ExpressionString;
4071 SourceLocation SrcExprEndLoc =
4072 getLocForEndOfToken(SrcExpr->getLocEnd());
4073 if (InstanceMethod->isPropertyAccessor())
4074 if (const ObjCPropertyDecl *PDecl =
4075 InstanceMethod->findPropertyDecl()) {
4076 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4077 ExpressionString = ".";
4078 ExpressionString += PDecl->getNameAsString();
4079 Diag(Loc, diag::err_objc_bridged_related_known_method)
4080 << SrcType << DestType << InstanceMethod->getSelector() << true
4081 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4083 if (ExpressionString.empty()) {
4084 // Provide a fixit: [ObjectExpr InstanceMethod]
4085 ExpressionString = " ";
4086 ExpressionString += InstanceMethod->getSelector().getAsString();
4087 ExpressionString += "]";
4089 Diag(Loc, diag::err_objc_bridged_related_known_method)
4090 << SrcType << DestType << InstanceMethod->getSelector() << true
4091 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
4092 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4094 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
4095 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
4098 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4099 InstanceMethod->getLocation(),
4100 InstanceMethod->getSelector(),
4101 InstanceMethod, None);
4102 SrcExpr = msg.get();
4110 Sema::ARCConversionResult
4111 Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4112 Expr *&castExpr, CheckedConversionKind CCK,
4113 bool Diagnose, bool DiagnoseCFAudited,
4114 BinaryOperatorKind Opc) {
4115 QualType castExprType = castExpr->getType();
4117 // For the purposes of the classification, we assume reference types
4118 // will bind to temporaries.
4119 QualType effCastType = castType;
4120 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4121 effCastType = ref->getPointeeType();
4123 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4124 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4125 if (exprACTC == castACTC) {
4126 // Check for viability and report error if casting an rvalue to a
4127 // life-time qualifier.
4128 if (castACTC == ACTC_retainable &&
4129 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4130 castType != castExprType) {
4131 const Type *DT = castType.getTypePtr();
4132 QualType QDT = castType;
4133 // We desugar some types but not others. We ignore those
4134 // that cannot happen in a cast; i.e. auto, and those which
4135 // should not be de-sugared; i.e typedef.
4136 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4137 QDT = PT->desugar();
4138 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4139 QDT = TP->desugar();
4140 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4141 QDT = AT->desugar();
4142 if (QDT != castType &&
4143 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
4145 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4146 : castExpr->getExprLoc());
4147 Diag(loc, diag::err_arc_nolifetime_behavior);
4155 // The life-time qualifier cast check above is all we need for ObjCWeak.
4156 // ObjCAutoRefCount has more restrictions on what is legal.
4157 if (!getLangOpts().ObjCAutoRefCount)
4160 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4162 // Allow all of these types to be cast to integer types (but not
4164 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4167 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4168 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4169 // must be explicit.
4170 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4172 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4173 CCK != CCK_ImplicitConversion)
4176 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4177 // For invalid casts, fall through.
4181 // Do nothing for both bottom and +0.
4186 // If the result is +1, consume it here.
4188 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4189 CK_ARCConsumeObject, castExpr,
4190 nullptr, VK_RValue);
4191 Cleanup.setExprNeedsCleanups(true);
4195 // If this is a non-implicit cast from id or block type to a
4196 // CoreFoundation type, delay complaining in case the cast is used
4197 // in an acceptable context.
4198 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4199 CCK != CCK_ImplicitConversion)
4200 return ACR_unbridged;
4202 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4203 // to 'NSString *', instead of falling through to report a "bridge cast"
4205 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4206 ConversionToObjCStringLiteralCheck(castType, castExpr, Diagnose))
4209 // Do not issue "bridge cast" diagnostic when implicit casting
4210 // a retainable object to a CF type parameter belonging to an audited
4211 // CF API function. Let caller issue a normal type mismatched diagnostic
4213 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4214 castACTC != ACTC_coreFoundation) &&
4215 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4216 (Opc == BO_NE || Opc == BO_EQ))) {
4218 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4219 castExpr, exprACTC, CCK);
4225 /// Given that we saw an expression with the ARCUnbridgedCastTy
4226 /// placeholder type, complain bitterly.
4227 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4228 // We expect the spurious ImplicitCastExpr to already have been stripped.
4229 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4230 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4232 SourceRange castRange;
4234 CheckedConversionKind CCK;
4236 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4237 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4238 castType = cast->getTypeAsWritten();
4239 CCK = CCK_CStyleCast;
4240 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4241 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4242 castType = cast->getTypeAsWritten();
4243 CCK = CCK_OtherCast;
4245 castType = cast->getType();
4246 CCK = CCK_ImplicitConversion;
4249 ARCConversionTypeClass castACTC =
4250 classifyTypeForARCConversion(castType.getNonReferenceType());
4252 Expr *castExpr = realCast->getSubExpr();
4253 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4255 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4256 castExpr, realCast, ACTC_retainable, CCK);
4259 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4260 /// type, remove the placeholder cast.
4261 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4262 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4264 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4265 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4266 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4267 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4268 assert(uo->getOpcode() == UO_Extension);
4269 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4270 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4271 sub->getValueKind(), sub->getObjectKind(),
4272 uo->getOperatorLoc());
4273 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4274 assert(!gse->isResultDependent());
4276 unsigned n = gse->getNumAssocs();
4277 SmallVector<Expr*, 4> subExprs(n);
4278 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4279 for (unsigned i = 0; i != n; ++i) {
4280 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4281 Expr *sub = gse->getAssocExpr(i);
4282 if (i == gse->getResultIndex())
4283 sub = stripARCUnbridgedCast(sub);
4287 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4288 gse->getControllingExpr(),
4290 gse->getDefaultLoc(),
4291 gse->getRParenLoc(),
4292 gse->containsUnexpandedParameterPack(),
4293 gse->getResultIndex());
4295 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4296 return cast<ImplicitCastExpr>(e)->getSubExpr();
4300 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4301 QualType exprType) {
4302 QualType canCastType =
4303 Context.getCanonicalType(castType).getUnqualifiedType();
4304 QualType canExprType =
4305 Context.getCanonicalType(exprType).getUnqualifiedType();
4306 if (isa<ObjCObjectPointerType>(canCastType) &&
4307 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4308 canExprType->isObjCObjectPointerType()) {
4309 if (const ObjCObjectPointerType *ObjT =
4310 canExprType->getAs<ObjCObjectPointerType>())
4311 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4312 return !ObjI->isArcWeakrefUnavailable();
4317 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4318 static Expr *maybeUndoReclaimObject(Expr *e) {
4319 // For now, we just undo operands that are *immediately* reclaim
4320 // expressions, which prevents the vast majority of potential
4321 // problems here. To catch them all, we'd need to rebuild arbitrary
4322 // value-propagating subexpressions --- we can't reliably rebuild
4323 // in-place because of expression sharing.
4324 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4325 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
4326 return ice->getSubExpr();
4331 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4332 ObjCBridgeCastKind Kind,
4333 SourceLocation BridgeKeywordLoc,
4334 TypeSourceInfo *TSInfo,
4336 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4337 if (SubResult.isInvalid()) return ExprError();
4338 SubExpr = SubResult.get();
4340 QualType T = TSInfo->getType();
4341 QualType FromType = SubExpr->getType();
4345 bool MustConsume = false;
4346 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4347 // Okay: we'll build a dependent expression type.
4349 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4351 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4352 : CK_CPointerToObjCPointerCast);
4357 case OBC_BridgeRetained: {
4358 bool br = isKnownName("CFBridgingRelease");
4359 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4362 << (T->isBlockPointerType()? 1 : 0)
4364 << SubExpr->getSourceRange()
4366 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4367 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4368 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4370 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4371 br ? "CFBridgingRelease "
4372 : "__bridge_transfer ");
4378 case OBC_BridgeTransfer:
4379 // We must consume the Objective-C object produced by the cast.
4383 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4388 // Reclaiming a value that's going to be __bridge-casted to CF
4389 // is very dangerous, so we don't do it.
4390 SubExpr = maybeUndoReclaimObject(SubExpr);
4393 case OBC_BridgeRetained:
4394 // Produce the object before casting it.
4395 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4396 CK_ARCProduceObject,
4397 SubExpr, nullptr, VK_RValue);
4400 case OBC_BridgeTransfer: {
4401 bool br = isKnownName("CFBridgingRetain");
4402 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4403 << (FromType->isBlockPointerType()? 1 : 0)
4407 << SubExpr->getSourceRange()
4410 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4411 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4412 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4414 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4415 br ? "CFBridgingRetain " : "__bridge_retained");
4422 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4423 << FromType << T << Kind
4424 << SubExpr->getSourceRange()
4425 << TSInfo->getTypeLoc().getSourceRange();
4429 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4434 Cleanup.setExprNeedsCleanups(true);
4435 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4436 nullptr, VK_RValue);
4442 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4443 SourceLocation LParenLoc,
4444 ObjCBridgeCastKind Kind,
4445 SourceLocation BridgeKeywordLoc,
4447 SourceLocation RParenLoc,
4449 TypeSourceInfo *TSInfo = nullptr;
4450 QualType T = GetTypeFromParser(Type, &TSInfo);
4451 if (Kind == OBC_Bridge)
4452 CheckTollFreeBridgeCast(T, SubExpr);
4454 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4455 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,