1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for Objective-C expressions.
11 //===----------------------------------------------------------------------===//
13 #include "clang/AST/ASTContext.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/ExprObjC.h"
16 #include "clang/AST/StmtVisitor.h"
17 #include "clang/AST/TypeLoc.h"
18 #include "clang/Analysis/DomainSpecific/CocoaConventions.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Edit/Commit.h"
21 #include "clang/Edit/Rewriters.h"
22 #include "clang/Lex/Preprocessor.h"
23 #include "clang/Sema/Initialization.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "llvm/ADT/SmallString.h"
29 #include "llvm/Support/ConvertUTF.h"
31 using namespace clang;
33 using llvm::makeArrayRef;
35 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
36 ArrayRef<Expr *> Strings) {
37 // Most ObjC strings are formed out of a single piece. However, we *can*
38 // have strings formed out of multiple @ strings with multiple pptokens in
39 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
40 // StringLiteral for ObjCStringLiteral to hold onto.
41 StringLiteral *S = cast<StringLiteral>(Strings[0]);
43 // If we have a multi-part string, merge it all together.
44 if (Strings.size() != 1) {
45 // Concatenate objc strings.
46 SmallString<128> StrBuf;
47 SmallVector<SourceLocation, 8> StrLocs;
49 for (Expr *E : Strings) {
50 S = cast<StringLiteral>(E);
52 // ObjC strings can't be wide or UTF.
54 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
55 << S->getSourceRange();
60 StrBuf += S->getString();
62 // Get the locations of the string tokens.
63 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
66 // Create the aggregate string with the appropriate content and location
68 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
69 assert(CAT && "String literal not of constant array type!");
70 QualType StrTy = Context.getConstantArrayType(
71 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), nullptr,
72 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
73 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
74 /*Pascal=*/false, StrTy, &StrLocs[0],
78 return BuildObjCStringLiteral(AtLocs[0], S);
81 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
82 // Verify that this composite string is acceptable for ObjC strings.
83 if (CheckObjCString(S))
86 // Initialize the constant string interface lazily. This assumes
87 // the NSString interface is seen in this translation unit. Note: We
88 // don't use NSConstantString, since the runtime team considers this
89 // interface private (even though it appears in the header files).
90 QualType Ty = Context.getObjCConstantStringInterface();
92 Ty = Context.getObjCObjectPointerType(Ty);
93 } else if (getLangOpts().NoConstantCFStrings) {
94 IdentifierInfo *NSIdent=nullptr;
95 std::string StringClass(getLangOpts().ObjCConstantStringClass);
97 if (StringClass.empty())
98 NSIdent = &Context.Idents.get("NSConstantString");
100 NSIdent = &Context.Idents.get(StringClass);
102 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
104 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
105 Context.setObjCConstantStringInterface(StrIF);
106 Ty = Context.getObjCConstantStringInterface();
107 Ty = Context.getObjCObjectPointerType(Ty);
109 // If there is no NSConstantString interface defined then treat this
110 // as error and recover from it.
111 Diag(S->getBeginLoc(), diag::err_no_nsconstant_string_class)
112 << NSIdent << S->getSourceRange();
113 Ty = Context.getObjCIdType();
116 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
117 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
119 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
120 Context.setObjCConstantStringInterface(StrIF);
121 Ty = Context.getObjCConstantStringInterface();
122 Ty = Context.getObjCObjectPointerType(Ty);
124 // If there is no NSString interface defined, implicitly declare
125 // a @class NSString; and use that instead. This is to make sure
126 // type of an NSString literal is represented correctly, instead of
127 // being an 'id' type.
128 Ty = Context.getObjCNSStringType();
130 ObjCInterfaceDecl *NSStringIDecl =
131 ObjCInterfaceDecl::Create (Context,
132 Context.getTranslationUnitDecl(),
133 SourceLocation(), NSIdent,
134 nullptr, nullptr, SourceLocation());
135 Ty = Context.getObjCInterfaceType(NSStringIDecl);
136 Context.setObjCNSStringType(Ty);
138 Ty = Context.getObjCObjectPointerType(Ty);
142 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145 /// Emits an error if the given method does not exist, or if the return
146 /// type is not an Objective-C object.
147 static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
148 const ObjCInterfaceDecl *Class,
149 Selector Sel, const ObjCMethodDecl *Method) {
151 // FIXME: Is there a better way to avoid quotes than using getName()?
152 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
156 // Make sure the return type is reasonable.
157 QualType ReturnType = Method->getReturnType();
158 if (!ReturnType->isObjCObjectPointerType()) {
159 S.Diag(Loc, diag::err_objc_literal_method_sig)
161 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
169 /// Maps ObjCLiteralKind to NSClassIdKindKind
170 static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind(
171 Sema::ObjCLiteralKind LiteralKind) {
172 switch (LiteralKind) {
174 return NSAPI::ClassId_NSArray;
175 case Sema::LK_Dictionary:
176 return NSAPI::ClassId_NSDictionary;
177 case Sema::LK_Numeric:
178 return NSAPI::ClassId_NSNumber;
179 case Sema::LK_String:
180 return NSAPI::ClassId_NSString;
182 return NSAPI::ClassId_NSValue;
184 // there is no corresponding matching
185 // between LK_None/LK_Block and NSClassIdKindKind
190 llvm_unreachable("LiteralKind can't be converted into a ClassKind");
193 /// Validates ObjCInterfaceDecl availability.
194 /// ObjCInterfaceDecl, used to create ObjC literals, should be defined
195 /// if clang not in a debugger mode.
196 static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl,
198 Sema::ObjCLiteralKind LiteralKind) {
200 NSAPI::NSClassIdKindKind Kind = ClassKindFromLiteralKind(LiteralKind);
201 IdentifierInfo *II = S.NSAPIObj->getNSClassId(Kind);
202 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
203 << II->getName() << LiteralKind;
205 } else if (!Decl->hasDefinition() && !S.getLangOpts().DebuggerObjCLiteral) {
206 S.Diag(Loc, diag::err_undeclared_objc_literal_class)
207 << Decl->getName() << LiteralKind;
208 S.Diag(Decl->getLocation(), diag::note_forward_class);
215 /// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind.
216 /// Used to create ObjC literals, such as NSDictionary (@{}),
217 /// NSArray (@[]) and Boxed Expressions (@())
218 static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S,
220 Sema::ObjCLiteralKind LiteralKind) {
221 NSAPI::NSClassIdKindKind ClassKind = ClassKindFromLiteralKind(LiteralKind);
222 IdentifierInfo *II = S.NSAPIObj->getNSClassId(ClassKind);
223 NamedDecl *IF = S.LookupSingleName(S.TUScope, II, Loc,
224 Sema::LookupOrdinaryName);
225 ObjCInterfaceDecl *ID = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
226 if (!ID && S.getLangOpts().DebuggerObjCLiteral) {
227 ASTContext &Context = S.Context;
228 TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
229 ID = ObjCInterfaceDecl::Create (Context, TU, SourceLocation(), II,
230 nullptr, nullptr, SourceLocation());
233 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) {
240 /// Retrieve the NSNumber factory method that should be used to create
241 /// an Objective-C literal for the given type.
242 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
244 bool isLiteral = false,
245 SourceRange R = SourceRange()) {
246 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
247 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
251 S.Diag(Loc, diag::err_invalid_nsnumber_type)
257 // If we already looked up this method, we're done.
258 if (S.NSNumberLiteralMethods[*Kind])
259 return S.NSNumberLiteralMethods[*Kind];
261 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
264 ASTContext &CX = S.Context;
266 // Look up the NSNumber class, if we haven't done so already. It's cached
267 // in the Sema instance.
268 if (!S.NSNumberDecl) {
269 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc,
271 if (!S.NSNumberDecl) {
276 if (S.NSNumberPointer.isNull()) {
277 // generate the pointer to NSNumber type.
278 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
279 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
282 // Look for the appropriate method within NSNumber.
283 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
284 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
285 // create a stub definition this NSNumber factory method.
286 TypeSourceInfo *ReturnTInfo = nullptr;
288 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
289 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
290 /*isInstance=*/false, /*isVariadic=*/false,
291 /*isPropertyAccessor=*/false,
292 /*isSynthesizedAccessorStub=*/false,
293 /*isImplicitlyDeclared=*/true,
294 /*isDefined=*/false, ObjCMethodDecl::Required,
295 /*HasRelatedResultType=*/false);
296 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
297 SourceLocation(), SourceLocation(),
298 &CX.Idents.get("value"),
299 NumberType, /*TInfo=*/nullptr,
301 Method->setMethodParams(S.Context, value, None);
304 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
307 // Note: if the parameter type is out-of-line, we'll catch it later in the
308 // implicit conversion.
310 S.NSNumberLiteralMethods[*Kind] = Method;
314 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
315 /// numeric literal expression. Type of the expression will be "NSNumber *".
316 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
317 // Determine the type of the literal.
318 QualType NumberType = Number->getType();
319 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
320 // In C, character literals have type 'int'. That's not the type we want
321 // to use to determine the Objective-c literal kind.
322 switch (Char->getKind()) {
323 case CharacterLiteral::Ascii:
324 case CharacterLiteral::UTF8:
325 NumberType = Context.CharTy;
328 case CharacterLiteral::Wide:
329 NumberType = Context.getWideCharType();
332 case CharacterLiteral::UTF16:
333 NumberType = Context.Char16Ty;
336 case CharacterLiteral::UTF32:
337 NumberType = Context.Char32Ty;
342 // Look for the appropriate method within NSNumber.
343 // Construct the literal.
344 SourceRange NR(Number->getSourceRange());
345 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
350 // Convert the number to the type that the parameter expects.
351 ParmVarDecl *ParamDecl = Method->parameters()[0];
352 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
354 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
357 if (ConvertedNumber.isInvalid())
359 Number = ConvertedNumber.get();
361 // Use the effective source range of the literal, including the leading '@'.
362 return MaybeBindToTemporary(
363 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
364 SourceRange(AtLoc, NR.getEnd())));
367 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
368 SourceLocation ValueLoc,
371 if (getLangOpts().CPlusPlus) {
372 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
374 // C doesn't actually have a way to represent literal values of type
375 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
376 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
377 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
378 CK_IntegralToBoolean);
381 return BuildObjCNumericLiteral(AtLoc, Inner.get());
384 /// Check that the given expression is a valid element of an Objective-C
385 /// collection literal.
386 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
388 bool ArrayLiteral = false) {
389 // If the expression is type-dependent, there's nothing for us to do.
390 if (Element->isTypeDependent())
393 ExprResult Result = S.CheckPlaceholderExpr(Element);
394 if (Result.isInvalid())
396 Element = Result.get();
398 // In C++, check for an implicit conversion to an Objective-C object pointer
400 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
401 InitializedEntity Entity
402 = InitializedEntity::InitializeParameter(S.Context, T,
404 InitializationKind Kind = InitializationKind::CreateCopy(
405 Element->getBeginLoc(), SourceLocation());
406 InitializationSequence Seq(S, Entity, Kind, Element);
408 return Seq.Perform(S, Entity, Kind, Element);
411 Expr *OrigElement = Element;
413 // Perform lvalue-to-rvalue conversion.
414 Result = S.DefaultLvalueConversion(Element);
415 if (Result.isInvalid())
417 Element = Result.get();
419 // Make sure that we have an Objective-C pointer type or block.
420 if (!Element->getType()->isObjCObjectPointerType() &&
421 !Element->getType()->isBlockPointerType()) {
422 bool Recovered = false;
424 // If this is potentially an Objective-C numeric literal, add the '@'.
425 if (isa<IntegerLiteral>(OrigElement) ||
426 isa<CharacterLiteral>(OrigElement) ||
427 isa<FloatingLiteral>(OrigElement) ||
428 isa<ObjCBoolLiteralExpr>(OrigElement) ||
429 isa<CXXBoolLiteralExpr>(OrigElement)) {
430 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
431 int Which = isa<CharacterLiteral>(OrigElement) ? 1
432 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
433 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
436 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
437 << Which << OrigElement->getSourceRange()
438 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
441 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement);
442 if (Result.isInvalid())
445 Element = Result.get();
449 // If this is potentially an Objective-C string literal, add the '@'.
450 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
451 if (String->isAscii()) {
452 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection)
453 << 0 << OrigElement->getSourceRange()
454 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@");
456 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String);
457 if (Result.isInvalid())
460 Element = Result.get();
466 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element)
467 << Element->getType();
472 if (ObjCStringLiteral *getString =
473 dyn_cast<ObjCStringLiteral>(OrigElement)) {
474 if (StringLiteral *SL = getString->getString()) {
475 unsigned numConcat = SL->getNumConcatenated();
477 // Only warn if the concatenated string doesn't come from a macro.
478 bool hasMacro = false;
479 for (unsigned i = 0; i < numConcat ; ++i)
480 if (SL->getStrTokenLoc(i).isMacroID()) {
485 S.Diag(Element->getBeginLoc(),
486 diag::warn_concatenated_nsarray_literal)
487 << Element->getType();
492 // Make sure that the element has the type that the container factory
494 return S.PerformCopyInitialization(
495 InitializedEntity::InitializeParameter(S.Context, T,
497 Element->getBeginLoc(), Element);
500 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
501 if (ValueExpr->isTypeDependent()) {
502 ObjCBoxedExpr *BoxedExpr =
503 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
506 ObjCMethodDecl *BoxingMethod = nullptr;
508 // Convert the expression to an RValue, so we can check for pointer types...
509 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
510 if (RValue.isInvalid()) {
513 SourceLocation Loc = SR.getBegin();
514 ValueExpr = RValue.get();
515 QualType ValueType(ValueExpr->getType());
516 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
517 QualType PointeeType = PT->getPointeeType();
518 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
521 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
526 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
527 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
530 // The boxed expression can be emitted as a compile time constant if it is
531 // a string literal whose character encoding is compatible with UTF-8.
532 if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr))
533 if (CE->getCastKind() == CK_ArrayToPointerDecay)
535 dyn_cast<StringLiteral>(CE->getSubExpr()->IgnoreParens())) {
536 assert((SL->isAscii() || SL->isUTF8()) &&
537 "unexpected character encoding");
538 StringRef Str = SL->getString();
539 const llvm::UTF8 *StrBegin = Str.bytes_begin();
540 const llvm::UTF8 *StrEnd = Str.bytes_end();
541 // Check that this is a valid UTF-8 string.
542 if (llvm::isLegalUTF8String(&StrBegin, StrEnd)) {
543 BoxedType = Context.getAttributedType(
544 AttributedType::getNullabilityAttrKind(
545 NullabilityKind::NonNull),
546 NSStringPointer, NSStringPointer);
547 return new (Context) ObjCBoxedExpr(CE, BoxedType, nullptr, SR);
550 Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string)
551 << NSStringPointer << SL->getSourceRange();
554 if (!StringWithUTF8StringMethod) {
555 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
556 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
558 // Look for the appropriate method within NSString.
559 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
560 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
561 // Debugger needs to work even if NSString hasn't been defined.
562 TypeSourceInfo *ReturnTInfo = nullptr;
563 ObjCMethodDecl *M = ObjCMethodDecl::Create(
564 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
565 NSStringPointer, ReturnTInfo, NSStringDecl,
566 /*isInstance=*/false, /*isVariadic=*/false,
567 /*isPropertyAccessor=*/false,
568 /*isSynthesizedAccessorStub=*/false,
569 /*isImplicitlyDeclared=*/true,
570 /*isDefined=*/false, ObjCMethodDecl::Required,
571 /*HasRelatedResultType=*/false);
572 QualType ConstCharType = Context.CharTy.withConst();
574 ParmVarDecl::Create(Context, M,
575 SourceLocation(), SourceLocation(),
576 &Context.Idents.get("value"),
577 Context.getPointerType(ConstCharType),
580 M->setMethodParams(Context, value, None);
584 if (!validateBoxingMethod(*this, Loc, NSStringDecl,
585 stringWithUTF8String, BoxingMethod))
588 StringWithUTF8StringMethod = BoxingMethod;
591 BoxingMethod = StringWithUTF8StringMethod;
592 BoxedType = NSStringPointer;
593 // Transfer the nullability from method's return type.
594 Optional<NullabilityKind> Nullability =
595 BoxingMethod->getReturnType()->getNullability(Context);
597 BoxedType = Context.getAttributedType(
598 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType,
601 } else if (ValueType->isBuiltinType()) {
602 // The other types we support are numeric, char and BOOL/bool. We could also
603 // provide limited support for structure types, such as NSRange, NSRect, and
604 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
607 // Check for a top-level character literal.
608 if (const CharacterLiteral *Char =
609 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
610 // In C, character literals have type 'int'. That's not the type we want
611 // to use to determine the Objective-c literal kind.
612 switch (Char->getKind()) {
613 case CharacterLiteral::Ascii:
614 case CharacterLiteral::UTF8:
615 ValueType = Context.CharTy;
618 case CharacterLiteral::Wide:
619 ValueType = Context.getWideCharType();
622 case CharacterLiteral::UTF16:
623 ValueType = Context.Char16Ty;
626 case CharacterLiteral::UTF32:
627 ValueType = Context.Char32Ty;
631 // FIXME: Do I need to do anything special with BoolTy expressions?
633 // Look for the appropriate method within NSNumber.
634 BoxingMethod = getNSNumberFactoryMethod(*this, Loc, ValueType);
635 BoxedType = NSNumberPointer;
636 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
637 if (!ET->getDecl()->isComplete()) {
638 Diag(Loc, diag::err_objc_incomplete_boxed_expression_type)
639 << ValueType << ValueExpr->getSourceRange();
643 BoxingMethod = getNSNumberFactoryMethod(*this, Loc,
644 ET->getDecl()->getIntegerType());
645 BoxedType = NSNumberPointer;
646 } else if (ValueType->isObjCBoxableRecordType()) {
647 // Support for structure types, that marked as objc_boxable
648 // struct __attribute__((objc_boxable)) s { ... };
650 // Look up the NSValue class, if we haven't done so already. It's cached
651 // in the Sema instance.
653 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
659 // generate the pointer to NSValue type.
660 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl);
661 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject);
664 if (!ValueWithBytesObjCTypeMethod) {
665 IdentifierInfo *II[] = {
666 &Context.Idents.get("valueWithBytes"),
667 &Context.Idents.get("objCType")
669 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II);
671 // Look for the appropriate method within NSValue.
672 BoxingMethod = NSValueDecl->lookupClassMethod(ValueWithBytesObjCType);
673 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
674 // Debugger needs to work even if NSValue hasn't been defined.
675 TypeSourceInfo *ReturnTInfo = nullptr;
676 ObjCMethodDecl *M = ObjCMethodDecl::Create(
677 Context, SourceLocation(), SourceLocation(), ValueWithBytesObjCType,
678 NSValuePointer, ReturnTInfo, NSValueDecl,
679 /*isInstance=*/false,
680 /*isVariadic=*/false,
681 /*isPropertyAccessor=*/false,
682 /*isSynthesizedAccessorStub=*/false,
683 /*isImplicitlyDeclared=*/true,
684 /*isDefined=*/false, ObjCMethodDecl::Required,
685 /*HasRelatedResultType=*/false);
687 SmallVector<ParmVarDecl *, 2> Params;
690 ParmVarDecl::Create(Context, M,
691 SourceLocation(), SourceLocation(),
692 &Context.Idents.get("bytes"),
693 Context.VoidPtrTy.withConst(),
696 Params.push_back(bytes);
698 QualType ConstCharType = Context.CharTy.withConst();
700 ParmVarDecl::Create(Context, M,
701 SourceLocation(), SourceLocation(),
702 &Context.Idents.get("type"),
703 Context.getPointerType(ConstCharType),
706 Params.push_back(type);
708 M->setMethodParams(Context, Params, None);
712 if (!validateBoxingMethod(*this, Loc, NSValueDecl,
713 ValueWithBytesObjCType, BoxingMethod))
716 ValueWithBytesObjCTypeMethod = BoxingMethod;
719 if (!ValueType.isTriviallyCopyableType(Context)) {
720 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type)
721 << ValueType << ValueExpr->getSourceRange();
725 BoxingMethod = ValueWithBytesObjCTypeMethod;
726 BoxedType = NSValuePointer;
730 Diag(Loc, diag::err_objc_illegal_boxed_expression_type)
731 << ValueType << ValueExpr->getSourceRange();
735 DiagnoseUseOfDecl(BoxingMethod, Loc);
737 ExprResult ConvertedValueExpr;
738 if (ValueType->isObjCBoxableRecordType()) {
739 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType);
740 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(),
743 // Convert the expression to the type that the parameter requires.
744 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
745 InitializedEntity IE = InitializedEntity::InitializeParameter(Context,
747 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(),
751 if (ConvertedValueExpr.isInvalid())
753 ValueExpr = ConvertedValueExpr.get();
755 ObjCBoxedExpr *BoxedExpr =
756 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
758 return MaybeBindToTemporary(BoxedExpr);
761 /// Build an ObjC subscript pseudo-object expression, given that
762 /// that's supported by the runtime.
763 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
765 ObjCMethodDecl *getterMethod,
766 ObjCMethodDecl *setterMethod) {
767 assert(!LangOpts.isSubscriptPointerArithmetic());
769 // We can't get dependent types here; our callers should have
770 // filtered them out.
771 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
772 "base or index cannot have dependent type here");
774 // Filter out placeholders in the index. In theory, overloads could
775 // be preserved here, although that might not actually work correctly.
776 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
777 if (Result.isInvalid())
779 IndexExpr = Result.get();
781 // Perform lvalue-to-rvalue conversion on the base.
782 Result = DefaultLvalueConversion(BaseExpr);
783 if (Result.isInvalid())
785 BaseExpr = Result.get();
787 // Build the pseudo-object expression.
788 return new (Context) ObjCSubscriptRefExpr(
789 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript,
790 getterMethod, setterMethod, RB);
793 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
794 SourceLocation Loc = SR.getBegin();
797 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
804 // Find the arrayWithObjects:count: method, if we haven't done so already.
805 QualType IdT = Context.getObjCIdType();
806 if (!ArrayWithObjectsMethod) {
808 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
809 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
810 if (!Method && getLangOpts().DebuggerObjCLiteral) {
811 TypeSourceInfo *ReturnTInfo = nullptr;
812 Method = ObjCMethodDecl::Create(
813 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
814 Context.getTranslationUnitDecl(), false /*Instance*/,
815 false /*isVariadic*/,
816 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
817 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
818 ObjCMethodDecl::Required, false);
819 SmallVector<ParmVarDecl *, 2> Params;
820 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
823 &Context.Idents.get("objects"),
824 Context.getPointerType(IdT),
827 Params.push_back(objects);
828 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
831 &Context.Idents.get("cnt"),
832 Context.UnsignedLongTy,
833 /*TInfo=*/nullptr, SC_None,
835 Params.push_back(cnt);
836 Method->setMethodParams(Context, Params, None);
839 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method))
842 // Dig out the type that all elements should be converted to.
843 QualType T = Method->parameters()[0]->getType();
844 const PointerType *PtrT = T->getAs<PointerType>();
846 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
847 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
849 Diag(Method->parameters()[0]->getLocation(),
850 diag::note_objc_literal_method_param)
852 << Context.getPointerType(IdT.withConst());
856 // Check that the 'count' parameter is integral.
857 if (!Method->parameters()[1]->getType()->isIntegerType()) {
858 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
860 Diag(Method->parameters()[1]->getLocation(),
861 diag::note_objc_literal_method_param)
863 << Method->parameters()[1]->getType()
868 // We've found a good +arrayWithObjects:count: method. Save it!
869 ArrayWithObjectsMethod = Method;
872 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
873 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
875 // Check that each of the elements provided is valid in a collection literal,
876 // performing conversions as necessary.
877 Expr **ElementsBuffer = Elements.data();
878 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
879 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
882 if (Converted.isInvalid())
885 ElementsBuffer[I] = Converted.get();
889 = Context.getObjCObjectPointerType(
890 Context.getObjCInterfaceType(NSArrayDecl));
892 return MaybeBindToTemporary(
893 ObjCArrayLiteral::Create(Context, Elements, Ty,
894 ArrayWithObjectsMethod, SR));
897 /// Check for duplicate keys in an ObjC dictionary literal. For instance:
898 /// NSDictionary *nd = @{ @"foo" : @"bar", @"foo" : @"baz" };
900 CheckObjCDictionaryLiteralDuplicateKeys(Sema &S,
901 ObjCDictionaryLiteral *Literal) {
902 if (Literal->isValueDependent() || Literal->isTypeDependent())
905 // NSNumber has quite relaxed equality semantics (for instance, @YES is
906 // considered equal to @1.0). For now, ignore floating points and just do a
907 // bit-width and sign agnostic integer compare.
908 struct APSIntCompare {
909 bool operator()(const llvm::APSInt &LHS, const llvm::APSInt &RHS) const {
910 return llvm::APSInt::compareValues(LHS, RHS) < 0;
914 llvm::DenseMap<StringRef, SourceLocation> StringKeys;
915 std::map<llvm::APSInt, SourceLocation, APSIntCompare> IntegralKeys;
917 auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) {
918 auto Pair = Map.insert({Key, Loc});
920 S.Diag(Loc, diag::warn_nsdictionary_duplicate_key);
921 S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here);
925 for (unsigned Idx = 0, End = Literal->getNumElements(); Idx != End; ++Idx) {
926 Expr *Key = Literal->getKeyValueElement(Idx).Key->IgnoreParenImpCasts();
928 if (auto *StrLit = dyn_cast<ObjCStringLiteral>(Key)) {
929 StringRef Bytes = StrLit->getString()->getBytes();
930 SourceLocation Loc = StrLit->getExprLoc();
931 checkOneKey(StringKeys, Bytes, Loc);
934 if (auto *BE = dyn_cast<ObjCBoxedExpr>(Key)) {
935 Expr *Boxed = BE->getSubExpr();
936 SourceLocation Loc = BE->getExprLoc();
938 // Check for @("foo").
939 if (auto *Str = dyn_cast<StringLiteral>(Boxed->IgnoreParenImpCasts())) {
940 checkOneKey(StringKeys, Str->getBytes(), Loc);
944 Expr::EvalResult Result;
945 if (Boxed->EvaluateAsInt(Result, S.getASTContext(),
946 Expr::SE_AllowSideEffects)) {
947 checkOneKey(IntegralKeys, Result.Val.getInt(), Loc);
953 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
954 MutableArrayRef<ObjCDictionaryElement> Elements) {
955 SourceLocation Loc = SR.getBegin();
957 if (!NSDictionaryDecl) {
958 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc,
959 Sema::LK_Dictionary);
960 if (!NSDictionaryDecl) {
965 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
967 QualType IdT = Context.getObjCIdType();
968 if (!DictionaryWithObjectsMethod) {
969 Selector Sel = NSAPIObj->getNSDictionarySelector(
970 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
971 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
972 if (!Method && getLangOpts().DebuggerObjCLiteral) {
973 Method = ObjCMethodDecl::Create(
974 Context, SourceLocation(), SourceLocation(), Sel, IdT,
975 nullptr /*TypeSourceInfo */, Context.getTranslationUnitDecl(),
976 false /*Instance*/, false /*isVariadic*/,
977 /*isPropertyAccessor=*/false,
978 /*isSynthesizedAccessorStub=*/false,
979 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
980 ObjCMethodDecl::Required, false);
981 SmallVector<ParmVarDecl *, 3> Params;
982 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
985 &Context.Idents.get("objects"),
986 Context.getPointerType(IdT),
987 /*TInfo=*/nullptr, SC_None,
989 Params.push_back(objects);
990 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
993 &Context.Idents.get("keys"),
994 Context.getPointerType(IdT),
995 /*TInfo=*/nullptr, SC_None,
997 Params.push_back(keys);
998 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
1001 &Context.Idents.get("cnt"),
1002 Context.UnsignedLongTy,
1003 /*TInfo=*/nullptr, SC_None,
1005 Params.push_back(cnt);
1006 Method->setMethodParams(Context, Params, None);
1009 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
1013 // Dig out the type that all values should be converted to.
1014 QualType ValueT = Method->parameters()[0]->getType();
1015 const PointerType *PtrValue = ValueT->getAs<PointerType>();
1017 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
1018 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1020 Diag(Method->parameters()[0]->getLocation(),
1021 diag::note_objc_literal_method_param)
1023 << Context.getPointerType(IdT.withConst());
1027 // Dig out the type that all keys should be converted to.
1028 QualType KeyT = Method->parameters()[1]->getType();
1029 const PointerType *PtrKey = KeyT->getAs<PointerType>();
1031 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1035 if (QIDNSCopying.isNull()) {
1036 // key argument of selector is id<NSCopying>?
1037 if (ObjCProtocolDecl *NSCopyingPDecl =
1038 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
1039 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
1041 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { },
1043 (ObjCProtocolDecl**) PQ,
1046 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
1049 if (!QIDNSCopying.isNull())
1050 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
1055 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1057 Diag(Method->parameters()[1]->getLocation(),
1058 diag::note_objc_literal_method_param)
1060 << Context.getPointerType(IdT.withConst());
1065 // Check that the 'count' parameter is integral.
1066 QualType CountType = Method->parameters()[2]->getType();
1067 if (!CountType->isIntegerType()) {
1068 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
1070 Diag(Method->parameters()[2]->getLocation(),
1071 diag::note_objc_literal_method_param)
1077 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
1078 DictionaryWithObjectsMethod = Method;
1081 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
1082 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
1083 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
1084 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
1086 // Check that each of the keys and values provided is valid in a collection
1087 // literal, performing conversions as necessary.
1088 bool HasPackExpansions = false;
1089 for (ObjCDictionaryElement &Element : Elements) {
1091 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key,
1093 if (Key.isInvalid())
1098 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT);
1099 if (Value.isInvalid())
1102 Element.Key = Key.get();
1103 Element.Value = Value.get();
1105 if (Element.EllipsisLoc.isInvalid())
1108 if (!Element.Key->containsUnexpandedParameterPack() &&
1109 !Element.Value->containsUnexpandedParameterPack()) {
1110 Diag(Element.EllipsisLoc,
1111 diag::err_pack_expansion_without_parameter_packs)
1112 << SourceRange(Element.Key->getBeginLoc(),
1113 Element.Value->getEndLoc());
1117 HasPackExpansions = true;
1120 QualType Ty = Context.getObjCObjectPointerType(
1121 Context.getObjCInterfaceType(NSDictionaryDecl));
1124 ObjCDictionaryLiteral::Create(Context, Elements, HasPackExpansions, Ty,
1125 DictionaryWithObjectsMethod, SR);
1126 CheckObjCDictionaryLiteralDuplicateKeys(*this, Literal);
1127 return MaybeBindToTemporary(Literal);
1130 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
1131 TypeSourceInfo *EncodedTypeInfo,
1132 SourceLocation RParenLoc) {
1133 QualType EncodedType = EncodedTypeInfo->getType();
1135 if (EncodedType->isDependentType())
1136 StrTy = Context.DependentTy;
1138 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
1139 !EncodedType->isVoidType()) // void is handled too.
1140 if (RequireCompleteType(AtLoc, EncodedType,
1141 diag::err_incomplete_type_objc_at_encode,
1142 EncodedTypeInfo->getTypeLoc()))
1146 QualType NotEncodedT;
1147 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
1148 if (!NotEncodedT.isNull())
1149 Diag(AtLoc, diag::warn_incomplete_encoded_type)
1150 << EncodedType << NotEncodedT;
1152 // The type of @encode is the same as the type of the corresponding string,
1153 // which is an array type.
1154 StrTy = Context.getStringLiteralArrayType(Context.CharTy, Str.size());
1157 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
1160 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1161 SourceLocation EncodeLoc,
1162 SourceLocation LParenLoc,
1164 SourceLocation RParenLoc) {
1165 // FIXME: Preserve type source info ?
1166 TypeSourceInfo *TInfo;
1167 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1169 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1170 getLocForEndOfToken(LParenLoc));
1172 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
1175 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1176 SourceLocation AtLoc,
1177 SourceLocation LParenLoc,
1178 SourceLocation RParenLoc,
1179 ObjCMethodDecl *Method,
1180 ObjCMethodList &MethList) {
1181 ObjCMethodList *M = &MethList;
1182 bool Warned = false;
1183 for (M = M->getNext(); M; M=M->getNext()) {
1184 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
1185 if (MatchingMethodDecl == Method ||
1186 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1187 MatchingMethodDecl->getSelector() != Method->getSelector())
1189 if (!S.MatchTwoMethodDeclarations(Method,
1190 MatchingMethodDecl, Sema::MMS_loose)) {
1193 S.Diag(AtLoc, diag::warn_multiple_selectors)
1194 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1195 << FixItHint::CreateInsertion(RParenLoc, ")");
1196 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1197 << Method->getDeclName();
1199 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1200 << MatchingMethodDecl->getDeclName();
1206 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
1207 ObjCMethodDecl *Method,
1208 SourceLocation LParenLoc,
1209 SourceLocation RParenLoc,
1210 bool WarnMultipleSelectors) {
1211 if (!WarnMultipleSelectors ||
1212 S.Diags.isIgnored(diag::warn_multiple_selectors, SourceLocation()))
1214 bool Warned = false;
1215 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1216 e = S.MethodPool.end(); b != e; b++) {
1217 // first, instance methods
1218 ObjCMethodList &InstMethList = b->second.first;
1219 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1220 Method, InstMethList))
1223 // second, class methods
1224 ObjCMethodList &ClsMethList = b->second.second;
1225 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1226 Method, ClsMethList) || Warned)
1231 static ObjCMethodDecl *LookupDirectMethodInMethodList(Sema &S, Selector Sel,
1232 ObjCMethodList &MethList,
1236 ObjCMethodList *M = &MethList;
1237 ObjCMethodDecl *DirectMethod = nullptr;
1238 for (; M; M = M->getNext()) {
1239 ObjCMethodDecl *Method = M->getMethod();
1242 assert(Method->getSelector() == Sel && "Method with wrong selector in method list");
1243 if (Method->isDirectMethod()) {
1245 DirectMethod = Method;
1250 return DirectMethod;
1253 // Search the global pool for (potentially) direct methods matching the given
1254 // selector. If a non-direct method is found, set \param onlyDirect to false. If
1255 // a direct method is found, set \param anyDirect to true. Returns a direct
1257 static ObjCMethodDecl *LookupDirectMethodInGlobalPool(Sema &S, Selector Sel,
1260 auto Iter = S.MethodPool.find(Sel);
1261 if (Iter == S.MethodPool.end())
1264 ObjCMethodDecl *DirectInstance = LookupDirectMethodInMethodList(
1265 S, Sel, Iter->second.first, onlyDirect, anyDirect);
1266 ObjCMethodDecl *DirectClass = LookupDirectMethodInMethodList(
1267 S, Sel, Iter->second.second, onlyDirect, anyDirect);
1269 return DirectInstance ? DirectInstance : DirectClass;
1272 static ObjCMethodDecl *findMethodInCurrentClass(Sema &S, Selector Sel) {
1273 auto *CurMD = S.getCurMethodDecl();
1276 ObjCInterfaceDecl *IFace = CurMD->getClassInterface();
1278 // The language enforce that only one direct method is present in a given
1279 // class, so we just need to find one method in the current class to know
1280 // whether Sel is potentially direct in this context.
1281 if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/true))
1283 if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*isInstance=*/true))
1285 if (ObjCMethodDecl *MD = IFace->lookupMethod(Sel, /*isInstance=*/false))
1287 if (ObjCMethodDecl *MD = IFace->lookupPrivateMethod(Sel, /*isInstance=*/false))
1293 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1294 SourceLocation AtLoc,
1295 SourceLocation SelLoc,
1296 SourceLocation LParenLoc,
1297 SourceLocation RParenLoc,
1298 bool WarnMultipleSelectors) {
1299 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1300 SourceRange(LParenLoc, RParenLoc));
1302 Method = LookupFactoryMethodInGlobalPool(Sel,
1303 SourceRange(LParenLoc, RParenLoc));
1305 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1306 Selector MatchedSel = OM->getSelector();
1307 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1308 RParenLoc.getLocWithOffset(-1));
1309 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1310 << Sel << MatchedSel
1311 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1314 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
1316 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1317 WarnMultipleSelectors);
1319 bool onlyDirect = true;
1320 bool anyDirect = false;
1321 ObjCMethodDecl *GlobalDirectMethod =
1322 LookupDirectMethodInGlobalPool(*this, Sel, onlyDirect, anyDirect);
1325 Diag(AtLoc, diag::err_direct_selector_expression)
1326 << Method->getSelector();
1327 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
1328 << Method->getDeclName();
1329 } else if (anyDirect) {
1330 // If we saw any direct methods, see if we see a direct member of the
1331 // current class. If so, the @selector will likely be used to refer to
1332 // this direct method.
1333 ObjCMethodDecl *LikelyTargetMethod = findMethodInCurrentClass(*this, Sel);
1334 if (LikelyTargetMethod && LikelyTargetMethod->isDirectMethod()) {
1335 Diag(AtLoc, diag::warn_potentially_direct_selector_expression) << Sel;
1336 Diag(LikelyTargetMethod->getLocation(),
1337 diag::note_direct_method_declared_at)
1338 << LikelyTargetMethod->getDeclName();
1339 } else if (!LikelyTargetMethod) {
1340 // Otherwise, emit the "strict" variant of this diagnostic, unless
1341 // LikelyTargetMethod is non-direct.
1342 Diag(AtLoc, diag::warn_strict_potentially_direct_selector_expression)
1344 Diag(GlobalDirectMethod->getLocation(),
1345 diag::note_direct_method_declared_at)
1346 << GlobalDirectMethod->getDeclName();
1352 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1353 !getSourceManager().isInSystemHeader(Method->getLocation()))
1354 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
1356 // In ARC, forbid the user from using @selector for
1357 // retain/release/autorelease/dealloc/retainCount.
1358 if (getLangOpts().ObjCAutoRefCount) {
1359 switch (Sel.getMethodFamily()) {
1362 case OMF_autorelease:
1363 case OMF_retainCount:
1365 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1366 Sel << SourceRange(LParenLoc, RParenLoc);
1374 case OMF_mutableCopy:
1377 case OMF_initialize:
1378 case OMF_performSelector:
1382 QualType Ty = Context.getObjCSelType();
1383 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
1386 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1387 SourceLocation AtLoc,
1388 SourceLocation ProtoLoc,
1389 SourceLocation LParenLoc,
1390 SourceLocation ProtoIdLoc,
1391 SourceLocation RParenLoc) {
1392 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
1394 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
1397 if (!PDecl->hasDefinition()) {
1398 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl;
1399 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
1401 PDecl = PDecl->getDefinition();
1404 QualType Ty = Context.getObjCProtoType();
1407 Ty = Context.getObjCObjectPointerType(Ty);
1408 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
1411 /// Try to capture an implicit reference to 'self'.
1412 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1413 DeclContext *DC = getFunctionLevelDeclContext();
1415 // If we're not in an ObjC method, error out. Note that, unlike the
1416 // C++ case, we don't require an instance method --- class methods
1417 // still have a 'self', and we really do still need to capture it!
1418 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1422 tryCaptureVariable(method->getSelfDecl(), Loc);
1427 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1428 QualType origType = T;
1429 if (auto nullability = AttributedType::stripOuterNullability(T)) {
1430 if (T == Context.getObjCInstanceType()) {
1431 return Context.getAttributedType(
1432 AttributedType::getNullabilityAttrKind(*nullability),
1433 Context.getObjCIdType(),
1434 Context.getObjCIdType());
1440 if (T == Context.getObjCInstanceType())
1441 return Context.getObjCIdType();
1446 /// Determine the result type of a message send based on the receiver type,
1447 /// method, and the kind of message send.
1449 /// This is the "base" result type, which will still need to be adjusted
1450 /// to account for nullability.
1451 static QualType getBaseMessageSendResultType(Sema &S,
1452 QualType ReceiverType,
1453 ObjCMethodDecl *Method,
1454 bool isClassMessage,
1455 bool isSuperMessage) {
1456 assert(Method && "Must have a method");
1457 if (!Method->hasRelatedResultType())
1458 return Method->getSendResultType(ReceiverType);
1460 ASTContext &Context = S.Context;
1462 // Local function that transfers the nullability of the method's
1463 // result type to the returned result.
1464 auto transferNullability = [&](QualType type) -> QualType {
1465 // If the method's result type has nullability, extract it.
1466 if (auto nullability = Method->getSendResultType(ReceiverType)
1467 ->getNullability(Context)){
1468 // Strip off any outer nullability sugar from the provided type.
1469 (void)AttributedType::stripOuterNullability(type);
1471 // Form a new attributed type using the method result type's nullability.
1472 return Context.getAttributedType(
1473 AttributedType::getNullabilityAttrKind(*nullability),
1481 // If a method has a related return type:
1482 // - if the method found is an instance method, but the message send
1483 // was a class message send, T is the declared return type of the method
1485 if (Method->isInstanceMethod() && isClassMessage)
1486 return stripObjCInstanceType(Context,
1487 Method->getSendResultType(ReceiverType));
1489 // - if the receiver is super, T is a pointer to the class of the
1490 // enclosing method definition
1491 if (isSuperMessage) {
1492 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl())
1493 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1494 return transferNullability(
1495 Context.getObjCObjectPointerType(
1496 Context.getObjCInterfaceType(Class)));
1500 // - if the receiver is the name of a class U, T is a pointer to U
1501 if (ReceiverType->getAsObjCInterfaceType())
1502 return transferNullability(Context.getObjCObjectPointerType(ReceiverType));
1503 // - if the receiver is of type Class or qualified Class type,
1504 // T is the declared return type of the method.
1505 if (ReceiverType->isObjCClassType() ||
1506 ReceiverType->isObjCQualifiedClassType())
1507 return stripObjCInstanceType(Context,
1508 Method->getSendResultType(ReceiverType));
1510 // - if the receiver is id, qualified id, Class, or qualified Class, T
1511 // is the receiver type, otherwise
1512 // - T is the type of the receiver expression.
1513 return transferNullability(ReceiverType);
1516 QualType Sema::getMessageSendResultType(const Expr *Receiver,
1517 QualType ReceiverType,
1518 ObjCMethodDecl *Method,
1519 bool isClassMessage,
1520 bool isSuperMessage) {
1521 // Produce the result type.
1522 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType,
1527 // If this is a class message, ignore the nullability of the receiver.
1528 if (isClassMessage) {
1529 // In a class method, class messages to 'self' that return instancetype can
1530 // be typed as the current class. We can safely do this in ARC because self
1531 // can't be reassigned, and we do it unsafely outside of ARC because in
1532 // practice people never reassign self in class methods and there's some
1533 // virtue in not being aggressively pedantic.
1534 if (Receiver && Receiver->isObjCSelfExpr()) {
1535 assert(ReceiverType->isObjCClassType() && "expected a Class self");
1536 QualType T = Method->getSendResultType(ReceiverType);
1537 AttributedType::stripOuterNullability(T);
1538 if (T == Context.getObjCInstanceType()) {
1539 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>(
1540 cast<ImplicitParamDecl>(
1541 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl())
1542 ->getDeclContext());
1543 assert(MD->isClassMethod() && "expected a class method");
1544 QualType NewResultType = Context.getObjCObjectPointerType(
1545 Context.getObjCInterfaceType(MD->getClassInterface()));
1546 if (auto Nullability = resultType->getNullability(Context))
1547 NewResultType = Context.getAttributedType(
1548 AttributedType::getNullabilityAttrKind(*Nullability),
1549 NewResultType, NewResultType);
1550 return NewResultType;
1556 // There is nothing left to do if the result type cannot have a nullability
1558 if (!resultType->canHaveNullability())
1561 // Map the nullability of the result into a table index.
1562 unsigned receiverNullabilityIdx = 0;
1563 if (auto nullability = ReceiverType->getNullability(Context))
1564 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1566 unsigned resultNullabilityIdx = 0;
1567 if (auto nullability = resultType->getNullability(Context))
1568 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability);
1570 // The table of nullability mappings, indexed by the receiver's nullability
1571 // and then the result type's nullability.
1572 static const uint8_t None = 0;
1573 static const uint8_t NonNull = 1;
1574 static const uint8_t Nullable = 2;
1575 static const uint8_t Unspecified = 3;
1576 static const uint8_t nullabilityMap[4][4] = {
1577 // None NonNull Nullable Unspecified
1578 /* None */ { None, None, Nullable, None },
1579 /* NonNull */ { None, NonNull, Nullable, Unspecified },
1580 /* Nullable */ { Nullable, Nullable, Nullable, Nullable },
1581 /* Unspecified */ { None, Unspecified, Nullable, Unspecified }
1584 unsigned newResultNullabilityIdx
1585 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx];
1586 if (newResultNullabilityIdx == resultNullabilityIdx)
1589 // Strip off the existing nullability. This removes as little type sugar as
1592 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) {
1593 resultType = attributed->getModifiedType();
1595 resultType = resultType.getDesugaredType(Context);
1597 } while (resultType->getNullability(Context));
1599 // Add nullability back if needed.
1600 if (newResultNullabilityIdx > 0) {
1602 = static_cast<NullabilityKind>(newResultNullabilityIdx-1);
1603 return Context.getAttributedType(
1604 AttributedType::getNullabilityAttrKind(newNullability),
1605 resultType, resultType);
1611 /// Look for an ObjC method whose result type exactly matches the given type.
1612 static const ObjCMethodDecl *
1613 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1614 QualType instancetype) {
1615 if (MD->getReturnType() == instancetype)
1618 // For these purposes, a method in an @implementation overrides a
1619 // declaration in the @interface.
1620 if (const ObjCImplDecl *impl =
1621 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1622 const ObjCContainerDecl *iface;
1623 if (const ObjCCategoryImplDecl *catImpl =
1624 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1625 iface = catImpl->getCategoryDecl();
1627 iface = impl->getClassInterface();
1630 const ObjCMethodDecl *ifaceMD =
1631 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1632 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1635 SmallVector<const ObjCMethodDecl *, 4> overrides;
1636 MD->getOverriddenMethods(overrides);
1637 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1638 if (const ObjCMethodDecl *result =
1639 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1646 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1647 // Only complain if we're in an ObjC method and the required return
1648 // type doesn't match the method's declared return type.
1649 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1650 if (!MD || !MD->hasRelatedResultType() ||
1651 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
1654 // Look for a method overridden by this method which explicitly uses
1656 if (const ObjCMethodDecl *overridden =
1657 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1658 SourceRange range = overridden->getReturnTypeSourceRange();
1659 SourceLocation loc = range.getBegin();
1660 if (loc.isInvalid())
1661 loc = overridden->getLocation();
1662 Diag(loc, diag::note_related_result_type_explicit)
1663 << /*current method*/ 1 << range;
1667 // Otherwise, if we have an interesting method family, note that.
1668 // This should always trigger if the above didn't.
1669 if (ObjCMethodFamily family = MD->getMethodFamily())
1670 Diag(MD->getLocation(), diag::note_related_result_type_family)
1671 << /*current method*/ 1
1675 void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1676 E = E->IgnoreParenImpCasts();
1677 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1681 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1685 if (!Method->hasRelatedResultType())
1688 if (Context.hasSameUnqualifiedType(
1689 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
1692 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
1693 Context.getObjCInstanceType()))
1696 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1697 << Method->isInstanceMethod() << Method->getSelector()
1698 << MsgSend->getType();
1701 bool Sema::CheckMessageArgumentTypes(
1702 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args,
1703 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method,
1704 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac,
1705 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType,
1706 ExprValueKind &VK) {
1707 SourceLocation SelLoc;
1708 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1709 SelLoc = SelectorLocs.front();
1714 // Apply default argument promotion as for (C99 6.5.2.2p6).
1715 for (unsigned i = 0, e = Args.size(); i != e; i++) {
1716 if (Args[i]->isTypeDependent())
1720 if (getLangOpts().DebuggerSupport) {
1721 QualType paramTy; // ignored
1722 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
1724 result = DefaultArgumentPromotion(Args[i]);
1726 if (result.isInvalid())
1728 Args[i] = result.get();
1732 if (getLangOpts().ObjCAutoRefCount)
1733 DiagID = diag::err_arc_method_not_found;
1735 DiagID = isClassMessage ? diag::warn_class_method_not_found
1736 : diag::warn_inst_method_not_found;
1737 if (!getLangOpts().DebuggerSupport) {
1738 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
1739 if (OMD && !OMD->isInvalidDecl()) {
1740 if (getLangOpts().ObjCAutoRefCount)
1741 DiagID = diag::err_method_not_found_with_typo;
1743 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1744 : diag::warn_instance_method_not_found_with_typo;
1745 Selector MatchedSel = OMD->getSelector();
1746 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
1747 if (MatchedSel.isUnarySelector())
1748 Diag(SelLoc, DiagID)
1749 << Sel<< isClassMessage << MatchedSel
1750 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1752 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
1755 Diag(SelLoc, DiagID)
1756 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1757 SelectorLocs.back());
1758 // Find the class to which we are sending this message.
1759 if (auto *ObjPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
1760 if (ObjCInterfaceDecl *ThisClass = ObjPT->getInterfaceDecl()) {
1761 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1762 if (!RecRange.isInvalid())
1763 if (ThisClass->lookupClassMethod(Sel))
1764 Diag(RecRange.getBegin(), diag::note_receiver_expr_here)
1765 << FixItHint::CreateReplacement(RecRange,
1766 ThisClass->getNameAsString());
1771 // In debuggers, we want to use __unknown_anytype for these
1772 // results so that clients can cast them.
1773 if (getLangOpts().DebuggerSupport) {
1774 ReturnType = Context.UnknownAnyTy;
1776 ReturnType = Context.getObjCIdType();
1782 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method,
1783 isClassMessage, isSuperMessage);
1784 VK = Expr::getValueKindForType(Method->getReturnType());
1786 unsigned NumNamedArgs = Sel.getNumArgs();
1787 // Method might have more arguments than selector indicates. This is due
1788 // to addition of c-style arguments in method.
1789 if (Method->param_size() > Sel.getNumArgs())
1790 NumNamedArgs = Method->param_size();
1791 // FIXME. This need be cleaned up.
1792 if (Args.size() < NumNamedArgs) {
1793 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
1794 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
1798 // Compute the set of type arguments to be substituted into each parameter
1800 Optional<ArrayRef<QualType>> typeArgs
1801 = ReceiverType->getObjCSubstitutions(Method->getDeclContext());
1802 bool IsError = false;
1803 for (unsigned i = 0; i < NumNamedArgs; i++) {
1804 // We can't do any type-checking on a type-dependent argument.
1805 if (Args[i]->isTypeDependent())
1808 Expr *argExpr = Args[i];
1810 ParmVarDecl *param = Method->parameters()[i];
1811 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
1813 if (param->hasAttr<NoEscapeAttr>())
1814 if (auto *BE = dyn_cast<BlockExpr>(
1815 argExpr->IgnoreParenNoopCasts(Context)))
1816 BE->getBlockDecl()->setDoesNotEscape();
1818 // Strip the unbridged-cast placeholder expression off unless it's
1819 // a consumed argument.
1820 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1821 !param->hasAttr<CFConsumedAttr>())
1822 argExpr = stripARCUnbridgedCast(argExpr);
1824 // If the parameter is __unknown_anytype, infer its type
1825 // from the argument.
1826 if (param->getType() == Context.UnknownAnyTy) {
1828 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
1829 if (argE.isInvalid()) {
1832 Args[i] = argE.get();
1834 // Update the parameter type in-place.
1835 param->setType(paramType);
1840 QualType origParamType = param->getType();
1841 QualType paramType = param->getType();
1843 paramType = paramType.substObjCTypeArgs(
1846 ObjCSubstitutionContext::Parameter);
1848 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
1850 diag::err_call_incomplete_argument, argExpr))
1853 InitializedEntity Entity
1854 = InitializedEntity::InitializeParameter(Context, param, paramType);
1855 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
1856 if (ArgE.isInvalid())
1859 Args[i] = ArgE.getAs<Expr>();
1861 // If we are type-erasing a block to a block-compatible
1862 // Objective-C pointer type, we may need to extend the lifetime
1863 // of the block object.
1864 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() &&
1865 Args[i]->getType()->isBlockPointerType() &&
1866 origParamType->isObjCObjectPointerType()) {
1867 ExprResult arg = Args[i];
1868 maybeExtendBlockObject(arg);
1869 Args[i] = arg.get();
1874 // Promote additional arguments to variadic methods.
1875 if (Method->isVariadic()) {
1876 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
1877 if (Args[i]->isTypeDependent())
1880 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1882 IsError |= Arg.isInvalid();
1883 Args[i] = Arg.get();
1886 // Check for extra arguments to non-variadic methods.
1887 if (Args.size() != NumNamedArgs) {
1888 Diag(Args[NumNamedArgs]->getBeginLoc(),
1889 diag::err_typecheck_call_too_many_args)
1890 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
1891 << Method->getSourceRange()
1892 << SourceRange(Args[NumNamedArgs]->getBeginLoc(),
1893 Args.back()->getEndLoc());
1897 DiagnoseSentinelCalls(Method, SelLoc, Args);
1899 // Do additional checkings on method.
1900 IsError |= CheckObjCMethodCall(
1901 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
1906 bool Sema::isSelfExpr(Expr *RExpr) {
1907 // 'self' is objc 'self' in an objc method only.
1908 ObjCMethodDecl *Method =
1909 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1910 return isSelfExpr(RExpr, Method);
1913 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
1914 if (!method) return false;
1916 receiver = receiver->IgnoreParenLValueCasts();
1917 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
1918 if (DRE->getDecl() == method->getSelfDecl())
1923 /// LookupMethodInType - Look up a method in an ObjCObjectType.
1924 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1926 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1927 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1928 // Look it up in the main interface (and categories, etc.)
1929 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1932 // Okay, look for "private" methods declared in any
1933 // @implementations we've seen.
1934 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1938 // Check qualifiers.
1939 for (const auto *I : objType->quals())
1940 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
1946 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1947 /// list of a qualified objective pointer type.
1948 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1949 const ObjCObjectPointerType *OPT,
1952 ObjCMethodDecl *MD = nullptr;
1953 for (const auto *PROTO : OPT->quals()) {
1954 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1961 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1962 /// objective C interface. This is a property reference expression.
1964 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
1965 Expr *BaseExpr, SourceLocation OpLoc,
1966 DeclarationName MemberName,
1967 SourceLocation MemberLoc,
1968 SourceLocation SuperLoc, QualType SuperType,
1970 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1971 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
1973 if (!MemberName.isIdentifier()) {
1974 Diag(MemberLoc, diag::err_invalid_property_name)
1975 << MemberName << QualType(OPT, 0);
1979 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1981 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1982 : BaseExpr->getSourceRange();
1983 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1984 diag::err_property_not_found_forward_class,
1985 MemberName, BaseRange))
1988 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(
1989 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1990 // Check whether we can reference this property.
1991 if (DiagnoseUseOfDecl(PD, MemberLoc))
1994 return new (Context)
1995 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1996 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
1998 return new (Context)
1999 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2000 OK_ObjCProperty, MemberLoc, BaseExpr);
2002 // Check protocols on qualified interfaces.
2003 for (const auto *I : OPT->quals())
2004 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
2005 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2006 // Check whether we can reference this property.
2007 if (DiagnoseUseOfDecl(PD, MemberLoc))
2011 return new (Context) ObjCPropertyRefExpr(
2012 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
2013 SuperLoc, SuperType);
2015 return new (Context)
2016 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
2017 OK_ObjCProperty, MemberLoc, BaseExpr);
2019 // If that failed, look for an "implicit" property by seeing if the nullary
2020 // selector is implemented.
2022 // FIXME: The logic for looking up nullary and unary selectors should be
2023 // shared with the code in ActOnInstanceMessage.
2025 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2026 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2028 // May be found in property's qualified list.
2030 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
2032 // If this reference is in an @implementation, check for 'private' methods.
2034 Getter = IFace->lookupPrivateMethod(Sel);
2037 // Check if we can reference this property.
2038 if (DiagnoseUseOfDecl(Getter, MemberLoc))
2041 // If we found a getter then this may be a valid dot-reference, we
2042 // will look for the matching setter, in case it is needed.
2043 Selector SetterSel =
2044 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
2045 PP.getSelectorTable(), Member);
2046 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2048 // May be found in property's qualified list.
2050 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
2053 // If this reference is in an @implementation, also check for 'private'
2055 Setter = IFace->lookupPrivateMethod(SetterSel);
2058 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2061 // Special warning if member name used in a property-dot for a setter accessor
2062 // does not use a property with same name; e.g. obj.X = ... for a property with
2064 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() &&
2065 !IFace->FindPropertyDeclaration(
2066 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
2067 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
2068 // Do not warn if user is using property-dot syntax to make call to
2069 // user named setter.
2070 if (!(PDecl->getPropertyAttributes() &
2071 ObjCPropertyAttribute::kind_setter))
2073 diag::warn_property_access_suggest)
2074 << MemberName << QualType(OPT, 0) << PDecl->getName()
2075 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
2079 if (Getter || Setter) {
2081 return new (Context)
2082 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2083 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
2085 return new (Context)
2086 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2087 OK_ObjCProperty, MemberLoc, BaseExpr);
2091 // Attempt to correct for typos in property names.
2092 DeclFilterCCC<ObjCPropertyDecl> CCC{};
2093 if (TypoCorrection Corrected = CorrectTypo(
2094 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
2095 nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) {
2096 DeclarationName TypoResult = Corrected.getCorrection();
2097 if (TypoResult.isIdentifier() &&
2098 TypoResult.getAsIdentifierInfo() == Member) {
2099 // There is no need to try the correction if it is the same.
2100 NamedDecl *ChosenDecl =
2101 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl();
2102 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl))
2103 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) {
2104 // This is a class property, we should not use the instance to
2106 Diag(MemberLoc, diag::err_class_property_found) << MemberName
2107 << OPT->getInterfaceDecl()->getName()
2108 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(),
2109 OPT->getInterfaceDecl()->getName());
2113 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
2114 << MemberName << QualType(OPT, 0));
2115 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
2116 TypoResult, MemberLoc,
2117 SuperLoc, SuperType, Super);
2120 ObjCInterfaceDecl *ClassDeclared;
2121 if (ObjCIvarDecl *Ivar =
2122 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
2123 QualType T = Ivar->getType();
2124 if (const ObjCObjectPointerType * OBJPT =
2125 T->getAsObjCInterfacePointerType()) {
2126 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
2127 diag::err_property_not_as_forward_class,
2128 MemberName, BaseExpr))
2132 diag::err_ivar_access_using_property_syntax_suggest)
2133 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
2134 << FixItHint::CreateReplacement(OpLoc, "->");
2138 Diag(MemberLoc, diag::err_property_not_found)
2139 << MemberName << QualType(OPT, 0);
2141 Diag(Setter->getLocation(), diag::note_getter_unavailable)
2142 << MemberName << BaseExpr->getSourceRange();
2147 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
2148 IdentifierInfo &propertyName,
2149 SourceLocation receiverNameLoc,
2150 SourceLocation propertyNameLoc) {
2152 IdentifierInfo *receiverNamePtr = &receiverName;
2153 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
2158 // If the "receiver" is 'super' in a method, handle it as an expression-like
2159 // property reference.
2160 if (receiverNamePtr->isStr("super")) {
2161 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
2162 if (auto classDecl = CurMethod->getClassInterface()) {
2163 SuperType = QualType(classDecl->getSuperClassType(), 0);
2164 if (CurMethod->isInstanceMethod()) {
2165 if (SuperType.isNull()) {
2166 // The current class does not have a superclass.
2167 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super)
2168 << CurMethod->getClassInterface()->getIdentifier();
2171 QualType T = Context.getObjCObjectPointerType(SuperType);
2173 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(),
2174 /*BaseExpr*/nullptr,
2175 SourceLocation()/*OpLoc*/,
2178 receiverNameLoc, T, true);
2181 // Otherwise, if this is a class method, try dispatching to our
2183 IFace = CurMethod->getClassInterface()->getSuperClass();
2189 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
2197 if (auto PD = IFace->FindPropertyDeclaration(
2198 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) {
2199 GetterSel = PD->getGetterName();
2200 SetterSel = PD->getSetterName();
2202 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName);
2203 SetterSel = SelectorTable::constructSetterSelector(
2204 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName);
2207 // Search for a declared property first.
2208 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel);
2210 // If this reference is in an @implementation, check for 'private' methods.
2212 Getter = IFace->lookupPrivateClassMethod(GetterSel);
2215 // FIXME: refactor/share with ActOnMemberReference().
2216 // Check if we can reference this property.
2217 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
2221 // Look for the matching setter, in case it is needed.
2222 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2224 // If this reference is in an @implementation, also check for 'private'
2226 Setter = IFace->lookupPrivateClassMethod(SetterSel);
2228 // Look through local category implementations associated with the class.
2230 Setter = IFace->getCategoryClassMethod(SetterSel);
2232 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
2235 if (Getter || Setter) {
2236 if (!SuperType.isNull())
2237 return new (Context)
2238 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
2239 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
2242 return new (Context) ObjCPropertyRefExpr(
2243 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
2244 propertyNameLoc, receiverNameLoc, IFace);
2246 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
2247 << &propertyName << Context.getObjCInterfaceType(IFace));
2252 class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback {
2254 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
2255 // Determine whether "super" is acceptable in the current context.
2256 if (Method && Method->getClassInterface())
2257 WantObjCSuper = Method->getClassInterface()->getSuperClass();
2260 bool ValidateCandidate(const TypoCorrection &candidate) override {
2261 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
2262 candidate.isKeyword("super");
2265 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2266 return std::make_unique<ObjCInterfaceOrSuperCCC>(*this);
2270 } // end anonymous namespace
2272 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
2273 IdentifierInfo *Name,
2274 SourceLocation NameLoc,
2276 bool HasTrailingDot,
2277 ParsedType &ReceiverType) {
2278 ReceiverType = nullptr;
2280 // If the identifier is "super" and there is no trailing dot, we're
2281 // messaging super. If the identifier is "super" and there is a
2282 // trailing dot, it's an instance message.
2283 if (IsSuper && S->isInObjcMethodScope())
2284 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
2286 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
2287 LookupName(Result, S);
2289 switch (Result.getResultKind()) {
2290 case LookupResult::NotFound:
2291 // Normal name lookup didn't find anything. If we're in an
2292 // Objective-C method, look for ivars. If we find one, we're done!
2293 // FIXME: This is a hack. Ivar lookup should be part of normal
2295 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
2296 if (!Method->getClassInterface()) {
2297 // Fall back: let the parser try to parse it as an instance message.
2298 return ObjCInstanceMessage;
2301 ObjCInterfaceDecl *ClassDeclared;
2302 if (Method->getClassInterface()->lookupInstanceVariable(Name,
2304 return ObjCInstanceMessage;
2307 // Break out; we'll perform typo correction below.
2310 case LookupResult::NotFoundInCurrentInstantiation:
2311 case LookupResult::FoundOverloaded:
2312 case LookupResult::FoundUnresolvedValue:
2313 case LookupResult::Ambiguous:
2314 Result.suppressDiagnostics();
2315 return ObjCInstanceMessage;
2317 case LookupResult::Found: {
2318 // If the identifier is a class or not, and there is a trailing dot,
2319 // it's an instance message.
2321 return ObjCInstanceMessage;
2322 // We found something. If it's a type, then we have a class
2323 // message. Otherwise, it's an instance message.
2324 NamedDecl *ND = Result.getFoundDecl();
2326 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
2327 T = Context.getObjCInterfaceType(Class);
2328 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
2329 T = Context.getTypeDeclType(Type);
2330 DiagnoseUseOfDecl(Type, NameLoc);
2333 return ObjCInstanceMessage;
2335 // We have a class message, and T is the type we're
2336 // messaging. Build source-location information for it.
2337 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2338 ReceiverType = CreateParsedType(T, TSInfo);
2339 return ObjCClassMessage;
2343 ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl());
2344 if (TypoCorrection Corrected = CorrectTypo(
2345 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC,
2346 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
2347 if (Corrected.isKeyword()) {
2348 // If we've found the keyword "super" (the only keyword that would be
2349 // returned by CorrectTypo), this is a send to super.
2350 diagnoseTypo(Corrected,
2351 PDiag(diag::err_unknown_receiver_suggest) << Name);
2352 return ObjCSuperMessage;
2353 } else if (ObjCInterfaceDecl *Class =
2354 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2355 // If we found a declaration, correct when it refers to an Objective-C
2357 diagnoseTypo(Corrected,
2358 PDiag(diag::err_unknown_receiver_suggest) << Name);
2359 QualType T = Context.getObjCInterfaceType(Class);
2360 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
2361 ReceiverType = CreateParsedType(T, TSInfo);
2362 return ObjCClassMessage;
2366 // Fall back: let the parser try to parse it as an instance message.
2367 return ObjCInstanceMessage;
2370 ExprResult Sema::ActOnSuperMessage(Scope *S,
2371 SourceLocation SuperLoc,
2373 SourceLocation LBracLoc,
2374 ArrayRef<SourceLocation> SelectorLocs,
2375 SourceLocation RBracLoc,
2376 MultiExprArg Args) {
2377 // Determine whether we are inside a method or not.
2378 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
2380 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
2384 ObjCInterfaceDecl *Class = Method->getClassInterface();
2386 Diag(SuperLoc, diag::err_no_super_class_message)
2387 << Method->getDeclName();
2391 QualType SuperTy(Class->getSuperClassType(), 0);
2392 if (SuperTy.isNull()) {
2393 // The current class does not have a superclass.
2394 Diag(SuperLoc, diag::err_root_class_cannot_use_super)
2395 << Class->getIdentifier();
2399 // We are in a method whose class has a superclass, so 'super'
2400 // is acting as a keyword.
2401 if (Method->getSelector() == Sel)
2402 getCurFunction()->ObjCShouldCallSuper = false;
2404 if (Method->isInstanceMethod()) {
2405 // Since we are in an instance method, this is an instance
2406 // message to the superclass instance.
2407 SuperTy = Context.getObjCObjectPointerType(SuperTy);
2408 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2409 Sel, /*Method=*/nullptr,
2410 LBracLoc, SelectorLocs, RBracLoc, Args);
2413 // Since we are in a class method, this is a class message to
2415 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
2417 SuperLoc, Sel, /*Method=*/nullptr,
2418 LBracLoc, SelectorLocs, RBracLoc, Args);
2421 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2422 bool isSuperReceiver,
2425 ObjCMethodDecl *Method,
2426 MultiExprArg Args) {
2427 TypeSourceInfo *receiverTypeInfo = nullptr;
2428 if (!ReceiverType.isNull())
2429 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2431 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2432 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2433 Sel, Method, Loc, Loc, Loc, Args,
2434 /*isImplicit=*/true);
2437 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2439 bool (*refactor)(const ObjCMessageExpr *,
2440 const NSAPI &, edit::Commit &)) {
2441 SourceLocation MsgLoc = Msg->getExprLoc();
2442 if (S.Diags.isIgnored(DiagID, MsgLoc))
2445 SourceManager &SM = S.SourceMgr;
2446 edit::Commit ECommit(SM, S.LangOpts);
2447 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2448 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2449 << Msg->getSelector() << Msg->getSourceRange();
2450 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2451 if (!ECommit.isCommitable())
2453 for (edit::Commit::edit_iterator
2454 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2455 const edit::Commit::Edit &Edit = *I;
2456 switch (Edit.Kind) {
2457 case edit::Commit::Act_Insert:
2458 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2462 case edit::Commit::Act_InsertFromRange:
2463 Builder.AddFixItHint(
2464 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2465 Edit.getInsertFromRange(SM),
2468 case edit::Commit::Act_Remove:
2469 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2476 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2477 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2478 edit::rewriteObjCRedundantCallWithLiteral);
2481 static void checkFoundationAPI(Sema &S, SourceLocation Loc,
2482 const ObjCMethodDecl *Method,
2483 ArrayRef<Expr *> Args, QualType ReceiverType,
2484 bool IsClassObjectCall) {
2485 // Check if this is a performSelector method that uses a selector that returns
2486 // a record or a vector type.
2487 if (Method->getSelector().getMethodFamily() != OMF_performSelector ||
2490 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens());
2493 ObjCMethodDecl *ImpliedMethod;
2494 if (!IsClassObjectCall) {
2495 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>();
2496 if (!OPT || !OPT->getInterfaceDecl())
2499 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector());
2502 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector());
2504 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>();
2507 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector());
2510 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector());
2514 QualType Ret = ImpliedMethod->getReturnType();
2515 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) {
2516 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector)
2517 << Method->getSelector()
2518 << (!Ret->isRecordType()
2520 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0);
2521 S.Diag(ImpliedMethod->getBeginLoc(),
2522 diag::note_objc_unsafe_perform_selector_method_declared_here)
2523 << ImpliedMethod->getSelector() << Ret;
2527 /// Diagnose use of %s directive in an NSString which is being passed
2528 /// as formatting string to formatting method.
2530 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2531 ObjCMethodDecl *Method,
2533 Expr **Args, unsigned NumArgs) {
2535 bool Format = false;
2536 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2537 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
2542 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2543 if (S.GetFormatNSStringIdx(I, Idx)) {
2549 if (!Format || NumArgs <= Idx)
2552 Expr *FormatExpr = Args[Idx];
2553 if (ObjCStringLiteral *OSL =
2554 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2555 StringLiteral *FormatString = OSL->getString();
2556 if (S.FormatStringHasSArg(FormatString)) {
2557 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2560 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2561 << Method->getDeclName();
2566 /// Build an Objective-C class message expression.
2568 /// This routine takes care of both normal class messages and
2569 /// class messages to the superclass.
2571 /// \param ReceiverTypeInfo Type source information that describes the
2572 /// receiver of this message. This may be NULL, in which case we are
2573 /// sending to the superclass and \p SuperLoc must be a valid source
2576 /// \param ReceiverType The type of the object receiving the
2577 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2578 /// type as that refers to. For a superclass send, this is the type of
2581 /// \param SuperLoc The location of the "super" keyword in a
2582 /// superclass message.
2584 /// \param Sel The selector to which the message is being sent.
2586 /// \param Method The method that this class message is invoking, if
2589 /// \param LBracLoc The location of the opening square bracket ']'.
2591 /// \param RBracLoc The location of the closing square bracket ']'.
2593 /// \param ArgsIn The message arguments.
2594 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
2595 QualType ReceiverType,
2596 SourceLocation SuperLoc,
2598 ObjCMethodDecl *Method,
2599 SourceLocation LBracLoc,
2600 ArrayRef<SourceLocation> SelectorLocs,
2601 SourceLocation RBracLoc,
2602 MultiExprArg ArgsIn,
2604 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
2605 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
2606 if (LBracLoc.isInvalid()) {
2607 Diag(Loc, diag::err_missing_open_square_message_send)
2608 << FixItHint::CreateInsertion(Loc, "[");
2611 ArrayRef<SourceLocation> SelectorSlotLocs;
2612 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2613 SelectorSlotLocs = SelectorLocs;
2615 SelectorSlotLocs = Loc;
2616 SourceLocation SelLoc = SelectorSlotLocs.front();
2618 if (ReceiverType->isDependentType()) {
2619 // If the receiver type is dependent, we can't type-check anything
2620 // at this point. Build a dependent expression.
2621 unsigned NumArgs = ArgsIn.size();
2622 Expr **Args = ArgsIn.data();
2623 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2624 return ObjCMessageExpr::Create(
2625 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2626 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2630 // Find the class to which we are sending this message.
2631 ObjCInterfaceDecl *Class = nullptr;
2632 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2633 if (!ClassType || !(Class = ClassType->getInterface())) {
2634 Diag(Loc, diag::err_invalid_receiver_class_message)
2638 assert(Class && "We don't know which class we're messaging?");
2639 // objc++ diagnoses during typename annotation.
2640 if (!getLangOpts().CPlusPlus)
2641 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs);
2642 // Find the method we are messaging.
2644 SourceRange TypeRange
2645 = SuperLoc.isValid()? SourceRange(SuperLoc)
2646 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
2647 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
2648 (getLangOpts().ObjCAutoRefCount
2649 ? diag::err_arc_receiver_forward_class
2650 : diag::warn_receiver_forward_class),
2652 // A forward class used in messaging is treated as a 'Class'
2653 Method = LookupFactoryMethodInGlobalPool(Sel,
2654 SourceRange(LBracLoc, RBracLoc));
2655 if (Method && !getLangOpts().ObjCAutoRefCount)
2656 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2657 << Method->getDeclName();
2660 Method = Class->lookupClassMethod(Sel);
2662 // If we have an implementation in scope, check "private" methods.
2664 Method = Class->lookupPrivateClassMethod(Sel);
2666 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs,
2667 nullptr, false, false, Class))
2671 // Check the argument types and determine the result type.
2672 QualType ReturnType;
2673 ExprValueKind VK = VK_RValue;
2675 unsigned NumArgs = ArgsIn.size();
2676 Expr **Args = ArgsIn.data();
2677 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType,
2678 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
2679 Method, true, SuperLoc.isValid(), LBracLoc,
2680 RBracLoc, SourceRange(), ReturnType, VK))
2683 if (Method && !Method->getReturnType()->isVoidType() &&
2684 RequireCompleteType(LBracLoc, Method->getReturnType(),
2685 diag::err_illegal_message_expr_incomplete_type))
2688 if (Method && Method->isDirectMethod() && SuperLoc.isValid()) {
2689 Diag(SuperLoc, diag::err_messaging_super_with_direct_method)
2690 << FixItHint::CreateReplacement(
2691 SuperLoc, getLangOpts().ObjCAutoRefCount
2693 : Method->getClassInterface()->getName());
2694 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
2695 << Method->getDeclName();
2698 // Warn about explicit call of +initialize on its own class. But not on 'super'.
2699 if (Method && Method->getMethodFamily() == OMF_initialize) {
2700 if (!SuperLoc.isValid()) {
2701 const ObjCInterfaceDecl *ID =
2702 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2704 Diag(Loc, diag::warn_direct_initialize_call);
2705 Diag(Method->getLocation(), diag::note_method_declared_at)
2706 << Method->getDeclName();
2709 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2710 // [super initialize] is allowed only within an +initialize implementation
2711 if (CurMeth->getMethodFamily() != OMF_initialize) {
2712 Diag(Loc, diag::warn_direct_super_initialize_call);
2713 Diag(Method->getLocation(), diag::note_method_declared_at)
2714 << Method->getDeclName();
2715 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2716 << CurMeth->getDeclName();
2721 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2723 // Construct the appropriate ObjCMessageExpr.
2724 ObjCMessageExpr *Result;
2725 if (SuperLoc.isValid())
2726 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2727 SuperLoc, /*IsInstanceSuper=*/false,
2728 ReceiverType, Sel, SelectorLocs,
2729 Method, makeArrayRef(Args, NumArgs),
2730 RBracLoc, isImplicit);
2732 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
2733 ReceiverTypeInfo, Sel, SelectorLocs,
2734 Method, makeArrayRef(Args, NumArgs),
2735 RBracLoc, isImplicit);
2737 checkCocoaAPI(*this, Result);
2740 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
2741 ReceiverType, /*IsClassObjectCall=*/true);
2742 return MaybeBindToTemporary(Result);
2745 // ActOnClassMessage - used for both unary and keyword messages.
2746 // ArgExprs is optional - if it is present, the number of expressions
2747 // is obtained from Sel.getNumArgs().
2748 ExprResult Sema::ActOnClassMessage(Scope *S,
2749 ParsedType Receiver,
2751 SourceLocation LBracLoc,
2752 ArrayRef<SourceLocation> SelectorLocs,
2753 SourceLocation RBracLoc,
2754 MultiExprArg Args) {
2755 TypeSourceInfo *ReceiverTypeInfo;
2756 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2757 if (ReceiverType.isNull())
2760 if (!ReceiverTypeInfo)
2761 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2763 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
2764 /*SuperLoc=*/SourceLocation(), Sel,
2765 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2769 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2770 QualType ReceiverType,
2773 ObjCMethodDecl *Method,
2774 MultiExprArg Args) {
2775 return BuildInstanceMessage(Receiver, ReceiverType,
2776 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2777 Sel, Method, Loc, Loc, Loc, Args,
2778 /*isImplicit=*/true);
2781 static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) {
2784 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext());
2787 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
2788 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>(
2789 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(),
2790 Sema::LookupOrdinaryName))) {
2791 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) {
2792 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl())
2799 /// Build an Objective-C instance message expression.
2801 /// This routine takes care of both normal instance messages and
2802 /// instance messages to the superclass instance.
2804 /// \param Receiver The expression that computes the object that will
2805 /// receive this message. This may be empty, in which case we are
2806 /// sending to the superclass instance and \p SuperLoc must be a valid
2807 /// source location.
2809 /// \param ReceiverType The (static) type of the object receiving the
2810 /// message. When a \p Receiver expression is provided, this is the
2811 /// same type as that expression. For a superclass instance send, this
2812 /// is a pointer to the type of the superclass.
2814 /// \param SuperLoc The location of the "super" keyword in a
2815 /// superclass instance message.
2817 /// \param Sel The selector to which the message is being sent.
2819 /// \param Method The method that this instance message is invoking, if
2822 /// \param LBracLoc The location of the opening square bracket ']'.
2824 /// \param RBracLoc The location of the closing square bracket ']'.
2826 /// \param ArgsIn The message arguments.
2827 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
2828 QualType ReceiverType,
2829 SourceLocation SuperLoc,
2831 ObjCMethodDecl *Method,
2832 SourceLocation LBracLoc,
2833 ArrayRef<SourceLocation> SelectorLocs,
2834 SourceLocation RBracLoc,
2835 MultiExprArg ArgsIn,
2837 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the "
2838 "SuperLoc must be valid so we can "
2841 // The location of the receiver.
2842 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc();
2843 SourceRange RecRange =
2844 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2845 ArrayRef<SourceLocation> SelectorSlotLocs;
2846 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2847 SelectorSlotLocs = SelectorLocs;
2849 SelectorSlotLocs = Loc;
2850 SourceLocation SelLoc = SelectorSlotLocs.front();
2852 if (LBracLoc.isInvalid()) {
2853 Diag(Loc, diag::err_missing_open_square_message_send)
2854 << FixItHint::CreateInsertion(Loc, "[");
2858 // If we have a receiver expression, perform appropriate promotions
2859 // and determine receiver type.
2861 if (Receiver->hasPlaceholderType()) {
2863 if (Receiver->getType() == Context.UnknownAnyTy)
2864 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2866 Result = CheckPlaceholderExpr(Receiver);
2867 if (Result.isInvalid()) return ExprError();
2868 Receiver = Result.get();
2871 if (Receiver->isTypeDependent()) {
2872 // If the receiver is type-dependent, we can't type-check anything
2873 // at this point. Build a dependent expression.
2874 unsigned NumArgs = ArgsIn.size();
2875 Expr **Args = ArgsIn.data();
2876 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2877 return ObjCMessageExpr::Create(
2878 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2879 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2880 RBracLoc, isImplicit);
2883 // If necessary, apply function/array conversion to the receiver.
2884 // C99 6.7.5.3p[7,8].
2885 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2886 if (Result.isInvalid())
2888 Receiver = Result.get();
2889 ReceiverType = Receiver->getType();
2891 // If the receiver is an ObjC pointer, a block pointer, or an
2892 // __attribute__((NSObject)) pointer, we don't need to do any
2893 // special conversion in order to look up a receiver.
2894 if (ReceiverType->isObjCRetainableType()) {
2896 } else if (!getLangOpts().ObjCAutoRefCount &&
2897 !Context.getObjCIdType().isNull() &&
2898 (ReceiverType->isPointerType() ||
2899 ReceiverType->isIntegerType())) {
2900 // Implicitly convert integers and pointers to 'id' but emit a warning.
2902 Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << RecRange;
2903 if (ReceiverType->isPointerType()) {
2904 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2905 CK_CPointerToObjCPointerCast).get();
2907 // TODO: specialized warning on null receivers?
2908 bool IsNull = Receiver->isNullPointerConstant(Context,
2909 Expr::NPC_ValueDependentIsNull);
2910 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2911 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2914 ReceiverType = Receiver->getType();
2915 } else if (getLangOpts().CPlusPlus) {
2916 // The receiver must be a complete type.
2917 if (RequireCompleteType(Loc, Receiver->getType(),
2918 diag::err_incomplete_receiver_type))
2921 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2922 if (result.isUsable()) {
2923 Receiver = result.get();
2924 ReceiverType = Receiver->getType();
2929 // There's a somewhat weird interaction here where we assume that we
2930 // won't actually have a method unless we also don't need to do some
2931 // of the more detailed type-checking on the receiver.
2934 // Handle messages to id and __kindof types (where we use the
2935 // global method pool).
2936 const ObjCObjectType *typeBound = nullptr;
2937 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context,
2939 if (receiverIsIdLike || ReceiverType->isBlockPointerType() ||
2940 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2941 SmallVector<ObjCMethodDecl*, 4> Methods;
2942 // If we have a type bound, further filter the methods.
2943 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/,
2944 true/*CheckTheOther*/, typeBound);
2945 if (!Methods.empty()) {
2946 // We choose the first method as the initial candidate, then try to
2947 // select a better one.
2948 Method = Methods[0];
2950 if (ObjCMethodDecl *BestMethod =
2951 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods))
2952 Method = BestMethod;
2954 if (!AreMultipleMethodsInGlobalPool(Sel, Method,
2955 SourceRange(LBracLoc, RBracLoc),
2956 receiverIsIdLike, Methods))
2957 DiagnoseUseOfDecl(Method, SelectorSlotLocs);
2959 } else if (ReceiverType->isObjCClassOrClassKindOfType() ||
2960 ReceiverType->isObjCQualifiedClassType()) {
2961 // Handle messages to Class.
2962 // We allow sending a message to a qualified Class ("Class<foo>"), which
2963 // is ok as long as one of the protocols implements the selector (if not,
2965 if (!ReceiverType->isObjCClassOrClassKindOfType()) {
2966 const ObjCObjectPointerType *QClassTy
2967 = ReceiverType->getAsObjCQualifiedClassType();
2968 // Search protocols for class methods.
2969 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2971 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2972 // warn if instance method found for a Class message.
2973 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) {
2974 Diag(SelLoc, diag::warn_instance_method_on_class_found)
2975 << Method->getSelector() << Sel;
2976 Diag(Method->getLocation(), diag::note_method_declared_at)
2977 << Method->getDeclName();
2981 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2982 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2983 // As a guess, try looking for the method in the current interface.
2984 // This very well may not produce the "right" method.
2986 // First check the public methods in the class interface.
2987 Method = ClassDecl->lookupClassMethod(Sel);
2990 Method = ClassDecl->lookupPrivateClassMethod(Sel);
2992 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
2997 // If not messaging 'self', look for any factory method named 'Sel'.
2998 if (!Receiver || !isSelfExpr(Receiver)) {
2999 // If no class (factory) method was found, check if an _instance_
3000 // method of the same name exists in the root class only.
3001 SmallVector<ObjCMethodDecl*, 4> Methods;
3002 CollectMultipleMethodsInGlobalPool(Sel, Methods,
3003 false/*InstanceFirst*/,
3004 true/*CheckTheOther*/);
3005 if (!Methods.empty()) {
3006 // We choose the first method as the initial candidate, then try
3007 // to select a better one.
3008 Method = Methods[0];
3010 // If we find an instance method, emit warning.
3011 if (Method->isInstanceMethod()) {
3012 if (const ObjCInterfaceDecl *ID =
3013 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
3014 if (ID->getSuperClass())
3015 Diag(SelLoc, diag::warn_root_inst_method_not_found)
3016 << Sel << SourceRange(LBracLoc, RBracLoc);
3020 if (ObjCMethodDecl *BestMethod =
3021 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3023 Method = BestMethod;
3029 ObjCInterfaceDecl *ClassDecl = nullptr;
3031 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
3032 // long as one of the protocols implements the selector (if not, warn).
3033 // And as long as message is not deprecated/unavailable (warn if it is).
3034 if (const ObjCObjectPointerType *QIdTy
3035 = ReceiverType->getAsObjCQualifiedIdType()) {
3036 // Search protocols for instance methods.
3037 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
3039 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
3040 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs))
3042 } else if (const ObjCObjectPointerType *OCIType
3043 = ReceiverType->getAsObjCInterfacePointerType()) {
3044 // We allow sending a message to a pointer to an interface (an object).
3045 ClassDecl = OCIType->getInterfaceDecl();
3047 // Try to complete the type. Under ARC, this is a hard error from which
3048 // we don't try to recover.
3049 // FIXME: In the non-ARC case, this will still be a hard error if the
3050 // definition is found in a module that's not visible.
3051 const ObjCInterfaceDecl *forwardClass = nullptr;
3052 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
3053 getLangOpts().ObjCAutoRefCount
3054 ? diag::err_arc_receiver_forward_instance
3055 : diag::warn_receiver_forward_instance,
3057 if (getLangOpts().ObjCAutoRefCount)
3060 forwardClass = OCIType->getInterfaceDecl();
3061 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc,
3062 diag::note_receiver_is_id);
3065 Method = ClassDecl->lookupInstanceMethod(Sel);
3069 // Search protocol qualifiers.
3070 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
3073 // If we have implementations in scope, check "private" methods.
3074 Method = ClassDecl->lookupPrivateMethod(Sel);
3076 if (!Method && getLangOpts().ObjCAutoRefCount) {
3077 Diag(SelLoc, diag::err_arc_may_not_respond)
3078 << OCIType->getPointeeType() << Sel << RecRange
3079 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
3083 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
3084 // If we still haven't found a method, look in the global pool. This
3085 // behavior isn't very desirable, however we need it for GCC
3086 // compatibility. FIXME: should we deviate??
3087 if (OCIType->qual_empty()) {
3088 SmallVector<ObjCMethodDecl*, 4> Methods;
3089 CollectMultipleMethodsInGlobalPool(Sel, Methods,
3090 true/*InstanceFirst*/,
3091 false/*CheckTheOther*/);
3092 if (!Methods.empty()) {
3093 // We choose the first method as the initial candidate, then try
3094 // to select a better one.
3095 Method = Methods[0];
3097 if (ObjCMethodDecl *BestMethod =
3098 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(),
3100 Method = BestMethod;
3102 AreMultipleMethodsInGlobalPool(Sel, Method,
3103 SourceRange(LBracLoc, RBracLoc),
3104 true/*receiverIdOrClass*/,
3107 if (Method && !forwardClass)
3108 Diag(SelLoc, diag::warn_maynot_respond)
3109 << OCIType->getInterfaceDecl()->getIdentifier()
3114 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass))
3117 // Reject other random receiver types (e.g. structs).
3118 Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << RecRange;
3124 FunctionScopeInfo *DIFunctionScopeInfo =
3125 (Method && Method->getMethodFamily() == OMF_init)
3126 ? getEnclosingFunction() : nullptr;
3128 if (Method && Method->isDirectMethod()) {
3129 if (ReceiverType->isObjCIdType() && !isImplicit) {
3130 Diag(Receiver->getExprLoc(),
3131 diag::err_messaging_unqualified_id_with_direct_method);
3132 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3133 << Method->getDeclName();
3136 // Under ARC, self can't be assigned, and doing a direct call to `self`
3137 // when it's a Class is hence safe. For other cases, we can't trust `self`
3138 // is what we think it is, so we reject it.
3139 if (ReceiverType->isObjCClassType() && !isImplicit &&
3140 !(Receiver->isObjCSelfExpr() && getLangOpts().ObjCAutoRefCount)) {
3142 DiagnosticBuilder Builder =
3143 Diag(Receiver->getExprLoc(),
3144 diag::err_messaging_class_with_direct_method);
3145 if (Receiver->isObjCSelfExpr()) {
3146 Builder.AddFixItHint(FixItHint::CreateReplacement(
3147 RecRange, Method->getClassInterface()->getName()));
3150 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3151 << Method->getDeclName();
3154 if (SuperLoc.isValid()) {
3156 DiagnosticBuilder Builder =
3157 Diag(SuperLoc, diag::err_messaging_super_with_direct_method);
3158 if (ReceiverType->isObjCClassType()) {
3159 Builder.AddFixItHint(FixItHint::CreateReplacement(
3160 SuperLoc, Method->getClassInterface()->getName()));
3162 Builder.AddFixItHint(FixItHint::CreateReplacement(SuperLoc, "self"));
3165 Diag(Method->getLocation(), diag::note_direct_method_declared_at)
3166 << Method->getDeclName();
3168 } else if (ReceiverType->isObjCIdType() && !isImplicit) {
3169 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id);
3172 if (DIFunctionScopeInfo &&
3173 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
3174 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3175 bool isDesignatedInitChain = false;
3176 if (SuperLoc.isValid()) {
3177 if (const ObjCObjectPointerType *
3178 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
3179 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
3180 // Either we know this is a designated initializer or we
3181 // conservatively assume it because we don't know for sure.
3182 if (!ID->declaresOrInheritsDesignatedInitializers() ||
3183 ID->isDesignatedInitializer(Sel)) {
3184 isDesignatedInitChain = true;
3185 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
3190 if (!isDesignatedInitChain) {
3191 const ObjCMethodDecl *InitMethod = nullptr;
3193 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
3194 assert(isDesignated && InitMethod);
3196 Diag(SelLoc, SuperLoc.isValid() ?
3197 diag::warn_objc_designated_init_non_designated_init_call :
3198 diag::warn_objc_designated_init_non_super_designated_init_call);
3199 Diag(InitMethod->getLocation(),
3200 diag::note_objc_designated_init_marked_here);
3204 if (DIFunctionScopeInfo &&
3205 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
3206 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3207 if (SuperLoc.isValid()) {
3208 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
3210 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
3214 // Check the message arguments.
3215 unsigned NumArgs = ArgsIn.size();
3216 Expr **Args = ArgsIn.data();
3217 QualType ReturnType;
3218 ExprValueKind VK = VK_RValue;
3219 bool ClassMessage = (ReceiverType->isObjCClassType() ||
3220 ReceiverType->isObjCQualifiedClassType());
3221 if (CheckMessageArgumentTypes(Receiver, ReceiverType,
3222 MultiExprArg(Args, NumArgs), Sel, SelectorLocs,
3223 Method, ClassMessage, SuperLoc.isValid(),
3224 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
3227 if (Method && !Method->getReturnType()->isVoidType() &&
3228 RequireCompleteType(LBracLoc, Method->getReturnType(),
3229 diag::err_illegal_message_expr_incomplete_type))
3232 // In ARC, forbid the user from sending messages to
3233 // retain/release/autorelease/dealloc/retainCount explicitly.
3234 if (getLangOpts().ObjCAutoRefCount) {
3235 ObjCMethodFamily family =
3236 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
3240 checkInitMethod(Method, ReceiverType);
3247 case OMF_mutableCopy:
3250 case OMF_initialize:
3256 case OMF_autorelease:
3257 case OMF_retainCount:
3258 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
3262 case OMF_performSelector:
3263 if (Method && NumArgs >= 1) {
3264 if (const auto *SelExp =
3265 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) {
3266 Selector ArgSel = SelExp->getSelector();
3267 ObjCMethodDecl *SelMethod =
3268 LookupInstanceMethodInGlobalPool(ArgSel,
3269 SelExp->getSourceRange());
3272 LookupFactoryMethodInGlobalPool(ArgSel,
3273 SelExp->getSourceRange());
3275 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
3276 switch (SelFamily) {
3279 case OMF_mutableCopy:
3282 // Issue error, unless ns_returns_not_retained.
3283 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
3284 // selector names a +1 method
3286 diag::err_arc_perform_selector_retains);
3287 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3288 << SelMethod->getDeclName();
3292 // +0 call. OK. unless ns_returns_retained.
3293 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
3294 // selector names a +1 method
3296 diag::err_arc_perform_selector_retains);
3297 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
3298 << SelMethod->getDeclName();
3304 // error (may leak).
3305 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
3306 Diag(Args[0]->getExprLoc(), diag::note_used_here);
3313 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
3315 // Construct the appropriate ObjCMessageExpr instance.
3316 ObjCMessageExpr *Result;
3317 if (SuperLoc.isValid())
3318 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3319 SuperLoc, /*IsInstanceSuper=*/true,
3320 ReceiverType, Sel, SelectorLocs, Method,
3321 makeArrayRef(Args, NumArgs), RBracLoc,
3324 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
3325 Receiver, Sel, SelectorLocs, Method,
3326 makeArrayRef(Args, NumArgs), RBracLoc,
3329 checkCocoaAPI(*this, Result);
3332 bool IsClassObjectCall = ClassMessage;
3333 // 'self' message receivers in class methods should be treated as message
3334 // sends to the class object in order for the semantic checks to be
3335 // performed correctly. Messages to 'super' already count as class messages,
3336 // so they don't need to be handled here.
3337 if (Receiver && isSelfExpr(Receiver)) {
3338 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) {
3339 if (OPT->getObjectType()->isObjCClass()) {
3340 if (const auto *CurMeth = getCurMethodDecl()) {
3341 IsClassObjectCall = true;
3343 Context.getObjCInterfaceType(CurMeth->getClassInterface());
3348 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs),
3349 ReceiverType, IsClassObjectCall);
3352 if (getLangOpts().ObjCAutoRefCount) {
3353 // In ARC, annotate delegate init calls.
3354 if (Result->getMethodFamily() == OMF_init &&
3355 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
3356 // Only consider init calls *directly* in init implementations,
3357 // not within blocks.
3358 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
3359 if (method && method->getMethodFamily() == OMF_init) {
3360 // The implicit assignment to self means we also don't want to
3361 // consume the result.
3362 Result->setDelegateInitCall(true);
3367 // In ARC, check for message sends which are likely to introduce
3369 checkRetainCycles(Result);
3372 if (getLangOpts().ObjCWeak) {
3373 if (!isImplicit && Method) {
3374 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
3376 Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak;
3377 if (!IsWeak && Sel.isUnarySelector())
3378 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
3379 if (IsWeak && !isUnevaluatedContext() &&
3380 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
3381 getCurFunction()->recordUseOfWeak(Result, Prop);
3386 CheckObjCCircularContainer(Result);
3388 return MaybeBindToTemporary(Result);
3391 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
3392 if (ObjCSelectorExpr *OSE =
3393 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
3394 Selector Sel = OSE->getSelector();
3395 SourceLocation Loc = OSE->getAtLoc();
3396 auto Pos = S.ReferencedSelectors.find(Sel);
3397 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
3398 S.ReferencedSelectors.erase(Pos);
3402 // ActOnInstanceMessage - used for both unary and keyword messages.
3403 // ArgExprs is optional - if it is present, the number of expressions
3404 // is obtained from Sel.getNumArgs().
3405 ExprResult Sema::ActOnInstanceMessage(Scope *S,
3408 SourceLocation LBracLoc,
3409 ArrayRef<SourceLocation> SelectorLocs,
3410 SourceLocation RBracLoc,
3411 MultiExprArg Args) {
3415 // A ParenListExpr can show up while doing error recovery with invalid code.
3416 if (isa<ParenListExpr>(Receiver)) {
3417 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
3418 if (Result.isInvalid()) return ExprError();
3419 Receiver = Result.get();
3422 if (RespondsToSelectorSel.isNull()) {
3423 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
3424 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
3426 if (Sel == RespondsToSelectorSel)
3427 RemoveSelectorFromWarningCache(*this, Args[0]);
3429 return BuildInstanceMessage(Receiver, Receiver->getType(),
3430 /*SuperLoc=*/SourceLocation(), Sel,
3431 /*Method=*/nullptr, LBracLoc, SelectorLocs,
3435 enum ARCConversionTypeClass {
3436 /// int, void, struct A
3442 /// id*, id***, void (^*)(),
3443 ACTC_indirectRetainable,
3445 /// void* might be a normal C type, or it might a CF type.
3452 static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
3453 return (ACTC == ACTC_retainable ||
3454 ACTC == ACTC_coreFoundation ||
3455 ACTC == ACTC_voidPtr);
3458 static bool isAnyCLike(ARCConversionTypeClass ACTC) {
3459 return ACTC == ACTC_none ||
3460 ACTC == ACTC_voidPtr ||
3461 ACTC == ACTC_coreFoundation;
3464 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
3465 bool isIndirect = false;
3467 // Ignore an outermost reference type.
3468 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
3469 type = ref->getPointeeType();
3473 // Drill through pointers and arrays recursively.
3475 if (const PointerType *ptr = type->getAs<PointerType>()) {
3476 type = ptr->getPointeeType();
3478 // The first level of pointer may be the innermost pointer on a CF type.
3480 if (type->isVoidType()) return ACTC_voidPtr;
3481 if (type->isRecordType()) return ACTC_coreFoundation;
3483 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
3484 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
3492 if (type->isObjCARCBridgableType())
3493 return ACTC_indirectRetainable;
3497 if (type->isObjCARCBridgableType())
3498 return ACTC_retainable;
3504 /// A result from the cast checker.
3506 /// Cannot be casted.
3509 /// Can be safely retained or not retained.
3512 /// Can be casted at +0.
3515 /// Can be casted at +1.
3518 ACCResult merge(ACCResult left, ACCResult right) {
3519 if (left == right) return left;
3520 if (left == ACC_bottom) return right;
3521 if (right == ACC_bottom) return left;
3525 /// A checker which white-lists certain expressions whose conversion
3526 /// to or from retainable type would otherwise be forbidden in ARC.
3527 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
3528 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
3530 ASTContext &Context;
3531 ARCConversionTypeClass SourceClass;
3532 ARCConversionTypeClass TargetClass;
3535 static bool isCFType(QualType type) {
3536 // Someday this can use ns_bridged. For now, it has to do this.
3537 return type->isCARCBridgableType();
3541 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
3542 ARCConversionTypeClass target, bool diagnose)
3543 : Context(Context), SourceClass(source), TargetClass(target),
3544 Diagnose(diagnose) {}
3547 ACCResult Visit(Expr *e) {
3548 return super::Visit(e->IgnoreParens());
3551 ACCResult VisitStmt(Stmt *s) {
3555 /// Null pointer constants can be casted however you please.
3556 ACCResult VisitExpr(Expr *e) {
3557 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
3562 /// Objective-C string literals can be safely casted.
3563 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
3564 // If we're casting to any retainable type, go ahead. Global
3565 // strings are immune to retains, so this is bottom.
3566 if (isAnyRetainable(TargetClass)) return ACC_bottom;
3571 /// Look through certain implicit and explicit casts.
3572 ACCResult VisitCastExpr(CastExpr *e) {
3573 switch (e->getCastKind()) {
3574 case CK_NullToPointer:
3578 case CK_LValueToRValue:
3580 case CK_CPointerToObjCPointerCast:
3581 case CK_BlockPointerToObjCPointerCast:
3582 case CK_AnyPointerToBlockPointerCast:
3583 return Visit(e->getSubExpr());
3590 /// Look through unary extension.
3591 ACCResult VisitUnaryExtension(UnaryOperator *e) {
3592 return Visit(e->getSubExpr());
3595 /// Ignore the LHS of a comma operator.
3596 ACCResult VisitBinComma(BinaryOperator *e) {
3597 return Visit(e->getRHS());
3600 /// Conditional operators are okay if both sides are okay.
3601 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
3602 ACCResult left = Visit(e->getTrueExpr());
3603 if (left == ACC_invalid) return ACC_invalid;
3604 return merge(left, Visit(e->getFalseExpr()));
3607 /// Look through pseudo-objects.
3608 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
3609 // If we're getting here, we should always have a result.
3610 return Visit(e->getResultExpr());
3613 /// Statement expressions are okay if their result expression is okay.
3614 ACCResult VisitStmtExpr(StmtExpr *e) {
3615 return Visit(e->getSubStmt()->body_back());
3618 /// Some declaration references are okay.
3619 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
3620 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
3621 // References to global constants are okay.
3622 if (isAnyRetainable(TargetClass) &&
3623 isAnyRetainable(SourceClass) &&
3625 !var->hasDefinition(Context) &&
3626 var->getType().isConstQualified()) {
3628 // In system headers, they can also be assumed to be immune to retains.
3629 // These are things like 'kCFStringTransformToLatin'.
3630 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
3633 return ACC_plusZero;
3640 /// Some calls are okay.
3641 ACCResult VisitCallExpr(CallExpr *e) {
3642 if (FunctionDecl *fn = e->getDirectCallee())
3643 if (ACCResult result = checkCallToFunction(fn))
3646 return super::VisitCallExpr(e);
3649 ACCResult checkCallToFunction(FunctionDecl *fn) {
3650 // Require a CF*Ref return type.
3651 if (!isCFType(fn->getReturnType()))
3654 if (!isAnyRetainable(TargetClass))
3657 // Honor an explicit 'not retained' attribute.
3658 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3659 return ACC_plusZero;
3661 // Honor an explicit 'retained' attribute, except that for
3662 // now we're not going to permit implicit handling of +1 results,
3663 // because it's a bit frightening.
3664 if (fn->hasAttr<CFReturnsRetainedAttr>())
3665 return Diagnose ? ACC_plusOne
3666 : ACC_invalid; // ACC_plusOne if we start accepting this
3668 // Recognize this specific builtin function, which is used by CFSTR.
3669 unsigned builtinID = fn->getBuiltinID();
3670 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3673 // Otherwise, don't do anything implicit with an unaudited function.
3674 if (!fn->hasAttr<CFAuditedTransferAttr>())
3677 // Otherwise, it's +0 unless it follows the create convention.
3678 if (ento::coreFoundation::followsCreateRule(fn))
3679 return Diagnose ? ACC_plusOne
3680 : ACC_invalid; // ACC_plusOne if we start accepting this
3682 return ACC_plusZero;
3685 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3686 return checkCallToMethod(e->getMethodDecl());
3689 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3690 ObjCMethodDecl *method;
3691 if (e->isExplicitProperty())
3692 method = e->getExplicitProperty()->getGetterMethodDecl();
3694 method = e->getImplicitPropertyGetter();
3695 return checkCallToMethod(method);
3698 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3699 if (!method) return ACC_invalid;
3701 // Check for message sends to functions returning CF types. We
3702 // just obey the Cocoa conventions with these, even though the
3703 // return type is CF.
3704 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
3707 // If the method is explicitly marked not-retained, it's +0.
3708 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3709 return ACC_plusZero;
3711 // If the method is explicitly marked as returning retained, or its
3712 // selector follows a +1 Cocoa convention, treat it as +1.
3713 if (method->hasAttr<CFReturnsRetainedAttr>())
3716 switch (method->getSelector().getMethodFamily()) {
3719 case OMF_mutableCopy:
3724 // Otherwise, treat it as +0.
3725 return ACC_plusZero;
3729 } // end anonymous namespace
3731 bool Sema::isKnownName(StringRef name) {
3734 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
3735 Sema::LookupOrdinaryName);
3736 return LookupName(R, TUScope, false);
3739 static void addFixitForObjCARCConversion(Sema &S,
3740 DiagnosticBuilder &DiagB,
3741 Sema::CheckedConversionKind CCK,
3742 SourceLocation afterLParen,
3746 const char *bridgeKeyword,
3747 const char *CFBridgeName) {
3748 // We handle C-style and implicit casts here.
3750 case Sema::CCK_ImplicitConversion:
3751 case Sema::CCK_ForBuiltinOverloadedOp:
3752 case Sema::CCK_CStyleCast:
3753 case Sema::CCK_OtherCast:
3755 case Sema::CCK_FunctionalCast:
3760 if (CCK == Sema::CCK_OtherCast) {
3761 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3762 SourceRange range(NCE->getOperatorLoc(),
3763 NCE->getAngleBrackets().getEnd());
3764 SmallString<32> BridgeCall;
3766 SourceManager &SM = S.getSourceManager();
3767 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3768 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3771 BridgeCall += CFBridgeName;
3772 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3776 Expr *castedE = castExpr;
3777 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3778 castedE = CCE->getSubExpr();
3779 castedE = castedE->IgnoreImpCasts();
3780 SourceRange range = castedE->getSourceRange();
3782 SmallString<32> BridgeCall;
3784 SourceManager &SM = S.getSourceManager();
3785 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3786 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3789 BridgeCall += CFBridgeName;
3791 if (isa<ParenExpr>(castedE)) {
3792 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3796 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3798 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3799 S.getLocForEndOfToken(range.getEnd()),
3805 if (CCK == Sema::CCK_CStyleCast) {
3806 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
3807 } else if (CCK == Sema::CCK_OtherCast) {
3808 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3809 std::string castCode = "(";
3810 castCode += bridgeKeyword;
3811 castCode += castType.getAsString();
3813 SourceRange Range(NCE->getOperatorLoc(),
3814 NCE->getAngleBrackets().getEnd());
3815 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3818 std::string castCode = "(";
3819 castCode += bridgeKeyword;
3820 castCode += castType.getAsString();
3822 Expr *castedE = castExpr->IgnoreImpCasts();
3823 SourceRange range = castedE->getSourceRange();
3824 if (isa<ParenExpr>(castedE)) {
3825 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3829 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3831 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3832 S.getLocForEndOfToken(range.getEnd()),
3838 template <typename T>
3839 static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3840 TypedefNameDecl *TDNDecl = TD->getDecl();
3841 QualType QT = TDNDecl->getUnderlyingType();
3842 if (QT->isPointerType()) {
3843 QT = QT->getPointeeType();
3844 if (const RecordType *RT = QT->getAs<RecordType>())
3845 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
3846 return RD->getAttr<T>();
3851 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3852 TypedefNameDecl *&TDNDecl) {
3853 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3854 TDNDecl = TD->getDecl();
3855 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3856 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3858 T = TDNDecl->getUnderlyingType();
3864 diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3865 QualType castType, ARCConversionTypeClass castACTC,
3866 Expr *castExpr, Expr *realCast,
3867 ARCConversionTypeClass exprACTC,
3868 Sema::CheckedConversionKind CCK) {
3869 SourceLocation loc =
3870 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
3872 if (S.makeUnavailableInSystemHeader(loc,
3873 UnavailableAttr::IR_ARCForbiddenConversion))
3876 QualType castExprType = castExpr->getType();
3877 // Defer emitting a diagnostic for bridge-related casts; that will be
3878 // handled by CheckObjCBridgeRelatedConversions.
3879 TypedefNameDecl *TDNDecl = nullptr;
3880 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3881 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3882 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
3883 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
3886 unsigned srcKind = 0;
3889 case ACTC_coreFoundation:
3891 srcKind = (castExprType->isPointerType() ? 1 : 0);
3893 case ACTC_retainable:
3894 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3896 case ACTC_indirectRetainable:
3901 // Check whether this could be fixed with a bridge cast.
3902 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin());
3903 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
3905 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1;
3907 // Bridge from an ARC type to a CF type.
3908 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
3910 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3912 << 2 // of C pointer type
3914 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3917 << castExpr->getSourceRange();
3918 bool br = S.isKnownName("CFBridgingRelease");
3919 ACCResult CreateRule =
3920 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3921 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3922 if (CreateRule != ACC_plusOne)
3924 DiagnosticBuilder DiagB =
3925 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3926 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3928 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3929 castType, castExpr, realCast, "__bridge ",
3932 if (CreateRule != ACC_plusZero)
3934 DiagnosticBuilder DiagB =
3935 (CCK == Sema::CCK_OtherCast && !br) ?
3936 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3937 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3938 diag::note_arc_bridge_transfer)
3939 << castExprType << br;
3941 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3942 castType, castExpr, realCast, "__bridge_transfer ",
3943 br ? "CFBridgingRelease" : nullptr);
3949 // Bridge from a CF type to an ARC type.
3950 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
3951 bool br = S.isKnownName("CFBridgingRetain");
3952 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3954 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3956 << 2 // to C pointer type
3959 << castExpr->getSourceRange();
3960 ACCResult CreateRule =
3961 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
3962 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
3963 if (CreateRule != ACC_plusOne)
3965 DiagnosticBuilder DiagB =
3966 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3967 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3968 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3969 castType, castExpr, realCast, "__bridge ",
3972 if (CreateRule != ACC_plusZero)
3974 DiagnosticBuilder DiagB =
3975 (CCK == Sema::CCK_OtherCast && !br) ?
3976 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3977 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3978 diag::note_arc_bridge_retained)
3981 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
3982 castType, castExpr, realCast, "__bridge_retained ",
3983 br ? "CFBridgingRetain" : nullptr);
3989 S.Diag(loc, diag::err_arc_mismatched_cast)
3991 << srcKind << castExprType << castType
3992 << castRange << castExpr->getSourceRange();
3995 template <typename TB>
3996 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3997 bool &HadTheAttribute, bool warn) {
3998 QualType T = castExpr->getType();
3999 HadTheAttribute = false;
4000 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4001 TypedefNameDecl *TDNDecl = TD->getDecl();
4002 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4003 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4004 HadTheAttribute = true;
4005 if (Parm->isStr("id"))
4008 NamedDecl *Target = nullptr;
4009 // Check for an existing type with this name.
4010 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4011 Sema::LookupOrdinaryName);
4012 if (S.LookupName(R, S.TUScope)) {
4013 Target = R.getFoundDecl();
4014 if (Target && isa<ObjCInterfaceDecl>(Target)) {
4015 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
4016 if (const ObjCObjectPointerType *InterfacePointerType =
4017 castType->getAsObjCInterfacePointerType()) {
4018 ObjCInterfaceDecl *CastClass
4019 = InterfacePointerType->getObjectType()->getInterface();
4020 if ((CastClass == ExprClass) ||
4021 (CastClass && CastClass->isSuperClassOf(ExprClass)))
4024 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4025 << T << Target->getName() << castType->getPointeeType();
4027 } else if (castType->isObjCIdType() ||
4028 (S.Context.ObjCObjectAdoptsQTypeProtocols(
4029 castType, ExprClass)))
4030 // ok to cast to 'id'.
4031 // casting to id<p-list> is ok if bridge type adopts all of
4032 // p-list protocols.
4036 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge)
4037 << T << Target->getName() << castType;
4038 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4039 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4044 } else if (!castType->isObjCIdType()) {
4045 S.Diag(castExpr->getBeginLoc(),
4046 diag::err_objc_cf_bridged_not_interface)
4047 << castExpr->getType() << Parm;
4048 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4050 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4056 T = TDNDecl->getUnderlyingType();
4061 template <typename TB>
4062 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
4063 bool &HadTheAttribute, bool warn) {
4064 QualType T = castType;
4065 HadTheAttribute = false;
4066 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
4067 TypedefNameDecl *TDNDecl = TD->getDecl();
4068 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
4069 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
4070 HadTheAttribute = true;
4071 if (Parm->isStr("id"))
4074 NamedDecl *Target = nullptr;
4075 // Check for an existing type with this name.
4076 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
4077 Sema::LookupOrdinaryName);
4078 if (S.LookupName(R, S.TUScope)) {
4079 Target = R.getFoundDecl();
4080 if (Target && isa<ObjCInterfaceDecl>(Target)) {
4081 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
4082 if (const ObjCObjectPointerType *InterfacePointerType =
4083 castExpr->getType()->getAsObjCInterfacePointerType()) {
4084 ObjCInterfaceDecl *ExprClass
4085 = InterfacePointerType->getObjectType()->getInterface();
4086 if ((CastClass == ExprClass) ||
4087 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
4090 S.Diag(castExpr->getBeginLoc(),
4091 diag::warn_objc_invalid_bridge_to_cf)
4092 << castExpr->getType()->getPointeeType() << T;
4093 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4096 } else if (castExpr->getType()->isObjCIdType() ||
4097 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
4098 castExpr->getType(), CastClass)))
4099 // ok to cast an 'id' expression to a CFtype.
4100 // ok to cast an 'id<plist>' expression to CFtype provided plist
4101 // adopts all of CFtype's ObjetiveC's class plist.
4105 S.Diag(castExpr->getBeginLoc(),
4106 diag::warn_objc_invalid_bridge_to_cf)
4107 << castExpr->getType() << castType;
4108 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4109 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4115 S.Diag(castExpr->getBeginLoc(),
4116 diag::err_objc_ns_bridged_invalid_cfobject)
4117 << castExpr->getType() << castType;
4118 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4120 S.Diag(Target->getBeginLoc(), diag::note_declared_at);
4125 T = TDNDecl->getUnderlyingType();
4130 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
4131 if (!getLangOpts().ObjC)
4133 // warn in presence of __bridge casting to or from a toll free bridge cast.
4134 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
4135 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4136 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
4137 bool HasObjCBridgeAttr;
4138 bool ObjCBridgeAttrWillNotWarn =
4139 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4141 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
4143 bool HasObjCBridgeMutableAttr;
4144 bool ObjCBridgeMutableAttrWillNotWarn =
4145 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4146 HasObjCBridgeMutableAttr, false);
4147 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
4150 if (HasObjCBridgeAttr)
4151 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4153 else if (HasObjCBridgeMutableAttr)
4154 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4155 HasObjCBridgeMutableAttr, true);
4157 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
4158 bool HasObjCBridgeAttr;
4159 bool ObjCBridgeAttrWillNotWarn =
4160 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4162 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
4164 bool HasObjCBridgeMutableAttr;
4165 bool ObjCBridgeMutableAttrWillNotWarn =
4166 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4167 HasObjCBridgeMutableAttr, false);
4168 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
4171 if (HasObjCBridgeAttr)
4172 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
4174 else if (HasObjCBridgeMutableAttr)
4175 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
4176 HasObjCBridgeMutableAttr, true);
4180 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
4181 QualType SrcType = castExpr->getType();
4182 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
4183 if (PRE->isExplicitProperty()) {
4184 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
4185 SrcType = PDecl->getType();
4187 else if (PRE->isImplicitProperty()) {
4188 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
4189 SrcType = Getter->getReturnType();
4193 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
4194 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
4195 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
4197 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType,
4201 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
4203 if (!getLangOpts().ObjC)
4205 ARCConversionTypeClass exprACTC =
4206 classifyTypeForARCConversion(castExpr->getType());
4207 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
4208 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
4209 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
4210 CheckTollFreeBridgeCast(castType, castExpr);
4211 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
4212 : CK_CPointerToObjCPointerCast;
4218 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
4219 QualType DestType, QualType SrcType,
4220 ObjCInterfaceDecl *&RelatedClass,
4221 ObjCMethodDecl *&ClassMethod,
4222 ObjCMethodDecl *&InstanceMethod,
4223 TypedefNameDecl *&TDNDecl,
4224 bool CfToNs, bool Diagnose) {
4225 QualType T = CfToNs ? SrcType : DestType;
4226 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
4230 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
4231 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
4232 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
4235 NamedDecl *Target = nullptr;
4236 // Check for an existing type with this name.
4237 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
4238 Sema::LookupOrdinaryName);
4239 if (!LookupName(R, TUScope)) {
4241 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
4242 << SrcType << DestType;
4243 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4247 Target = R.getFoundDecl();
4248 if (Target && isa<ObjCInterfaceDecl>(Target))
4249 RelatedClass = cast<ObjCInterfaceDecl>(Target);
4252 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
4253 << SrcType << DestType;
4254 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4256 Diag(Target->getBeginLoc(), diag::note_declared_at);
4261 // Check for an existing class method with the given selector name.
4262 if (CfToNs && CMId) {
4263 Selector Sel = Context.Selectors.getUnarySelector(CMId);
4264 ClassMethod = RelatedClass->lookupMethod(Sel, false);
4267 Diag(Loc, diag::err_objc_bridged_related_known_method)
4268 << SrcType << DestType << Sel << false;
4269 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4275 // Check for an existing instance method with the given selector name.
4276 if (!CfToNs && IMId) {
4277 Selector Sel = Context.Selectors.getNullarySelector(IMId);
4278 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
4279 if (!InstanceMethod) {
4281 Diag(Loc, diag::err_objc_bridged_related_known_method)
4282 << SrcType << DestType << Sel << true;
4283 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4292 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
4293 QualType DestType, QualType SrcType,
4294 Expr *&SrcExpr, bool Diagnose) {
4295 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
4296 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
4297 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
4298 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
4299 if (!CfToNs && !NsToCf)
4302 ObjCInterfaceDecl *RelatedClass;
4303 ObjCMethodDecl *ClassMethod = nullptr;
4304 ObjCMethodDecl *InstanceMethod = nullptr;
4305 TypedefNameDecl *TDNDecl = nullptr;
4306 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
4307 ClassMethod, InstanceMethod, TDNDecl,
4312 // Implicit conversion from CF to ObjC object is needed.
4315 std::string ExpressionString = "[";
4316 ExpressionString += RelatedClass->getNameAsString();
4317 ExpressionString += " ";
4318 ExpressionString += ClassMethod->getSelector().getAsString();
4319 SourceLocation SrcExprEndLoc =
4320 getLocForEndOfToken(SrcExpr->getEndLoc());
4321 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
4322 Diag(Loc, diag::err_objc_bridged_related_known_method)
4323 << SrcType << DestType << ClassMethod->getSelector() << false
4324 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(),
4326 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
4327 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4328 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4330 QualType receiverType = Context.getObjCInterfaceType(RelatedClass);
4332 Expr *args[] = { SrcExpr };
4333 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
4334 ClassMethod->getLocation(),
4335 ClassMethod->getSelector(), ClassMethod,
4336 MultiExprArg(args, 1));
4337 SrcExpr = msg.get();
4343 // Implicit conversion from ObjC type to CF object is needed.
4344 if (InstanceMethod) {
4346 std::string ExpressionString;
4347 SourceLocation SrcExprEndLoc =
4348 getLocForEndOfToken(SrcExpr->getEndLoc());
4349 if (InstanceMethod->isPropertyAccessor())
4350 if (const ObjCPropertyDecl *PDecl =
4351 InstanceMethod->findPropertyDecl()) {
4352 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
4353 ExpressionString = ".";
4354 ExpressionString += PDecl->getNameAsString();
4355 Diag(Loc, diag::err_objc_bridged_related_known_method)
4356 << SrcType << DestType << InstanceMethod->getSelector() << true
4357 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4359 if (ExpressionString.empty()) {
4360 // Provide a fixit: [ObjectExpr InstanceMethod]
4361 ExpressionString = " ";
4362 ExpressionString += InstanceMethod->getSelector().getAsString();
4363 ExpressionString += "]";
4365 Diag(Loc, diag::err_objc_bridged_related_known_method)
4366 << SrcType << DestType << InstanceMethod->getSelector() << true
4367 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[")
4368 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
4370 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at);
4371 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at);
4374 BuildInstanceMessageImplicit(SrcExpr, SrcType,
4375 InstanceMethod->getLocation(),
4376 InstanceMethod->getSelector(),
4377 InstanceMethod, None);
4378 SrcExpr = msg.get();
4386 Sema::ARCConversionResult
4387 Sema::CheckObjCConversion(SourceRange castRange, QualType castType,
4388 Expr *&castExpr, CheckedConversionKind CCK,
4389 bool Diagnose, bool DiagnoseCFAudited,
4390 BinaryOperatorKind Opc) {
4391 QualType castExprType = castExpr->getType();
4393 // For the purposes of the classification, we assume reference types
4394 // will bind to temporaries.
4395 QualType effCastType = castType;
4396 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
4397 effCastType = ref->getPointeeType();
4399 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
4400 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
4401 if (exprACTC == castACTC) {
4402 // Check for viability and report error if casting an rvalue to a
4403 // life-time qualifier.
4404 if (castACTC == ACTC_retainable &&
4405 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
4406 castType != castExprType) {
4407 const Type *DT = castType.getTypePtr();
4408 QualType QDT = castType;
4409 // We desugar some types but not others. We ignore those
4410 // that cannot happen in a cast; i.e. auto, and those which
4411 // should not be de-sugared; i.e typedef.
4412 if (const ParenType *PT = dyn_cast<ParenType>(DT))
4413 QDT = PT->desugar();
4414 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
4415 QDT = TP->desugar();
4416 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
4417 QDT = AT->desugar();
4418 if (QDT != castType &&
4419 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
4421 SourceLocation loc = (castRange.isValid() ? castRange.getBegin()
4422 : castExpr->getExprLoc());
4423 Diag(loc, diag::err_arc_nolifetime_behavior);
4431 // The life-time qualifier cast check above is all we need for ObjCWeak.
4432 // ObjCAutoRefCount has more restrictions on what is legal.
4433 if (!getLangOpts().ObjCAutoRefCount)
4436 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
4438 // Allow all of these types to be cast to integer types (but not
4440 if (castACTC == ACTC_none && castType->isIntegralType(Context))
4443 // Allow casts between pointers to lifetime types (e.g., __strong id*)
4444 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
4445 // must be explicit.
4446 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
4448 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
4452 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
4453 // For invalid casts, fall through.
4457 // Do nothing for both bottom and +0.
4462 // If the result is +1, consume it here.
4464 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
4465 CK_ARCConsumeObject, castExpr,
4466 nullptr, VK_RValue);
4467 Cleanup.setExprNeedsCleanups(true);
4471 // If this is a non-implicit cast from id or block type to a
4472 // CoreFoundation type, delay complaining in case the cast is used
4473 // in an acceptable context.
4474 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK))
4475 return ACR_unbridged;
4477 // Issue a diagnostic about a missing @-sign when implicit casting a cstring
4478 // to 'NSString *', instead of falling through to report a "bridge cast"
4480 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
4481 CheckConversionToObjCLiteral(castType, castExpr, Diagnose))
4484 // Do not issue "bridge cast" diagnostic when implicit casting
4485 // a retainable object to a CF type parameter belonging to an audited
4486 // CF API function. Let caller issue a normal type mismatched diagnostic
4488 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
4489 castACTC != ACTC_coreFoundation) &&
4490 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
4491 (Opc == BO_NE || Opc == BO_EQ))) {
4493 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr,
4494 castExpr, exprACTC, CCK);
4500 /// Given that we saw an expression with the ARCUnbridgedCastTy
4501 /// placeholder type, complain bitterly.
4502 void Sema::diagnoseARCUnbridgedCast(Expr *e) {
4503 // We expect the spurious ImplicitCastExpr to already have been stripped.
4504 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4505 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
4507 SourceRange castRange;
4509 CheckedConversionKind CCK;
4511 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
4512 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
4513 castType = cast->getTypeAsWritten();
4514 CCK = CCK_CStyleCast;
4515 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
4516 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
4517 castType = cast->getTypeAsWritten();
4518 CCK = CCK_OtherCast;
4520 llvm_unreachable("Unexpected ImplicitCastExpr");
4523 ARCConversionTypeClass castACTC =
4524 classifyTypeForARCConversion(castType.getNonReferenceType());
4526 Expr *castExpr = realCast->getSubExpr();
4527 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
4529 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
4530 castExpr, realCast, ACTC_retainable, CCK);
4533 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
4534 /// type, remove the placeholder cast.
4535 Expr *Sema::stripARCUnbridgedCast(Expr *e) {
4536 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
4538 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
4539 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
4540 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
4541 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
4542 assert(uo->getOpcode() == UO_Extension);
4543 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
4544 return UnaryOperator::Create(Context, sub, UO_Extension, sub->getType(),
4545 sub->getValueKind(), sub->getObjectKind(),
4546 uo->getOperatorLoc(), false,
4547 CurFPFeatureOverrides());
4548 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
4549 assert(!gse->isResultDependent());
4551 unsigned n = gse->getNumAssocs();
4552 SmallVector<Expr *, 4> subExprs;
4553 SmallVector<TypeSourceInfo *, 4> subTypes;
4554 subExprs.reserve(n);
4555 subTypes.reserve(n);
4556 for (const GenericSelectionExpr::Association assoc : gse->associations()) {
4557 subTypes.push_back(assoc.getTypeSourceInfo());
4558 Expr *sub = assoc.getAssociationExpr();
4559 if (assoc.isSelected())
4560 sub = stripARCUnbridgedCast(sub);
4561 subExprs.push_back(sub);
4564 return GenericSelectionExpr::Create(
4565 Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes,
4566 subExprs, gse->getDefaultLoc(), gse->getRParenLoc(),
4567 gse->containsUnexpandedParameterPack(), gse->getResultIndex());
4569 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
4570 return cast<ImplicitCastExpr>(e)->getSubExpr();
4574 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
4575 QualType exprType) {
4576 QualType canCastType =
4577 Context.getCanonicalType(castType).getUnqualifiedType();
4578 QualType canExprType =
4579 Context.getCanonicalType(exprType).getUnqualifiedType();
4580 if (isa<ObjCObjectPointerType>(canCastType) &&
4581 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
4582 canExprType->isObjCObjectPointerType()) {
4583 if (const ObjCObjectPointerType *ObjT =
4584 canExprType->getAs<ObjCObjectPointerType>())
4585 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
4586 return !ObjI->isArcWeakrefUnavailable();
4591 /// Look for an ObjCReclaimReturnedObject cast and destroy it.
4592 static Expr *maybeUndoReclaimObject(Expr *e) {
4593 Expr *curExpr = e, *prevExpr = nullptr;
4595 // Walk down the expression until we hit an implicit cast of kind
4596 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast.
4598 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) {
4600 curExpr = pe->getSubExpr();
4604 if (auto *ce = dyn_cast<CastExpr>(curExpr)) {
4605 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce))
4606 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) {
4608 return ice->getSubExpr();
4609 if (auto *pe = dyn_cast<ParenExpr>(prevExpr))
4610 pe->setSubExpr(ice->getSubExpr());
4612 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr());
4617 curExpr = ce->getSubExpr();
4621 // Break out of the loop if curExpr is neither a Paren nor a Cast.
4628 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
4629 ObjCBridgeCastKind Kind,
4630 SourceLocation BridgeKeywordLoc,
4631 TypeSourceInfo *TSInfo,
4633 ExprResult SubResult = UsualUnaryConversions(SubExpr);
4634 if (SubResult.isInvalid()) return ExprError();
4635 SubExpr = SubResult.get();
4637 QualType T = TSInfo->getType();
4638 QualType FromType = SubExpr->getType();
4642 bool MustConsume = false;
4643 if (T->isDependentType() || SubExpr->isTypeDependent()) {
4644 // Okay: we'll build a dependent expression type.
4646 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
4648 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
4649 : CK_CPointerToObjCPointerCast);
4654 case OBC_BridgeRetained: {
4655 bool br = isKnownName("CFBridgingRelease");
4656 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4659 << (T->isBlockPointerType()? 1 : 0)
4661 << SubExpr->getSourceRange()
4663 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4664 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
4665 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
4667 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4668 br ? "CFBridgingRelease "
4669 : "__bridge_transfer ");
4675 case OBC_BridgeTransfer:
4676 // We must consume the Objective-C object produced by the cast.
4680 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
4685 // Reclaiming a value that's going to be __bridge-casted to CF
4686 // is very dangerous, so we don't do it.
4687 SubExpr = maybeUndoReclaimObject(SubExpr);
4690 case OBC_BridgeRetained:
4691 // Produce the object before casting it.
4692 SubExpr = ImplicitCastExpr::Create(Context, FromType,
4693 CK_ARCProduceObject,
4694 SubExpr, nullptr, VK_RValue);
4697 case OBC_BridgeTransfer: {
4698 bool br = isKnownName("CFBridgingRetain");
4699 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
4700 << (FromType->isBlockPointerType()? 1 : 0)
4704 << SubExpr->getSourceRange()
4707 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
4708 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
4709 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
4711 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4712 br ? "CFBridgingRetain " : "__bridge_retained");
4719 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4720 << FromType << T << Kind
4721 << SubExpr->getSourceRange()
4722 << TSInfo->getTypeLoc().getSourceRange();
4726 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
4731 Cleanup.setExprNeedsCleanups(true);
4732 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
4733 nullptr, VK_RValue);
4739 ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4740 SourceLocation LParenLoc,
4741 ObjCBridgeCastKind Kind,
4742 SourceLocation BridgeKeywordLoc,
4744 SourceLocation RParenLoc,
4746 TypeSourceInfo *TSInfo = nullptr;
4747 QualType T = GetTypeFromParser(Type, &TSInfo);
4748 if (Kind == OBC_Bridge)
4749 CheckTollFreeBridgeCast(T, SubExpr);
4751 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4752 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,