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 NumberType = Context.CharTy;
325 case CharacterLiteral::Wide:
326 NumberType = Context.getWideCharType();
329 case CharacterLiteral::UTF16:
330 NumberType = Context.Char16Ty;
333 case CharacterLiteral::UTF32:
334 NumberType = Context.Char32Ty;
339 // Look for the appropriate method within NSNumber.
340 // Construct the literal.
341 SourceRange NR(Number->getSourceRange());
342 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
347 // Convert the number to the type that the parameter expects.
348 ParmVarDecl *ParamDecl = Method->parameters()[0];
349 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
351 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
354 if (ConvertedNumber.isInvalid())
356 Number = ConvertedNumber.get();
358 // Use the effective source range of the literal, including the leading '@'.
359 return MaybeBindToTemporary(
360 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
361 SourceRange(AtLoc, NR.getEnd())));
364 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
365 SourceLocation ValueLoc,
368 if (getLangOpts().CPlusPlus) {
369 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
371 // C doesn't actually have a way to represent literal values of type
372 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
373 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
374 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
375 CK_IntegralToBoolean);
378 return BuildObjCNumericLiteral(AtLoc, Inner.get());
381 /// \brief Check that the given expression is a valid element of an Objective-C
382 /// collection literal.
383 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
385 bool ArrayLiteral = false) {
386 // If the expression is type-dependent, there's nothing for us to do.
387 if (Element->isTypeDependent())
390 ExprResult Result = S.CheckPlaceholderExpr(Element);
391 if (Result.isInvalid())
393 Element = Result.get();
395 // In C++, check for an implicit conversion to an Objective-C object pointer
397 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
398 InitializedEntity Entity
399 = InitializedEntity::InitializeParameter(S.Context, T,
401 InitializationKind Kind
402 = InitializationKind::CreateCopy(Element->getLocStart(),
404 InitializationSequence Seq(S, Entity, Kind, Element);
406 return Seq.Perform(S, Entity, Kind, Element);
409 Expr *OrigElement = Element;
411 // Perform lvalue-to-rvalue conversion.
412 Result = S.DefaultLvalueConversion(Element);
413 if (Result.isInvalid())
415 Element = Result.get();
417 // Make sure that we have an Objective-C pointer type or block.
418 if (!Element->getType()->isObjCObjectPointerType() &&
419 !Element->getType()->isBlockPointerType()) {
420 bool Recovered = false;
422 // If this is potentially an Objective-C numeric literal, add the '@'.
423 if (isa<IntegerLiteral>(OrigElement) ||
424 isa<CharacterLiteral>(OrigElement) ||
425 isa<FloatingLiteral>(OrigElement) ||
426 isa<ObjCBoolLiteralExpr>(OrigElement) ||
427 isa<CXXBoolLiteralExpr>(OrigElement)) {
428 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
429 int Which = isa<CharacterLiteral>(OrigElement) ? 1
430 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
431 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
434 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
435 << Which << OrigElement->getSourceRange()
436 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
438 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
440 if (Result.isInvalid())
443 Element = Result.get();
447 // If this is potentially an Objective-C string literal, add the '@'.
448 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
449 if (String->isAscii()) {
450 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
451 << 0 << OrigElement->getSourceRange()
452 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
454 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
455 if (Result.isInvalid())
458 Element = Result.get();
464 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
465 << Element->getType();
470 if (ObjCStringLiteral *getString =
471 dyn_cast<ObjCStringLiteral>(OrigElement)) {
472 if (StringLiteral *SL = getString->getString()) {
473 unsigned numConcat = SL->getNumConcatenated();
475 // Only warn if the concatenated string doesn't come from a macro.
476 bool hasMacro = false;
477 for (unsigned i = 0; i < numConcat ; ++i)
478 if (SL->getStrTokenLoc(i).isMacroID()) {
483 S.Diag(Element->getLocStart(),
484 diag::warn_concatenated_nsarray_literal)
485 << Element->getType();
490 // Make sure that the element has the type that the container factory
492 return S.PerformCopyInitialization(
493 InitializedEntity::InitializeParameter(S.Context, T,
495 Element->getLocStart(), Element);
498 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
499 if (ValueExpr->isTypeDependent()) {
500 ObjCBoxedExpr *BoxedExpr =
501 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
504 ObjCMethodDecl *BoxingMethod = nullptr;
506 // Convert the expression to an RValue, so we can check for pointer types...
507 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
508 if (RValue.isInvalid()) {
511 SourceLocation Loc = SR.getBegin();
512 ValueExpr = RValue.get();
513 QualType ValueType(ValueExpr->getType());
514 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
515 QualType PointeeType = PT->getPointeeType();
516 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
519 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
524 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
525 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
528 if (!StringWithUTF8StringMethod) {
529 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
530 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
532 // Look for the appropriate method within NSString.
533 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
534 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
535 // Debugger needs to work even if NSString hasn't been defined.
536 TypeSourceInfo *ReturnTInfo = nullptr;
537 ObjCMethodDecl *M = ObjCMethodDecl::Create(
538 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
539 NSStringPointer, ReturnTInfo, NSStringDecl,
540 /*isInstance=*/false, /*isVariadic=*/false,
541 /*isPropertyAccessor=*/false,
542 /*isImplicitlyDeclared=*/true,
543 /*isDefined=*/false, ObjCMethodDecl::Required,
544 /*HasRelatedResultType=*/false);
545 QualType ConstCharType = Context.CharTy.withConst();
547 ParmVarDecl::Create(Context, M,
548 SourceLocation(), SourceLocation(),
549 &Context.Idents.get("value"),
550 Context.getPointerType(ConstCharType),
553 M->setMethodParams(Context, value, None);
557 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
558 stringWithUTF8String, BoxingMethod))
561 StringWithUTF8StringMethod = BoxingMethod;
564 BoxingMethod = StringWithUTF8StringMethod;
565 BoxedType = NSStringPointer;
567 } else if (ValueType->isBuiltinType()) {
568 // The other types we support are numeric, char and BOOL/bool. We could also
569 // provide limited support for structure types, such as NSRange, NSRect, and
570 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
573 // Check for a top-level character literal.
574 if (const CharacterLiteral *Char =
575 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
576 // In C, character literals have type 'int'. That's not the type we want
577 // to use to determine the Objective-c literal kind.
578 switch (Char->getKind()) {
579 case CharacterLiteral::Ascii:
580 ValueType = Context.CharTy;
583 case CharacterLiteral::Wide:
584 ValueType = Context.getWideCharType();
587 case CharacterLiteral::UTF16:
588 ValueType = Context.Char16Ty;
591 case CharacterLiteral::UTF32:
592 ValueType = Context.Char32Ty;
596 CheckForIntOverflow(ValueExpr);
597 // FIXME: Do I need to do anything special with BoolTy expressions?
599 // Look for the appropriate method within NSNumber.
600 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
601 BoxedType = NSNumberPointer;
602 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
603 if (!ET->getDecl()->isComplete()) {
604 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
605 << ValueType << ValueExpr->getSourceRange();
609 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
610 ET->getDecl()->getIntegerType());
611 BoxedType = NSNumberPointer;
612 } else if (ValueType->isObjCBoxableRecordType()) {
613 // Support for structure types, that marked as objc_boxable
614 // struct __attribute__((objc_boxable)) s { ... };
616 // Look up the NSValue class, if we haven't done so already. It's cached
617 // in the Sema instance.
619 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
625 // generate the pointer to NSValue type.
626 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
627 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
630 if (!ValueWithBytesObjCTypeMethod) {
631 IdentifierInfo *II[] = {
632 &Context.Idents.get("valueWithBytes"),
633 &Context.Idents.get("objCType")
635 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
637 // Look for the appropriate method within NSValue.
638 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
639 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
640 // Debugger needs to work even if NSValue hasn't been defined.
641 TypeSourceInfo *ReturnTInfo = nullptr;
642 ObjCMethodDecl *M = ObjCMethodDecl::Create(
646 ValueWithBytesObjCType,
650 /*isInstance=*/false,
651 /*isVariadic=*/false,
652 /*isPropertyAccessor=*/false,
653 /*isImplicitlyDeclared=*/true,
655 ObjCMethodDecl::Required,
656 /*HasRelatedResultType=*/false);
658 SmallVector<ParmVarDecl *, 2> Params;
661 ParmVarDecl::Create(Context, M,
662 SourceLocation(), SourceLocation(),
663 &Context.Idents.get("bytes"),
664 Context.VoidPtrTy.withConst(),
667 Params.push_back(bytes);
669 QualType ConstCharType = Context.CharTy.withConst();
671 ParmVarDecl::Create(Context, M,
672 SourceLocation(), SourceLocation(),
673 &Context.Idents.get("type"),
674 Context.getPointerType(ConstCharType),
677 Params.push_back(type);
679 M->setMethodParams(Context, Params, None);
683 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
684 ValueWithBytesObjCType, BoxingMethod))
687 ValueWithBytesObjCTypeMethod = BoxingMethod;
690 if (!ValueType.isTriviallyCopyableType(Context)) {
691 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
692 << ValueType << ValueExpr->getSourceRange();
696 BoxingMethod = ValueWithBytesObjCTypeMethod;
697 BoxedType = NSValuePointer;
701 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
702 << ValueType << ValueExpr->getSourceRange();
706 DiagnoseUseOfDecl(BoxingMethod, Loc);
708 ExprResult ConvertedValueExpr;
709 if (ValueType->isObjCBoxableRecordType()) {
710 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
711 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
714 // Convert the expression to the type that the parameter requires.
715 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
716 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
718 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
722 if (ConvertedValueExpr.isInvalid())
724 ValueExpr = ConvertedValueExpr.get();
726 ObjCBoxedExpr *BoxedExpr =
727 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
729 return MaybeBindToTemporary(BoxedExpr);
732 /// Build an ObjC subscript pseudo-object expression, given that
733 /// that's supported by the runtime.
734 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
736 ObjCMethodDecl *getterMethod,
737 ObjCMethodDecl *setterMethod) {
738 assert(!LangOpts.isSubscriptPointerArithmetic());
740 // We can't get dependent types here; our callers should have
741 // filtered them out.
742 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
743 "base or index cannot have dependent type here");
745 // Filter out placeholders in the index. In theory, overloads could
746 // be preserved here, although that might not actually work correctly.
747 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
748 if (Result.isInvalid())
750 IndexExpr = Result.get();
752 // Perform lvalue-to-rvalue conversion on the base.
753 Result = DefaultLvalueConversion(BaseExpr);
754 if (Result.isInvalid())
756 BaseExpr = Result.get();
758 // Build the pseudo-object expression.
759 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
760 Context.PseudoObjectTy, getterMethod,
764 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
765 SourceLocation Loc = SR.getBegin();
768 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
775 // Find the arrayWithObjects:count: method, if we haven't done so already.
776 QualType IdT = Context.getObjCIdType();
777 if (!ArrayWithObjectsMethod) {
779 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
780 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
781 if (!Method && getLangOpts().DebuggerObjCLiteral) {
782 TypeSourceInfo *ReturnTInfo = nullptr;
783 Method = ObjCMethodDecl::Create(
784 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
785 Context.getTranslationUnitDecl(), false /*Instance*/,
786 false /*isVariadic*/,
787 /*isPropertyAccessor=*/false,
788 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
789 ObjCMethodDecl::Required, false);
790 SmallVector<ParmVarDecl *, 2> Params;
791 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
794 &Context.Idents.get("objects"),
795 Context.getPointerType(IdT),
798 Params.push_back(objects);
799 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
802 &Context.Idents.get("cnt"),
803 Context.UnsignedLongTy,
804 /*TInfo=*/nullptr, SC_None,
806 Params.push_back(cnt);
807 Method->setMethodParams(Context, Params, None);
810 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
813 // Dig out the type that all elements should be converted to.
814 QualType T = Method->parameters()[0]->getType();
815 const PointerType *PtrT = T->getAs<PointerType>();
817 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
818 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
820 Diag(Method->parameters()[0]->getLocation(),
821 diag::note_objc_literal_method_param)
823 << Context.getPointerType(IdT.withConst());
827 // Check that the 'count' parameter is integral.
828 if (!Method->parameters()[1]->getType()->isIntegerType()) {
829 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
831 Diag(Method->parameters()[1]->getLocation(),
832 diag::note_objc_literal_method_param)
834 << Method->parameters()[1]->getType()
839 // We've found a good +arrayWithObjects:count: method. Save it!
840 ArrayWithObjectsMethod = Method;
843 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
844 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
846 // Check that each of the elements provided is valid in a collection literal,
847 // performing conversions as necessary.
848 Expr **ElementsBuffer = Elements.data();
849 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
850 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
853 if (Converted.isInvalid())
856 ElementsBuffer[I] = Converted.get();
860 = Context.getObjCObjectPointerType(
861 Context.getObjCInterfaceType(NSArrayDecl));
863 return MaybeBindToTemporary(
864 ObjCArrayLiteral::Create(Context, Elements, Ty,
865 ArrayWithObjectsMethod, SR));
868 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
869 MutableArrayRef<ObjCDictionaryElement> Elements) {
870 SourceLocation Loc = SR.getBegin();
872 if (!NSDictionaryDecl) {
873 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
874 Sema::LK_Dictionary);
875 if (!NSDictionaryDecl) {
880 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
882 QualType IdT = Context.getObjCIdType();
883 if (!DictionaryWithObjectsMethod) {
884 Selector Sel = NSAPIObj->getNSDictionarySelector(
885 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
886 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
887 if (!Method && getLangOpts().DebuggerObjCLiteral) {
888 Method = ObjCMethodDecl::Create(Context,
889 SourceLocation(), SourceLocation(), Sel,
891 nullptr /*TypeSourceInfo */,
892 Context.getTranslationUnitDecl(),
893 false /*Instance*/, false/*isVariadic*/,
894 /*isPropertyAccessor=*/false,
895 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
896 ObjCMethodDecl::Required,
898 SmallVector<ParmVarDecl *, 3> Params;
899 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
902 &Context.Idents.get("objects"),
903 Context.getPointerType(IdT),
904 /*TInfo=*/nullptr, SC_None,
906 Params.push_back(objects);
907 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
910 &Context.Idents.get("keys"),
911 Context.getPointerType(IdT),
912 /*TInfo=*/nullptr, SC_None,
914 Params.push_back(keys);
915 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
918 &Context.Idents.get("cnt"),
919 Context.UnsignedLongTy,
920 /*TInfo=*/nullptr, SC_None,
922 Params.push_back(cnt);
923 Method->setMethodParams(Context, Params, None);
926 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
930 // Dig out the type that all values should be converted to.
931 QualType ValueT = Method->parameters()[0]->getType();
932 const PointerType *PtrValue = ValueT->getAs<PointerType>();
934 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
935 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
937 Diag(Method->parameters()[0]->getLocation(),
938 diag::note_objc_literal_method_param)
940 << Context.getPointerType(IdT.withConst());
944 // Dig out the type that all keys should be converted to.
945 QualType KeyT = Method->parameters()[1]->getType();
946 const PointerType *PtrKey = KeyT->getAs<PointerType>();
948 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
952 if (QIDNSCopying.isNull()) {
953 // key argument of selector is id<NSCopying>?
954 if (ObjCProtocolDecl *NSCopyingPDecl =
955 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
956 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
958 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
960 (ObjCProtocolDecl**) PQ,
963 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
966 if (!QIDNSCopying.isNull())
967 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
972 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
974 Diag(Method->parameters()[1]->getLocation(),
975 diag::note_objc_literal_method_param)
977 << Context.getPointerType(IdT.withConst());
982 // Check that the 'count' parameter is integral.
983 QualType CountType = Method->parameters()[2]->getType();
984 if (!CountType->isIntegerType()) {
985 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
987 Diag(Method->parameters()[2]->getLocation(),
988 diag::note_objc_literal_method_param)
994 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
995 DictionaryWithObjectsMethod = Method;
998 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
999 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1000 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1001 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1003 // Check that each of the keys and values provided is valid in a collection
1004 // literal, performing conversions as necessary.
1005 bool HasPackExpansions = false;
1006 for (ObjCDictionaryElement &Element : Elements) {
1008 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1010 if (Key.isInvalid())
1015 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1016 if (Value.isInvalid())
1019 Element.Key = Key.get();
1020 Element.Value = Value.get();
1022 if (Element.EllipsisLoc.isInvalid())
1025 if (!Element.Key->containsUnexpandedParameterPack() &&
1026 !Element.Value->containsUnexpandedParameterPack()) {
1027 Diag(Element.EllipsisLoc,
1028 diag::err_pack_expansion_without_parameter_packs)
1029 << SourceRange(Element.Key->getLocStart(),
1030 Element.Value->getLocEnd());
1034 HasPackExpansions = true;
1039 = Context.getObjCObjectPointerType(
1040 Context.getObjCInterfaceType(NSDictionaryDecl));
1041 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
1042 Context, Elements, HasPackExpansions, Ty,
1043 DictionaryWithObjectsMethod, SR));
1046 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1047 TypeSourceInfo *EncodedTypeInfo,
1048 SourceLocation RParenLoc) {
1049 QualType EncodedType = EncodedTypeInfo->getType();
1051 if (EncodedType->isDependentType())
1052 StrTy = Context.DependentTy;
1054 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1055 !EncodedType->isVoidType()) // void is handled too.
1056 if (RequireCompleteType(AtLoc, EncodedType,
1057 diag::err_incomplete_type_objc_at_encode,
1058 EncodedTypeInfo->getTypeLoc()))
1062 QualType NotEncodedT;
1063 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1064 if (!NotEncodedT.isNull())
1065 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1066 << EncodedType << NotEncodedT;
1068 // The type of @encode is the same as the type of the corresponding string,
1069 // which is an array type.
1070 StrTy = Context.CharTy;
1071 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1072 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1074 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1075 ArrayType::Normal, 0);
1078 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1081 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1082 SourceLocation EncodeLoc,
1083 SourceLocation LParenLoc,
1085 SourceLocation RParenLoc) {
1086 // FIXME: Preserve type source info ?
1087 TypeSourceInfo *TInfo;
1088 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1090 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1091 getLocForEndOfToken(LParenLoc));
1093 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1096 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1097 SourceLocation AtLoc,
1098 SourceLocation LParenLoc,
1099 SourceLocation RParenLoc,
1100 ObjCMethodDecl *Method,
1101 ObjCMethodList &MethList) {
1102 ObjCMethodList *M = &MethList;
1103 bool Warned = false;
1104 for (M = M->getNext(); M; M=M->getNext()) {
1105 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1106 if (MatchingMethodDecl == Method ||
1107 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1108 MatchingMethodDecl->getSelector() != Method->getSelector())
1110 if (!S.MatchTwoMethodDeclarations(Method,
1111 MatchingMethodDecl, Sema::MMS_loose)) {
1114 S.Diag(AtLoc, diag::warning_multiple_selectors)
1115 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1116 << FixItHint::CreateInsertion(RParenLoc, ")");
1117 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1118 << Method->getDeclName();
1120 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1121 << MatchingMethodDecl->getDeclName();
1127 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1128 ObjCMethodDecl *Method,
1129 SourceLocation LParenLoc,
1130 SourceLocation RParenLoc,
1131 bool WarnMultipleSelectors) {
1132 if (!WarnMultipleSelectors ||
1133 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
1135 bool Warned = false;
1136 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1137 e = S.MethodPool.end(); b != e; b++) {
1138 // first, instance methods
1139 ObjCMethodList &InstMethList = b->second.first;
1140 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1141 Method, InstMethList))
1144 // second, class methods
1145 ObjCMethodList &ClsMethList = b->second.second;
1146 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1147 Method, ClsMethList) || Warned)
1152 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1153 SourceLocation AtLoc,
1154 SourceLocation SelLoc,
1155 SourceLocation LParenLoc,
1156 SourceLocation RParenLoc,
1157 bool WarnMultipleSelectors) {
1158 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1159 SourceRange(LParenLoc, RParenLoc));
1161 Method = LookupFactoryMethodInGlobalPool(Sel,
1162 SourceRange(LParenLoc, RParenLoc));
1164 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1165 Selector MatchedSel = OM->getSelector();
1166 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1167 RParenLoc.getLocWithOffset(-1));
1168 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1169 << Sel << MatchedSel
1170 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1173 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1175 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1176 WarnMultipleSelectors);
1179 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1180 !getSourceManager().isInSystemHeader(Method->getLocation()))
1181 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1183 // In ARC, forbid the user from using @selector for
1184 // retain/release/autorelease/dealloc/retainCount.
1185 if (getLangOpts().ObjCAutoRefCount) {
1186 switch (Sel.getMethodFamily()) {
1189 case OMF_autorelease:
1190 case OMF_retainCount:
1192 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1193 Sel << SourceRange(LParenLoc, RParenLoc);
1201 case OMF_mutableCopy:
1204 case OMF_initialize:
1205 case OMF_performSelector:
1209 QualType Ty = Context.getObjCSelType();
1210 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1213 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1214 SourceLocation AtLoc,
1215 SourceLocation ProtoLoc,
1216 SourceLocation LParenLoc,
1217 SourceLocation ProtoIdLoc,
1218 SourceLocation RParenLoc) {
1219 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1221 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1224 if (PDecl->hasDefinition())
1225 PDecl = PDecl->getDefinition();
1227 QualType Ty = Context.getObjCProtoType();
1230 Ty = Context.getObjCObjectPointerType(Ty);
1231 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1234 /// Try to capture an implicit reference to 'self'.
1235 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1236 DeclContext *DC = getFunctionLevelDeclContext();
1238 // If we're not in an ObjC method, error out. Note that, unlike the
1239 // C++ case, we don't require an instance method --- class methods
1240 // still have a 'self', and we really do still need to capture it!
1241 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1245 tryCaptureVariable(method->getSelfDecl(), Loc);
1250 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1251 QualType origType = T;
1252 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1253 if (T == Context.getObjCInstanceType()) {
1254 return Context.getAttributedType(
1255 AttributedType::getNullabilityAttrKind(*nullability),
1256 Context.getObjCIdType(),
1257 Context.getObjCIdType());
1263 if (T == Context.getObjCInstanceType())
1264 return Context.getObjCIdType();
1269 /// Determine the result type of a message send based on the receiver type,
1270 /// method, and the kind of message send.
1272 /// This is the "base" result type, which will still need to be adjusted
1273 /// to account for nullability.
1274 static QualType getBaseMessageSendResultType(Sema &S,
1275 QualType ReceiverType,
1276 ObjCMethodDecl *Method,
1277 bool isClassMessage,
1278 bool isSuperMessage) {
1279 assert(Method && "Must have a method");
1280 if (!Method->hasRelatedResultType())
1281 return Method->getSendResultType(ReceiverType);
1283 ASTContext &Context = S.Context;
1285 // Local function that transfers the nullability of the method's
1286 // result type to the returned result.
1287 auto transferNullability = [&](QualType type) -> QualType {
1288 // If the method's result type has nullability, extract it.
1289 if (auto nullability = Method->getSendResultType(ReceiverType)
1290 ->getNullability(Context)){
1291 // Strip off any outer nullability sugar from the provided type.
1292 (void)AttributedType::stripOuterNullability(type);
1294 // Form a new attributed type using the method result type's nullability.
1295 return Context.getAttributedType(
1296 AttributedType::getNullabilityAttrKind(*nullability),
1304 // If a method has a related return type:
1305 // - if the method found is an instance method, but the message send
1306 // was a class message send, T is the declared return type of the method
1308 if (Method->isInstanceMethod() && isClassMessage)
1309 return stripObjCInstanceType(Context,
1310 Method->getSendResultType(ReceiverType));
1312 // - if the receiver is super, T is a pointer to the class of the
1313 // enclosing method definition
1314 if (isSuperMessage) {
1315 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1316 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1317 return transferNullability(
1318 Context.getObjCObjectPointerType(
1319 Context.getObjCInterfaceType(Class)));
1323 // - if the receiver is the name of a class U, T is a pointer to U
1324 if (ReceiverType->getAsObjCInterfaceType())
1325 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1326 // - if the receiver is of type Class or qualified Class type,
1327 // T is the declared return type of the method.
1328 if (ReceiverType->isObjCClassType() ||
1329 ReceiverType->isObjCQualifiedClassType())
1330 return stripObjCInstanceType(Context,
1331 Method->getSendResultType(ReceiverType));
1333 // - if the receiver is id, qualified id, Class, or qualified Class, T
1334 // is the receiver type, otherwise
1335 // - T is the type of the receiver expression.
1336 return transferNullability(ReceiverType);
1339 QualType Sema::getMessageSendResultType(QualType ReceiverType,
1340 ObjCMethodDecl *Method,
1341 bool isClassMessage,
1342 bool isSuperMessage) {
1343 // Produce the result type.
1344 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1349 // If this is a class message, ignore the nullability of the receiver.
1353 // Map the nullability of the result into a table index.
1354 unsigned receiverNullabilityIdx = 0;
1355 if (auto nullability = ReceiverType->getNullability(Context))
1356 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1358 unsigned resultNullabilityIdx = 0;
1359 if (auto nullability = resultType->getNullability(Context))
1360 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1362 // The table of nullability mappings, indexed by the receiver's nullability
1363 // and then the result type's nullability.
1364 static const uint8_t None = 0;
1365 static const uint8_t NonNull = 1;
1366 static const uint8_t Nullable = 2;
1367 static const uint8_t Unspecified = 3;
1368 static const uint8_t nullabilityMap[4][4] = {
1369 // None NonNull Nullable Unspecified
1370 /* None */ { None, None, Nullable, None },
1371 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1372 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1373 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1376 unsigned newResultNullabilityIdx
1377 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1378 if (newResultNullabilityIdx == resultNullabilityIdx)
1381 // Strip off the existing nullability. This removes as little type sugar as
1384 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1385 resultType = attributed->getModifiedType();
1387 resultType = resultType.getDesugaredType(Context);
1389 } while (resultType->getNullability(Context));
1391 // Add nullability back if needed.
1392 if (newResultNullabilityIdx > 0) {
1394 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1395 return Context.getAttributedType(
1396 AttributedType::getNullabilityAttrKind(newNullability),
1397 resultType, resultType);
1403 /// Look for an ObjC method whose result type exactly matches the given type.
1404 static const ObjCMethodDecl *
1405 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1406 QualType instancetype) {
1407 if (MD->getReturnType() == instancetype)
1410 // For these purposes, a method in an @implementation overrides a
1411 // declaration in the @interface.
1412 if (const ObjCImplDecl *impl =
1413 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1414 const ObjCContainerDecl *iface;
1415 if (const ObjCCategoryImplDecl *catImpl =
1416 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1417 iface = catImpl->getCategoryDecl();
1419 iface = impl->getClassInterface();
1422 const ObjCMethodDecl *ifaceMD =
1423 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1424 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1427 SmallVector<const ObjCMethodDecl *, 4> overrides;
1428 MD->getOverriddenMethods(overrides);
1429 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1430 if (const ObjCMethodDecl *result =
1431 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1438 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1439 // Only complain if we're in an ObjC method and the required return
1440 // type doesn't match the method's declared return type.
1441 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1442 if (!MD || !MD->hasRelatedResultType() ||
1443 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1446 // Look for a method overridden by this method which explicitly uses
1448 if (const ObjCMethodDecl *overridden =
1449 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1450 SourceRange range = overridden->getReturnTypeSourceRange();
1451 SourceLocation loc = range.getBegin();
1452 if (loc.isInvalid())
1453 loc = overridden->getLocation();
1454 Diag(loc, diag::note_related_result_type_explicit)
1455 << /*current method*/ 1 << range;
1459 // Otherwise, if we have an interesting method family, note that.
1460 // This should always trigger if the above didn't.
1461 if (ObjCMethodFamily family = MD->getMethodFamily())
1462 Diag(MD->getLocation(), diag::note_related_result_type_family)
1463 << /*current method*/ 1
1467 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1468 E = E->IgnoreParenImpCasts();
1469 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1473 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1477 if (!Method->hasRelatedResultType())
1480 if (Context.hasSameUnqualifiedType(
1481 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1484 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1485 Context.getObjCInstanceType()))
1488 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1489 << Method->isInstanceMethod() << Method->getSelector()
1490 << MsgSend->getType();
1493 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1496 ArrayRef<SourceLocation> SelectorLocs,
1497 ObjCMethodDecl *Method,
1498 bool isClassMessage, bool isSuperMessage,
1499 SourceLocation lbrac, SourceLocation rbrac,
1500 SourceRange RecRange,
1501 QualType &ReturnType, ExprValueKind &VK) {
1502 SourceLocation SelLoc;
1503 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1504 SelLoc = SelectorLocs.front();
1509 // Apply default argument promotion as for (C99 6.5.2.2p6).
1510 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1511 if (Args[i]->isTypeDependent())
1515 if (getLangOpts().DebuggerSupport) {
1516 QualType paramTy; // ignored
1517 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1519 result = DefaultArgumentPromotion(Args[i]);
1521 if (result.isInvalid())
1523 Args[i] = result.get();
1527 if (getLangOpts().ObjCAutoRefCount)
1528 DiagID = diag::err_arc_method_not_found;
1530 DiagID = isClassMessage ? diag::warn_class_method_not_found
1531 : diag::warn_inst_method_not_found;
1532 if (!getLangOpts().DebuggerSupport) {
1533 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1534 if (OMD && !OMD->isInvalidDecl()) {
1535 if (getLangOpts().ObjCAutoRefCount)
1536 DiagID = diag::error_method_not_found_with_typo;
1538 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1539 : diag::warn_instance_method_not_found_with_typo;
1540 Selector MatchedSel = OMD->getSelector();
1541 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1542 if (MatchedSel.isUnarySelector())
1543 Diag(SelLoc, DiagID)
1544 << Sel<< isClassMessage << MatchedSel
1545 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1547 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1550 Diag(SelLoc, DiagID)
1551 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1552 SelectorLocs.back());
1553 // Find the class to which we are sending this message.
1554 if (ReceiverType->isObjCObjectPointerType()) {
1555 if (ObjCInterfaceDecl *ThisClass =
1556 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1557 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1558 if (!RecRange.isInvalid())
1559 if (ThisClass->lookupClassMethod(Sel))
1560 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1561 << FixItHint::CreateReplacement(RecRange,
1562 ThisClass->getNameAsString());
1567 // In debuggers, we want to use __unknown_anytype for these
1568 // results so that clients can cast them.
1569 if (getLangOpts().DebuggerSupport) {
1570 ReturnType = Context.UnknownAnyTy;
1572 ReturnType = Context.getObjCIdType();
1578 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1580 VK = Expr::getValueKindForType(Method->getReturnType());
1582 unsigned NumNamedArgs = Sel.getNumArgs();
1583 // Method might have more arguments than selector indicates. This is due
1584 // to addition of c-style arguments in method.
1585 if (Method->param_size() > Sel.getNumArgs())
1586 NumNamedArgs = Method->param_size();
1587 // FIXME. This need be cleaned up.
1588 if (Args.size() < NumNamedArgs) {
1589 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1590 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1594 // Compute the set of type arguments to be substituted into each parameter
1596 Optional<ArrayRef<QualType>> typeArgs
1597 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1598 bool IsError = false;
1599 for (unsigned i = 0; i < NumNamedArgs; i++) {
1600 // We can't do any type-checking on a type-dependent argument.
1601 if (Args[i]->isTypeDependent())
1604 Expr *argExpr = Args[i];
1606 ParmVarDecl *param = Method->parameters()[i];
1607 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1609 // Strip the unbridged-cast placeholder expression off unless it's
1610 // a consumed argument.
1611 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1612 !param->hasAttr<CFConsumedAttr>())
1613 argExpr = stripARCUnbridgedCast(argExpr);
1615 // If the parameter is __unknown_anytype, infer its type
1616 // from the argument.
1617 if (param->getType() == Context.UnknownAnyTy) {
1619 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1620 if (argE.isInvalid()) {
1623 Args[i] = argE.get();
1625 // Update the parameter type in-place.
1626 param->setType(paramType);
1631 QualType origParamType = param->getType();
1632 QualType paramType = param->getType();
1634 paramType = paramType.substObjCTypeArgs(
1637 ObjCSubstitutionContext::Parameter);
1639 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1641 diag::err_call_incomplete_argument, argExpr))
1644 InitializedEntity Entity
1645 = InitializedEntity::InitializeParameter(Context, param, paramType);
1646 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1647 if (ArgE.isInvalid())
1650 Args[i] = ArgE.getAs<Expr>();
1652 // If we are type-erasing a block to a block-compatible
1653 // Objective-C pointer type, we may need to extend the lifetime
1654 // of the block object.
1655 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1656 Args[i]->getType()->isBlockPointerType() &&
1657 origParamType->isObjCObjectPointerType()) {
1658 ExprResult arg = Args[i];
1659 maybeExtendBlockObject(arg);
1660 Args[i] = arg.get();
1665 // Promote additional arguments to variadic methods.
1666 if (Method->isVariadic()) {
1667 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1668 if (Args[i]->isTypeDependent())
1671 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1673 IsError |= Arg.isInvalid();
1674 Args[i] = Arg.get();
1677 // Check for extra arguments to non-variadic methods.
1678 if (Args.size() != NumNamedArgs) {
1679 Diag(Args[NumNamedArgs]->getLocStart(),
1680 diag::err_typecheck_call_too_many_args)
1681 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1682 << Method->getSourceRange()
1683 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1684 Args.back()->getLocEnd());
1688 DiagnoseSentinelCalls(Method, SelLoc, Args);
1690 // Do additional checkings on method.
1691 IsError |= CheckObjCMethodCall(
1692 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1697 bool Sema::isSelfExpr(Expr *RExpr) {
1698 // 'self' is objc 'self' in an objc method only.
1699 ObjCMethodDecl *Method =
1700 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1701 return isSelfExpr(RExpr, Method);
1704 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1705 if (!method) return false;
1707 receiver = receiver->IgnoreParenLValueCasts();
1708 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1709 if (DRE->getDecl() == method->getSelfDecl())
1714 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1715 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1717 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1718 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1719 // Look it up in the main interface (and categories, etc.)
1720 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1723 // Okay, look for "private" methods declared in any
1724 // @implementations we've seen.
1725 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1729 // Check qualifiers.
1730 for (const auto *I : objType->quals())
1731 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1737 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1738 /// list of a qualified objective pointer type.
1739 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1740 const ObjCObjectPointerType *OPT,
1743 ObjCMethodDecl *MD = nullptr;
1744 for (const auto *PROTO : OPT->quals()) {
1745 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1752 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1753 /// objective C interface. This is a property reference expression.
1755 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1756 Expr *BaseExpr, SourceLocation OpLoc,
1757 DeclarationName MemberName,
1758 SourceLocation MemberLoc,
1759 SourceLocation SuperLoc, QualType SuperType,
1761 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1762 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1764 if (!MemberName.isIdentifier()) {
1765 Diag(MemberLoc, diag::err_invalid_property_name)
1766 << MemberName << QualType(OPT, 0);
1770 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1772 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1773 : BaseExpr->getSourceRange();
1774 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1775 diag::err_property_not_found_forward_class,
1776 MemberName, BaseRange))
1779 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1780 // Check whether we can reference this property.
1781 if (DiagnoseUseOfDecl(PD, MemberLoc))
1784 return new (Context)
1785 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1786 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1788 return new (Context)
1789 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1790 OK_ObjCProperty, MemberLoc, BaseExpr);
1792 // Check protocols on qualified interfaces.
1793 for (const auto *I : OPT->quals())
1794 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
1795 // Check whether we can reference this property.
1796 if (DiagnoseUseOfDecl(PD, MemberLoc))
1800 return new (Context) ObjCPropertyRefExpr(
1801 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1802 SuperLoc, SuperType);
1804 return new (Context)
1805 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1806 OK_ObjCProperty, MemberLoc, BaseExpr);
1808 // If that failed, look for an "implicit" property by seeing if the nullary
1809 // selector is implemented.
1811 // FIXME: The logic for looking up nullary and unary selectors should be
1812 // shared with the code in ActOnInstanceMessage.
1814 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1815 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1817 // May be founf in property's qualified list.
1819 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
1821 // If this reference is in an @implementation, check for 'private' methods.
1823 Getter = IFace->lookupPrivateMethod(Sel);
1826 // Check if we can reference this property.
1827 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1830 // If we found a getter then this may be a valid dot-reference, we
1831 // will look for the matching setter, in case it is needed.
1832 Selector SetterSel =
1833 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1834 PP.getSelectorTable(), Member);
1835 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1837 // May be founf in property's qualified list.
1839 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1842 // If this reference is in an @implementation, also check for 'private'
1844 Setter = IFace->lookupPrivateMethod(SetterSel);
1847 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1850 // Special warning if member name used in a property-dot for a setter accessor
1851 // does not use a property with same name; e.g. obj.X = ... for a property with
1853 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1854 && !IFace->FindPropertyDeclaration(Member)) {
1855 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1856 // Do not warn if user is using property-dot syntax to make call to
1857 // user named setter.
1858 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
1860 diag::warn_property_access_suggest)
1861 << MemberName << QualType(OPT, 0) << PDecl->getName()
1862 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
1866 if (Getter || Setter) {
1868 return new (Context)
1869 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1870 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1872 return new (Context)
1873 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1874 OK_ObjCProperty, MemberLoc, BaseExpr);
1878 // Attempt to correct for typos in property names.
1879 if (TypoCorrection Corrected =
1880 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1881 LookupOrdinaryName, nullptr, nullptr,
1882 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1883 CTK_ErrorRecovery, IFace, false, OPT)) {
1884 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1885 << MemberName << QualType(OPT, 0));
1886 DeclarationName TypoResult = Corrected.getCorrection();
1887 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1888 TypoResult, MemberLoc,
1889 SuperLoc, SuperType, Super);
1891 ObjCInterfaceDecl *ClassDeclared;
1892 if (ObjCIvarDecl *Ivar =
1893 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1894 QualType T = Ivar->getType();
1895 if (const ObjCObjectPointerType * OBJPT =
1896 T->getAsObjCInterfacePointerType()) {
1897 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1898 diag::err_property_not_as_forward_class,
1899 MemberName, BaseExpr))
1903 diag::err_ivar_access_using_property_syntax_suggest)
1904 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1905 << FixItHint::CreateReplacement(OpLoc, "->");
1909 Diag(MemberLoc, diag::err_property_not_found)
1910 << MemberName << QualType(OPT, 0);
1912 Diag(Setter->getLocation(), diag::note_getter_unavailable)
1913 << MemberName << BaseExpr->getSourceRange();
1920 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1921 IdentifierInfo &propertyName,
1922 SourceLocation receiverNameLoc,
1923 SourceLocation propertyNameLoc) {
1925 IdentifierInfo *receiverNamePtr = &receiverName;
1926 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1931 // If the "receiver" is 'super' in a method, handle it as an expression-like
1932 // property reference.
1933 if (receiverNamePtr->isStr("super")) {
1934 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
1935 if (auto classDecl = CurMethod->getClassInterface()) {
1936 SuperType = QualType(classDecl->getSuperClassType(), 0);
1937 if (CurMethod->isInstanceMethod()) {
1938 if (SuperType.isNull()) {
1939 // The current class does not have a superclass.
1940 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1941 << CurMethod->getClassInterface()->getIdentifier();
1944 QualType T = Context.getObjCObjectPointerType(SuperType);
1946 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
1947 /*BaseExpr*/nullptr,
1948 SourceLocation()/*OpLoc*/,
1951 receiverNameLoc, T, true);
1954 // Otherwise, if this is a class method, try dispatching to our
1956 IFace = CurMethod->getClassInterface()->getSuperClass();
1962 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1968 // Search for a declared property first.
1969 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
1970 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
1972 // If this reference is in an @implementation, check for 'private' methods.
1974 Getter = IFace->lookupPrivateClassMethod(Sel);
1977 // FIXME: refactor/share with ActOnMemberReference().
1978 // Check if we can reference this property.
1979 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1983 // Look for the matching setter, in case it is needed.
1984 Selector SetterSel =
1985 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1986 PP.getSelectorTable(),
1989 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1991 // If this reference is in an @implementation, also check for 'private'
1993 Setter = IFace->lookupPrivateClassMethod(SetterSel);
1995 // Look through local category implementations associated with the class.
1997 Setter = IFace->getCategoryClassMethod(SetterSel);
1999 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2002 if (Getter || Setter) {
2003 if (!SuperType.isNull())
2004 return new (Context)
2005 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2006 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2009 return new (Context) ObjCPropertyRefExpr(
2010 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2011 propertyNameLoc, receiverNameLoc, IFace);
2013 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2014 << &propertyName << Context.getObjCInterfaceType(IFace));
2019 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
2021 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2022 // Determine whether "super" is acceptable in the current context.
2023 if (Method && Method->getClassInterface())
2024 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2027 bool ValidateCandidate(const TypoCorrection &candidate) override {
2028 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2029 candidate.isKeyword("super");
2035 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2036 IdentifierInfo *Name,
2037 SourceLocation NameLoc,
2039 bool HasTrailingDot,
2040 ParsedType &ReceiverType) {
2041 ReceiverType = ParsedType();
2043 // If the identifier is "super" and there is no trailing dot, we're
2044 // messaging super. If the identifier is "super" and there is a
2045 // trailing dot, it's an instance message.
2046 if (IsSuper && S->isInObjcMethodScope())
2047 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2049 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2050 LookupName(Result, S);
2052 switch (Result.getResultKind()) {
2053 case LookupResult::NotFound:
2054 // Normal name lookup didn't find anything. If we're in an
2055 // Objective-C method, look for ivars. If we find one, we're done!
2056 // FIXME: This is a hack. Ivar lookup should be part of normal
2058 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2059 if (!Method->getClassInterface()) {
2060 // Fall back: let the parser try to parse it as an instance message.
2061 return ObjCInstanceMessage;
2064 ObjCInterfaceDecl *ClassDeclared;
2065 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2067 return ObjCInstanceMessage;
2070 // Break out; we'll perform typo correction below.
2073 case LookupResult::NotFoundInCurrentInstantiation:
2074 case LookupResult::FoundOverloaded:
2075 case LookupResult::FoundUnresolvedValue:
2076 case LookupResult::Ambiguous:
2077 Result.suppressDiagnostics();
2078 return ObjCInstanceMessage;
2080 case LookupResult::Found: {
2081 // If the identifier is a class or not, and there is a trailing dot,
2082 // it's an instance message.
2084 return ObjCInstanceMessage;
2085 // We found something. If it's a type, then we have a class
2086 // message. Otherwise, it's an instance message.
2087 NamedDecl *ND = Result.getFoundDecl();
2089 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2090 T = Context.getObjCInterfaceType(Class);
2091 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2092 T = Context.getTypeDeclType(Type);
2093 DiagnoseUseOfDecl(Type, NameLoc);
2096 return ObjCInstanceMessage;
2098 // We have a class message, and T is the type we're
2099 // messaging. Build source-location information for it.
2100 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2101 ReceiverType = CreateParsedType(T, TSInfo);
2102 return ObjCClassMessage;
2106 if (TypoCorrection Corrected = CorrectTypo(
2107 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
2108 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
2109 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2110 if (Corrected.isKeyword()) {
2111 // If we've found the keyword "super" (the only keyword that would be
2112 // returned by CorrectTypo), this is a send to super.
2113 diagnoseTypo(Corrected,
2114 PDiag(diag::err_unknown_receiver_suggest) << Name);
2115 return ObjCSuperMessage;
2116 } else if (ObjCInterfaceDecl *Class =
2117 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2118 // If we found a declaration, correct when it refers to an Objective-C
2120 diagnoseTypo(Corrected,
2121 PDiag(diag::err_unknown_receiver_suggest) << Name);
2122 QualType T = Context.getObjCInterfaceType(Class);
2123 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2124 ReceiverType = CreateParsedType(T, TSInfo);
2125 return ObjCClassMessage;
2129 // Fall back: let the parser try to parse it as an instance message.
2130 return ObjCInstanceMessage;
2133 ExprResult Sema::ActOnSuperMessage(Scope *S,
2134 SourceLocation SuperLoc,
2136 SourceLocation LBracLoc,
2137 ArrayRef<SourceLocation> SelectorLocs,
2138 SourceLocation RBracLoc,
2139 MultiExprArg Args) {
2140 // Determine whether we are inside a method or not.
2141 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2143 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2147 ObjCInterfaceDecl *Class = Method->getClassInterface();
2149 Diag(SuperLoc, diag::error_no_super_class_message)
2150 << Method->getDeclName();
2154 QualType SuperTy(Class->getSuperClassType(), 0);
2155 if (SuperTy.isNull()) {
2156 // The current class does not have a superclass.
2157 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
2158 << Class->getIdentifier();
2162 // We are in a method whose class has a superclass, so 'super'
2163 // is acting as a keyword.
2164 if (Method->getSelector() == Sel)
2165 getCurFunction()->ObjCShouldCallSuper = false;
2167 if (Method->isInstanceMethod()) {
2168 // Since we are in an instance method, this is an instance
2169 // message to the superclass instance.
2170 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2171 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2172 Sel, /*Method=*/nullptr,
2173 LBracLoc, SelectorLocs, RBracLoc, Args);
2176 // Since we are in a class method, this is a class message to
2178 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2180 SuperLoc, Sel, /*Method=*/nullptr,
2181 LBracLoc, SelectorLocs, RBracLoc, Args);
2185 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2186 bool isSuperReceiver,
2189 ObjCMethodDecl *Method,
2190 MultiExprArg Args) {
2191 TypeSourceInfo *receiverTypeInfo = nullptr;
2192 if (!ReceiverType.isNull())
2193 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2195 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2196 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2197 Sel, Method, Loc, Loc, Loc, Args,
2198 /*isImplicit=*/true);
2202 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2204 bool (*refactor)(const ObjCMessageExpr *,
2205 const NSAPI &, edit::Commit &)) {
2206 SourceLocation MsgLoc = Msg->getExprLoc();
2207 if (S.Diags.isIgnored(DiagID, MsgLoc))
2210 SourceManager &SM = S.SourceMgr;
2211 edit::Commit ECommit(SM, S.LangOpts);
2212 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2213 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2214 << Msg->getSelector() << Msg->getSourceRange();
2215 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2216 if (!ECommit.isCommitable())
2218 for (edit::Commit::edit_iterator
2219 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2220 const edit::Commit::Edit &Edit = *I;
2221 switch (Edit.Kind) {
2222 case edit::Commit::Act_Insert:
2223 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2227 case edit::Commit::Act_InsertFromRange:
2228 Builder.AddFixItHint(
2229 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2230 Edit.getInsertFromRange(SM),
2233 case edit::Commit::Act_Remove:
2234 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2241 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2242 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2243 edit::rewriteObjCRedundantCallWithLiteral);
2246 /// \brief Diagnose use of %s directive in an NSString which is being passed
2247 /// as formatting string to formatting method.
2249 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2250 ObjCMethodDecl *Method,
2252 Expr **Args, unsigned NumArgs) {
2254 bool Format = false;
2255 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2256 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2261 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2262 if (S.GetFormatNSStringIdx(I, Idx)) {
2268 if (!Format || NumArgs <= Idx)
2271 Expr *FormatExpr = Args[Idx];
2272 if (ObjCStringLiteral *OSL =
2273 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2274 StringLiteral *FormatString = OSL->getString();
2275 if (S.FormatStringHasSArg(FormatString)) {
2276 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2279 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2280 << Method->getDeclName();
2285 /// \brief Build an Objective-C class message expression.
2287 /// This routine takes care of both normal class messages and
2288 /// class messages to the superclass.
2290 /// \param ReceiverTypeInfo Type source information that describes the
2291 /// receiver of this message. This may be NULL, in which case we are
2292 /// sending to the superclass and \p SuperLoc must be a valid source
2295 /// \param ReceiverType The type of the object receiving the
2296 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2297 /// type as that refers to. For a superclass send, this is the type of
2300 /// \param SuperLoc The location of the "super" keyword in a
2301 /// superclass message.
2303 /// \param Sel The selector to which the message is being sent.
2305 /// \param Method The method that this class message is invoking, if
2308 /// \param LBracLoc The location of the opening square bracket ']'.
2310 /// \param RBracLoc The location of the closing square bracket ']'.
2312 /// \param ArgsIn The message arguments.
2313 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2314 QualType ReceiverType,
2315 SourceLocation SuperLoc,
2317 ObjCMethodDecl *Method,
2318 SourceLocation LBracLoc,
2319 ArrayRef<SourceLocation> SelectorLocs,
2320 SourceLocation RBracLoc,
2321 MultiExprArg ArgsIn,
2323 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2324 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2325 if (LBracLoc.isInvalid()) {
2326 Diag(Loc, diag::err_missing_open_square_message_send)
2327 << FixItHint::CreateInsertion(Loc, "[");
2330 SourceLocation SelLoc;
2331 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2332 SelLoc = SelectorLocs.front();
2336 if (ReceiverType->isDependentType()) {
2337 // If the receiver type is dependent, we can't type-check anything
2338 // at this point. Build a dependent expression.
2339 unsigned NumArgs = ArgsIn.size();
2340 Expr **Args = ArgsIn.data();
2341 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2342 return ObjCMessageExpr::Create(
2343 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2344 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2348 // Find the class to which we are sending this message.
2349 ObjCInterfaceDecl *Class = nullptr;
2350 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2351 if (!ClassType || !(Class = ClassType->getInterface())) {
2352 Diag(Loc, diag::err_invalid_receiver_class_message)
2356 assert(Class && "We don't know which class we're messaging?");
2357 // objc++ diagnoses during typename annotation.
2358 if (!getLangOpts().CPlusPlus)
2359 (void)DiagnoseUseOfDecl(Class, SelLoc);
2360 // Find the method we are messaging.
2362 SourceRange TypeRange
2363 = SuperLoc.isValid()? SourceRange(SuperLoc)
2364 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2365 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2366 (getLangOpts().ObjCAutoRefCount
2367 ? diag::err_arc_receiver_forward_class
2368 : diag::warn_receiver_forward_class),
2370 // A forward class used in messaging is treated as a 'Class'
2371 Method = LookupFactoryMethodInGlobalPool(Sel,
2372 SourceRange(LBracLoc, RBracLoc));
2373 if (Method && !getLangOpts().ObjCAutoRefCount)
2374 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2375 << Method->getDeclName();
2378 Method = Class->lookupClassMethod(Sel);
2380 // If we have an implementation in scope, check "private" methods.
2382 Method = Class->lookupPrivateClassMethod(Sel);
2384 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2388 // Check the argument types and determine the result type.
2389 QualType ReturnType;
2390 ExprValueKind VK = VK_RValue;
2392 unsigned NumArgs = ArgsIn.size();
2393 Expr **Args = ArgsIn.data();
2394 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2397 SuperLoc.isValid(), LBracLoc, RBracLoc,
2402 if (Method && !Method->getReturnType()->isVoidType() &&
2403 RequireCompleteType(LBracLoc, Method->getReturnType(),
2404 diag::err_illegal_message_expr_incomplete_type))
2407 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2408 if (Method && Method->getMethodFamily() == OMF_initialize) {
2409 if (!SuperLoc.isValid()) {
2410 const ObjCInterfaceDecl *ID =
2411 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2413 Diag(Loc, diag::warn_direct_initialize_call);
2414 Diag(Method->getLocation(), diag::note_method_declared_at)
2415 << Method->getDeclName();
2418 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2419 // [super initialize] is allowed only within an +initialize implementation
2420 if (CurMeth->getMethodFamily() != OMF_initialize) {
2421 Diag(Loc, diag::warn_direct_super_initialize_call);
2422 Diag(Method->getLocation(), diag::note_method_declared_at)
2423 << Method->getDeclName();
2424 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2425 << CurMeth->getDeclName();
2430 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2432 // Construct the appropriate ObjCMessageExpr.
2433 ObjCMessageExpr *Result;
2434 if (SuperLoc.isValid())
2435 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2436 SuperLoc, /*IsInstanceSuper=*/false,
2437 ReceiverType, Sel, SelectorLocs,
2438 Method, makeArrayRef(Args, NumArgs),
2439 RBracLoc, isImplicit);
2441 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2442 ReceiverTypeInfo, Sel, SelectorLocs,
2443 Method, makeArrayRef(Args, NumArgs),
2444 RBracLoc, isImplicit);
2446 checkCocoaAPI(*this, Result);
2448 return MaybeBindToTemporary(Result);
2451 // ActOnClassMessage - used for both unary and keyword messages.
2452 // ArgExprs is optional - if it is present, the number of expressions
2453 // is obtained from Sel.getNumArgs().
2454 ExprResult Sema::ActOnClassMessage(Scope *S,
2455 ParsedType Receiver,
2457 SourceLocation LBracLoc,
2458 ArrayRef<SourceLocation> SelectorLocs,
2459 SourceLocation RBracLoc,
2460 MultiExprArg Args) {
2461 TypeSourceInfo *ReceiverTypeInfo;
2462 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2463 if (ReceiverType.isNull())
2467 if (!ReceiverTypeInfo)
2468 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2470 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2471 /*SuperLoc=*/SourceLocation(), Sel,
2472 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2476 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2477 QualType ReceiverType,
2480 ObjCMethodDecl *Method,
2481 MultiExprArg Args) {
2482 return BuildInstanceMessage(Receiver, ReceiverType,
2483 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2484 Sel, Method, Loc, Loc, Loc, Args,
2485 /*isImplicit=*/true);
2488 /// \brief Build an Objective-C instance message expression.
2490 /// This routine takes care of both normal instance messages and
2491 /// instance messages to the superclass instance.
2493 /// \param Receiver The expression that computes the object that will
2494 /// receive this message. This may be empty, in which case we are
2495 /// sending to the superclass instance and \p SuperLoc must be a valid
2496 /// source location.
2498 /// \param ReceiverType The (static) type of the object receiving the
2499 /// message. When a \p Receiver expression is provided, this is the
2500 /// same type as that expression. For a superclass instance send, this
2501 /// is a pointer to the type of the superclass.
2503 /// \param SuperLoc The location of the "super" keyword in a
2504 /// superclass instance message.
2506 /// \param Sel The selector to which the message is being sent.
2508 /// \param Method The method that this instance message is invoking, if
2511 /// \param LBracLoc The location of the opening square bracket ']'.
2513 /// \param RBracLoc The location of the closing square bracket ']'.
2515 /// \param ArgsIn The message arguments.
2516 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2517 QualType ReceiverType,
2518 SourceLocation SuperLoc,
2520 ObjCMethodDecl *Method,
2521 SourceLocation LBracLoc,
2522 ArrayRef<SourceLocation> SelectorLocs,
2523 SourceLocation RBracLoc,
2524 MultiExprArg ArgsIn,
2526 // The location of the receiver.
2527 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2528 SourceRange RecRange =
2529 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2530 SourceLocation SelLoc;
2531 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2532 SelLoc = SelectorLocs.front();
2536 if (LBracLoc.isInvalid()) {
2537 Diag(Loc, diag::err_missing_open_square_message_send)
2538 << FixItHint::CreateInsertion(Loc, "[");
2542 // If we have a receiver expression, perform appropriate promotions
2543 // and determine receiver type.
2545 if (Receiver->hasPlaceholderType()) {
2547 if (Receiver->getType() == Context.UnknownAnyTy)
2548 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2550 Result = CheckPlaceholderExpr(Receiver);
2551 if (Result.isInvalid()) return ExprError();
2552 Receiver = Result.get();
2555 if (Receiver->isTypeDependent()) {
2556 // If the receiver is type-dependent, we can't type-check anything
2557 // at this point. Build a dependent expression.
2558 unsigned NumArgs = ArgsIn.size();
2559 Expr **Args = ArgsIn.data();
2560 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2561 return ObjCMessageExpr::Create(
2562 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2563 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2564 RBracLoc, isImplicit);
2567 // If necessary, apply function/array conversion to the receiver.
2568 // C99 6.7.5.3p[7,8].
2569 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2570 if (Result.isInvalid())
2572 Receiver = Result.get();
2573 ReceiverType = Receiver->getType();
2575 // If the receiver is an ObjC pointer, a block pointer, or an
2576 // __attribute__((NSObject)) pointer, we don't need to do any
2577 // special conversion in order to look up a receiver.
2578 if (ReceiverType->isObjCRetainableType()) {
2580 } else if (!getLangOpts().ObjCAutoRefCount &&
2581 !Context.getObjCIdType().isNull() &&
2582 (ReceiverType->isPointerType() ||
2583 ReceiverType->isIntegerType())) {
2584 // Implicitly convert integers and pointers to 'id' but emit a warning.
2586 Diag(Loc, diag::warn_bad_receiver_type)
2588 << Receiver->getSourceRange();
2589 if (ReceiverType->isPointerType()) {
2590 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2591 CK_CPointerToObjCPointerCast).get();
2593 // TODO: specialized warning on null receivers?
2594 bool IsNull = Receiver->isNullPointerConstant(Context,
2595 Expr::NPC_ValueDependentIsNull);
2596 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2597 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2600 ReceiverType = Receiver->getType();
2601 } else if (getLangOpts().CPlusPlus) {
2602 // The receiver must be a complete type.
2603 if (RequireCompleteType(Loc, Receiver->getType(),
2604 diag::err_incomplete_receiver_type))
2607 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2608 if (result.isUsable()) {
2609 Receiver = result.get();
2610 ReceiverType = Receiver->getType();
2615 // There's a somewhat weird interaction here where we assume that we
2616 // won't actually have a method unless we also don't need to do some
2617 // of the more detailed type-checking on the receiver.
2620 // Handle messages to id and __kindof types (where we use the
2621 // global method pool).
2622 // FIXME: The type bound is currently ignored by lookup in the
2624 const ObjCObjectType *typeBound = nullptr;
2625 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2627 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2628 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2629 Method = LookupInstanceMethodInGlobalPool(Sel,
2630 SourceRange(LBracLoc, RBracLoc),
2633 Method = LookupFactoryMethodInGlobalPool(Sel,
2634 SourceRange(LBracLoc,RBracLoc),
2637 if (ObjCMethodDecl *BestMethod =
2638 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2639 Method = BestMethod;
2640 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2641 SourceRange(LBracLoc, RBracLoc),
2642 receiverIsIdLike)) {
2643 DiagnoseUseOfDecl(Method, SelLoc);
2646 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2647 ReceiverType->isObjCQualifiedClassType()) {
2648 // Handle messages to Class.
2649 // We allow sending a message to a qualified Class ("Class<foo>"), which
2650 // is ok as long as one of the protocols implements the selector (if not,
2652 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2653 const ObjCObjectPointerType *QClassTy
2654 = ReceiverType->getAsObjCQualifiedClassType();
2655 // Search protocols for class methods.
2656 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2658 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2659 // warn if instance method found for a Class message.
2661 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2662 << Method->getSelector() << Sel;
2663 Diag(Method->getLocation(), diag::note_method_declared_at)
2664 << Method->getDeclName();
2668 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2669 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2670 // First check the public methods in the class interface.
2671 Method = ClassDecl->lookupClassMethod(Sel);
2674 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2676 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2680 // If not messaging 'self', look for any factory method named 'Sel'.
2681 if (!Receiver || !isSelfExpr(Receiver)) {
2682 Method = LookupFactoryMethodInGlobalPool(Sel,
2683 SourceRange(LBracLoc, RBracLoc));
2685 // If no class (factory) method was found, check if an _instance_
2686 // method of the same name exists in the root class only.
2687 Method = LookupInstanceMethodInGlobalPool(Sel,
2688 SourceRange(LBracLoc, RBracLoc));
2690 if (const ObjCInterfaceDecl *ID =
2691 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2692 if (ID->getSuperClass())
2693 Diag(SelLoc, diag::warn_root_inst_method_not_found)
2694 << Sel << SourceRange(LBracLoc, RBracLoc);
2698 if (ObjCMethodDecl *BestMethod =
2699 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2700 Method = BestMethod;
2705 ObjCInterfaceDecl *ClassDecl = nullptr;
2707 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2708 // long as one of the protocols implements the selector (if not, warn).
2709 // And as long as message is not deprecated/unavailable (warn if it is).
2710 if (const ObjCObjectPointerType *QIdTy
2711 = ReceiverType->getAsObjCQualifiedIdType()) {
2712 // Search protocols for instance methods.
2713 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2715 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
2716 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
2718 } else if (const ObjCObjectPointerType *OCIType
2719 = ReceiverType->getAsObjCInterfacePointerType()) {
2720 // We allow sending a message to a pointer to an interface (an object).
2721 ClassDecl = OCIType->getInterfaceDecl();
2723 // Try to complete the type. Under ARC, this is a hard error from which
2724 // we don't try to recover.
2725 // FIXME: In the non-ARC case, this will still be a hard error if the
2726 // definition is found in a module that's not visible.
2727 const ObjCInterfaceDecl *forwardClass = nullptr;
2728 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
2729 getLangOpts().ObjCAutoRefCount
2730 ? diag::err_arc_receiver_forward_instance
2731 : diag::warn_receiver_forward_instance,
2732 Receiver? Receiver->getSourceRange()
2733 : SourceRange(SuperLoc))) {
2734 if (getLangOpts().ObjCAutoRefCount)
2737 forwardClass = OCIType->getInterfaceDecl();
2738 Diag(Receiver ? Receiver->getLocStart()
2739 : SuperLoc, diag::note_receiver_is_id);
2742 Method = ClassDecl->lookupInstanceMethod(Sel);
2746 // Search protocol qualifiers.
2747 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2750 // If we have implementations in scope, check "private" methods.
2751 Method = ClassDecl->lookupPrivateMethod(Sel);
2753 if (!Method && getLangOpts().ObjCAutoRefCount) {
2754 Diag(SelLoc, diag::err_arc_may_not_respond)
2755 << OCIType->getPointeeType() << Sel << RecRange
2756 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
2760 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
2761 // If we still haven't found a method, look in the global pool. This
2762 // behavior isn't very desirable, however we need it for GCC
2763 // compatibility. FIXME: should we deviate??
2764 if (OCIType->qual_empty()) {
2765 Method = LookupInstanceMethodInGlobalPool(Sel,
2766 SourceRange(LBracLoc, RBracLoc));
2768 if (auto BestMethod =
2769 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2770 Method = BestMethod;
2771 AreMultipleMethodsInGlobalPool(Sel, Method,
2772 SourceRange(LBracLoc, RBracLoc),
2775 if (Method && !forwardClass)
2776 Diag(SelLoc, diag::warn_maynot_respond)
2777 << OCIType->getInterfaceDecl()->getIdentifier()
2782 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
2785 // Reject other random receiver types (e.g. structs).
2786 Diag(Loc, diag::err_bad_receiver_type)
2787 << ReceiverType << Receiver->getSourceRange();
2793 FunctionScopeInfo *DIFunctionScopeInfo =
2794 (Method && Method->getMethodFamily() == OMF_init)
2795 ? getEnclosingFunction() : nullptr;
2797 if (DIFunctionScopeInfo &&
2798 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
2799 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2800 bool isDesignatedInitChain = false;
2801 if (SuperLoc.isValid()) {
2802 if (const ObjCObjectPointerType *
2803 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2804 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
2805 // Either we know this is a designated initializer or we
2806 // conservatively assume it because we don't know for sure.
2807 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2808 ID->isDesignatedInitializer(Sel)) {
2809 isDesignatedInitChain = true;
2810 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
2815 if (!isDesignatedInitChain) {
2816 const ObjCMethodDecl *InitMethod = nullptr;
2818 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2819 assert(isDesignated && InitMethod);
2821 Diag(SelLoc, SuperLoc.isValid() ?
2822 diag::warn_objc_designated_init_non_designated_init_call :
2823 diag::warn_objc_designated_init_non_super_designated_init_call);
2824 Diag(InitMethod->getLocation(),
2825 diag::note_objc_designated_init_marked_here);
2829 if (DIFunctionScopeInfo &&
2830 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
2831 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2832 if (SuperLoc.isValid()) {
2833 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2835 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
2839 // Check the message arguments.
2840 unsigned NumArgs = ArgsIn.size();
2841 Expr **Args = ArgsIn.data();
2842 QualType ReturnType;
2843 ExprValueKind VK = VK_RValue;
2844 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2845 ReceiverType->isObjCQualifiedClassType());
2846 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2847 Sel, SelectorLocs, Method,
2848 ClassMessage, SuperLoc.isValid(),
2849 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
2852 if (Method && !Method->getReturnType()->isVoidType() &&
2853 RequireCompleteType(LBracLoc, Method->getReturnType(),
2854 diag::err_illegal_message_expr_incomplete_type))
2857 // In ARC, forbid the user from sending messages to
2858 // retain/release/autorelease/dealloc/retainCount explicitly.
2859 if (getLangOpts().ObjCAutoRefCount) {
2860 ObjCMethodFamily family =
2861 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2865 checkInitMethod(Method, ReceiverType);
2871 case OMF_mutableCopy:
2874 case OMF_initialize:
2880 case OMF_autorelease:
2881 case OMF_retainCount:
2882 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2886 case OMF_performSelector:
2887 if (Method && NumArgs >= 1) {
2888 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2889 Selector ArgSel = SelExp->getSelector();
2890 ObjCMethodDecl *SelMethod =
2891 LookupInstanceMethodInGlobalPool(ArgSel,
2892 SelExp->getSourceRange());
2895 LookupFactoryMethodInGlobalPool(ArgSel,
2896 SelExp->getSourceRange());
2898 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2899 switch (SelFamily) {
2902 case OMF_mutableCopy:
2906 // Issue error, unless ns_returns_not_retained.
2907 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2908 // selector names a +1 method
2910 diag::err_arc_perform_selector_retains);
2911 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2912 << SelMethod->getDeclName();
2916 // +0 call. OK. unless ns_returns_retained.
2917 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2918 // selector names a +1 method
2920 diag::err_arc_perform_selector_retains);
2921 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2922 << SelMethod->getDeclName();
2928 // error (may leak).
2929 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
2930 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2937 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2939 // Construct the appropriate ObjCMessageExpr instance.
2940 ObjCMessageExpr *Result;
2941 if (SuperLoc.isValid())
2942 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2943 SuperLoc, /*IsInstanceSuper=*/true,
2944 ReceiverType, Sel, SelectorLocs, Method,
2945 makeArrayRef(Args, NumArgs), RBracLoc,
2948 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2949 Receiver, Sel, SelectorLocs, Method,
2950 makeArrayRef(Args, NumArgs), RBracLoc,
2953 checkCocoaAPI(*this, Result);
2956 if (getLangOpts().ObjCAutoRefCount) {
2957 // In ARC, annotate delegate init calls.
2958 if (Result->getMethodFamily() == OMF_init &&
2959 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2960 // Only consider init calls *directly* in init implementations,
2961 // not within blocks.
2962 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2963 if (method && method->getMethodFamily() == OMF_init) {
2964 // The implicit assignment to self means we also don't want to
2965 // consume the result.
2966 Result->setDelegateInitCall(true);
2971 // In ARC, check for message sends which are likely to introduce
2973 checkRetainCycles(Result);
2975 if (!isImplicit && Method) {
2976 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2978 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2979 if (!IsWeak && Sel.isUnarySelector())
2980 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2982 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2983 getCurFunction()->recordUseOfWeak(Result, Prop);
2988 CheckObjCCircularContainer(Result);
2990 return MaybeBindToTemporary(Result);
2993 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2994 if (ObjCSelectorExpr *OSE =
2995 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2996 Selector Sel = OSE->getSelector();
2997 SourceLocation Loc = OSE->getAtLoc();
2998 auto Pos = S.ReferencedSelectors.find(Sel);
2999 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3000 S.ReferencedSelectors.erase(Pos);
3004 // ActOnInstanceMessage - used for both unary and keyword messages.
3005 // ArgExprs is optional - if it is present, the number of expressions
3006 // is obtained from Sel.getNumArgs().
3007 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3010 SourceLocation LBracLoc,
3011 ArrayRef<SourceLocation> SelectorLocs,
3012 SourceLocation RBracLoc,
3013 MultiExprArg Args) {
3017 // A ParenListExpr can show up while doing error recovery with invalid code.
3018 if (isa<ParenListExpr>(Receiver)) {
3019 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3020 if (Result.isInvalid()) return ExprError();
3021 Receiver = Result.get();
3024 if (RespondsToSelectorSel.isNull()) {
3025 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3026 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3028 if (Sel == RespondsToSelectorSel)
3029 RemoveSelectorFromWarningCache(*this, Args[0]);
3031 return BuildInstanceMessage(Receiver, Receiver->getType(),
3032 /*SuperLoc=*/SourceLocation(), Sel,
3033 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3037 enum ARCConversionTypeClass {
3038 /// int, void, struct A
3044 /// id*, id***, void (^*)(),
3045 ACTC_indirectRetainable,
3047 /// void* might be a normal C type, or it might a CF type.
3053 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3054 return (ACTC == ACTC_retainable ||
3055 ACTC == ACTC_coreFoundation ||
3056 ACTC == ACTC_voidPtr);
3058 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3059 return ACTC == ACTC_none ||
3060 ACTC == ACTC_voidPtr ||
3061 ACTC == ACTC_coreFoundation;
3064 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3065 bool isIndirect = false;
3067 // Ignore an outermost reference type.
3068 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3069 type = ref->getPointeeType();
3073 // Drill through pointers and arrays recursively.
3075 if (const PointerType *ptr = type->getAs<PointerType>()) {
3076 type = ptr->getPointeeType();
3078 // The first level of pointer may be the innermost pointer on a CF type.
3080 if (type->isVoidType()) return ACTC_voidPtr;
3081 if (type->isRecordType()) return ACTC_coreFoundation;
3083 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3084 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3092 if (type->isObjCARCBridgableType())
3093 return ACTC_indirectRetainable;
3097 if (type->isObjCARCBridgableType())
3098 return ACTC_retainable;
3104 /// A result from the cast checker.
3106 /// Cannot be casted.
3109 /// Can be safely retained or not retained.
3112 /// Can be casted at +0.
3115 /// Can be casted at +1.
3118 ACCResult merge(ACCResult left, ACCResult right) {
3119 if (left == right) return left;
3120 if (left == ACC_bottom) return right;
3121 if (right == ACC_bottom) return left;
3125 /// A checker which white-lists certain expressions whose conversion
3126 /// to or from retainable type would otherwise be forbidden in ARC.
3127 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3128 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3130 ASTContext &Context;
3131 ARCConversionTypeClass SourceClass;
3132 ARCConversionTypeClass TargetClass;
3135 static bool isCFType(QualType type) {
3136 // Someday this can use ns_bridged. For now, it has to do this.
3137 return type->isCARCBridgableType();
3141 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3142 ARCConversionTypeClass target, bool diagnose)
3143 : Context(Context), SourceClass(source), TargetClass(target),
3144 Diagnose(diagnose) {}
3147 ACCResult Visit(Expr *e) {
3148 return super::Visit(e->IgnoreParens());
3151 ACCResult VisitStmt(Stmt *s) {
3155 /// Null pointer constants can be casted however you please.
3156 ACCResult VisitExpr(Expr *e) {
3157 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3162 /// Objective-C string literals can be safely casted.
3163 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3164 // If we're casting to any retainable type, go ahead. Global
3165 // strings are immune to retains, so this is bottom.
3166 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3171 /// Look through certain implicit and explicit casts.
3172 ACCResult VisitCastExpr(CastExpr *e) {
3173 switch (e->getCastKind()) {
3174 case CK_NullToPointer:
3178 case CK_LValueToRValue:
3180 case CK_CPointerToObjCPointerCast:
3181 case CK_BlockPointerToObjCPointerCast:
3182 case CK_AnyPointerToBlockPointerCast:
3183 return Visit(e->getSubExpr());
3190 /// Look through unary extension.
3191 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3192 return Visit(e->getSubExpr());
3195 /// Ignore the LHS of a comma operator.
3196 ACCResult VisitBinComma(BinaryOperator *e) {
3197 return Visit(e->getRHS());
3200 /// Conditional operators are okay if both sides are okay.
3201 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3202 ACCResult left = Visit(e->getTrueExpr());
3203 if (left == ACC_invalid) return ACC_invalid;
3204 return merge(left, Visit(e->getFalseExpr()));
3207 /// Look through pseudo-objects.
3208 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3209 // If we're getting here, we should always have a result.
3210 return Visit(e->getResultExpr());
3213 /// Statement expressions are okay if their result expression is okay.
3214 ACCResult VisitStmtExpr(StmtExpr *e) {
3215 return Visit(e->getSubStmt()->body_back());
3218 /// Some declaration references are okay.
3219 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3220 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3221 // References to global constants are okay.
3222 if (isAnyRetainable(TargetClass) &&
3223 isAnyRetainable(SourceClass) &&
3225 var->getStorageClass() == SC_Extern &&
3226 var->getType().isConstQualified()) {
3228 // In system headers, they can also be assumed to be immune to retains.
3229 // These are things like 'kCFStringTransformToLatin'.
3230 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3233 return ACC_plusZero;
3240 /// Some calls are okay.
3241 ACCResult VisitCallExpr(CallExpr *e) {
3242 if (FunctionDecl *fn = e->getDirectCallee())
3243 if (ACCResult result = checkCallToFunction(fn))
3246 return super::VisitCallExpr(e);
3249 ACCResult checkCallToFunction(FunctionDecl *fn) {
3250 // Require a CF*Ref return type.
3251 if (!isCFType(fn->getReturnType()))
3254 if (!isAnyRetainable(TargetClass))
3257 // Honor an explicit 'not retained' attribute.
3258 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3259 return ACC_plusZero;
3261 // Honor an explicit 'retained' attribute, except that for
3262 // now we're not going to permit implicit handling of +1 results,
3263 // because it's a bit frightening.
3264 if (fn->hasAttr<CFReturnsRetainedAttr>())
3265 return Diagnose ? ACC_plusOne
3266 : ACC_invalid; // ACC_plusOne if we start accepting this
3268 // Recognize this specific builtin function, which is used by CFSTR.
3269 unsigned builtinID = fn->getBuiltinID();
3270 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3273 // Otherwise, don't do anything implicit with an unaudited function.
3274 if (!fn->hasAttr<CFAuditedTransferAttr>())
3277 // Otherwise, it's +0 unless it follows the create convention.
3278 if (ento::coreFoundation::followsCreateRule(fn))
3279 return Diagnose ? ACC_plusOne
3280 : ACC_invalid; // ACC_plusOne if we start accepting this
3282 return ACC_plusZero;
3285 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3286 return checkCallToMethod(e->getMethodDecl());
3289 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3290 ObjCMethodDecl *method;
3291 if (e->isExplicitProperty())
3292 method = e->getExplicitProperty()->getGetterMethodDecl();
3294 method = e->getImplicitPropertyGetter();
3295 return checkCallToMethod(method);
3298 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3299 if (!method) return ACC_invalid;
3301 // Check for message sends to functions returning CF types. We
3302 // just obey the Cocoa conventions with these, even though the
3303 // return type is CF.
3304 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3307 // If the method is explicitly marked not-retained, it's +0.
3308 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3309 return ACC_plusZero;
3311 // If the method is explicitly marked as returning retained, or its
3312 // selector follows a +1 Cocoa convention, treat it as +1.
3313 if (method->hasAttr<CFReturnsRetainedAttr>())
3316 switch (method->getSelector().getMethodFamily()) {
3319 case OMF_mutableCopy:
3324 // Otherwise, treat it as +0.
3325 return ACC_plusZero;
3331 bool Sema::isKnownName(StringRef name) {
3334 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3335 Sema::LookupOrdinaryName);
3336 return LookupName(R, TUScope, false);
3339 static void addFixitForObjCARCConversion(Sema &S,
3340 DiagnosticBuilder &DiagB,
3341 Sema::CheckedConversionKind CCK,
3342 SourceLocation afterLParen,
3346 const char *bridgeKeyword,
3347 const char *CFBridgeName) {
3348 // We handle C-style and implicit casts here.
3350 case Sema::CCK_ImplicitConversion:
3351 case Sema::CCK_CStyleCast:
3352 case Sema::CCK_OtherCast:
3354 case Sema::CCK_FunctionalCast:
3359 if (CCK == Sema::CCK_OtherCast) {
3360 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3361 SourceRange range(NCE->getOperatorLoc(),
3362 NCE->getAngleBrackets().getEnd());
3363 SmallString<32> BridgeCall;
3365 SourceManager &SM = S.getSourceManager();
3366 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3367 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3370 BridgeCall += CFBridgeName;
3371 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3375 Expr *castedE = castExpr;
3376 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3377 castedE = CCE->getSubExpr();
3378 castedE = castedE->IgnoreImpCasts();
3379 SourceRange range = castedE->getSourceRange();
3381 SmallString<32> BridgeCall;
3383 SourceManager &SM = S.getSourceManager();
3384 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3385 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3388 BridgeCall += CFBridgeName;
3390 if (isa<ParenExpr>(castedE)) {
3391 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3395 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3397 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3398 S.getLocForEndOfToken(range.getEnd()),
3404 if (CCK == Sema::CCK_CStyleCast) {
3405 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3406 } else if (CCK == Sema::CCK_OtherCast) {
3407 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3408 std::string castCode = "(";
3409 castCode += bridgeKeyword;
3410 castCode += castType.getAsString();
3412 SourceRange Range(NCE->getOperatorLoc(),
3413 NCE->getAngleBrackets().getEnd());
3414 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3417 std::string castCode = "(";
3418 castCode += bridgeKeyword;
3419 castCode += castType.getAsString();
3421 Expr *castedE = castExpr->IgnoreImpCasts();
3422 SourceRange range = castedE->getSourceRange();
3423 if (isa<ParenExpr>(castedE)) {
3424 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3428 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3430 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3431 S.getLocForEndOfToken(range.getEnd()),
3437 template <typename T>
3438 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3439 TypedefNameDecl *TDNDecl = TD->getDecl();
3440 QualType QT = TDNDecl->getUnderlyingType();
3441 if (QT->isPointerType()) {
3442 QT = QT->getPointeeType();
3443 if (const RecordType *RT = QT->getAs<RecordType>())
3444 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3445 return RD->getAttr<T>();
3450 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3451 TypedefNameDecl *&TDNDecl) {
3452 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3453 TDNDecl = TD->getDecl();
3454 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3455 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3457 T = TDNDecl->getUnderlyingType();
3463 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3464 QualType castType, ARCConversionTypeClass castACTC,
3465 Expr *castExpr, Expr *realCast,
3466 ARCConversionTypeClass exprACTC,
3467 Sema::CheckedConversionKind CCK) {
3468 SourceLocation loc =
3469 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3471 if (S.makeUnavailableInSystemHeader(loc,
3472 UnavailableAttr::IR_ARCForbiddenConversion))
3475 QualType castExprType = castExpr->getType();
3476 TypedefNameDecl *TDNDecl = nullptr;
3477 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3478 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3479 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3480 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3483 unsigned srcKind = 0;
3486 case ACTC_coreFoundation:
3488 srcKind = (castExprType->isPointerType() ? 1 : 0);
3490 case ACTC_retainable:
3491 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3493 case ACTC_indirectRetainable:
3498 // Check whether this could be fixed with a bridge cast.
3499 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3500 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3502 // Bridge from an ARC type to a CF type.
3503 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3505 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3506 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3507 << 2 // of C pointer type
3509 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3512 << castExpr->getSourceRange();
3513 bool br = S.isKnownName("CFBridgingRelease");
3514 ACCResult CreateRule =
3515 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3516 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3517 if (CreateRule != ACC_plusOne)
3519 DiagnosticBuilder DiagB =
3520 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3521 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3523 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3524 castType, castExpr, realCast, "__bridge ",
3527 if (CreateRule != ACC_plusZero)
3529 DiagnosticBuilder DiagB =
3530 (CCK == Sema::CCK_OtherCast && !br) ?
3531 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3532 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3533 diag::note_arc_bridge_transfer)
3534 << castExprType << br;
3536 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3537 castType, castExpr, realCast, "__bridge_transfer ",
3538 br ? "CFBridgingRelease" : nullptr);
3544 // Bridge from a CF type to an ARC type.
3545 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3546 bool br = S.isKnownName("CFBridgingRetain");
3547 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3548 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3549 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3551 << 2 // to C pointer type
3554 << castExpr->getSourceRange();
3555 ACCResult CreateRule =
3556 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3557 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3558 if (CreateRule != ACC_plusOne)
3560 DiagnosticBuilder DiagB =
3561 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3562 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3563 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3564 castType, castExpr, realCast, "__bridge ",
3567 if (CreateRule != ACC_plusZero)
3569 DiagnosticBuilder DiagB =
3570 (CCK == Sema::CCK_OtherCast && !br) ?
3571 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3572 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3573 diag::note_arc_bridge_retained)
3576 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3577 castType, castExpr, realCast, "__bridge_retained ",
3578 br ? "CFBridgingRetain" : nullptr);
3584 S.Diag(loc, diag::err_arc_mismatched_cast)
3585 << (CCK != Sema::CCK_ImplicitConversion)
3586 << srcKind << castExprType << castType
3587 << castRange << castExpr->getSourceRange();
3590 template <typename TB>
3591 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3592 bool &HadTheAttribute, bool warn) {
3593 QualType T = castExpr->getType();
3594 HadTheAttribute = false;
3595 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3596 TypedefNameDecl *TDNDecl = TD->getDecl();
3597 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3598 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3599 HadTheAttribute = true;
3600 if (Parm->isStr("id"))
3603 NamedDecl *Target = nullptr;
3604 // Check for an existing type with this name.
3605 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3606 Sema::LookupOrdinaryName);
3607 if (S.LookupName(R, S.TUScope)) {
3608 Target = R.getFoundDecl();
3609 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3610 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3611 if (const ObjCObjectPointerType *InterfacePointerType =
3612 castType->getAsObjCInterfacePointerType()) {
3613 ObjCInterfaceDecl *CastClass
3614 = InterfacePointerType->getObjectType()->getInterface();
3615 if ((CastClass == ExprClass) ||
3616 (CastClass && CastClass->isSuperClassOf(ExprClass)))
3619 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3620 << T << Target->getName() << castType->getPointeeType();
3622 } else if (castType->isObjCIdType() ||
3623 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3624 castType, ExprClass)))
3625 // ok to cast to 'id'.
3626 // casting to id<p-list> is ok if bridge type adopts all of
3627 // p-list protocols.
3631 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3632 << T << Target->getName() << castType;
3633 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3634 S.Diag(Target->getLocStart(), diag::note_declared_at);
3639 } else if (!castType->isObjCIdType()) {
3640 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3641 << castExpr->getType() << Parm;
3642 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3644 S.Diag(Target->getLocStart(), diag::note_declared_at);
3650 T = TDNDecl->getUnderlyingType();
3655 template <typename TB>
3656 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3657 bool &HadTheAttribute, bool warn) {
3658 QualType T = castType;
3659 HadTheAttribute = false;
3660 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3661 TypedefNameDecl *TDNDecl = TD->getDecl();
3662 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
3663 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
3664 HadTheAttribute = true;
3665 if (Parm->isStr("id"))
3668 NamedDecl *Target = nullptr;
3669 // Check for an existing type with this name.
3670 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3671 Sema::LookupOrdinaryName);
3672 if (S.LookupName(R, S.TUScope)) {
3673 Target = R.getFoundDecl();
3674 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3675 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3676 if (const ObjCObjectPointerType *InterfacePointerType =
3677 castExpr->getType()->getAsObjCInterfacePointerType()) {
3678 ObjCInterfaceDecl *ExprClass
3679 = InterfacePointerType->getObjectType()->getInterface();
3680 if ((CastClass == ExprClass) ||
3681 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
3684 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3685 << castExpr->getType()->getPointeeType() << T;
3686 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3689 } else if (castExpr->getType()->isObjCIdType() ||
3690 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3691 castExpr->getType(), CastClass)))
3692 // ok to cast an 'id' expression to a CFtype.
3693 // ok to cast an 'id<plist>' expression to CFtype provided plist
3694 // adopts all of CFtype's ObjetiveC's class plist.
3698 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3699 << castExpr->getType() << castType;
3700 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3701 S.Diag(Target->getLocStart(), diag::note_declared_at);
3707 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3708 << castExpr->getType() << castType;
3709 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3711 S.Diag(Target->getLocStart(), diag::note_declared_at);
3716 T = TDNDecl->getUnderlyingType();
3721 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
3722 if (!getLangOpts().ObjC1)
3724 // warn in presence of __bridge casting to or from a toll free bridge cast.
3725 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3726 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3727 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
3728 bool HasObjCBridgeAttr;
3729 bool ObjCBridgeAttrWillNotWarn =
3730 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3732 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3734 bool HasObjCBridgeMutableAttr;
3735 bool ObjCBridgeMutableAttrWillNotWarn =
3736 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3737 HasObjCBridgeMutableAttr, false);
3738 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3741 if (HasObjCBridgeAttr)
3742 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3744 else if (HasObjCBridgeMutableAttr)
3745 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3746 HasObjCBridgeMutableAttr, true);
3748 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
3749 bool HasObjCBridgeAttr;
3750 bool ObjCBridgeAttrWillNotWarn =
3751 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3753 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3755 bool HasObjCBridgeMutableAttr;
3756 bool ObjCBridgeMutableAttrWillNotWarn =
3757 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3758 HasObjCBridgeMutableAttr, false);
3759 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3762 if (HasObjCBridgeAttr)
3763 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3765 else if (HasObjCBridgeMutableAttr)
3766 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3767 HasObjCBridgeMutableAttr, true);
3771 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3772 QualType SrcType = castExpr->getType();
3773 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3774 if (PRE->isExplicitProperty()) {
3775 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3776 SrcType = PDecl->getType();
3778 else if (PRE->isImplicitProperty()) {
3779 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3780 SrcType = Getter->getReturnType();
3785 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3786 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3787 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3789 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3790 castType, SrcType, castExpr);
3794 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3796 if (!getLangOpts().ObjC1)
3798 ARCConversionTypeClass exprACTC =
3799 classifyTypeForARCConversion(castExpr->getType());
3800 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3801 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3802 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3803 CheckTollFreeBridgeCast(castType, castExpr);
3804 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3805 : CK_CPointerToObjCPointerCast;
3811 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3812 QualType DestType, QualType SrcType,
3813 ObjCInterfaceDecl *&RelatedClass,
3814 ObjCMethodDecl *&ClassMethod,
3815 ObjCMethodDecl *&InstanceMethod,
3816 TypedefNameDecl *&TDNDecl,
3818 QualType T = CfToNs ? SrcType : DestType;
3819 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3823 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3824 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3825 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3828 NamedDecl *Target = nullptr;
3829 // Check for an existing type with this name.
3830 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3831 Sema::LookupOrdinaryName);
3832 if (!LookupName(R, TUScope)) {
3833 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
3834 << SrcType << DestType;
3835 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3838 Target = R.getFoundDecl();
3839 if (Target && isa<ObjCInterfaceDecl>(Target))
3840 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3842 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3843 << SrcType << DestType;
3844 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3846 Diag(Target->getLocStart(), diag::note_declared_at);
3850 // Check for an existing class method with the given selector name.
3851 if (CfToNs && CMId) {
3852 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3853 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3855 Diag(Loc, diag::err_objc_bridged_related_known_method)
3856 << SrcType << DestType << Sel << false;
3857 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3862 // Check for an existing instance method with the given selector name.
3863 if (!CfToNs && IMId) {
3864 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3865 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3866 if (!InstanceMethod) {
3867 Diag(Loc, diag::err_objc_bridged_related_known_method)
3868 << SrcType << DestType << Sel << true;
3869 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3877 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
3878 QualType DestType, QualType SrcType,
3880 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3881 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3882 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3883 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3884 if (!CfToNs && !NsToCf)
3887 ObjCInterfaceDecl *RelatedClass;
3888 ObjCMethodDecl *ClassMethod = nullptr;
3889 ObjCMethodDecl *InstanceMethod = nullptr;
3890 TypedefNameDecl *TDNDecl = nullptr;
3891 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3892 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3896 // Implicit conversion from CF to ObjC object is needed.
3898 std::string ExpressionString = "[";
3899 ExpressionString += RelatedClass->getNameAsString();
3900 ExpressionString += " ";
3901 ExpressionString += ClassMethod->getSelector().getAsString();
3902 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
3903 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
3904 Diag(Loc, diag::err_objc_bridged_related_known_method)
3905 << SrcType << DestType << ClassMethod->getSelector() << false
3906 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3907 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
3908 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3909 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3911 QualType receiverType =
3912 Context.getObjCInterfaceType(RelatedClass);
3914 Expr *args[] = { SrcExpr };
3915 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3916 ClassMethod->getLocation(),
3917 ClassMethod->getSelector(), ClassMethod,
3918 MultiExprArg(args, 1));
3919 SrcExpr = msg.get();
3924 // Implicit conversion from ObjC type to CF object is needed.
3925 if (InstanceMethod) {
3926 std::string ExpressionString;
3927 SourceLocation SrcExprEndLoc = getLocForEndOfToken(SrcExpr->getLocEnd());
3928 if (InstanceMethod->isPropertyAccessor())
3929 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3930 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3931 ExpressionString = ".";
3932 ExpressionString += PDecl->getNameAsString();
3933 Diag(Loc, diag::err_objc_bridged_related_known_method)
3934 << SrcType << DestType << InstanceMethod->getSelector() << true
3935 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3937 if (ExpressionString.empty()) {
3938 // Provide a fixit: [ObjectExpr InstanceMethod]
3939 ExpressionString = " ";
3940 ExpressionString += InstanceMethod->getSelector().getAsString();
3941 ExpressionString += "]";
3943 Diag(Loc, diag::err_objc_bridged_related_known_method)
3944 << SrcType << DestType << InstanceMethod->getSelector() << true
3945 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3946 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3948 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3949 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3952 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3953 InstanceMethod->getLocation(),
3954 InstanceMethod->getSelector(),
3955 InstanceMethod, None);
3956 SrcExpr = msg.get();
3963 Sema::ARCConversionResult
3964 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
3965 Expr *&castExpr, CheckedConversionKind CCK,
3966 bool DiagnoseCFAudited,
3967 BinaryOperatorKind Opc) {
3968 QualType castExprType = castExpr->getType();
3970 // For the purposes of the classification, we assume reference types
3971 // will bind to temporaries.
3972 QualType effCastType = castType;
3973 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3974 effCastType = ref->getPointeeType();
3976 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3977 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
3978 if (exprACTC == castACTC) {
3979 // check for viablity and report error if casting an rvalue to a
3980 // life-time qualifier.
3981 if ((castACTC == ACTC_retainable) &&
3982 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
3983 (castType != castExprType)) {
3984 const Type *DT = castType.getTypePtr();
3985 QualType QDT = castType;
3986 // We desugar some types but not others. We ignore those
3987 // that cannot happen in a cast; i.e. auto, and those which
3988 // should not be de-sugared; i.e typedef.
3989 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3990 QDT = PT->desugar();
3991 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3992 QDT = TP->desugar();
3993 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3994 QDT = AT->desugar();
3995 if (QDT != castType &&
3996 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3997 SourceLocation loc =
3998 (castRange.isValid() ? castRange.getBegin()
3999 : castExpr->getExprLoc());
4000 Diag(loc, diag::err_arc_nolifetime_behavior);
4006 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4008 // Allow all of these types to be cast to integer types (but not
4010 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4013 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4014 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4015 // must be explicit.
4016 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4018 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4019 CCK != CCK_ImplicitConversion)
4022 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4023 // For invalid casts, fall through.
4027 // Do nothing for both bottom and +0.
4032 // If the result is +1, consume it here.
4034 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4035 CK_ARCConsumeObject, castExpr,
4036 nullptr, VK_RValue);
4037 ExprNeedsCleanups = true;
4041 // If this is a non-implicit cast from id or block type to a
4042 // CoreFoundation type, delay complaining in case the cast is used
4043 // in an acceptable context.
4044 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
4045 CCK != CCK_ImplicitConversion)
4046 return ACR_unbridged;
4048 // Do not issue bridge cast" diagnostic when implicit casting a cstring
4049 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
4051 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4052 ConversionToObjCStringLiteralCheck(castType, castExpr))
4055 // Do not issue "bridge cast" diagnostic when implicit casting
4056 // a retainable object to a CF type parameter belonging to an audited
4057 // CF API function. Let caller issue a normal type mismatched diagnostic
4059 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4060 castACTC != ACTC_coreFoundation)
4061 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4062 (Opc == BO_NE || Opc == BO_EQ)))
4063 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4064 castExpr, castExpr, exprACTC, CCK);
4068 /// Given that we saw an expression with the ARCUnbridgedCastTy
4069 /// placeholder type, complain bitterly.
4070 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4071 // We expect the spurious ImplicitCastExpr to already have been stripped.
4072 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4073 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4075 SourceRange castRange;
4077 CheckedConversionKind CCK;
4079 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4080 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4081 castType = cast->getTypeAsWritten();
4082 CCK = CCK_CStyleCast;
4083 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4084 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4085 castType = cast->getTypeAsWritten();
4086 CCK = CCK_OtherCast;
4088 castType = cast->getType();
4089 CCK = CCK_ImplicitConversion;
4092 ARCConversionTypeClass castACTC =
4093 classifyTypeForARCConversion(castType.getNonReferenceType());
4095 Expr *castExpr = realCast->getSubExpr();
4096 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4098 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4099 castExpr, realCast, ACTC_retainable, CCK);
4102 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4103 /// type, remove the placeholder cast.
4104 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4105 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4107 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4108 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4109 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4110 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4111 assert(uo->getOpcode() == UO_Extension);
4112 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4113 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
4114 sub->getValueKind(), sub->getObjectKind(),
4115 uo->getOperatorLoc());
4116 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4117 assert(!gse->isResultDependent());
4119 unsigned n = gse->getNumAssocs();
4120 SmallVector<Expr*, 4> subExprs(n);
4121 SmallVector<TypeSourceInfo*, 4> subTypes(n);
4122 for (unsigned i = 0; i != n; ++i) {
4123 subTypes[i] = gse->getAssocTypeSourceInfo(i);
4124 Expr *sub = gse->getAssocExpr(i);
4125 if (i == gse->getResultIndex())
4126 sub = stripARCUnbridgedCast(sub);
4130 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
4131 gse->getControllingExpr(),
4133 gse->getDefaultLoc(),
4134 gse->getRParenLoc(),
4135 gse->containsUnexpandedParameterPack(),
4136 gse->getResultIndex());
4138 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4139 return cast<ImplicitCastExpr>(e)->getSubExpr();
4143 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4144 QualType exprType) {
4145 QualType canCastType =
4146 Context.getCanonicalType(castType).getUnqualifiedType();
4147 QualType canExprType =
4148 Context.getCanonicalType(exprType).getUnqualifiedType();
4149 if (isa<ObjCObjectPointerType>(canCastType) &&
4150 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4151 canExprType->isObjCObjectPointerType()) {
4152 if (const ObjCObjectPointerType *ObjT =
4153 canExprType->getAs<ObjCObjectPointerType>())
4154 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4155 return !ObjI->isArcWeakrefUnavailable();
4160 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4161 static Expr *maybeUndoReclaimObject(Expr *e) {
4162 // For now, we just undo operands that are *immediately* reclaim
4163 // expressions, which prevents the vast majority of potential
4164 // problems here. To catch them all, we'd need to rebuild arbitrary
4165 // value-propagating subexpressions --- we can't reliably rebuild
4166 // in-place because of expression sharing.
4167 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4168 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
4169 return ice->getSubExpr();
4174 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4175 ObjCBridgeCastKind Kind,
4176 SourceLocation BridgeKeywordLoc,
4177 TypeSourceInfo *TSInfo,
4179 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4180 if (SubResult.isInvalid()) return ExprError();
4181 SubExpr = SubResult.get();
4183 QualType T = TSInfo->getType();
4184 QualType FromType = SubExpr->getType();
4188 bool MustConsume = false;
4189 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4190 // Okay: we'll build a dependent expression type.
4192 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4194 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4195 : CK_CPointerToObjCPointerCast);
4200 case OBC_BridgeRetained: {
4201 bool br = isKnownName("CFBridgingRelease");
4202 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4205 << (T->isBlockPointerType()? 1 : 0)
4207 << SubExpr->getSourceRange()
4209 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4210 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4211 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4213 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4214 br ? "CFBridgingRelease "
4215 : "__bridge_transfer ");
4221 case OBC_BridgeTransfer:
4222 // We must consume the Objective-C object produced by the cast.
4226 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4231 // Reclaiming a value that's going to be __bridge-casted to CF
4232 // is very dangerous, so we don't do it.
4233 SubExpr = maybeUndoReclaimObject(SubExpr);
4236 case OBC_BridgeRetained:
4237 // Produce the object before casting it.
4238 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4239 CK_ARCProduceObject,
4240 SubExpr, nullptr, VK_RValue);
4243 case OBC_BridgeTransfer: {
4244 bool br = isKnownName("CFBridgingRetain");
4245 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4246 << (FromType->isBlockPointerType()? 1 : 0)
4250 << SubExpr->getSourceRange()
4253 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4254 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4255 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4257 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4258 br ? "CFBridgingRetain " : "__bridge_retained");
4265 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4266 << FromType << T << Kind
4267 << SubExpr->getSourceRange()
4268 << TSInfo->getTypeLoc().getSourceRange();
4272 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4277 ExprNeedsCleanups = true;
4278 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4279 nullptr, VK_RValue);
4285 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4286 SourceLocation LParenLoc,
4287 ObjCBridgeCastKind Kind,
4288 SourceLocation BridgeKeywordLoc,
4290 SourceLocation RParenLoc,
4292 TypeSourceInfo *TSInfo = nullptr;
4293 QualType T = GetTypeFromParser(Type, &TSInfo);
4294 if (Kind == OBC_Bridge)
4295 CheckTollFreeBridgeCast(T, SubExpr);
4297 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4298 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,