1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements semantic analysis for Objective-C expressions. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/DeclObjC.h" 15 #include "clang/AST/ExprObjC.h" 16 #include "clang/AST/StmtVisitor.h" 17 #include "clang/AST/TypeLoc.h" 18 #include "clang/Analysis/DomainSpecific/CocoaConventions.h" 19 #include "clang/Basic/Builtins.h" 20 #include "clang/Edit/Commit.h" 21 #include "clang/Edit/Rewriters.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "clang/Sema/Initialization.h" 24 #include "clang/Sema/Lookup.h" 25 #include "clang/Sema/Scope.h" 26 #include "clang/Sema/ScopeInfo.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "llvm/ADT/SmallString.h" 29 #include "llvm/Support/ConvertUTF.h" 30 31 using namespace clang; 32 using namespace sema; 33 using llvm::makeArrayRef; 34 35 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, 36 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]); 42 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; 48 49 for (Expr *E : Strings) { 50 S = cast<StringLiteral>(E); 51 52 // ObjC strings can't be wide or UTF. 53 if (!S->isAscii()) { 54 Diag(S->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 55 << S->getSourceRange(); 56 return true; 57 } 58 59 // Append the string. 60 StrBuf += S->getString(); 61 62 // Get the locations of the string tokens. 63 StrLocs.append(S->tokloc_begin(), S->tokloc_end()); 64 } 65 66 // Create the aggregate string with the appropriate content and location 67 // information. 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], 75 StrLocs.size()); 76 } 77 78 return BuildObjCStringLiteral(AtLocs[0], S); 79 } 80 81 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ 82 // Verify that this composite string is acceptable for ObjC strings. 83 if (CheckObjCString(S)) 84 return true; 85 86 // Initialize the constant string interface lazily. This assumes 87 // the NSString interface is seen in this translation unit. Note: We 88 // don't use NSConstantString, since the runtime team considers this 89 // interface private (even though it appears in the header files). 90 QualType Ty = Context.getObjCConstantStringInterface(); 91 if (!Ty.isNull()) { 92 Ty = Context.getObjCObjectPointerType(Ty); 93 } else if (getLangOpts().NoConstantCFStrings) { 94 IdentifierInfo *NSIdent=nullptr; 95 std::string StringClass(getLangOpts().ObjCConstantStringClass); 96 97 if (StringClass.empty()) 98 NSIdent = &Context.Idents.get("NSConstantString"); 99 else 100 NSIdent = &Context.Idents.get(StringClass); 101 102 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 103 LookupOrdinaryName); 104 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 105 Context.setObjCConstantStringInterface(StrIF); 106 Ty = Context.getObjCConstantStringInterface(); 107 Ty = Context.getObjCObjectPointerType(Ty); 108 } else { 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(); 114 } 115 } else { 116 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); 117 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 118 LookupOrdinaryName); 119 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 120 Context.setObjCConstantStringInterface(StrIF); 121 Ty = Context.getObjCConstantStringInterface(); 122 Ty = Context.getObjCObjectPointerType(Ty); 123 } else { 124 // If there is no NSString interface defined, implicitly declare 125 // a @class NSString; and use that instead. This is to make sure 126 // type of an NSString literal is represented correctly, instead of 127 // being an 'id' type. 128 Ty = Context.getObjCNSStringType(); 129 if (Ty.isNull()) { 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); 137 } 138 Ty = Context.getObjCObjectPointerType(Ty); 139 } 140 } 141 142 return new (Context) ObjCStringLiteral(S, Ty, AtLoc); 143 } 144 145 /// Emits an error if the given method does not exist, or if the return 146 /// type is not an Objective-C object. 147 static bool validateBoxingMethod(Sema &S, SourceLocation Loc, 148 const ObjCInterfaceDecl *Class, 149 Selector Sel, const ObjCMethodDecl *Method) { 150 if (!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(); 153 return false; 154 } 155 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) 160 << Sel; 161 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return) 162 << ReturnType; 163 return false; 164 } 165 166 return true; 167 } 168 169 /// Maps ObjCLiteralKind to NSClassIdKindKind 170 static NSAPI::NSClassIdKindKind ClassKindFromLiteralKind( 171 Sema::ObjCLiteralKind LiteralKind) { 172 switch (LiteralKind) { 173 case Sema::LK_Array: 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; 181 case Sema::LK_Boxed: 182 return NSAPI::ClassId_NSValue; 183 184 // there is no corresponding matching 185 // between LK_None/LK_Block and NSClassIdKindKind 186 case Sema::LK_Block: 187 case Sema::LK_None: 188 break; 189 } 190 llvm_unreachable("LiteralKind can't be converted into a ClassKind"); 191 } 192 193 /// Validates ObjCInterfaceDecl availability. 194 /// ObjCInterfaceDecl, used to create ObjC literals, should be defined 195 /// if clang not in a debugger mode. 196 static bool ValidateObjCLiteralInterfaceDecl(Sema &S, ObjCInterfaceDecl *Decl, 197 SourceLocation Loc, 198 Sema::ObjCLiteralKind LiteralKind) { 199 if (!Decl) { 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; 204 return false; 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); 209 return false; 210 } 211 212 return true; 213 } 214 215 /// Looks up ObjCInterfaceDecl of a given NSClassIdKindKind. 216 /// Used to create ObjC literals, such as NSDictionary (@{}), 217 /// NSArray (@[]) and Boxed Expressions (@()) 218 static ObjCInterfaceDecl *LookupObjCInterfaceDeclForLiteral(Sema &S, 219 SourceLocation Loc, 220 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()); 231 } 232 233 if (!ValidateObjCLiteralInterfaceDecl(S, ID, Loc, LiteralKind)) { 234 ID = nullptr; 235 } 236 237 return ID; 238 } 239 240 /// Retrieve the NSNumber factory method that should be used to create 241 /// an Objective-C literal for the given type. 242 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, 243 QualType NumberType, 244 bool isLiteral = false, 245 SourceRange R = SourceRange()) { 246 Optional<NSAPI::NSNumberLiteralMethodKind> Kind = 247 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType); 248 249 if (!Kind) { 250 if (isLiteral) { 251 S.Diag(Loc, diag::err_invalid_nsnumber_type) 252 << NumberType << R; 253 } 254 return nullptr; 255 } 256 257 // If we already looked up this method, we're done. 258 if (S.NSNumberLiteralMethods[*Kind]) 259 return S.NSNumberLiteralMethods[*Kind]; 260 261 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, 262 /*Instance=*/false); 263 264 ASTContext &CX = S.Context; 265 266 // Look up the NSNumber class, if we haven't done so already. It's cached 267 // in the Sema instance. 268 if (!S.NSNumberDecl) { 269 S.NSNumberDecl = LookupObjCInterfaceDeclForLiteral(S, Loc, 270 Sema::LK_Numeric); 271 if (!S.NSNumberDecl) { 272 return nullptr; 273 } 274 } 275 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); 280 } 281 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; 287 Method = 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, 300 SC_None, nullptr); 301 Method->setMethodParams(S.Context, value, None); 302 } 303 304 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method)) 305 return nullptr; 306 307 // Note: if the parameter type is out-of-line, we'll catch it later in the 308 // implicit conversion. 309 310 S.NSNumberLiteralMethods[*Kind] = Method; 311 return Method; 312 } 313 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; 326 break; 327 328 case CharacterLiteral::Wide: 329 NumberType = Context.getWideCharType(); 330 break; 331 332 case CharacterLiteral::UTF16: 333 NumberType = Context.Char16Ty; 334 break; 335 336 case CharacterLiteral::UTF32: 337 NumberType = Context.Char32Ty; 338 break; 339 } 340 } 341 342 // Look for the appropriate method within NSNumber. 343 // Construct the literal. 344 SourceRange NR(Number->getSourceRange()); 345 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType, 346 true, NR); 347 if (!Method) 348 return ExprError(); 349 350 // Convert the number to the type that the parameter expects. 351 ParmVarDecl *ParamDecl = Method->parameters()[0]; 352 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 353 ParamDecl); 354 ExprResult ConvertedNumber = PerformCopyInitialization(Entity, 355 SourceLocation(), 356 Number); 357 if (ConvertedNumber.isInvalid()) 358 return ExprError(); 359 Number = ConvertedNumber.get(); 360 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()))); 365 } 366 367 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, 368 SourceLocation ValueLoc, 369 bool Value) { 370 ExprResult Inner; 371 if (getLangOpts().CPlusPlus) { 372 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); 373 } else { 374 // C doesn't actually have a way to represent literal values of type 375 // _Bool. So, we'll use 0/1 and implicit cast to _Bool. 376 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); 377 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, 378 CK_IntegralToBoolean); 379 } 380 381 return BuildObjCNumericLiteral(AtLoc, Inner.get()); 382 } 383 384 /// Check that the given expression is a valid element of an Objective-C 385 /// collection literal. 386 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, 387 QualType T, 388 bool ArrayLiteral = false) { 389 // If the expression is type-dependent, there's nothing for us to do. 390 if (Element->isTypeDependent()) 391 return Element; 392 393 ExprResult Result = S.CheckPlaceholderExpr(Element); 394 if (Result.isInvalid()) 395 return ExprError(); 396 Element = Result.get(); 397 398 // In C++, check for an implicit conversion to an Objective-C object pointer 399 // type. 400 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { 401 InitializedEntity Entity 402 = InitializedEntity::InitializeParameter(S.Context, T, 403 /*Consumed=*/false); 404 InitializationKind Kind = InitializationKind::CreateCopy( 405 Element->getBeginLoc(), SourceLocation()); 406 InitializationSequence Seq(S, Entity, Kind, Element); 407 if (!Seq.Failed()) 408 return Seq.Perform(S, Entity, Kind, Element); 409 } 410 411 Expr *OrigElement = Element; 412 413 // Perform lvalue-to-rvalue conversion. 414 Result = S.DefaultLvalueConversion(Element); 415 if (Result.isInvalid()) 416 return ExprError(); 417 Element = Result.get(); 418 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; 423 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 434 : 3; 435 436 S.Diag(OrigElement->getBeginLoc(), diag::err_box_literal_collection) 437 << Which << OrigElement->getSourceRange() 438 << FixItHint::CreateInsertion(OrigElement->getBeginLoc(), "@"); 439 440 Result = 441 S.BuildObjCNumericLiteral(OrigElement->getBeginLoc(), OrigElement); 442 if (Result.isInvalid()) 443 return ExprError(); 444 445 Element = Result.get(); 446 Recovered = true; 447 } 448 } 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(), "@"); 455 456 Result = S.BuildObjCStringLiteral(OrigElement->getBeginLoc(), String); 457 if (Result.isInvalid()) 458 return ExprError(); 459 460 Element = Result.get(); 461 Recovered = true; 462 } 463 } 464 465 if (!Recovered) { 466 S.Diag(Element->getBeginLoc(), diag::err_invalid_collection_element) 467 << Element->getType(); 468 return ExprError(); 469 } 470 } 471 if (ArrayLiteral) 472 if (ObjCStringLiteral *getString = 473 dyn_cast<ObjCStringLiteral>(OrigElement)) { 474 if (StringLiteral *SL = getString->getString()) { 475 unsigned numConcat = SL->getNumConcatenated(); 476 if (numConcat > 1) { 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()) { 481 hasMacro = true; 482 break; 483 } 484 if (!hasMacro) 485 S.Diag(Element->getBeginLoc(), 486 diag::warn_concatenated_nsarray_literal) 487 << Element->getType(); 488 } 489 } 490 } 491 492 // Make sure that the element has the type that the container factory 493 // function expects. 494 return S.PerformCopyInitialization( 495 InitializedEntity::InitializeParameter(S.Context, T, 496 /*Consumed=*/false), 497 Element->getBeginLoc(), Element); 498 } 499 500 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { 501 if (ValueExpr->isTypeDependent()) { 502 ObjCBoxedExpr *BoxedExpr = 503 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR); 504 return BoxedExpr; 505 } 506 ObjCMethodDecl *BoxingMethod = nullptr; 507 QualType BoxedType; 508 // Convert the expression to an RValue, so we can check for pointer types... 509 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr); 510 if (RValue.isInvalid()) { 511 return ExprError(); 512 } 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)) { 519 520 if (!NSStringDecl) { 521 NSStringDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc, 522 Sema::LK_String); 523 if (!NSStringDecl) { 524 return ExprError(); 525 } 526 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); 527 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); 528 } 529 530 // The boxed expression can be emitted as a compile time constant if it is 531 // a string literal whose character encoding is compatible with UTF-8. 532 if (auto *CE = dyn_cast<ImplicitCastExpr>(ValueExpr)) 533 if (CE->getCastKind() == CK_ArrayToPointerDecay) 534 if (auto *SL = 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); 548 } 549 550 Diag(SL->getBeginLoc(), diag::warn_objc_boxing_invalid_utf8_string) 551 << NSStringPointer << SL->getSourceRange(); 552 } 553 554 if (!StringWithUTF8StringMethod) { 555 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); 556 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); 557 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(); 573 ParmVarDecl *value = 574 ParmVarDecl::Create(Context, M, 575 SourceLocation(), SourceLocation(), 576 &Context.Idents.get("value"), 577 Context.getPointerType(ConstCharType), 578 /*TInfo=*/nullptr, 579 SC_None, nullptr); 580 M->setMethodParams(Context, value, None); 581 BoxingMethod = M; 582 } 583 584 if (!validateBoxingMethod(*this, Loc, NSStringDecl, 585 stringWithUTF8String, BoxingMethod)) 586 return ExprError(); 587 588 StringWithUTF8StringMethod = BoxingMethod; 589 } 590 591 BoxingMethod = StringWithUTF8StringMethod; 592 BoxedType = NSStringPointer; 593 // Transfer the nullability from method's return type. 594 Optional<NullabilityKind> Nullability = 595 BoxingMethod->getReturnType()->getNullability(Context); 596 if (Nullability) 597 BoxedType = Context.getAttributedType( 598 AttributedType::getNullabilityAttrKind(*Nullability), BoxedType, 599 BoxedType); 600 } 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> 605 // for more details. 606 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; 616 break; 617 618 case CharacterLiteral::Wide: 619 ValueType = Context.getWideCharType(); 620 break; 621 622 case CharacterLiteral::UTF16: 623 ValueType = Context.Char16Ty; 624 break; 625 626 case CharacterLiteral::UTF32: 627 ValueType = Context.Char32Ty; 628 break; 629 } 630 } 631 // FIXME: Do I need to do anything special with BoolTy expressions? 632 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(); 640 return ExprError(); 641 } 642 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 { ... }; 649 650 // Look up the NSValue class, if we haven't done so already. It's cached 651 // in the Sema instance. 652 if (!NSValueDecl) { 653 NSValueDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc, 654 Sema::LK_Boxed); 655 if (!NSValueDecl) { 656 return ExprError(); 657 } 658 659 // generate the pointer to NSValue type. 660 QualType NSValueObject = Context.getObjCInterfaceType(NSValueDecl); 661 NSValuePointer = Context.getObjCObjectPointerType(NSValueObject); 662 } 663 664 if (!ValueWithBytesObjCTypeMethod) { 665 IdentifierInfo *II[] = { 666 &Context.Idents.get("valueWithBytes"), 667 &Context.Idents.get("objCType") 668 }; 669 Selector ValueWithBytesObjCType = Context.Selectors.getSelector(2, II); 670 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); 686 687 SmallVector<ParmVarDecl *, 2> Params; 688 689 ParmVarDecl *bytes = 690 ParmVarDecl::Create(Context, M, 691 SourceLocation(), SourceLocation(), 692 &Context.Idents.get("bytes"), 693 Context.VoidPtrTy.withConst(), 694 /*TInfo=*/nullptr, 695 SC_None, nullptr); 696 Params.push_back(bytes); 697 698 QualType ConstCharType = Context.CharTy.withConst(); 699 ParmVarDecl *type = 700 ParmVarDecl::Create(Context, M, 701 SourceLocation(), SourceLocation(), 702 &Context.Idents.get("type"), 703 Context.getPointerType(ConstCharType), 704 /*TInfo=*/nullptr, 705 SC_None, nullptr); 706 Params.push_back(type); 707 708 M->setMethodParams(Context, Params, None); 709 BoxingMethod = M; 710 } 711 712 if (!validateBoxingMethod(*this, Loc, NSValueDecl, 713 ValueWithBytesObjCType, BoxingMethod)) 714 return ExprError(); 715 716 ValueWithBytesObjCTypeMethod = BoxingMethod; 717 } 718 719 if (!ValueType.isTriviallyCopyableType(Context)) { 720 Diag(Loc, diag::err_objc_non_trivially_copyable_boxed_expression_type) 721 << ValueType << ValueExpr->getSourceRange(); 722 return ExprError(); 723 } 724 725 BoxingMethod = ValueWithBytesObjCTypeMethod; 726 BoxedType = NSValuePointer; 727 } 728 729 if (!BoxingMethod) { 730 Diag(Loc, diag::err_objc_illegal_boxed_expression_type) 731 << ValueType << ValueExpr->getSourceRange(); 732 return ExprError(); 733 } 734 735 DiagnoseUseOfDecl(BoxingMethod, Loc); 736 737 ExprResult ConvertedValueExpr; 738 if (ValueType->isObjCBoxableRecordType()) { 739 InitializedEntity IE = InitializedEntity::InitializeTemporary(ValueType); 740 ConvertedValueExpr = PerformCopyInitialization(IE, ValueExpr->getExprLoc(), 741 ValueExpr); 742 } else { 743 // Convert the expression to the type that the parameter requires. 744 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0]; 745 InitializedEntity IE = InitializedEntity::InitializeParameter(Context, 746 ParamDecl); 747 ConvertedValueExpr = PerformCopyInitialization(IE, SourceLocation(), 748 ValueExpr); 749 } 750 751 if (ConvertedValueExpr.isInvalid()) 752 return ExprError(); 753 ValueExpr = ConvertedValueExpr.get(); 754 755 ObjCBoxedExpr *BoxedExpr = 756 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, 757 BoxingMethod, SR); 758 return MaybeBindToTemporary(BoxedExpr); 759 } 760 761 /// Build an ObjC subscript pseudo-object expression, given that 762 /// that's supported by the runtime. 763 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 764 Expr *IndexExpr, 765 ObjCMethodDecl *getterMethod, 766 ObjCMethodDecl *setterMethod) { 767 assert(!LangOpts.isSubscriptPointerArithmetic()); 768 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"); 773 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()) 778 return ExprError(); 779 IndexExpr = Result.get(); 780 781 // Perform lvalue-to-rvalue conversion on the base. 782 Result = DefaultLvalueConversion(BaseExpr); 783 if (Result.isInvalid()) 784 return ExprError(); 785 BaseExpr = Result.get(); 786 787 // Build the pseudo-object expression. 788 return new (Context) ObjCSubscriptRefExpr( 789 BaseExpr, IndexExpr, Context.PseudoObjectTy, VK_LValue, OK_ObjCSubscript, 790 getterMethod, setterMethod, RB); 791 } 792 793 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { 794 SourceLocation Loc = SR.getBegin(); 795 796 if (!NSArrayDecl) { 797 NSArrayDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc, 798 Sema::LK_Array); 799 if (!NSArrayDecl) { 800 return ExprError(); 801 } 802 } 803 804 // Find the arrayWithObjects:count: method, if we haven't done so already. 805 QualType IdT = Context.getObjCIdType(); 806 if (!ArrayWithObjectsMethod) { 807 Selector 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, 821 SourceLocation(), 822 SourceLocation(), 823 &Context.Idents.get("objects"), 824 Context.getPointerType(IdT), 825 /*TInfo=*/nullptr, 826 SC_None, nullptr); 827 Params.push_back(objects); 828 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 829 SourceLocation(), 830 SourceLocation(), 831 &Context.Idents.get("cnt"), 832 Context.UnsignedLongTy, 833 /*TInfo=*/nullptr, SC_None, 834 nullptr); 835 Params.push_back(cnt); 836 Method->setMethodParams(Context, Params, None); 837 } 838 839 if (!validateBoxingMethod(*this, Loc, NSArrayDecl, Sel, Method)) 840 return ExprError(); 841 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>(); 845 if (!PtrT || 846 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { 847 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 848 << Sel; 849 Diag(Method->parameters()[0]->getLocation(), 850 diag::note_objc_literal_method_param) 851 << 0 << T 852 << Context.getPointerType(IdT.withConst()); 853 return ExprError(); 854 } 855 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) 859 << Sel; 860 Diag(Method->parameters()[1]->getLocation(), 861 diag::note_objc_literal_method_param) 862 << 1 863 << Method->parameters()[1]->getType() 864 << "integral"; 865 return ExprError(); 866 } 867 868 // We've found a good +arrayWithObjects:count: method. Save it! 869 ArrayWithObjectsMethod = Method; 870 } 871 872 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType(); 873 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType(); 874 875 // Check that each of the elements provided is valid in a collection literal, 876 // performing conversions as necessary. 877 Expr **ElementsBuffer = Elements.data(); 878 for (unsigned I = 0, N = Elements.size(); I != N; ++I) { 879 ExprResult Converted = CheckObjCCollectionLiteralElement(*this, 880 ElementsBuffer[I], 881 RequiredType, true); 882 if (Converted.isInvalid()) 883 return ExprError(); 884 885 ElementsBuffer[I] = Converted.get(); 886 } 887 888 QualType Ty 889 = Context.getObjCObjectPointerType( 890 Context.getObjCInterfaceType(NSArrayDecl)); 891 892 return MaybeBindToTemporary( 893 ObjCArrayLiteral::Create(Context, Elements, Ty, 894 ArrayWithObjectsMethod, SR)); 895 } 896 897 /// Check for duplicate keys in an ObjC dictionary literal. For instance: 898 /// NSDictionary *nd = @{ @"foo" : @"bar", @"foo" : @"baz" }; 899 static void 900 CheckObjCDictionaryLiteralDuplicateKeys(Sema &S, 901 ObjCDictionaryLiteral *Literal) { 902 if (Literal->isValueDependent() || Literal->isTypeDependent()) 903 return; 904 905 // NSNumber has quite relaxed equality semantics (for instance, @YES is 906 // considered equal to @1.0). For now, ignore floating points and just do a 907 // bit-width and sign agnostic integer compare. 908 struct APSIntCompare { 909 bool operator()(const llvm::APSInt &LHS, const llvm::APSInt &RHS) const { 910 return llvm::APSInt::compareValues(LHS, RHS) < 0; 911 } 912 }; 913 914 llvm::DenseMap<StringRef, SourceLocation> StringKeys; 915 std::map<llvm::APSInt, SourceLocation, APSIntCompare> IntegralKeys; 916 917 auto checkOneKey = [&](auto &Map, const auto &Key, SourceLocation Loc) { 918 auto Pair = Map.insert({Key, Loc}); 919 if (!Pair.second) { 920 S.Diag(Loc, diag::warn_nsdictionary_duplicate_key); 921 S.Diag(Pair.first->second, diag::note_nsdictionary_duplicate_key_here); 922 } 923 }; 924 925 for (unsigned Idx = 0, End = Literal->getNumElements(); Idx != End; ++Idx) { 926 Expr *Key = Literal->getKeyValueElement(Idx).Key->IgnoreParenImpCasts(); 927 928 if (auto *StrLit = dyn_cast<ObjCStringLiteral>(Key)) { 929 StringRef Bytes = StrLit->getString()->getBytes(); 930 SourceLocation Loc = StrLit->getExprLoc(); 931 checkOneKey(StringKeys, Bytes, Loc); 932 } 933 934 if (auto *BE = dyn_cast<ObjCBoxedExpr>(Key)) { 935 Expr *Boxed = BE->getSubExpr(); 936 SourceLocation Loc = BE->getExprLoc(); 937 938 // Check for @("foo"). 939 if (auto *Str = dyn_cast<StringLiteral>(Boxed->IgnoreParenImpCasts())) { 940 checkOneKey(StringKeys, Str->getBytes(), Loc); 941 continue; 942 } 943 944 Expr::EvalResult Result; 945 if (Boxed->EvaluateAsInt(Result, S.getASTContext(), 946 Expr::SE_AllowSideEffects)) { 947 checkOneKey(IntegralKeys, Result.Val.getInt(), Loc); 948 } 949 } 950 } 951 } 952 953 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, 954 MutableArrayRef<ObjCDictionaryElement> Elements) { 955 SourceLocation Loc = SR.getBegin(); 956 957 if (!NSDictionaryDecl) { 958 NSDictionaryDecl = LookupObjCInterfaceDeclForLiteral(*this, Loc, 959 Sema::LK_Dictionary); 960 if (!NSDictionaryDecl) { 961 return ExprError(); 962 } 963 } 964 965 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done 966 // so already. 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, 983 SourceLocation(), 984 SourceLocation(), 985 &Context.Idents.get("objects"), 986 Context.getPointerType(IdT), 987 /*TInfo=*/nullptr, SC_None, 988 nullptr); 989 Params.push_back(objects); 990 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method, 991 SourceLocation(), 992 SourceLocation(), 993 &Context.Idents.get("keys"), 994 Context.getPointerType(IdT), 995 /*TInfo=*/nullptr, SC_None, 996 nullptr); 997 Params.push_back(keys); 998 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 999 SourceLocation(), 1000 SourceLocation(), 1001 &Context.Idents.get("cnt"), 1002 Context.UnsignedLongTy, 1003 /*TInfo=*/nullptr, SC_None, 1004 nullptr); 1005 Params.push_back(cnt); 1006 Method->setMethodParams(Context, Params, None); 1007 } 1008 1009 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel, 1010 Method)) 1011 return ExprError(); 1012 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>(); 1016 if (!PtrValue || 1017 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { 1018 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 1019 << Sel; 1020 Diag(Method->parameters()[0]->getLocation(), 1021 diag::note_objc_literal_method_param) 1022 << 0 << ValueT 1023 << Context.getPointerType(IdT.withConst()); 1024 return ExprError(); 1025 } 1026 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>(); 1030 if (!PtrKey || 1031 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 1032 IdT)) { 1033 bool err = true; 1034 if (PtrKey) { 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}; 1040 QIDNSCopying = 1041 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, { }, 1042 llvm::makeArrayRef( 1043 (ObjCProtocolDecl**) PQ, 1044 1), 1045 false); 1046 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying); 1047 } 1048 } 1049 if (!QIDNSCopying.isNull()) 1050 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 1051 QIDNSCopying); 1052 } 1053 1054 if (err) { 1055 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 1056 << Sel; 1057 Diag(Method->parameters()[1]->getLocation(), 1058 diag::note_objc_literal_method_param) 1059 << 1 << KeyT 1060 << Context.getPointerType(IdT.withConst()); 1061 return ExprError(); 1062 } 1063 } 1064 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) 1069 << Sel; 1070 Diag(Method->parameters()[2]->getLocation(), 1071 diag::note_objc_literal_method_param) 1072 << 2 << CountType 1073 << "integral"; 1074 return ExprError(); 1075 } 1076 1077 // We've found a good +dictionaryWithObjects:keys:count: method; save it! 1078 DictionaryWithObjectsMethod = Method; 1079 } 1080 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(); 1085 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) { 1090 // Check the key. 1091 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Element.Key, 1092 KeyT); 1093 if (Key.isInvalid()) 1094 return ExprError(); 1095 1096 // Check the value. 1097 ExprResult Value 1098 = CheckObjCCollectionLiteralElement(*this, Element.Value, ValueT); 1099 if (Value.isInvalid()) 1100 return ExprError(); 1101 1102 Element.Key = Key.get(); 1103 Element.Value = Value.get(); 1104 1105 if (Element.EllipsisLoc.isInvalid()) 1106 continue; 1107 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()); 1114 return ExprError(); 1115 } 1116 1117 HasPackExpansions = true; 1118 } 1119 1120 QualType Ty = Context.getObjCObjectPointerType( 1121 Context.getObjCInterfaceType(NSDictionaryDecl)); 1122 1123 auto *Literal = 1124 ObjCDictionaryLiteral::Create(Context, Elements, HasPackExpansions, Ty, 1125 DictionaryWithObjectsMethod, SR); 1126 CheckObjCDictionaryLiteralDuplicateKeys(*this, Literal); 1127 return MaybeBindToTemporary(Literal); 1128 } 1129 1130 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, 1131 TypeSourceInfo *EncodedTypeInfo, 1132 SourceLocation RParenLoc) { 1133 QualType EncodedType = EncodedTypeInfo->getType(); 1134 QualType StrTy; 1135 if (EncodedType->isDependentType()) 1136 StrTy = Context.DependentTy; 1137 else { 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())) 1143 return ExprError(); 1144 1145 std::string Str; 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; 1151 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()); 1155 } 1156 1157 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc); 1158 } 1159 1160 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, 1161 SourceLocation EncodeLoc, 1162 SourceLocation LParenLoc, 1163 ParsedType ty, 1164 SourceLocation RParenLoc) { 1165 // FIXME: Preserve type source info ? 1166 TypeSourceInfo *TInfo; 1167 QualType EncodedType = GetTypeFromParser(ty, &TInfo); 1168 if (!TInfo) 1169 TInfo = Context.getTrivialTypeSourceInfo(EncodedType, 1170 getLocForEndOfToken(LParenLoc)); 1171 1172 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc); 1173 } 1174 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()) 1188 continue; 1189 if (!S.MatchTwoMethodDeclarations(Method, 1190 MatchingMethodDecl, Sema::MMS_loose)) { 1191 if (!Warned) { 1192 Warned = true; 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(); 1198 } 1199 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at) 1200 << MatchingMethodDecl->getDeclName(); 1201 } 1202 } 1203 return Warned; 1204 } 1205 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())) 1213 return; 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)) 1221 Warned = true; 1222 1223 // second, class methods 1224 ObjCMethodList &ClsMethList = b->second.second; 1225 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc, 1226 Method, ClsMethList) || Warned) 1227 return; 1228 } 1229 } 1230 1231 static void HelperToDiagnoseDirectSelectorsExpr(Sema &S, SourceLocation AtLoc, 1232 Selector Sel, 1233 ObjCMethodList &MethList, 1234 bool &onlyDirect) { 1235 ObjCMethodList *M = &MethList; 1236 for (M = M->getNext(); M; M = M->getNext()) { 1237 ObjCMethodDecl *Method = M->getMethod(); 1238 if (Method->getSelector() != Sel) 1239 continue; 1240 if (!Method->isDirectMethod()) 1241 onlyDirect = false; 1242 } 1243 } 1244 1245 static void DiagnoseDirectSelectorsExpr(Sema &S, SourceLocation AtLoc, 1246 Selector Sel, bool &onlyDirect) { 1247 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(), 1248 e = S.MethodPool.end(); b != e; b++) { 1249 // first, instance methods 1250 ObjCMethodList &InstMethList = b->second.first; 1251 HelperToDiagnoseDirectSelectorsExpr(S, AtLoc, Sel, InstMethList, 1252 onlyDirect); 1253 1254 // second, class methods 1255 ObjCMethodList &ClsMethList = b->second.second; 1256 HelperToDiagnoseDirectSelectorsExpr(S, AtLoc, Sel, ClsMethList, onlyDirect); 1257 } 1258 } 1259 1260 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, 1261 SourceLocation AtLoc, 1262 SourceLocation SelLoc, 1263 SourceLocation LParenLoc, 1264 SourceLocation RParenLoc, 1265 bool WarnMultipleSelectors) { 1266 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, 1267 SourceRange(LParenLoc, RParenLoc)); 1268 if (!Method) 1269 Method = LookupFactoryMethodInGlobalPool(Sel, 1270 SourceRange(LParenLoc, RParenLoc)); 1271 if (!Method) { 1272 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) { 1273 Selector MatchedSel = OM->getSelector(); 1274 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1), 1275 RParenLoc.getLocWithOffset(-1)); 1276 Diag(SelLoc, diag::warn_undeclared_selector_with_typo) 1277 << Sel << MatchedSel 1278 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 1279 1280 } else 1281 Diag(SelLoc, diag::warn_undeclared_selector) << Sel; 1282 } else { 1283 bool onlyDirect = Method->isDirectMethod(); 1284 DiagnoseDirectSelectorsExpr(*this, AtLoc, Sel, onlyDirect); 1285 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc, 1286 WarnMultipleSelectors); 1287 if (onlyDirect) { 1288 Diag(AtLoc, diag::err_direct_selector_expression) 1289 << Method->getSelector(); 1290 Diag(Method->getLocation(), diag::note_direct_method_declared_at) 1291 << Method->getDeclName(); 1292 } 1293 } 1294 1295 if (Method && 1296 Method->getImplementationControl() != ObjCMethodDecl::Optional && 1297 !getSourceManager().isInSystemHeader(Method->getLocation())) 1298 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); 1299 1300 // In ARC, forbid the user from using @selector for 1301 // retain/release/autorelease/dealloc/retainCount. 1302 if (getLangOpts().ObjCAutoRefCount) { 1303 switch (Sel.getMethodFamily()) { 1304 case OMF_retain: 1305 case OMF_release: 1306 case OMF_autorelease: 1307 case OMF_retainCount: 1308 case OMF_dealloc: 1309 Diag(AtLoc, diag::err_arc_illegal_selector) << 1310 Sel << SourceRange(LParenLoc, RParenLoc); 1311 break; 1312 1313 case OMF_None: 1314 case OMF_alloc: 1315 case OMF_copy: 1316 case OMF_finalize: 1317 case OMF_init: 1318 case OMF_mutableCopy: 1319 case OMF_new: 1320 case OMF_self: 1321 case OMF_initialize: 1322 case OMF_performSelector: 1323 break; 1324 } 1325 } 1326 QualType Ty = Context.getObjCSelType(); 1327 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); 1328 } 1329 1330 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, 1331 SourceLocation AtLoc, 1332 SourceLocation ProtoLoc, 1333 SourceLocation LParenLoc, 1334 SourceLocation ProtoIdLoc, 1335 SourceLocation RParenLoc) { 1336 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc); 1337 if (!PDecl) { 1338 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; 1339 return true; 1340 } 1341 if (!PDecl->hasDefinition()) { 1342 Diag(ProtoLoc, diag::err_atprotocol_protocol) << PDecl; 1343 Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl; 1344 } else { 1345 PDecl = PDecl->getDefinition(); 1346 } 1347 1348 QualType Ty = Context.getObjCProtoType(); 1349 if (Ty.isNull()) 1350 return true; 1351 Ty = Context.getObjCObjectPointerType(Ty); 1352 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc); 1353 } 1354 1355 /// Try to capture an implicit reference to 'self'. 1356 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) { 1357 DeclContext *DC = getFunctionLevelDeclContext(); 1358 1359 // If we're not in an ObjC method, error out. Note that, unlike the 1360 // C++ case, we don't require an instance method --- class methods 1361 // still have a 'self', and we really do still need to capture it! 1362 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC); 1363 if (!method) 1364 return nullptr; 1365 1366 tryCaptureVariable(method->getSelfDecl(), Loc); 1367 1368 return method; 1369 } 1370 1371 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { 1372 QualType origType = T; 1373 if (auto nullability = AttributedType::stripOuterNullability(T)) { 1374 if (T == Context.getObjCInstanceType()) { 1375 return Context.getAttributedType( 1376 AttributedType::getNullabilityAttrKind(*nullability), 1377 Context.getObjCIdType(), 1378 Context.getObjCIdType()); 1379 } 1380 1381 return origType; 1382 } 1383 1384 if (T == Context.getObjCInstanceType()) 1385 return Context.getObjCIdType(); 1386 1387 return origType; 1388 } 1389 1390 /// Determine the result type of a message send based on the receiver type, 1391 /// method, and the kind of message send. 1392 /// 1393 /// This is the "base" result type, which will still need to be adjusted 1394 /// to account for nullability. 1395 static QualType getBaseMessageSendResultType(Sema &S, 1396 QualType ReceiverType, 1397 ObjCMethodDecl *Method, 1398 bool isClassMessage, 1399 bool isSuperMessage) { 1400 assert(Method && "Must have a method"); 1401 if (!Method->hasRelatedResultType()) 1402 return Method->getSendResultType(ReceiverType); 1403 1404 ASTContext &Context = S.Context; 1405 1406 // Local function that transfers the nullability of the method's 1407 // result type to the returned result. 1408 auto transferNullability = [&](QualType type) -> QualType { 1409 // If the method's result type has nullability, extract it. 1410 if (auto nullability = Method->getSendResultType(ReceiverType) 1411 ->getNullability(Context)){ 1412 // Strip off any outer nullability sugar from the provided type. 1413 (void)AttributedType::stripOuterNullability(type); 1414 1415 // Form a new attributed type using the method result type's nullability. 1416 return Context.getAttributedType( 1417 AttributedType::getNullabilityAttrKind(*nullability), 1418 type, 1419 type); 1420 } 1421 1422 return type; 1423 }; 1424 1425 // If a method has a related return type: 1426 // - if the method found is an instance method, but the message send 1427 // was a class message send, T is the declared return type of the method 1428 // found 1429 if (Method->isInstanceMethod() && isClassMessage) 1430 return stripObjCInstanceType(Context, 1431 Method->getSendResultType(ReceiverType)); 1432 1433 // - if the receiver is super, T is a pointer to the class of the 1434 // enclosing method definition 1435 if (isSuperMessage) { 1436 if (ObjCMethodDecl *CurMethod = S.getCurMethodDecl()) 1437 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) { 1438 return transferNullability( 1439 Context.getObjCObjectPointerType( 1440 Context.getObjCInterfaceType(Class))); 1441 } 1442 } 1443 1444 // - if the receiver is the name of a class U, T is a pointer to U 1445 if (ReceiverType->getAsObjCInterfaceType()) 1446 return transferNullability(Context.getObjCObjectPointerType(ReceiverType)); 1447 // - if the receiver is of type Class or qualified Class type, 1448 // T is the declared return type of the method. 1449 if (ReceiverType->isObjCClassType() || 1450 ReceiverType->isObjCQualifiedClassType()) 1451 return stripObjCInstanceType(Context, 1452 Method->getSendResultType(ReceiverType)); 1453 1454 // - if the receiver is id, qualified id, Class, or qualified Class, T 1455 // is the receiver type, otherwise 1456 // - T is the type of the receiver expression. 1457 return transferNullability(ReceiverType); 1458 } 1459 1460 QualType Sema::getMessageSendResultType(const Expr *Receiver, 1461 QualType ReceiverType, 1462 ObjCMethodDecl *Method, 1463 bool isClassMessage, 1464 bool isSuperMessage) { 1465 // Produce the result type. 1466 QualType resultType = getBaseMessageSendResultType(*this, ReceiverType, 1467 Method, 1468 isClassMessage, 1469 isSuperMessage); 1470 1471 // If this is a class message, ignore the nullability of the receiver. 1472 if (isClassMessage) { 1473 // In a class method, class messages to 'self' that return instancetype can 1474 // be typed as the current class. We can safely do this in ARC because self 1475 // can't be reassigned, and we do it unsafely outside of ARC because in 1476 // practice people never reassign self in class methods and there's some 1477 // virtue in not being aggressively pedantic. 1478 if (Receiver && Receiver->isObjCSelfExpr()) { 1479 assert(ReceiverType->isObjCClassType() && "expected a Class self"); 1480 QualType T = Method->getSendResultType(ReceiverType); 1481 AttributedType::stripOuterNullability(T); 1482 if (T == Context.getObjCInstanceType()) { 1483 const ObjCMethodDecl *MD = cast<ObjCMethodDecl>( 1484 cast<ImplicitParamDecl>( 1485 cast<DeclRefExpr>(Receiver->IgnoreParenImpCasts())->getDecl()) 1486 ->getDeclContext()); 1487 assert(MD->isClassMethod() && "expected a class method"); 1488 QualType NewResultType = Context.getObjCObjectPointerType( 1489 Context.getObjCInterfaceType(MD->getClassInterface())); 1490 if (auto Nullability = resultType->getNullability(Context)) 1491 NewResultType = Context.getAttributedType( 1492 AttributedType::getNullabilityAttrKind(*Nullability), 1493 NewResultType, NewResultType); 1494 return NewResultType; 1495 } 1496 } 1497 return resultType; 1498 } 1499 1500 // There is nothing left to do if the result type cannot have a nullability 1501 // specifier. 1502 if (!resultType->canHaveNullability()) 1503 return resultType; 1504 1505 // Map the nullability of the result into a table index. 1506 unsigned receiverNullabilityIdx = 0; 1507 if (auto nullability = ReceiverType->getNullability(Context)) 1508 receiverNullabilityIdx = 1 + static_cast<unsigned>(*nullability); 1509 1510 unsigned resultNullabilityIdx = 0; 1511 if (auto nullability = resultType->getNullability(Context)) 1512 resultNullabilityIdx = 1 + static_cast<unsigned>(*nullability); 1513 1514 // The table of nullability mappings, indexed by the receiver's nullability 1515 // and then the result type's nullability. 1516 static const uint8_t None = 0; 1517 static const uint8_t NonNull = 1; 1518 static const uint8_t Nullable = 2; 1519 static const uint8_t Unspecified = 3; 1520 static const uint8_t nullabilityMap[4][4] = { 1521 // None NonNull Nullable Unspecified 1522 /* None */ { None, None, Nullable, None }, 1523 /* NonNull */ { None, NonNull, Nullable, Unspecified }, 1524 /* Nullable */ { Nullable, Nullable, Nullable, Nullable }, 1525 /* Unspecified */ { None, Unspecified, Nullable, Unspecified } 1526 }; 1527 1528 unsigned newResultNullabilityIdx 1529 = nullabilityMap[receiverNullabilityIdx][resultNullabilityIdx]; 1530 if (newResultNullabilityIdx == resultNullabilityIdx) 1531 return resultType; 1532 1533 // Strip off the existing nullability. This removes as little type sugar as 1534 // possible. 1535 do { 1536 if (auto attributed = dyn_cast<AttributedType>(resultType.getTypePtr())) { 1537 resultType = attributed->getModifiedType(); 1538 } else { 1539 resultType = resultType.getDesugaredType(Context); 1540 } 1541 } while (resultType->getNullability(Context)); 1542 1543 // Add nullability back if needed. 1544 if (newResultNullabilityIdx > 0) { 1545 auto newNullability 1546 = static_cast<NullabilityKind>(newResultNullabilityIdx-1); 1547 return Context.getAttributedType( 1548 AttributedType::getNullabilityAttrKind(newNullability), 1549 resultType, resultType); 1550 } 1551 1552 return resultType; 1553 } 1554 1555 /// Look for an ObjC method whose result type exactly matches the given type. 1556 static const ObjCMethodDecl * 1557 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, 1558 QualType instancetype) { 1559 if (MD->getReturnType() == instancetype) 1560 return MD; 1561 1562 // For these purposes, a method in an @implementation overrides a 1563 // declaration in the @interface. 1564 if (const ObjCImplDecl *impl = 1565 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { 1566 const ObjCContainerDecl *iface; 1567 if (const ObjCCategoryImplDecl *catImpl = 1568 dyn_cast<ObjCCategoryImplDecl>(impl)) { 1569 iface = catImpl->getCategoryDecl(); 1570 } else { 1571 iface = impl->getClassInterface(); 1572 } 1573 1574 const ObjCMethodDecl *ifaceMD = 1575 iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); 1576 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); 1577 } 1578 1579 SmallVector<const ObjCMethodDecl *, 4> overrides; 1580 MD->getOverriddenMethods(overrides); 1581 for (unsigned i = 0, e = overrides.size(); i != e; ++i) { 1582 if (const ObjCMethodDecl *result = 1583 findExplicitInstancetypeDeclarer(overrides[i], instancetype)) 1584 return result; 1585 } 1586 1587 return nullptr; 1588 } 1589 1590 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) { 1591 // Only complain if we're in an ObjC method and the required return 1592 // type doesn't match the method's declared return type. 1593 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext); 1594 if (!MD || !MD->hasRelatedResultType() || 1595 Context.hasSameUnqualifiedType(destType, MD->getReturnType())) 1596 return; 1597 1598 // Look for a method overridden by this method which explicitly uses 1599 // 'instancetype'. 1600 if (const ObjCMethodDecl *overridden = 1601 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) { 1602 SourceRange range = overridden->getReturnTypeSourceRange(); 1603 SourceLocation loc = range.getBegin(); 1604 if (loc.isInvalid()) 1605 loc = overridden->getLocation(); 1606 Diag(loc, diag::note_related_result_type_explicit) 1607 << /*current method*/ 1 << range; 1608 return; 1609 } 1610 1611 // Otherwise, if we have an interesting method family, note that. 1612 // This should always trigger if the above didn't. 1613 if (ObjCMethodFamily family = MD->getMethodFamily()) 1614 Diag(MD->getLocation(), diag::note_related_result_type_family) 1615 << /*current method*/ 1 1616 << family; 1617 } 1618 1619 void Sema::EmitRelatedResultTypeNote(const Expr *E) { 1620 E = E->IgnoreParenImpCasts(); 1621 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); 1622 if (!MsgSend) 1623 return; 1624 1625 const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); 1626 if (!Method) 1627 return; 1628 1629 if (!Method->hasRelatedResultType()) 1630 return; 1631 1632 if (Context.hasSameUnqualifiedType( 1633 Method->getReturnType().getNonReferenceType(), MsgSend->getType())) 1634 return; 1635 1636 if (!Context.hasSameUnqualifiedType(Method->getReturnType(), 1637 Context.getObjCInstanceType())) 1638 return; 1639 1640 Diag(Method->getLocation(), diag::note_related_result_type_inferred) 1641 << Method->isInstanceMethod() << Method->getSelector() 1642 << MsgSend->getType(); 1643 } 1644 1645 bool Sema::CheckMessageArgumentTypes( 1646 const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, 1647 Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, 1648 bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, 1649 SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, 1650 ExprValueKind &VK) { 1651 SourceLocation SelLoc; 1652 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 1653 SelLoc = SelectorLocs.front(); 1654 else 1655 SelLoc = lbrac; 1656 1657 if (!Method) { 1658 // Apply default argument promotion as for (C99 6.5.2.2p6). 1659 for (unsigned i = 0, e = Args.size(); i != e; i++) { 1660 if (Args[i]->isTypeDependent()) 1661 continue; 1662 1663 ExprResult result; 1664 if (getLangOpts().DebuggerSupport) { 1665 QualType paramTy; // ignored 1666 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy); 1667 } else { 1668 result = DefaultArgumentPromotion(Args[i]); 1669 } 1670 if (result.isInvalid()) 1671 return true; 1672 Args[i] = result.get(); 1673 } 1674 1675 unsigned DiagID; 1676 if (getLangOpts().ObjCAutoRefCount) 1677 DiagID = diag::err_arc_method_not_found; 1678 else 1679 DiagID = isClassMessage ? diag::warn_class_method_not_found 1680 : diag::warn_inst_method_not_found; 1681 if (!getLangOpts().DebuggerSupport) { 1682 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType); 1683 if (OMD && !OMD->isInvalidDecl()) { 1684 if (getLangOpts().ObjCAutoRefCount) 1685 DiagID = diag::err_method_not_found_with_typo; 1686 else 1687 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo 1688 : diag::warn_instance_method_not_found_with_typo; 1689 Selector MatchedSel = OMD->getSelector(); 1690 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back()); 1691 if (MatchedSel.isUnarySelector()) 1692 Diag(SelLoc, DiagID) 1693 << Sel<< isClassMessage << MatchedSel 1694 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 1695 else 1696 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel; 1697 } 1698 else 1699 Diag(SelLoc, DiagID) 1700 << Sel << isClassMessage << SourceRange(SelectorLocs.front(), 1701 SelectorLocs.back()); 1702 // Find the class to which we are sending this message. 1703 if (auto *ObjPT = ReceiverType->getAs<ObjCObjectPointerType>()) { 1704 if (ObjCInterfaceDecl *ThisClass = ObjPT->getInterfaceDecl()) { 1705 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared); 1706 if (!RecRange.isInvalid()) 1707 if (ThisClass->lookupClassMethod(Sel)) 1708 Diag(RecRange.getBegin(), diag::note_receiver_expr_here) 1709 << FixItHint::CreateReplacement(RecRange, 1710 ThisClass->getNameAsString()); 1711 } 1712 } 1713 } 1714 1715 // In debuggers, we want to use __unknown_anytype for these 1716 // results so that clients can cast them. 1717 if (getLangOpts().DebuggerSupport) { 1718 ReturnType = Context.UnknownAnyTy; 1719 } else { 1720 ReturnType = Context.getObjCIdType(); 1721 } 1722 VK = VK_RValue; 1723 return false; 1724 } 1725 1726 ReturnType = getMessageSendResultType(Receiver, ReceiverType, Method, 1727 isClassMessage, isSuperMessage); 1728 VK = Expr::getValueKindForType(Method->getReturnType()); 1729 1730 unsigned NumNamedArgs = Sel.getNumArgs(); 1731 // Method might have more arguments than selector indicates. This is due 1732 // to addition of c-style arguments in method. 1733 if (Method->param_size() > Sel.getNumArgs()) 1734 NumNamedArgs = Method->param_size(); 1735 // FIXME. This need be cleaned up. 1736 if (Args.size() < NumNamedArgs) { 1737 Diag(SelLoc, diag::err_typecheck_call_too_few_args) 1738 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size()); 1739 return false; 1740 } 1741 1742 // Compute the set of type arguments to be substituted into each parameter 1743 // type. 1744 Optional<ArrayRef<QualType>> typeArgs 1745 = ReceiverType->getObjCSubstitutions(Method->getDeclContext()); 1746 bool IsError = false; 1747 for (unsigned i = 0; i < NumNamedArgs; i++) { 1748 // We can't do any type-checking on a type-dependent argument. 1749 if (Args[i]->isTypeDependent()) 1750 continue; 1751 1752 Expr *argExpr = Args[i]; 1753 1754 ParmVarDecl *param = Method->parameters()[i]; 1755 assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); 1756 1757 if (param->hasAttr<NoEscapeAttr>()) 1758 if (auto *BE = dyn_cast<BlockExpr>( 1759 argExpr->IgnoreParenNoopCasts(Context))) 1760 BE->getBlockDecl()->setDoesNotEscape(); 1761 1762 // Strip the unbridged-cast placeholder expression off unless it's 1763 // a consumed argument. 1764 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 1765 !param->hasAttr<CFConsumedAttr>()) 1766 argExpr = stripARCUnbridgedCast(argExpr); 1767 1768 // If the parameter is __unknown_anytype, infer its type 1769 // from the argument. 1770 if (param->getType() == Context.UnknownAnyTy) { 1771 QualType paramType; 1772 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType); 1773 if (argE.isInvalid()) { 1774 IsError = true; 1775 } else { 1776 Args[i] = argE.get(); 1777 1778 // Update the parameter type in-place. 1779 param->setType(paramType); 1780 } 1781 continue; 1782 } 1783 1784 QualType origParamType = param->getType(); 1785 QualType paramType = param->getType(); 1786 if (typeArgs) 1787 paramType = paramType.substObjCTypeArgs( 1788 Context, 1789 *typeArgs, 1790 ObjCSubstitutionContext::Parameter); 1791 1792 if (RequireCompleteType(argExpr->getSourceRange().getBegin(), 1793 paramType, 1794 diag::err_call_incomplete_argument, argExpr)) 1795 return true; 1796 1797 InitializedEntity Entity 1798 = InitializedEntity::InitializeParameter(Context, param, paramType); 1799 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr); 1800 if (ArgE.isInvalid()) 1801 IsError = true; 1802 else { 1803 Args[i] = ArgE.getAs<Expr>(); 1804 1805 // If we are type-erasing a block to a block-compatible 1806 // Objective-C pointer type, we may need to extend the lifetime 1807 // of the block object. 1808 if (typeArgs && Args[i]->isRValue() && paramType->isBlockPointerType() && 1809 Args[i]->getType()->isBlockPointerType() && 1810 origParamType->isObjCObjectPointerType()) { 1811 ExprResult arg = Args[i]; 1812 maybeExtendBlockObject(arg); 1813 Args[i] = arg.get(); 1814 } 1815 } 1816 } 1817 1818 // Promote additional arguments to variadic methods. 1819 if (Method->isVariadic()) { 1820 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 1821 if (Args[i]->isTypeDependent()) 1822 continue; 1823 1824 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 1825 nullptr); 1826 IsError |= Arg.isInvalid(); 1827 Args[i] = Arg.get(); 1828 } 1829 } else { 1830 // Check for extra arguments to non-variadic methods. 1831 if (Args.size() != NumNamedArgs) { 1832 Diag(Args[NumNamedArgs]->getBeginLoc(), 1833 diag::err_typecheck_call_too_many_args) 1834 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size()) 1835 << Method->getSourceRange() 1836 << SourceRange(Args[NumNamedArgs]->getBeginLoc(), 1837 Args.back()->getEndLoc()); 1838 } 1839 } 1840 1841 DiagnoseSentinelCalls(Method, SelLoc, Args); 1842 1843 // Do additional checkings on method. 1844 IsError |= CheckObjCMethodCall( 1845 Method, SelLoc, makeArrayRef(Args.data(), Args.size())); 1846 1847 return IsError; 1848 } 1849 1850 bool Sema::isSelfExpr(Expr *RExpr) { 1851 // 'self' is objc 'self' in an objc method only. 1852 ObjCMethodDecl *Method = 1853 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor()); 1854 return isSelfExpr(RExpr, Method); 1855 } 1856 1857 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) { 1858 if (!method) return false; 1859 1860 receiver = receiver->IgnoreParenLValueCasts(); 1861 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver)) 1862 if (DRE->getDecl() == method->getSelfDecl()) 1863 return true; 1864 return false; 1865 } 1866 1867 /// LookupMethodInType - Look up a method in an ObjCObjectType. 1868 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, 1869 bool isInstance) { 1870 const ObjCObjectType *objType = type->castAs<ObjCObjectType>(); 1871 if (ObjCInterfaceDecl *iface = objType->getInterface()) { 1872 // Look it up in the main interface (and categories, etc.) 1873 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance)) 1874 return method; 1875 1876 // Okay, look for "private" methods declared in any 1877 // @implementations we've seen. 1878 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance)) 1879 return method; 1880 } 1881 1882 // Check qualifiers. 1883 for (const auto *I : objType->quals()) 1884 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance)) 1885 return method; 1886 1887 return nullptr; 1888 } 1889 1890 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier 1891 /// list of a qualified objective pointer type. 1892 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, 1893 const ObjCObjectPointerType *OPT, 1894 bool Instance) 1895 { 1896 ObjCMethodDecl *MD = nullptr; 1897 for (const auto *PROTO : OPT->quals()) { 1898 if ((MD = PROTO->lookupMethod(Sel, Instance))) { 1899 return MD; 1900 } 1901 } 1902 return nullptr; 1903 } 1904 1905 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an 1906 /// objective C interface. This is a property reference expression. 1907 ExprResult Sema:: 1908 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 1909 Expr *BaseExpr, SourceLocation OpLoc, 1910 DeclarationName MemberName, 1911 SourceLocation MemberLoc, 1912 SourceLocation SuperLoc, QualType SuperType, 1913 bool Super) { 1914 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 1915 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 1916 1917 if (!MemberName.isIdentifier()) { 1918 Diag(MemberLoc, diag::err_invalid_property_name) 1919 << MemberName << QualType(OPT, 0); 1920 return ExprError(); 1921 } 1922 1923 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1924 1925 SourceRange BaseRange = Super? SourceRange(SuperLoc) 1926 : BaseExpr->getSourceRange(); 1927 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), 1928 diag::err_property_not_found_forward_class, 1929 MemberName, BaseRange)) 1930 return ExprError(); 1931 1932 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration( 1933 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 1934 // Check whether we can reference this property. 1935 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1936 return ExprError(); 1937 if (Super) 1938 return new (Context) 1939 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 1940 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); 1941 else 1942 return new (Context) 1943 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 1944 OK_ObjCProperty, MemberLoc, BaseExpr); 1945 } 1946 // Check protocols on qualified interfaces. 1947 for (const auto *I : OPT->quals()) 1948 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration( 1949 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 1950 // Check whether we can reference this property. 1951 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1952 return ExprError(); 1953 1954 if (Super) 1955 return new (Context) ObjCPropertyRefExpr( 1956 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, 1957 SuperLoc, SuperType); 1958 else 1959 return new (Context) 1960 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 1961 OK_ObjCProperty, MemberLoc, BaseExpr); 1962 } 1963 // If that failed, look for an "implicit" property by seeing if the nullary 1964 // selector is implemented. 1965 1966 // FIXME: The logic for looking up nullary and unary selectors should be 1967 // shared with the code in ActOnInstanceMessage. 1968 1969 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1970 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 1971 1972 // May be found in property's qualified list. 1973 if (!Getter) 1974 Getter = LookupMethodInQualifiedType(Sel, OPT, true); 1975 1976 // If this reference is in an @implementation, check for 'private' methods. 1977 if (!Getter) 1978 Getter = IFace->lookupPrivateMethod(Sel); 1979 1980 if (Getter) { 1981 // Check if we can reference this property. 1982 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1983 return ExprError(); 1984 } 1985 // If we found a getter then this may be a valid dot-reference, we 1986 // will look for the matching setter, in case it is needed. 1987 Selector SetterSel = 1988 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1989 PP.getSelectorTable(), Member); 1990 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 1991 1992 // May be found in property's qualified list. 1993 if (!Setter) 1994 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); 1995 1996 if (!Setter) { 1997 // If this reference is in an @implementation, also check for 'private' 1998 // methods. 1999 Setter = IFace->lookupPrivateMethod(SetterSel); 2000 } 2001 2002 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 2003 return ExprError(); 2004 2005 // Special warning if member name used in a property-dot for a setter accessor 2006 // does not use a property with same name; e.g. obj.X = ... for a property with 2007 // name 'x'. 2008 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor() && 2009 !IFace->FindPropertyDeclaration( 2010 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { 2011 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) { 2012 // Do not warn if user is using property-dot syntax to make call to 2013 // user named setter. 2014 if (!(PDecl->getPropertyAttributes() & 2015 ObjCPropertyAttribute::kind_setter)) 2016 Diag(MemberLoc, 2017 diag::warn_property_access_suggest) 2018 << MemberName << QualType(OPT, 0) << PDecl->getName() 2019 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName()); 2020 } 2021 } 2022 2023 if (Getter || Setter) { 2024 if (Super) 2025 return new (Context) 2026 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 2027 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); 2028 else 2029 return new (Context) 2030 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 2031 OK_ObjCProperty, MemberLoc, BaseExpr); 2032 2033 } 2034 2035 // Attempt to correct for typos in property names. 2036 DeclFilterCCC<ObjCPropertyDecl> CCC{}; 2037 if (TypoCorrection Corrected = CorrectTypo( 2038 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, 2039 nullptr, nullptr, CCC, CTK_ErrorRecovery, IFace, false, OPT)) { 2040 DeclarationName TypoResult = Corrected.getCorrection(); 2041 if (TypoResult.isIdentifier() && 2042 TypoResult.getAsIdentifierInfo() == Member) { 2043 // There is no need to try the correction if it is the same. 2044 NamedDecl *ChosenDecl = 2045 Corrected.isKeyword() ? nullptr : Corrected.getFoundDecl(); 2046 if (ChosenDecl && isa<ObjCPropertyDecl>(ChosenDecl)) 2047 if (cast<ObjCPropertyDecl>(ChosenDecl)->isClassProperty()) { 2048 // This is a class property, we should not use the instance to 2049 // access it. 2050 Diag(MemberLoc, diag::err_class_property_found) << MemberName 2051 << OPT->getInterfaceDecl()->getName() 2052 << FixItHint::CreateReplacement(BaseExpr->getSourceRange(), 2053 OPT->getInterfaceDecl()->getName()); 2054 return ExprError(); 2055 } 2056 } else { 2057 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest) 2058 << MemberName << QualType(OPT, 0)); 2059 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc, 2060 TypoResult, MemberLoc, 2061 SuperLoc, SuperType, Super); 2062 } 2063 } 2064 ObjCInterfaceDecl *ClassDeclared; 2065 if (ObjCIvarDecl *Ivar = 2066 IFace->lookupInstanceVariable(Member, ClassDeclared)) { 2067 QualType T = Ivar->getType(); 2068 if (const ObjCObjectPointerType * OBJPT = 2069 T->getAsObjCInterfacePointerType()) { 2070 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), 2071 diag::err_property_not_as_forward_class, 2072 MemberName, BaseExpr)) 2073 return ExprError(); 2074 } 2075 Diag(MemberLoc, 2076 diag::err_ivar_access_using_property_syntax_suggest) 2077 << MemberName << QualType(OPT, 0) << Ivar->getDeclName() 2078 << FixItHint::CreateReplacement(OpLoc, "->"); 2079 return ExprError(); 2080 } 2081 2082 Diag(MemberLoc, diag::err_property_not_found) 2083 << MemberName << QualType(OPT, 0); 2084 if (Setter) 2085 Diag(Setter->getLocation(), diag::note_getter_unavailable) 2086 << MemberName << BaseExpr->getSourceRange(); 2087 return ExprError(); 2088 } 2089 2090 ExprResult Sema:: 2091 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 2092 IdentifierInfo &propertyName, 2093 SourceLocation receiverNameLoc, 2094 SourceLocation propertyNameLoc) { 2095 2096 IdentifierInfo *receiverNamePtr = &receiverName; 2097 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr, 2098 receiverNameLoc); 2099 2100 QualType SuperType; 2101 if (!IFace) { 2102 // If the "receiver" is 'super' in a method, handle it as an expression-like 2103 // property reference. 2104 if (receiverNamePtr->isStr("super")) { 2105 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) { 2106 if (auto classDecl = CurMethod->getClassInterface()) { 2107 SuperType = QualType(classDecl->getSuperClassType(), 0); 2108 if (CurMethod->isInstanceMethod()) { 2109 if (SuperType.isNull()) { 2110 // The current class does not have a superclass. 2111 Diag(receiverNameLoc, diag::err_root_class_cannot_use_super) 2112 << CurMethod->getClassInterface()->getIdentifier(); 2113 return ExprError(); 2114 } 2115 QualType T = Context.getObjCObjectPointerType(SuperType); 2116 2117 return HandleExprPropertyRefExpr(T->castAs<ObjCObjectPointerType>(), 2118 /*BaseExpr*/nullptr, 2119 SourceLocation()/*OpLoc*/, 2120 &propertyName, 2121 propertyNameLoc, 2122 receiverNameLoc, T, true); 2123 } 2124 2125 // Otherwise, if this is a class method, try dispatching to our 2126 // superclass. 2127 IFace = CurMethod->getClassInterface()->getSuperClass(); 2128 } 2129 } 2130 } 2131 2132 if (!IFace) { 2133 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier 2134 << tok::l_paren; 2135 return ExprError(); 2136 } 2137 } 2138 2139 Selector GetterSel; 2140 Selector SetterSel; 2141 if (auto PD = IFace->FindPropertyDeclaration( 2142 &propertyName, ObjCPropertyQueryKind::OBJC_PR_query_class)) { 2143 GetterSel = PD->getGetterName(); 2144 SetterSel = PD->getSetterName(); 2145 } else { 2146 GetterSel = PP.getSelectorTable().getNullarySelector(&propertyName); 2147 SetterSel = SelectorTable::constructSetterSelector( 2148 PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName); 2149 } 2150 2151 // Search for a declared property first. 2152 ObjCMethodDecl *Getter = IFace->lookupClassMethod(GetterSel); 2153 2154 // If this reference is in an @implementation, check for 'private' methods. 2155 if (!Getter) 2156 Getter = IFace->lookupPrivateClassMethod(GetterSel); 2157 2158 if (Getter) { 2159 // FIXME: refactor/share with ActOnMemberReference(). 2160 // Check if we can reference this property. 2161 if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) 2162 return ExprError(); 2163 } 2164 2165 // Look for the matching setter, in case it is needed. 2166 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 2167 if (!Setter) { 2168 // If this reference is in an @implementation, also check for 'private' 2169 // methods. 2170 Setter = IFace->lookupPrivateClassMethod(SetterSel); 2171 } 2172 // Look through local category implementations associated with the class. 2173 if (!Setter) 2174 Setter = IFace->getCategoryClassMethod(SetterSel); 2175 2176 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) 2177 return ExprError(); 2178 2179 if (Getter || Setter) { 2180 if (!SuperType.isNull()) 2181 return new (Context) 2182 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 2183 OK_ObjCProperty, propertyNameLoc, receiverNameLoc, 2184 SuperType); 2185 2186 return new (Context) ObjCPropertyRefExpr( 2187 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, 2188 propertyNameLoc, receiverNameLoc, IFace); 2189 } 2190 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) 2191 << &propertyName << Context.getObjCInterfaceType(IFace)); 2192 } 2193 2194 namespace { 2195 2196 class ObjCInterfaceOrSuperCCC final : public CorrectionCandidateCallback { 2197 public: 2198 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) { 2199 // Determine whether "super" is acceptable in the current context. 2200 if (Method && Method->getClassInterface()) 2201 WantObjCSuper = Method->getClassInterface()->getSuperClass(); 2202 } 2203 2204 bool ValidateCandidate(const TypoCorrection &candidate) override { 2205 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() || 2206 candidate.isKeyword("super"); 2207 } 2208 2209 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2210 return std::make_unique<ObjCInterfaceOrSuperCCC>(*this); 2211 } 2212 }; 2213 2214 } // end anonymous namespace 2215 2216 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, 2217 IdentifierInfo *Name, 2218 SourceLocation NameLoc, 2219 bool IsSuper, 2220 bool HasTrailingDot, 2221 ParsedType &ReceiverType) { 2222 ReceiverType = nullptr; 2223 2224 // If the identifier is "super" and there is no trailing dot, we're 2225 // messaging super. If the identifier is "super" and there is a 2226 // trailing dot, it's an instance message. 2227 if (IsSuper && S->isInObjcMethodScope()) 2228 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; 2229 2230 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 2231 LookupName(Result, S); 2232 2233 switch (Result.getResultKind()) { 2234 case LookupResult::NotFound: 2235 // Normal name lookup didn't find anything. If we're in an 2236 // Objective-C method, look for ivars. If we find one, we're done! 2237 // FIXME: This is a hack. Ivar lookup should be part of normal 2238 // lookup. 2239 if (ObjCMethodDecl *Method = getCurMethodDecl()) { 2240 if (!Method->getClassInterface()) { 2241 // Fall back: let the parser try to parse it as an instance message. 2242 return ObjCInstanceMessage; 2243 } 2244 2245 ObjCInterfaceDecl *ClassDeclared; 2246 if (Method->getClassInterface()->lookupInstanceVariable(Name, 2247 ClassDeclared)) 2248 return ObjCInstanceMessage; 2249 } 2250 2251 // Break out; we'll perform typo correction below. 2252 break; 2253 2254 case LookupResult::NotFoundInCurrentInstantiation: 2255 case LookupResult::FoundOverloaded: 2256 case LookupResult::FoundUnresolvedValue: 2257 case LookupResult::Ambiguous: 2258 Result.suppressDiagnostics(); 2259 return ObjCInstanceMessage; 2260 2261 case LookupResult::Found: { 2262 // If the identifier is a class or not, and there is a trailing dot, 2263 // it's an instance message. 2264 if (HasTrailingDot) 2265 return ObjCInstanceMessage; 2266 // We found something. If it's a type, then we have a class 2267 // message. Otherwise, it's an instance message. 2268 NamedDecl *ND = Result.getFoundDecl(); 2269 QualType T; 2270 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) 2271 T = Context.getObjCInterfaceType(Class); 2272 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) { 2273 T = Context.getTypeDeclType(Type); 2274 DiagnoseUseOfDecl(Type, NameLoc); 2275 } 2276 else 2277 return ObjCInstanceMessage; 2278 2279 // We have a class message, and T is the type we're 2280 // messaging. Build source-location information for it. 2281 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 2282 ReceiverType = CreateParsedType(T, TSInfo); 2283 return ObjCClassMessage; 2284 } 2285 } 2286 2287 ObjCInterfaceOrSuperCCC CCC(getCurMethodDecl()); 2288 if (TypoCorrection Corrected = CorrectTypo( 2289 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr, CCC, 2290 CTK_ErrorRecovery, nullptr, false, nullptr, false)) { 2291 if (Corrected.isKeyword()) { 2292 // If we've found the keyword "super" (the only keyword that would be 2293 // returned by CorrectTypo), this is a send to super. 2294 diagnoseTypo(Corrected, 2295 PDiag(diag::err_unknown_receiver_suggest) << Name); 2296 return ObjCSuperMessage; 2297 } else if (ObjCInterfaceDecl *Class = 2298 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 2299 // If we found a declaration, correct when it refers to an Objective-C 2300 // class. 2301 diagnoseTypo(Corrected, 2302 PDiag(diag::err_unknown_receiver_suggest) << Name); 2303 QualType T = Context.getObjCInterfaceType(Class); 2304 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 2305 ReceiverType = CreateParsedType(T, TSInfo); 2306 return ObjCClassMessage; 2307 } 2308 } 2309 2310 // Fall back: let the parser try to parse it as an instance message. 2311 return ObjCInstanceMessage; 2312 } 2313 2314 ExprResult Sema::ActOnSuperMessage(Scope *S, 2315 SourceLocation SuperLoc, 2316 Selector Sel, 2317 SourceLocation LBracLoc, 2318 ArrayRef<SourceLocation> SelectorLocs, 2319 SourceLocation RBracLoc, 2320 MultiExprArg Args) { 2321 // Determine whether we are inside a method or not. 2322 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc); 2323 if (!Method) { 2324 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super); 2325 return ExprError(); 2326 } 2327 2328 ObjCInterfaceDecl *Class = Method->getClassInterface(); 2329 if (!Class) { 2330 Diag(SuperLoc, diag::err_no_super_class_message) 2331 << Method->getDeclName(); 2332 return ExprError(); 2333 } 2334 2335 QualType SuperTy(Class->getSuperClassType(), 0); 2336 if (SuperTy.isNull()) { 2337 // The current class does not have a superclass. 2338 Diag(SuperLoc, diag::err_root_class_cannot_use_super) 2339 << Class->getIdentifier(); 2340 return ExprError(); 2341 } 2342 2343 // We are in a method whose class has a superclass, so 'super' 2344 // is acting as a keyword. 2345 if (Method->getSelector() == Sel) 2346 getCurFunction()->ObjCShouldCallSuper = false; 2347 2348 if (Method->isInstanceMethod()) { 2349 // Since we are in an instance method, this is an instance 2350 // message to the superclass instance. 2351 SuperTy = Context.getObjCObjectPointerType(SuperTy); 2352 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc, 2353 Sel, /*Method=*/nullptr, 2354 LBracLoc, SelectorLocs, RBracLoc, Args); 2355 } 2356 2357 // Since we are in a class method, this is a class message to 2358 // the superclass. 2359 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr, 2360 SuperTy, 2361 SuperLoc, Sel, /*Method=*/nullptr, 2362 LBracLoc, SelectorLocs, RBracLoc, Args); 2363 } 2364 2365 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType, 2366 bool isSuperReceiver, 2367 SourceLocation Loc, 2368 Selector Sel, 2369 ObjCMethodDecl *Method, 2370 MultiExprArg Args) { 2371 TypeSourceInfo *receiverTypeInfo = nullptr; 2372 if (!ReceiverType.isNull()) 2373 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType); 2374 2375 return BuildClassMessage(receiverTypeInfo, ReceiverType, 2376 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(), 2377 Sel, Method, Loc, Loc, Loc, Args, 2378 /*isImplicit=*/true); 2379 } 2380 2381 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg, 2382 unsigned DiagID, 2383 bool (*refactor)(const ObjCMessageExpr *, 2384 const NSAPI &, edit::Commit &)) { 2385 SourceLocation MsgLoc = Msg->getExprLoc(); 2386 if (S.Diags.isIgnored(DiagID, MsgLoc)) 2387 return; 2388 2389 SourceManager &SM = S.SourceMgr; 2390 edit::Commit ECommit(SM, S.LangOpts); 2391 if (refactor(Msg,*S.NSAPIObj, ECommit)) { 2392 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID) 2393 << Msg->getSelector() << Msg->getSourceRange(); 2394 // FIXME: Don't emit diagnostic at all if fixits are non-commitable. 2395 if (!ECommit.isCommitable()) 2396 return; 2397 for (edit::Commit::edit_iterator 2398 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) { 2399 const edit::Commit::Edit &Edit = *I; 2400 switch (Edit.Kind) { 2401 case edit::Commit::Act_Insert: 2402 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc, 2403 Edit.Text, 2404 Edit.BeforePrev)); 2405 break; 2406 case edit::Commit::Act_InsertFromRange: 2407 Builder.AddFixItHint( 2408 FixItHint::CreateInsertionFromRange(Edit.OrigLoc, 2409 Edit.getInsertFromRange(SM), 2410 Edit.BeforePrev)); 2411 break; 2412 case edit::Commit::Act_Remove: 2413 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM))); 2414 break; 2415 } 2416 } 2417 } 2418 } 2419 2420 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) { 2421 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use, 2422 edit::rewriteObjCRedundantCallWithLiteral); 2423 } 2424 2425 static void checkFoundationAPI(Sema &S, SourceLocation Loc, 2426 const ObjCMethodDecl *Method, 2427 ArrayRef<Expr *> Args, QualType ReceiverType, 2428 bool IsClassObjectCall) { 2429 // Check if this is a performSelector method that uses a selector that returns 2430 // a record or a vector type. 2431 if (Method->getSelector().getMethodFamily() != OMF_performSelector || 2432 Args.empty()) 2433 return; 2434 const auto *SE = dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens()); 2435 if (!SE) 2436 return; 2437 ObjCMethodDecl *ImpliedMethod; 2438 if (!IsClassObjectCall) { 2439 const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>(); 2440 if (!OPT || !OPT->getInterfaceDecl()) 2441 return; 2442 ImpliedMethod = 2443 OPT->getInterfaceDecl()->lookupInstanceMethod(SE->getSelector()); 2444 if (!ImpliedMethod) 2445 ImpliedMethod = 2446 OPT->getInterfaceDecl()->lookupPrivateMethod(SE->getSelector()); 2447 } else { 2448 const auto *IT = ReceiverType->getAs<ObjCInterfaceType>(); 2449 if (!IT) 2450 return; 2451 ImpliedMethod = IT->getDecl()->lookupClassMethod(SE->getSelector()); 2452 if (!ImpliedMethod) 2453 ImpliedMethod = 2454 IT->getDecl()->lookupPrivateClassMethod(SE->getSelector()); 2455 } 2456 if (!ImpliedMethod) 2457 return; 2458 QualType Ret = ImpliedMethod->getReturnType(); 2459 if (Ret->isRecordType() || Ret->isVectorType() || Ret->isExtVectorType()) { 2460 S.Diag(Loc, diag::warn_objc_unsafe_perform_selector) 2461 << Method->getSelector() 2462 << (!Ret->isRecordType() 2463 ? /*Vector*/ 2 2464 : Ret->isUnionType() ? /*Union*/ 1 : /*Struct*/ 0); 2465 S.Diag(ImpliedMethod->getBeginLoc(), 2466 diag::note_objc_unsafe_perform_selector_method_declared_here) 2467 << ImpliedMethod->getSelector() << Ret; 2468 } 2469 } 2470 2471 /// Diagnose use of %s directive in an NSString which is being passed 2472 /// as formatting string to formatting method. 2473 static void 2474 DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S, 2475 ObjCMethodDecl *Method, 2476 Selector Sel, 2477 Expr **Args, unsigned NumArgs) { 2478 unsigned Idx = 0; 2479 bool Format = false; 2480 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily(); 2481 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) { 2482 Idx = 0; 2483 Format = true; 2484 } 2485 else if (Method) { 2486 for (const auto *I : Method->specific_attrs<FormatAttr>()) { 2487 if (S.GetFormatNSStringIdx(I, Idx)) { 2488 Format = true; 2489 break; 2490 } 2491 } 2492 } 2493 if (!Format || NumArgs <= Idx) 2494 return; 2495 2496 Expr *FormatExpr = Args[Idx]; 2497 if (ObjCStringLiteral *OSL = 2498 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) { 2499 StringLiteral *FormatString = OSL->getString(); 2500 if (S.FormatStringHasSArg(FormatString)) { 2501 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 2502 << "%s" << 0 << 0; 2503 if (Method) 2504 S.Diag(Method->getLocation(), diag::note_method_declared_at) 2505 << Method->getDeclName(); 2506 } 2507 } 2508 } 2509 2510 /// Build an Objective-C class message expression. 2511 /// 2512 /// This routine takes care of both normal class messages and 2513 /// class messages to the superclass. 2514 /// 2515 /// \param ReceiverTypeInfo Type source information that describes the 2516 /// receiver of this message. This may be NULL, in which case we are 2517 /// sending to the superclass and \p SuperLoc must be a valid source 2518 /// location. 2519 2520 /// \param ReceiverType The type of the object receiving the 2521 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same 2522 /// type as that refers to. For a superclass send, this is the type of 2523 /// the superclass. 2524 /// 2525 /// \param SuperLoc The location of the "super" keyword in a 2526 /// superclass message. 2527 /// 2528 /// \param Sel The selector to which the message is being sent. 2529 /// 2530 /// \param Method The method that this class message is invoking, if 2531 /// already known. 2532 /// 2533 /// \param LBracLoc The location of the opening square bracket ']'. 2534 /// 2535 /// \param RBracLoc The location of the closing square bracket ']'. 2536 /// 2537 /// \param ArgsIn The message arguments. 2538 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 2539 QualType ReceiverType, 2540 SourceLocation SuperLoc, 2541 Selector Sel, 2542 ObjCMethodDecl *Method, 2543 SourceLocation LBracLoc, 2544 ArrayRef<SourceLocation> SelectorLocs, 2545 SourceLocation RBracLoc, 2546 MultiExprArg ArgsIn, 2547 bool isImplicit) { 2548 SourceLocation Loc = SuperLoc.isValid()? SuperLoc 2549 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin(); 2550 if (LBracLoc.isInvalid()) { 2551 Diag(Loc, diag::err_missing_open_square_message_send) 2552 << FixItHint::CreateInsertion(Loc, "["); 2553 LBracLoc = Loc; 2554 } 2555 ArrayRef<SourceLocation> SelectorSlotLocs; 2556 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 2557 SelectorSlotLocs = SelectorLocs; 2558 else 2559 SelectorSlotLocs = Loc; 2560 SourceLocation SelLoc = SelectorSlotLocs.front(); 2561 2562 if (ReceiverType->isDependentType()) { 2563 // If the receiver type is dependent, we can't type-check anything 2564 // at this point. Build a dependent expression. 2565 unsigned NumArgs = ArgsIn.size(); 2566 Expr **Args = ArgsIn.data(); 2567 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 2568 return ObjCMessageExpr::Create( 2569 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel, 2570 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc, 2571 isImplicit); 2572 } 2573 2574 // Find the class to which we are sending this message. 2575 ObjCInterfaceDecl *Class = nullptr; 2576 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); 2577 if (!ClassType || !(Class = ClassType->getInterface())) { 2578 Diag(Loc, diag::err_invalid_receiver_class_message) 2579 << ReceiverType; 2580 return ExprError(); 2581 } 2582 assert(Class && "We don't know which class we're messaging?"); 2583 // objc++ diagnoses during typename annotation. 2584 if (!getLangOpts().CPlusPlus) 2585 (void)DiagnoseUseOfDecl(Class, SelectorSlotLocs); 2586 // Find the method we are messaging. 2587 if (!Method) { 2588 SourceRange TypeRange 2589 = SuperLoc.isValid()? SourceRange(SuperLoc) 2590 : ReceiverTypeInfo->getTypeLoc().getSourceRange(); 2591 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), 2592 (getLangOpts().ObjCAutoRefCount 2593 ? diag::err_arc_receiver_forward_class 2594 : diag::warn_receiver_forward_class), 2595 TypeRange)) { 2596 // A forward class used in messaging is treated as a 'Class' 2597 Method = LookupFactoryMethodInGlobalPool(Sel, 2598 SourceRange(LBracLoc, RBracLoc)); 2599 if (Method && !getLangOpts().ObjCAutoRefCount) 2600 Diag(Method->getLocation(), diag::note_method_sent_forward_class) 2601 << Method->getDeclName(); 2602 } 2603 if (!Method) 2604 Method = Class->lookupClassMethod(Sel); 2605 2606 // If we have an implementation in scope, check "private" methods. 2607 if (!Method) 2608 Method = Class->lookupPrivateClassMethod(Sel); 2609 2610 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, 2611 nullptr, false, false, Class)) 2612 return ExprError(); 2613 } 2614 2615 // Check the argument types and determine the result type. 2616 QualType ReturnType; 2617 ExprValueKind VK = VK_RValue; 2618 2619 unsigned NumArgs = ArgsIn.size(); 2620 Expr **Args = ArgsIn.data(); 2621 if (CheckMessageArgumentTypes(/*Receiver=*/nullptr, ReceiverType, 2622 MultiExprArg(Args, NumArgs), Sel, SelectorLocs, 2623 Method, true, SuperLoc.isValid(), LBracLoc, 2624 RBracLoc, SourceRange(), ReturnType, VK)) 2625 return ExprError(); 2626 2627 if (Method && !Method->getReturnType()->isVoidType() && 2628 RequireCompleteType(LBracLoc, Method->getReturnType(), 2629 diag::err_illegal_message_expr_incomplete_type)) 2630 return ExprError(); 2631 2632 if (Method && Method->isDirectMethod() && SuperLoc.isValid()) { 2633 Diag(SuperLoc, diag::err_messaging_super_with_direct_method) 2634 << FixItHint::CreateReplacement( 2635 SuperLoc, getLangOpts().ObjCAutoRefCount 2636 ? "self" 2637 : Method->getClassInterface()->getName()); 2638 Diag(Method->getLocation(), diag::note_direct_method_declared_at) 2639 << Method->getDeclName(); 2640 } 2641 2642 // Warn about explicit call of +initialize on its own class. But not on 'super'. 2643 if (Method && Method->getMethodFamily() == OMF_initialize) { 2644 if (!SuperLoc.isValid()) { 2645 const ObjCInterfaceDecl *ID = 2646 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()); 2647 if (ID == Class) { 2648 Diag(Loc, diag::warn_direct_initialize_call); 2649 Diag(Method->getLocation(), diag::note_method_declared_at) 2650 << Method->getDeclName(); 2651 } 2652 } 2653 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 2654 // [super initialize] is allowed only within an +initialize implementation 2655 if (CurMeth->getMethodFamily() != OMF_initialize) { 2656 Diag(Loc, diag::warn_direct_super_initialize_call); 2657 Diag(Method->getLocation(), diag::note_method_declared_at) 2658 << Method->getDeclName(); 2659 Diag(CurMeth->getLocation(), diag::note_method_declared_at) 2660 << CurMeth->getDeclName(); 2661 } 2662 } 2663 } 2664 2665 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); 2666 2667 // Construct the appropriate ObjCMessageExpr. 2668 ObjCMessageExpr *Result; 2669 if (SuperLoc.isValid()) 2670 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2671 SuperLoc, /*IsInstanceSuper=*/false, 2672 ReceiverType, Sel, SelectorLocs, 2673 Method, makeArrayRef(Args, NumArgs), 2674 RBracLoc, isImplicit); 2675 else { 2676 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2677 ReceiverTypeInfo, Sel, SelectorLocs, 2678 Method, makeArrayRef(Args, NumArgs), 2679 RBracLoc, isImplicit); 2680 if (!isImplicit) 2681 checkCocoaAPI(*this, Result); 2682 } 2683 if (Method) 2684 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs), 2685 ReceiverType, /*IsClassObjectCall=*/true); 2686 return MaybeBindToTemporary(Result); 2687 } 2688 2689 // ActOnClassMessage - used for both unary and keyword messages. 2690 // ArgExprs is optional - if it is present, the number of expressions 2691 // is obtained from Sel.getNumArgs(). 2692 ExprResult Sema::ActOnClassMessage(Scope *S, 2693 ParsedType Receiver, 2694 Selector Sel, 2695 SourceLocation LBracLoc, 2696 ArrayRef<SourceLocation> SelectorLocs, 2697 SourceLocation RBracLoc, 2698 MultiExprArg Args) { 2699 TypeSourceInfo *ReceiverTypeInfo; 2700 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo); 2701 if (ReceiverType.isNull()) 2702 return ExprError(); 2703 2704 if (!ReceiverTypeInfo) 2705 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); 2706 2707 return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 2708 /*SuperLoc=*/SourceLocation(), Sel, 2709 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, 2710 Args); 2711 } 2712 2713 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver, 2714 QualType ReceiverType, 2715 SourceLocation Loc, 2716 Selector Sel, 2717 ObjCMethodDecl *Method, 2718 MultiExprArg Args) { 2719 return BuildInstanceMessage(Receiver, ReceiverType, 2720 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(), 2721 Sel, Method, Loc, Loc, Loc, Args, 2722 /*isImplicit=*/true); 2723 } 2724 2725 static bool isMethodDeclaredInRootProtocol(Sema &S, const ObjCMethodDecl *M) { 2726 if (!S.NSAPIObj) 2727 return false; 2728 const auto *Protocol = dyn_cast<ObjCProtocolDecl>(M->getDeclContext()); 2729 if (!Protocol) 2730 return false; 2731 const IdentifierInfo *II = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject); 2732 if (const auto *RootClass = dyn_cast_or_null<ObjCInterfaceDecl>( 2733 S.LookupSingleName(S.TUScope, II, Protocol->getBeginLoc(), 2734 Sema::LookupOrdinaryName))) { 2735 for (const ObjCProtocolDecl *P : RootClass->all_referenced_protocols()) { 2736 if (P->getCanonicalDecl() == Protocol->getCanonicalDecl()) 2737 return true; 2738 } 2739 } 2740 return false; 2741 } 2742 2743 /// Build an Objective-C instance message expression. 2744 /// 2745 /// This routine takes care of both normal instance messages and 2746 /// instance messages to the superclass instance. 2747 /// 2748 /// \param Receiver The expression that computes the object that will 2749 /// receive this message. This may be empty, in which case we are 2750 /// sending to the superclass instance and \p SuperLoc must be a valid 2751 /// source location. 2752 /// 2753 /// \param ReceiverType The (static) type of the object receiving the 2754 /// message. When a \p Receiver expression is provided, this is the 2755 /// same type as that expression. For a superclass instance send, this 2756 /// is a pointer to the type of the superclass. 2757 /// 2758 /// \param SuperLoc The location of the "super" keyword in a 2759 /// superclass instance message. 2760 /// 2761 /// \param Sel The selector to which the message is being sent. 2762 /// 2763 /// \param Method The method that this instance message is invoking, if 2764 /// already known. 2765 /// 2766 /// \param LBracLoc The location of the opening square bracket ']'. 2767 /// 2768 /// \param RBracLoc The location of the closing square bracket ']'. 2769 /// 2770 /// \param ArgsIn The message arguments. 2771 ExprResult Sema::BuildInstanceMessage(Expr *Receiver, 2772 QualType ReceiverType, 2773 SourceLocation SuperLoc, 2774 Selector Sel, 2775 ObjCMethodDecl *Method, 2776 SourceLocation LBracLoc, 2777 ArrayRef<SourceLocation> SelectorLocs, 2778 SourceLocation RBracLoc, 2779 MultiExprArg ArgsIn, 2780 bool isImplicit) { 2781 assert((Receiver || SuperLoc.isValid()) && "If the Receiver is null, the " 2782 "SuperLoc must be valid so we can " 2783 "use it instead."); 2784 2785 // The location of the receiver. 2786 SourceLocation Loc = SuperLoc.isValid() ? SuperLoc : Receiver->getBeginLoc(); 2787 SourceRange RecRange = 2788 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange(); 2789 ArrayRef<SourceLocation> SelectorSlotLocs; 2790 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 2791 SelectorSlotLocs = SelectorLocs; 2792 else 2793 SelectorSlotLocs = Loc; 2794 SourceLocation SelLoc = SelectorSlotLocs.front(); 2795 2796 if (LBracLoc.isInvalid()) { 2797 Diag(Loc, diag::err_missing_open_square_message_send) 2798 << FixItHint::CreateInsertion(Loc, "["); 2799 LBracLoc = Loc; 2800 } 2801 2802 // If we have a receiver expression, perform appropriate promotions 2803 // and determine receiver type. 2804 if (Receiver) { 2805 if (Receiver->hasPlaceholderType()) { 2806 ExprResult Result; 2807 if (Receiver->getType() == Context.UnknownAnyTy) 2808 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType()); 2809 else 2810 Result = CheckPlaceholderExpr(Receiver); 2811 if (Result.isInvalid()) return ExprError(); 2812 Receiver = Result.get(); 2813 } 2814 2815 if (Receiver->isTypeDependent()) { 2816 // If the receiver is type-dependent, we can't type-check anything 2817 // at this point. Build a dependent expression. 2818 unsigned NumArgs = ArgsIn.size(); 2819 Expr **Args = ArgsIn.data(); 2820 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 2821 return ObjCMessageExpr::Create( 2822 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel, 2823 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), 2824 RBracLoc, isImplicit); 2825 } 2826 2827 // If necessary, apply function/array conversion to the receiver. 2828 // C99 6.7.5.3p[7,8]. 2829 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver); 2830 if (Result.isInvalid()) 2831 return ExprError(); 2832 Receiver = Result.get(); 2833 ReceiverType = Receiver->getType(); 2834 2835 // If the receiver is an ObjC pointer, a block pointer, or an 2836 // __attribute__((NSObject)) pointer, we don't need to do any 2837 // special conversion in order to look up a receiver. 2838 if (ReceiverType->isObjCRetainableType()) { 2839 // do nothing 2840 } else if (!getLangOpts().ObjCAutoRefCount && 2841 !Context.getObjCIdType().isNull() && 2842 (ReceiverType->isPointerType() || 2843 ReceiverType->isIntegerType())) { 2844 // Implicitly convert integers and pointers to 'id' but emit a warning. 2845 // But not in ARC. 2846 Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << RecRange; 2847 if (ReceiverType->isPointerType()) { 2848 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 2849 CK_CPointerToObjCPointerCast).get(); 2850 } else { 2851 // TODO: specialized warning on null receivers? 2852 bool IsNull = Receiver->isNullPointerConstant(Context, 2853 Expr::NPC_ValueDependentIsNull); 2854 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer; 2855 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 2856 Kind).get(); 2857 } 2858 ReceiverType = Receiver->getType(); 2859 } else if (getLangOpts().CPlusPlus) { 2860 // The receiver must be a complete type. 2861 if (RequireCompleteType(Loc, Receiver->getType(), 2862 diag::err_incomplete_receiver_type)) 2863 return ExprError(); 2864 2865 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver); 2866 if (result.isUsable()) { 2867 Receiver = result.get(); 2868 ReceiverType = Receiver->getType(); 2869 } 2870 } 2871 } 2872 2873 // There's a somewhat weird interaction here where we assume that we 2874 // won't actually have a method unless we also don't need to do some 2875 // of the more detailed type-checking on the receiver. 2876 2877 if (!Method) { 2878 // Handle messages to id and __kindof types (where we use the 2879 // global method pool). 2880 const ObjCObjectType *typeBound = nullptr; 2881 bool receiverIsIdLike = ReceiverType->isObjCIdOrObjectKindOfType(Context, 2882 typeBound); 2883 if (receiverIsIdLike || ReceiverType->isBlockPointerType() || 2884 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) { 2885 SmallVector<ObjCMethodDecl*, 4> Methods; 2886 // If we have a type bound, further filter the methods. 2887 CollectMultipleMethodsInGlobalPool(Sel, Methods, true/*InstanceFirst*/, 2888 true/*CheckTheOther*/, typeBound); 2889 if (!Methods.empty()) { 2890 // We choose the first method as the initial candidate, then try to 2891 // select a better one. 2892 Method = Methods[0]; 2893 2894 if (ObjCMethodDecl *BestMethod = 2895 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), Methods)) 2896 Method = BestMethod; 2897 2898 if (!AreMultipleMethodsInGlobalPool(Sel, Method, 2899 SourceRange(LBracLoc, RBracLoc), 2900 receiverIsIdLike, Methods)) 2901 DiagnoseUseOfDecl(Method, SelectorSlotLocs); 2902 } 2903 } else if (ReceiverType->isObjCClassOrClassKindOfType() || 2904 ReceiverType->isObjCQualifiedClassType()) { 2905 // Handle messages to Class. 2906 // We allow sending a message to a qualified Class ("Class<foo>"), which 2907 // is ok as long as one of the protocols implements the selector (if not, 2908 // warn). 2909 if (!ReceiverType->isObjCClassOrClassKindOfType()) { 2910 const ObjCObjectPointerType *QClassTy 2911 = ReceiverType->getAsObjCQualifiedClassType(); 2912 // Search protocols for class methods. 2913 Method = LookupMethodInQualifiedType(Sel, QClassTy, false); 2914 if (!Method) { 2915 Method = LookupMethodInQualifiedType(Sel, QClassTy, true); 2916 // warn if instance method found for a Class message. 2917 if (Method && !isMethodDeclaredInRootProtocol(*this, Method)) { 2918 Diag(SelLoc, diag::warn_instance_method_on_class_found) 2919 << Method->getSelector() << Sel; 2920 Diag(Method->getLocation(), diag::note_method_declared_at) 2921 << Method->getDeclName(); 2922 } 2923 } 2924 } else { 2925 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 2926 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { 2927 // As a guess, try looking for the method in the current interface. 2928 // This very well may not produce the "right" method. 2929 2930 // First check the public methods in the class interface. 2931 Method = ClassDecl->lookupClassMethod(Sel); 2932 2933 if (!Method) 2934 Method = ClassDecl->lookupPrivateClassMethod(Sel); 2935 2936 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs)) 2937 return ExprError(); 2938 } 2939 } 2940 if (!Method) { 2941 // If not messaging 'self', look for any factory method named 'Sel'. 2942 if (!Receiver || !isSelfExpr(Receiver)) { 2943 // If no class (factory) method was found, check if an _instance_ 2944 // method of the same name exists in the root class only. 2945 SmallVector<ObjCMethodDecl*, 4> Methods; 2946 CollectMultipleMethodsInGlobalPool(Sel, Methods, 2947 false/*InstanceFirst*/, 2948 true/*CheckTheOther*/); 2949 if (!Methods.empty()) { 2950 // We choose the first method as the initial candidate, then try 2951 // to select a better one. 2952 Method = Methods[0]; 2953 2954 // If we find an instance method, emit warning. 2955 if (Method->isInstanceMethod()) { 2956 if (const ObjCInterfaceDecl *ID = 2957 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { 2958 if (ID->getSuperClass()) 2959 Diag(SelLoc, diag::warn_root_inst_method_not_found) 2960 << Sel << SourceRange(LBracLoc, RBracLoc); 2961 } 2962 } 2963 2964 if (ObjCMethodDecl *BestMethod = 2965 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), 2966 Methods)) 2967 Method = BestMethod; 2968 } 2969 } 2970 } 2971 } 2972 } else { 2973 ObjCInterfaceDecl *ClassDecl = nullptr; 2974 2975 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as 2976 // long as one of the protocols implements the selector (if not, warn). 2977 // And as long as message is not deprecated/unavailable (warn if it is). 2978 if (const ObjCObjectPointerType *QIdTy 2979 = ReceiverType->getAsObjCQualifiedIdType()) { 2980 // Search protocols for instance methods. 2981 Method = LookupMethodInQualifiedType(Sel, QIdTy, true); 2982 if (!Method) 2983 Method = LookupMethodInQualifiedType(Sel, QIdTy, false); 2984 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs)) 2985 return ExprError(); 2986 } else if (const ObjCObjectPointerType *OCIType 2987 = ReceiverType->getAsObjCInterfacePointerType()) { 2988 // We allow sending a message to a pointer to an interface (an object). 2989 ClassDecl = OCIType->getInterfaceDecl(); 2990 2991 // Try to complete the type. Under ARC, this is a hard error from which 2992 // we don't try to recover. 2993 // FIXME: In the non-ARC case, this will still be a hard error if the 2994 // definition is found in a module that's not visible. 2995 const ObjCInterfaceDecl *forwardClass = nullptr; 2996 if (RequireCompleteType(Loc, OCIType->getPointeeType(), 2997 getLangOpts().ObjCAutoRefCount 2998 ? diag::err_arc_receiver_forward_instance 2999 : diag::warn_receiver_forward_instance, 3000 RecRange)) { 3001 if (getLangOpts().ObjCAutoRefCount) 3002 return ExprError(); 3003 3004 forwardClass = OCIType->getInterfaceDecl(); 3005 Diag(Receiver ? Receiver->getBeginLoc() : SuperLoc, 3006 diag::note_receiver_is_id); 3007 Method = nullptr; 3008 } else { 3009 Method = ClassDecl->lookupInstanceMethod(Sel); 3010 } 3011 3012 if (!Method) 3013 // Search protocol qualifiers. 3014 Method = LookupMethodInQualifiedType(Sel, OCIType, true); 3015 3016 if (!Method) { 3017 // If we have implementations in scope, check "private" methods. 3018 Method = ClassDecl->lookupPrivateMethod(Sel); 3019 3020 if (!Method && getLangOpts().ObjCAutoRefCount) { 3021 Diag(SelLoc, diag::err_arc_may_not_respond) 3022 << OCIType->getPointeeType() << Sel << RecRange 3023 << SourceRange(SelectorLocs.front(), SelectorLocs.back()); 3024 return ExprError(); 3025 } 3026 3027 if (!Method && (!Receiver || !isSelfExpr(Receiver))) { 3028 // If we still haven't found a method, look in the global pool. This 3029 // behavior isn't very desirable, however we need it for GCC 3030 // compatibility. FIXME: should we deviate?? 3031 if (OCIType->qual_empty()) { 3032 SmallVector<ObjCMethodDecl*, 4> Methods; 3033 CollectMultipleMethodsInGlobalPool(Sel, Methods, 3034 true/*InstanceFirst*/, 3035 false/*CheckTheOther*/); 3036 if (!Methods.empty()) { 3037 // We choose the first method as the initial candidate, then try 3038 // to select a better one. 3039 Method = Methods[0]; 3040 3041 if (ObjCMethodDecl *BestMethod = 3042 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod(), 3043 Methods)) 3044 Method = BestMethod; 3045 3046 AreMultipleMethodsInGlobalPool(Sel, Method, 3047 SourceRange(LBracLoc, RBracLoc), 3048 true/*receiverIdOrClass*/, 3049 Methods); 3050 } 3051 if (Method && !forwardClass) 3052 Diag(SelLoc, diag::warn_maynot_respond) 3053 << OCIType->getInterfaceDecl()->getIdentifier() 3054 << Sel << RecRange; 3055 } 3056 } 3057 } 3058 if (Method && DiagnoseUseOfDecl(Method, SelectorSlotLocs, forwardClass)) 3059 return ExprError(); 3060 } else { 3061 // Reject other random receiver types (e.g. structs). 3062 Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << RecRange; 3063 return ExprError(); 3064 } 3065 } 3066 } 3067 3068 FunctionScopeInfo *DIFunctionScopeInfo = 3069 (Method && Method->getMethodFamily() == OMF_init) 3070 ? getEnclosingFunction() : nullptr; 3071 3072 if (Method && Method->isDirectMethod()) { 3073 if (ReceiverType->isObjCIdType() && !isImplicit) { 3074 Diag(Receiver->getExprLoc(), 3075 diag::err_messaging_unqualified_id_with_direct_method); 3076 Diag(Method->getLocation(), diag::note_direct_method_declared_at) 3077 << Method->getDeclName(); 3078 } 3079 3080 // Under ARC, self can't be assigned, and doing a direct call to `self` 3081 // when it's a Class is hence safe. For other cases, we can't trust `self` 3082 // is what we think it is, so we reject it. 3083 if (ReceiverType->isObjCClassType() && !isImplicit && 3084 !(Receiver->isObjCSelfExpr() && getLangOpts().ObjCAutoRefCount)) { 3085 { 3086 DiagnosticBuilder Builder = 3087 Diag(Receiver->getExprLoc(), 3088 diag::err_messaging_class_with_direct_method); 3089 if (Receiver->isObjCSelfExpr()) { 3090 Builder.AddFixItHint(FixItHint::CreateReplacement( 3091 RecRange, Method->getClassInterface()->getName())); 3092 } 3093 } 3094 Diag(Method->getLocation(), diag::note_direct_method_declared_at) 3095 << Method->getDeclName(); 3096 } 3097 3098 if (SuperLoc.isValid()) { 3099 { 3100 DiagnosticBuilder Builder = 3101 Diag(SuperLoc, diag::err_messaging_super_with_direct_method); 3102 if (ReceiverType->isObjCClassType()) { 3103 Builder.AddFixItHint(FixItHint::CreateReplacement( 3104 SuperLoc, Method->getClassInterface()->getName())); 3105 } else { 3106 Builder.AddFixItHint(FixItHint::CreateReplacement(SuperLoc, "self")); 3107 } 3108 } 3109 Diag(Method->getLocation(), diag::note_direct_method_declared_at) 3110 << Method->getDeclName(); 3111 } 3112 } else if (ReceiverType->isObjCIdType() && !isImplicit) { 3113 Diag(Receiver->getExprLoc(), diag::warn_messaging_unqualified_id); 3114 } 3115 3116 if (DIFunctionScopeInfo && 3117 DIFunctionScopeInfo->ObjCIsDesignatedInit && 3118 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 3119 bool isDesignatedInitChain = false; 3120 if (SuperLoc.isValid()) { 3121 if (const ObjCObjectPointerType * 3122 OCIType = ReceiverType->getAsObjCInterfacePointerType()) { 3123 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) { 3124 // Either we know this is a designated initializer or we 3125 // conservatively assume it because we don't know for sure. 3126 if (!ID->declaresOrInheritsDesignatedInitializers() || 3127 ID->isDesignatedInitializer(Sel)) { 3128 isDesignatedInitChain = true; 3129 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false; 3130 } 3131 } 3132 } 3133 } 3134 if (!isDesignatedInitChain) { 3135 const ObjCMethodDecl *InitMethod = nullptr; 3136 bool isDesignated = 3137 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod); 3138 assert(isDesignated && InitMethod); 3139 (void)isDesignated; 3140 Diag(SelLoc, SuperLoc.isValid() ? 3141 diag::warn_objc_designated_init_non_designated_init_call : 3142 diag::warn_objc_designated_init_non_super_designated_init_call); 3143 Diag(InitMethod->getLocation(), 3144 diag::note_objc_designated_init_marked_here); 3145 } 3146 } 3147 3148 if (DIFunctionScopeInfo && 3149 DIFunctionScopeInfo->ObjCIsSecondaryInit && 3150 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 3151 if (SuperLoc.isValid()) { 3152 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call); 3153 } else { 3154 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false; 3155 } 3156 } 3157 3158 // Check the message arguments. 3159 unsigned NumArgs = ArgsIn.size(); 3160 Expr **Args = ArgsIn.data(); 3161 QualType ReturnType; 3162 ExprValueKind VK = VK_RValue; 3163 bool ClassMessage = (ReceiverType->isObjCClassType() || 3164 ReceiverType->isObjCQualifiedClassType()); 3165 if (CheckMessageArgumentTypes(Receiver, ReceiverType, 3166 MultiExprArg(Args, NumArgs), Sel, SelectorLocs, 3167 Method, ClassMessage, SuperLoc.isValid(), 3168 LBracLoc, RBracLoc, RecRange, ReturnType, VK)) 3169 return ExprError(); 3170 3171 if (Method && !Method->getReturnType()->isVoidType() && 3172 RequireCompleteType(LBracLoc, Method->getReturnType(), 3173 diag::err_illegal_message_expr_incomplete_type)) 3174 return ExprError(); 3175 3176 // In ARC, forbid the user from sending messages to 3177 // retain/release/autorelease/dealloc/retainCount explicitly. 3178 if (getLangOpts().ObjCAutoRefCount) { 3179 ObjCMethodFamily family = 3180 (Method ? Method->getMethodFamily() : Sel.getMethodFamily()); 3181 switch (family) { 3182 case OMF_init: 3183 if (Method) 3184 checkInitMethod(Method, ReceiverType); 3185 break; 3186 3187 case OMF_None: 3188 case OMF_alloc: 3189 case OMF_copy: 3190 case OMF_finalize: 3191 case OMF_mutableCopy: 3192 case OMF_new: 3193 case OMF_self: 3194 case OMF_initialize: 3195 break; 3196 3197 case OMF_dealloc: 3198 case OMF_retain: 3199 case OMF_release: 3200 case OMF_autorelease: 3201 case OMF_retainCount: 3202 Diag(SelLoc, diag::err_arc_illegal_explicit_message) 3203 << Sel << RecRange; 3204 break; 3205 3206 case OMF_performSelector: 3207 if (Method && NumArgs >= 1) { 3208 if (const auto *SelExp = 3209 dyn_cast<ObjCSelectorExpr>(Args[0]->IgnoreParens())) { 3210 Selector ArgSel = SelExp->getSelector(); 3211 ObjCMethodDecl *SelMethod = 3212 LookupInstanceMethodInGlobalPool(ArgSel, 3213 SelExp->getSourceRange()); 3214 if (!SelMethod) 3215 SelMethod = 3216 LookupFactoryMethodInGlobalPool(ArgSel, 3217 SelExp->getSourceRange()); 3218 if (SelMethod) { 3219 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily(); 3220 switch (SelFamily) { 3221 case OMF_alloc: 3222 case OMF_copy: 3223 case OMF_mutableCopy: 3224 case OMF_new: 3225 case OMF_init: 3226 // Issue error, unless ns_returns_not_retained. 3227 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { 3228 // selector names a +1 method 3229 Diag(SelLoc, 3230 diag::err_arc_perform_selector_retains); 3231 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 3232 << SelMethod->getDeclName(); 3233 } 3234 break; 3235 default: 3236 // +0 call. OK. unless ns_returns_retained. 3237 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { 3238 // selector names a +1 method 3239 Diag(SelLoc, 3240 diag::err_arc_perform_selector_retains); 3241 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 3242 << SelMethod->getDeclName(); 3243 } 3244 break; 3245 } 3246 } 3247 } else { 3248 // error (may leak). 3249 Diag(SelLoc, diag::warn_arc_perform_selector_leaks); 3250 Diag(Args[0]->getExprLoc(), diag::note_used_here); 3251 } 3252 } 3253 break; 3254 } 3255 } 3256 3257 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs); 3258 3259 // Construct the appropriate ObjCMessageExpr instance. 3260 ObjCMessageExpr *Result; 3261 if (SuperLoc.isValid()) 3262 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 3263 SuperLoc, /*IsInstanceSuper=*/true, 3264 ReceiverType, Sel, SelectorLocs, Method, 3265 makeArrayRef(Args, NumArgs), RBracLoc, 3266 isImplicit); 3267 else { 3268 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 3269 Receiver, Sel, SelectorLocs, Method, 3270 makeArrayRef(Args, NumArgs), RBracLoc, 3271 isImplicit); 3272 if (!isImplicit) 3273 checkCocoaAPI(*this, Result); 3274 } 3275 if (Method) { 3276 bool IsClassObjectCall = ClassMessage; 3277 // 'self' message receivers in class methods should be treated as message 3278 // sends to the class object in order for the semantic checks to be 3279 // performed correctly. Messages to 'super' already count as class messages, 3280 // so they don't need to be handled here. 3281 if (Receiver && isSelfExpr(Receiver)) { 3282 if (const auto *OPT = ReceiverType->getAs<ObjCObjectPointerType>()) { 3283 if (OPT->getObjectType()->isObjCClass()) { 3284 if (const auto *CurMeth = getCurMethodDecl()) { 3285 IsClassObjectCall = true; 3286 ReceiverType = 3287 Context.getObjCInterfaceType(CurMeth->getClassInterface()); 3288 } 3289 } 3290 } 3291 } 3292 checkFoundationAPI(*this, SelLoc, Method, makeArrayRef(Args, NumArgs), 3293 ReceiverType, IsClassObjectCall); 3294 } 3295 3296 if (getLangOpts().ObjCAutoRefCount) { 3297 // In ARC, annotate delegate init calls. 3298 if (Result->getMethodFamily() == OMF_init && 3299 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 3300 // Only consider init calls *directly* in init implementations, 3301 // not within blocks. 3302 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext); 3303 if (method && method->getMethodFamily() == OMF_init) { 3304 // The implicit assignment to self means we also don't want to 3305 // consume the result. 3306 Result->setDelegateInitCall(true); 3307 return Result; 3308 } 3309 } 3310 3311 // In ARC, check for message sends which are likely to introduce 3312 // retain cycles. 3313 checkRetainCycles(Result); 3314 } 3315 3316 if (getLangOpts().ObjCWeak) { 3317 if (!isImplicit && Method) { 3318 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) { 3319 bool IsWeak = 3320 Prop->getPropertyAttributes() & ObjCPropertyAttribute::kind_weak; 3321 if (!IsWeak && Sel.isUnarySelector()) 3322 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak; 3323 if (IsWeak && !isUnevaluatedContext() && 3324 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc)) 3325 getCurFunction()->recordUseOfWeak(Result, Prop); 3326 } 3327 } 3328 } 3329 3330 CheckObjCCircularContainer(Result); 3331 3332 return MaybeBindToTemporary(Result); 3333 } 3334 3335 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { 3336 if (ObjCSelectorExpr *OSE = 3337 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) { 3338 Selector Sel = OSE->getSelector(); 3339 SourceLocation Loc = OSE->getAtLoc(); 3340 auto Pos = S.ReferencedSelectors.find(Sel); 3341 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc) 3342 S.ReferencedSelectors.erase(Pos); 3343 } 3344 } 3345 3346 // ActOnInstanceMessage - used for both unary and keyword messages. 3347 // ArgExprs is optional - if it is present, the number of expressions 3348 // is obtained from Sel.getNumArgs(). 3349 ExprResult Sema::ActOnInstanceMessage(Scope *S, 3350 Expr *Receiver, 3351 Selector Sel, 3352 SourceLocation LBracLoc, 3353 ArrayRef<SourceLocation> SelectorLocs, 3354 SourceLocation RBracLoc, 3355 MultiExprArg Args) { 3356 if (!Receiver) 3357 return ExprError(); 3358 3359 // A ParenListExpr can show up while doing error recovery with invalid code. 3360 if (isa<ParenListExpr>(Receiver)) { 3361 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver); 3362 if (Result.isInvalid()) return ExprError(); 3363 Receiver = Result.get(); 3364 } 3365 3366 if (RespondsToSelectorSel.isNull()) { 3367 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); 3368 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); 3369 } 3370 if (Sel == RespondsToSelectorSel) 3371 RemoveSelectorFromWarningCache(*this, Args[0]); 3372 3373 return BuildInstanceMessage(Receiver, Receiver->getType(), 3374 /*SuperLoc=*/SourceLocation(), Sel, 3375 /*Method=*/nullptr, LBracLoc, SelectorLocs, 3376 RBracLoc, Args); 3377 } 3378 3379 enum ARCConversionTypeClass { 3380 /// int, void, struct A 3381 ACTC_none, 3382 3383 /// id, void (^)() 3384 ACTC_retainable, 3385 3386 /// id*, id***, void (^*)(), 3387 ACTC_indirectRetainable, 3388 3389 /// void* might be a normal C type, or it might a CF type. 3390 ACTC_voidPtr, 3391 3392 /// struct A* 3393 ACTC_coreFoundation 3394 }; 3395 3396 static bool isAnyRetainable(ARCConversionTypeClass ACTC) { 3397 return (ACTC == ACTC_retainable || 3398 ACTC == ACTC_coreFoundation || 3399 ACTC == ACTC_voidPtr); 3400 } 3401 3402 static bool isAnyCLike(ARCConversionTypeClass ACTC) { 3403 return ACTC == ACTC_none || 3404 ACTC == ACTC_voidPtr || 3405 ACTC == ACTC_coreFoundation; 3406 } 3407 3408 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { 3409 bool isIndirect = false; 3410 3411 // Ignore an outermost reference type. 3412 if (const ReferenceType *ref = type->getAs<ReferenceType>()) { 3413 type = ref->getPointeeType(); 3414 isIndirect = true; 3415 } 3416 3417 // Drill through pointers and arrays recursively. 3418 while (true) { 3419 if (const PointerType *ptr = type->getAs<PointerType>()) { 3420 type = ptr->getPointeeType(); 3421 3422 // The first level of pointer may be the innermost pointer on a CF type. 3423 if (!isIndirect) { 3424 if (type->isVoidType()) return ACTC_voidPtr; 3425 if (type->isRecordType()) return ACTC_coreFoundation; 3426 } 3427 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) { 3428 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0); 3429 } else { 3430 break; 3431 } 3432 isIndirect = true; 3433 } 3434 3435 if (isIndirect) { 3436 if (type->isObjCARCBridgableType()) 3437 return ACTC_indirectRetainable; 3438 return ACTC_none; 3439 } 3440 3441 if (type->isObjCARCBridgableType()) 3442 return ACTC_retainable; 3443 3444 return ACTC_none; 3445 } 3446 3447 namespace { 3448 /// A result from the cast checker. 3449 enum ACCResult { 3450 /// Cannot be casted. 3451 ACC_invalid, 3452 3453 /// Can be safely retained or not retained. 3454 ACC_bottom, 3455 3456 /// Can be casted at +0. 3457 ACC_plusZero, 3458 3459 /// Can be casted at +1. 3460 ACC_plusOne 3461 }; 3462 ACCResult merge(ACCResult left, ACCResult right) { 3463 if (left == right) return left; 3464 if (left == ACC_bottom) return right; 3465 if (right == ACC_bottom) return left; 3466 return ACC_invalid; 3467 } 3468 3469 /// A checker which white-lists certain expressions whose conversion 3470 /// to or from retainable type would otherwise be forbidden in ARC. 3471 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> { 3472 typedef StmtVisitor<ARCCastChecker, ACCResult> super; 3473 3474 ASTContext &Context; 3475 ARCConversionTypeClass SourceClass; 3476 ARCConversionTypeClass TargetClass; 3477 bool Diagnose; 3478 3479 static bool isCFType(QualType type) { 3480 // Someday this can use ns_bridged. For now, it has to do this. 3481 return type->isCARCBridgableType(); 3482 } 3483 3484 public: 3485 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source, 3486 ARCConversionTypeClass target, bool diagnose) 3487 : Context(Context), SourceClass(source), TargetClass(target), 3488 Diagnose(diagnose) {} 3489 3490 using super::Visit; 3491 ACCResult Visit(Expr *e) { 3492 return super::Visit(e->IgnoreParens()); 3493 } 3494 3495 ACCResult VisitStmt(Stmt *s) { 3496 return ACC_invalid; 3497 } 3498 3499 /// Null pointer constants can be casted however you please. 3500 ACCResult VisitExpr(Expr *e) { 3501 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 3502 return ACC_bottom; 3503 return ACC_invalid; 3504 } 3505 3506 /// Objective-C string literals can be safely casted. 3507 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) { 3508 // If we're casting to any retainable type, go ahead. Global 3509 // strings are immune to retains, so this is bottom. 3510 if (isAnyRetainable(TargetClass)) return ACC_bottom; 3511 3512 return ACC_invalid; 3513 } 3514 3515 /// Look through certain implicit and explicit casts. 3516 ACCResult VisitCastExpr(CastExpr *e) { 3517 switch (e->getCastKind()) { 3518 case CK_NullToPointer: 3519 return ACC_bottom; 3520 3521 case CK_NoOp: 3522 case CK_LValueToRValue: 3523 case CK_BitCast: 3524 case CK_CPointerToObjCPointerCast: 3525 case CK_BlockPointerToObjCPointerCast: 3526 case CK_AnyPointerToBlockPointerCast: 3527 return Visit(e->getSubExpr()); 3528 3529 default: 3530 return ACC_invalid; 3531 } 3532 } 3533 3534 /// Look through unary extension. 3535 ACCResult VisitUnaryExtension(UnaryOperator *e) { 3536 return Visit(e->getSubExpr()); 3537 } 3538 3539 /// Ignore the LHS of a comma operator. 3540 ACCResult VisitBinComma(BinaryOperator *e) { 3541 return Visit(e->getRHS()); 3542 } 3543 3544 /// Conditional operators are okay if both sides are okay. 3545 ACCResult VisitConditionalOperator(ConditionalOperator *e) { 3546 ACCResult left = Visit(e->getTrueExpr()); 3547 if (left == ACC_invalid) return ACC_invalid; 3548 return merge(left, Visit(e->getFalseExpr())); 3549 } 3550 3551 /// Look through pseudo-objects. 3552 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) { 3553 // If we're getting here, we should always have a result. 3554 return Visit(e->getResultExpr()); 3555 } 3556 3557 /// Statement expressions are okay if their result expression is okay. 3558 ACCResult VisitStmtExpr(StmtExpr *e) { 3559 return Visit(e->getSubStmt()->body_back()); 3560 } 3561 3562 /// Some declaration references are okay. 3563 ACCResult VisitDeclRefExpr(DeclRefExpr *e) { 3564 VarDecl *var = dyn_cast<VarDecl>(e->getDecl()); 3565 // References to global constants are okay. 3566 if (isAnyRetainable(TargetClass) && 3567 isAnyRetainable(SourceClass) && 3568 var && 3569 !var->hasDefinition(Context) && 3570 var->getType().isConstQualified()) { 3571 3572 // In system headers, they can also be assumed to be immune to retains. 3573 // These are things like 'kCFStringTransformToLatin'. 3574 if (Context.getSourceManager().isInSystemHeader(var->getLocation())) 3575 return ACC_bottom; 3576 3577 return ACC_plusZero; 3578 } 3579 3580 // Nothing else. 3581 return ACC_invalid; 3582 } 3583 3584 /// Some calls are okay. 3585 ACCResult VisitCallExpr(CallExpr *e) { 3586 if (FunctionDecl *fn = e->getDirectCallee()) 3587 if (ACCResult result = checkCallToFunction(fn)) 3588 return result; 3589 3590 return super::VisitCallExpr(e); 3591 } 3592 3593 ACCResult checkCallToFunction(FunctionDecl *fn) { 3594 // Require a CF*Ref return type. 3595 if (!isCFType(fn->getReturnType())) 3596 return ACC_invalid; 3597 3598 if (!isAnyRetainable(TargetClass)) 3599 return ACC_invalid; 3600 3601 // Honor an explicit 'not retained' attribute. 3602 if (fn->hasAttr<CFReturnsNotRetainedAttr>()) 3603 return ACC_plusZero; 3604 3605 // Honor an explicit 'retained' attribute, except that for 3606 // now we're not going to permit implicit handling of +1 results, 3607 // because it's a bit frightening. 3608 if (fn->hasAttr<CFReturnsRetainedAttr>()) 3609 return Diagnose ? ACC_plusOne 3610 : ACC_invalid; // ACC_plusOne if we start accepting this 3611 3612 // Recognize this specific builtin function, which is used by CFSTR. 3613 unsigned builtinID = fn->getBuiltinID(); 3614 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString) 3615 return ACC_bottom; 3616 3617 // Otherwise, don't do anything implicit with an unaudited function. 3618 if (!fn->hasAttr<CFAuditedTransferAttr>()) 3619 return ACC_invalid; 3620 3621 // Otherwise, it's +0 unless it follows the create convention. 3622 if (ento::coreFoundation::followsCreateRule(fn)) 3623 return Diagnose ? ACC_plusOne 3624 : ACC_invalid; // ACC_plusOne if we start accepting this 3625 3626 return ACC_plusZero; 3627 } 3628 3629 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) { 3630 return checkCallToMethod(e->getMethodDecl()); 3631 } 3632 3633 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) { 3634 ObjCMethodDecl *method; 3635 if (e->isExplicitProperty()) 3636 method = e->getExplicitProperty()->getGetterMethodDecl(); 3637 else 3638 method = e->getImplicitPropertyGetter(); 3639 return checkCallToMethod(method); 3640 } 3641 3642 ACCResult checkCallToMethod(ObjCMethodDecl *method) { 3643 if (!method) return ACC_invalid; 3644 3645 // Check for message sends to functions returning CF types. We 3646 // just obey the Cocoa conventions with these, even though the 3647 // return type is CF. 3648 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType())) 3649 return ACC_invalid; 3650 3651 // If the method is explicitly marked not-retained, it's +0. 3652 if (method->hasAttr<CFReturnsNotRetainedAttr>()) 3653 return ACC_plusZero; 3654 3655 // If the method is explicitly marked as returning retained, or its 3656 // selector follows a +1 Cocoa convention, treat it as +1. 3657 if (method->hasAttr<CFReturnsRetainedAttr>()) 3658 return ACC_plusOne; 3659 3660 switch (method->getSelector().getMethodFamily()) { 3661 case OMF_alloc: 3662 case OMF_copy: 3663 case OMF_mutableCopy: 3664 case OMF_new: 3665 return ACC_plusOne; 3666 3667 default: 3668 // Otherwise, treat it as +0. 3669 return ACC_plusZero; 3670 } 3671 } 3672 }; 3673 } // end anonymous namespace 3674 3675 bool Sema::isKnownName(StringRef name) { 3676 if (name.empty()) 3677 return false; 3678 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(), 3679 Sema::LookupOrdinaryName); 3680 return LookupName(R, TUScope, false); 3681 } 3682 3683 static void addFixitForObjCARCConversion(Sema &S, 3684 DiagnosticBuilder &DiagB, 3685 Sema::CheckedConversionKind CCK, 3686 SourceLocation afterLParen, 3687 QualType castType, 3688 Expr *castExpr, 3689 Expr *realCast, 3690 const char *bridgeKeyword, 3691 const char *CFBridgeName) { 3692 // We handle C-style and implicit casts here. 3693 switch (CCK) { 3694 case Sema::CCK_ImplicitConversion: 3695 case Sema::CCK_ForBuiltinOverloadedOp: 3696 case Sema::CCK_CStyleCast: 3697 case Sema::CCK_OtherCast: 3698 break; 3699 case Sema::CCK_FunctionalCast: 3700 return; 3701 } 3702 3703 if (CFBridgeName) { 3704 if (CCK == Sema::CCK_OtherCast) { 3705 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 3706 SourceRange range(NCE->getOperatorLoc(), 3707 NCE->getAngleBrackets().getEnd()); 3708 SmallString<32> BridgeCall; 3709 3710 SourceManager &SM = S.getSourceManager(); 3711 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 3712 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 3713 BridgeCall += ' '; 3714 3715 BridgeCall += CFBridgeName; 3716 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); 3717 } 3718 return; 3719 } 3720 Expr *castedE = castExpr; 3721 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE)) 3722 castedE = CCE->getSubExpr(); 3723 castedE = castedE->IgnoreImpCasts(); 3724 SourceRange range = castedE->getSourceRange(); 3725 3726 SmallString<32> BridgeCall; 3727 3728 SourceManager &SM = S.getSourceManager(); 3729 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 3730 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 3731 BridgeCall += ' '; 3732 3733 BridgeCall += CFBridgeName; 3734 3735 if (isa<ParenExpr>(castedE)) { 3736 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3737 BridgeCall)); 3738 } else { 3739 BridgeCall += '('; 3740 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3741 BridgeCall)); 3742 DiagB.AddFixItHint(FixItHint::CreateInsertion( 3743 S.getLocForEndOfToken(range.getEnd()), 3744 ")")); 3745 } 3746 return; 3747 } 3748 3749 if (CCK == Sema::CCK_CStyleCast) { 3750 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword)); 3751 } else if (CCK == Sema::CCK_OtherCast) { 3752 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 3753 std::string castCode = "("; 3754 castCode += bridgeKeyword; 3755 castCode += castType.getAsString(); 3756 castCode += ")"; 3757 SourceRange Range(NCE->getOperatorLoc(), 3758 NCE->getAngleBrackets().getEnd()); 3759 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode)); 3760 } 3761 } else { 3762 std::string castCode = "("; 3763 castCode += bridgeKeyword; 3764 castCode += castType.getAsString(); 3765 castCode += ")"; 3766 Expr *castedE = castExpr->IgnoreImpCasts(); 3767 SourceRange range = castedE->getSourceRange(); 3768 if (isa<ParenExpr>(castedE)) { 3769 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3770 castCode)); 3771 } else { 3772 castCode += "("; 3773 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3774 castCode)); 3775 DiagB.AddFixItHint(FixItHint::CreateInsertion( 3776 S.getLocForEndOfToken(range.getEnd()), 3777 ")")); 3778 } 3779 } 3780 } 3781 3782 template <typename T> 3783 static inline T *getObjCBridgeAttr(const TypedefType *TD) { 3784 TypedefNameDecl *TDNDecl = TD->getDecl(); 3785 QualType QT = TDNDecl->getUnderlyingType(); 3786 if (QT->isPointerType()) { 3787 QT = QT->getPointeeType(); 3788 if (const RecordType *RT = QT->getAs<RecordType>()) 3789 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl()) 3790 return RD->getAttr<T>(); 3791 } 3792 return nullptr; 3793 } 3794 3795 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T, 3796 TypedefNameDecl *&TDNDecl) { 3797 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 3798 TDNDecl = TD->getDecl(); 3799 if (ObjCBridgeRelatedAttr *ObjCBAttr = 3800 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD)) 3801 return ObjCBAttr; 3802 T = TDNDecl->getUnderlyingType(); 3803 } 3804 return nullptr; 3805 } 3806 3807 static void 3808 diagnoseObjCARCConversion(Sema &S, SourceRange castRange, 3809 QualType castType, ARCConversionTypeClass castACTC, 3810 Expr *castExpr, Expr *realCast, 3811 ARCConversionTypeClass exprACTC, 3812 Sema::CheckedConversionKind CCK) { 3813 SourceLocation loc = 3814 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); 3815 3816 if (S.makeUnavailableInSystemHeader(loc, 3817 UnavailableAttr::IR_ARCForbiddenConversion)) 3818 return; 3819 3820 QualType castExprType = castExpr->getType(); 3821 // Defer emitting a diagnostic for bridge-related casts; that will be 3822 // handled by CheckObjCBridgeRelatedConversions. 3823 TypedefNameDecl *TDNDecl = nullptr; 3824 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable && 3825 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) || 3826 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable && 3827 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl))) 3828 return; 3829 3830 unsigned srcKind = 0; 3831 switch (exprACTC) { 3832 case ACTC_none: 3833 case ACTC_coreFoundation: 3834 case ACTC_voidPtr: 3835 srcKind = (castExprType->isPointerType() ? 1 : 0); 3836 break; 3837 case ACTC_retainable: 3838 srcKind = (castExprType->isBlockPointerType() ? 2 : 3); 3839 break; 3840 case ACTC_indirectRetainable: 3841 srcKind = 4; 3842 break; 3843 } 3844 3845 // Check whether this could be fixed with a bridge cast. 3846 SourceLocation afterLParen = S.getLocForEndOfToken(castRange.getBegin()); 3847 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; 3848 3849 unsigned convKindForDiag = Sema::isCast(CCK) ? 0 : 1; 3850 3851 // Bridge from an ARC type to a CF type. 3852 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) { 3853 3854 S.Diag(loc, diag::err_arc_cast_requires_bridge) 3855 << convKindForDiag 3856 << 2 // of C pointer type 3857 << castExprType 3858 << unsigned(castType->isBlockPointerType()) // to ObjC|block type 3859 << castType 3860 << castRange 3861 << castExpr->getSourceRange(); 3862 bool br = S.isKnownName("CFBridgingRelease"); 3863 ACCResult CreateRule = 3864 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 3865 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 3866 if (CreateRule != ACC_plusOne) 3867 { 3868 DiagnosticBuilder DiagB = 3869 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 3870 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 3871 3872 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3873 castType, castExpr, realCast, "__bridge ", 3874 nullptr); 3875 } 3876 if (CreateRule != ACC_plusZero) 3877 { 3878 DiagnosticBuilder DiagB = 3879 (CCK == Sema::CCK_OtherCast && !br) ? 3880 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType : 3881 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 3882 diag::note_arc_bridge_transfer) 3883 << castExprType << br; 3884 3885 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3886 castType, castExpr, realCast, "__bridge_transfer ", 3887 br ? "CFBridgingRelease" : nullptr); 3888 } 3889 3890 return; 3891 } 3892 3893 // Bridge from a CF type to an ARC type. 3894 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { 3895 bool br = S.isKnownName("CFBridgingRetain"); 3896 S.Diag(loc, diag::err_arc_cast_requires_bridge) 3897 << convKindForDiag 3898 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type 3899 << castExprType 3900 << 2 // to C pointer type 3901 << castType 3902 << castRange 3903 << castExpr->getSourceRange(); 3904 ACCResult CreateRule = 3905 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 3906 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 3907 if (CreateRule != ACC_plusOne) 3908 { 3909 DiagnosticBuilder DiagB = 3910 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 3911 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 3912 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3913 castType, castExpr, realCast, "__bridge ", 3914 nullptr); 3915 } 3916 if (CreateRule != ACC_plusZero) 3917 { 3918 DiagnosticBuilder DiagB = 3919 (CCK == Sema::CCK_OtherCast && !br) ? 3920 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType : 3921 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 3922 diag::note_arc_bridge_retained) 3923 << castType << br; 3924 3925 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3926 castType, castExpr, realCast, "__bridge_retained ", 3927 br ? "CFBridgingRetain" : nullptr); 3928 } 3929 3930 return; 3931 } 3932 3933 S.Diag(loc, diag::err_arc_mismatched_cast) 3934 << !convKindForDiag 3935 << srcKind << castExprType << castType 3936 << castRange << castExpr->getSourceRange(); 3937 } 3938 3939 template <typename TB> 3940 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr, 3941 bool &HadTheAttribute, bool warn) { 3942 QualType T = castExpr->getType(); 3943 HadTheAttribute = false; 3944 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 3945 TypedefNameDecl *TDNDecl = TD->getDecl(); 3946 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { 3947 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { 3948 HadTheAttribute = true; 3949 if (Parm->isStr("id")) 3950 return true; 3951 3952 NamedDecl *Target = nullptr; 3953 // Check for an existing type with this name. 3954 LookupResult R(S, DeclarationName(Parm), SourceLocation(), 3955 Sema::LookupOrdinaryName); 3956 if (S.LookupName(R, S.TUScope)) { 3957 Target = R.getFoundDecl(); 3958 if (Target && isa<ObjCInterfaceDecl>(Target)) { 3959 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target); 3960 if (const ObjCObjectPointerType *InterfacePointerType = 3961 castType->getAsObjCInterfacePointerType()) { 3962 ObjCInterfaceDecl *CastClass 3963 = InterfacePointerType->getObjectType()->getInterface(); 3964 if ((CastClass == ExprClass) || 3965 (CastClass && CastClass->isSuperClassOf(ExprClass))) 3966 return true; 3967 if (warn) 3968 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge) 3969 << T << Target->getName() << castType->getPointeeType(); 3970 return false; 3971 } else if (castType->isObjCIdType() || 3972 (S.Context.ObjCObjectAdoptsQTypeProtocols( 3973 castType, ExprClass))) 3974 // ok to cast to 'id'. 3975 // casting to id<p-list> is ok if bridge type adopts all of 3976 // p-list protocols. 3977 return true; 3978 else { 3979 if (warn) { 3980 S.Diag(castExpr->getBeginLoc(), diag::warn_objc_invalid_bridge) 3981 << T << Target->getName() << castType; 3982 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 3983 S.Diag(Target->getBeginLoc(), diag::note_declared_at); 3984 } 3985 return false; 3986 } 3987 } 3988 } else if (!castType->isObjCIdType()) { 3989 S.Diag(castExpr->getBeginLoc(), 3990 diag::err_objc_cf_bridged_not_interface) 3991 << castExpr->getType() << Parm; 3992 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 3993 if (Target) 3994 S.Diag(Target->getBeginLoc(), diag::note_declared_at); 3995 } 3996 return true; 3997 } 3998 return false; 3999 } 4000 T = TDNDecl->getUnderlyingType(); 4001 } 4002 return true; 4003 } 4004 4005 template <typename TB> 4006 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr, 4007 bool &HadTheAttribute, bool warn) { 4008 QualType T = castType; 4009 HadTheAttribute = false; 4010 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 4011 TypedefNameDecl *TDNDecl = TD->getDecl(); 4012 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { 4013 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { 4014 HadTheAttribute = true; 4015 if (Parm->isStr("id")) 4016 return true; 4017 4018 NamedDecl *Target = nullptr; 4019 // Check for an existing type with this name. 4020 LookupResult R(S, DeclarationName(Parm), SourceLocation(), 4021 Sema::LookupOrdinaryName); 4022 if (S.LookupName(R, S.TUScope)) { 4023 Target = R.getFoundDecl(); 4024 if (Target && isa<ObjCInterfaceDecl>(Target)) { 4025 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target); 4026 if (const ObjCObjectPointerType *InterfacePointerType = 4027 castExpr->getType()->getAsObjCInterfacePointerType()) { 4028 ObjCInterfaceDecl *ExprClass 4029 = InterfacePointerType->getObjectType()->getInterface(); 4030 if ((CastClass == ExprClass) || 4031 (ExprClass && CastClass->isSuperClassOf(ExprClass))) 4032 return true; 4033 if (warn) { 4034 S.Diag(castExpr->getBeginLoc(), 4035 diag::warn_objc_invalid_bridge_to_cf) 4036 << castExpr->getType()->getPointeeType() << T; 4037 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4038 } 4039 return false; 4040 } else if (castExpr->getType()->isObjCIdType() || 4041 (S.Context.QIdProtocolsAdoptObjCObjectProtocols( 4042 castExpr->getType(), CastClass))) 4043 // ok to cast an 'id' expression to a CFtype. 4044 // ok to cast an 'id<plist>' expression to CFtype provided plist 4045 // adopts all of CFtype's ObjetiveC's class plist. 4046 return true; 4047 else { 4048 if (warn) { 4049 S.Diag(castExpr->getBeginLoc(), 4050 diag::warn_objc_invalid_bridge_to_cf) 4051 << castExpr->getType() << castType; 4052 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4053 S.Diag(Target->getBeginLoc(), diag::note_declared_at); 4054 } 4055 return false; 4056 } 4057 } 4058 } 4059 S.Diag(castExpr->getBeginLoc(), 4060 diag::err_objc_ns_bridged_invalid_cfobject) 4061 << castExpr->getType() << castType; 4062 S.Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4063 if (Target) 4064 S.Diag(Target->getBeginLoc(), diag::note_declared_at); 4065 return true; 4066 } 4067 return false; 4068 } 4069 T = TDNDecl->getUnderlyingType(); 4070 } 4071 return true; 4072 } 4073 4074 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { 4075 if (!getLangOpts().ObjC) 4076 return; 4077 // warn in presence of __bridge casting to or from a toll free bridge cast. 4078 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType()); 4079 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); 4080 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) { 4081 bool HasObjCBridgeAttr; 4082 bool ObjCBridgeAttrWillNotWarn = 4083 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 4084 false); 4085 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) 4086 return; 4087 bool HasObjCBridgeMutableAttr; 4088 bool ObjCBridgeMutableAttrWillNotWarn = 4089 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 4090 HasObjCBridgeMutableAttr, false); 4091 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) 4092 return; 4093 4094 if (HasObjCBridgeAttr) 4095 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 4096 true); 4097 else if (HasObjCBridgeMutableAttr) 4098 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 4099 HasObjCBridgeMutableAttr, true); 4100 } 4101 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) { 4102 bool HasObjCBridgeAttr; 4103 bool ObjCBridgeAttrWillNotWarn = 4104 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 4105 false); 4106 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) 4107 return; 4108 bool HasObjCBridgeMutableAttr; 4109 bool ObjCBridgeMutableAttrWillNotWarn = 4110 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 4111 HasObjCBridgeMutableAttr, false); 4112 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) 4113 return; 4114 4115 if (HasObjCBridgeAttr) 4116 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 4117 true); 4118 else if (HasObjCBridgeMutableAttr) 4119 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 4120 HasObjCBridgeMutableAttr, true); 4121 } 4122 } 4123 4124 void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) { 4125 QualType SrcType = castExpr->getType(); 4126 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) { 4127 if (PRE->isExplicitProperty()) { 4128 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty()) 4129 SrcType = PDecl->getType(); 4130 } 4131 else if (PRE->isImplicitProperty()) { 4132 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter()) 4133 SrcType = Getter->getReturnType(); 4134 } 4135 } 4136 4137 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType); 4138 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType); 4139 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation) 4140 return; 4141 CheckObjCBridgeRelatedConversions(castExpr->getBeginLoc(), castType, SrcType, 4142 castExpr); 4143 } 4144 4145 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 4146 CastKind &Kind) { 4147 if (!getLangOpts().ObjC) 4148 return false; 4149 ARCConversionTypeClass exprACTC = 4150 classifyTypeForARCConversion(castExpr->getType()); 4151 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); 4152 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) || 4153 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) { 4154 CheckTollFreeBridgeCast(castType, castExpr); 4155 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast 4156 : CK_CPointerToObjCPointerCast; 4157 return true; 4158 } 4159 return false; 4160 } 4161 4162 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, 4163 QualType DestType, QualType SrcType, 4164 ObjCInterfaceDecl *&RelatedClass, 4165 ObjCMethodDecl *&ClassMethod, 4166 ObjCMethodDecl *&InstanceMethod, 4167 TypedefNameDecl *&TDNDecl, 4168 bool CfToNs, bool Diagnose) { 4169 QualType T = CfToNs ? SrcType : DestType; 4170 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl); 4171 if (!ObjCBAttr) 4172 return false; 4173 4174 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass(); 4175 IdentifierInfo *CMId = ObjCBAttr->getClassMethod(); 4176 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod(); 4177 if (!RCId) 4178 return false; 4179 NamedDecl *Target = nullptr; 4180 // Check for an existing type with this name. 4181 LookupResult R(*this, DeclarationName(RCId), SourceLocation(), 4182 Sema::LookupOrdinaryName); 4183 if (!LookupName(R, TUScope)) { 4184 if (Diagnose) { 4185 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId 4186 << SrcType << DestType; 4187 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4188 } 4189 return false; 4190 } 4191 Target = R.getFoundDecl(); 4192 if (Target && isa<ObjCInterfaceDecl>(Target)) 4193 RelatedClass = cast<ObjCInterfaceDecl>(Target); 4194 else { 4195 if (Diagnose) { 4196 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId 4197 << SrcType << DestType; 4198 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4199 if (Target) 4200 Diag(Target->getBeginLoc(), diag::note_declared_at); 4201 } 4202 return false; 4203 } 4204 4205 // Check for an existing class method with the given selector name. 4206 if (CfToNs && CMId) { 4207 Selector Sel = Context.Selectors.getUnarySelector(CMId); 4208 ClassMethod = RelatedClass->lookupMethod(Sel, false); 4209 if (!ClassMethod) { 4210 if (Diagnose) { 4211 Diag(Loc, diag::err_objc_bridged_related_known_method) 4212 << SrcType << DestType << Sel << false; 4213 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4214 } 4215 return false; 4216 } 4217 } 4218 4219 // Check for an existing instance method with the given selector name. 4220 if (!CfToNs && IMId) { 4221 Selector Sel = Context.Selectors.getNullarySelector(IMId); 4222 InstanceMethod = RelatedClass->lookupMethod(Sel, true); 4223 if (!InstanceMethod) { 4224 if (Diagnose) { 4225 Diag(Loc, diag::err_objc_bridged_related_known_method) 4226 << SrcType << DestType << Sel << true; 4227 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4228 } 4229 return false; 4230 } 4231 } 4232 return true; 4233 } 4234 4235 bool 4236 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, 4237 QualType DestType, QualType SrcType, 4238 Expr *&SrcExpr, bool Diagnose) { 4239 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType); 4240 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType); 4241 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable); 4242 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation); 4243 if (!CfToNs && !NsToCf) 4244 return false; 4245 4246 ObjCInterfaceDecl *RelatedClass; 4247 ObjCMethodDecl *ClassMethod = nullptr; 4248 ObjCMethodDecl *InstanceMethod = nullptr; 4249 TypedefNameDecl *TDNDecl = nullptr; 4250 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass, 4251 ClassMethod, InstanceMethod, TDNDecl, 4252 CfToNs, Diagnose)) 4253 return false; 4254 4255 if (CfToNs) { 4256 // Implicit conversion from CF to ObjC object is needed. 4257 if (ClassMethod) { 4258 if (Diagnose) { 4259 std::string ExpressionString = "["; 4260 ExpressionString += RelatedClass->getNameAsString(); 4261 ExpressionString += " "; 4262 ExpressionString += ClassMethod->getSelector().getAsString(); 4263 SourceLocation SrcExprEndLoc = 4264 getLocForEndOfToken(SrcExpr->getEndLoc()); 4265 // Provide a fixit: [RelatedClass ClassMethod SrcExpr] 4266 Diag(Loc, diag::err_objc_bridged_related_known_method) 4267 << SrcType << DestType << ClassMethod->getSelector() << false 4268 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), 4269 ExpressionString) 4270 << FixItHint::CreateInsertion(SrcExprEndLoc, "]"); 4271 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at); 4272 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4273 4274 QualType receiverType = Context.getObjCInterfaceType(RelatedClass); 4275 // Argument. 4276 Expr *args[] = { SrcExpr }; 4277 ExprResult msg = BuildClassMessageImplicit(receiverType, false, 4278 ClassMethod->getLocation(), 4279 ClassMethod->getSelector(), ClassMethod, 4280 MultiExprArg(args, 1)); 4281 SrcExpr = msg.get(); 4282 } 4283 return true; 4284 } 4285 } 4286 else { 4287 // Implicit conversion from ObjC type to CF object is needed. 4288 if (InstanceMethod) { 4289 if (Diagnose) { 4290 std::string ExpressionString; 4291 SourceLocation SrcExprEndLoc = 4292 getLocForEndOfToken(SrcExpr->getEndLoc()); 4293 if (InstanceMethod->isPropertyAccessor()) 4294 if (const ObjCPropertyDecl *PDecl = 4295 InstanceMethod->findPropertyDecl()) { 4296 // fixit: ObjectExpr.propertyname when it is aproperty accessor. 4297 ExpressionString = "."; 4298 ExpressionString += PDecl->getNameAsString(); 4299 Diag(Loc, diag::err_objc_bridged_related_known_method) 4300 << SrcType << DestType << InstanceMethod->getSelector() << true 4301 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); 4302 } 4303 if (ExpressionString.empty()) { 4304 // Provide a fixit: [ObjectExpr InstanceMethod] 4305 ExpressionString = " "; 4306 ExpressionString += InstanceMethod->getSelector().getAsString(); 4307 ExpressionString += "]"; 4308 4309 Diag(Loc, diag::err_objc_bridged_related_known_method) 4310 << SrcType << DestType << InstanceMethod->getSelector() << true 4311 << FixItHint::CreateInsertion(SrcExpr->getBeginLoc(), "[") 4312 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); 4313 } 4314 Diag(RelatedClass->getBeginLoc(), diag::note_declared_at); 4315 Diag(TDNDecl->getBeginLoc(), diag::note_declared_at); 4316 4317 ExprResult msg = 4318 BuildInstanceMessageImplicit(SrcExpr, SrcType, 4319 InstanceMethod->getLocation(), 4320 InstanceMethod->getSelector(), 4321 InstanceMethod, None); 4322 SrcExpr = msg.get(); 4323 } 4324 return true; 4325 } 4326 } 4327 return false; 4328 } 4329 4330 Sema::ARCConversionResult 4331 Sema::CheckObjCConversion(SourceRange castRange, QualType castType, 4332 Expr *&castExpr, CheckedConversionKind CCK, 4333 bool Diagnose, bool DiagnoseCFAudited, 4334 BinaryOperatorKind Opc) { 4335 QualType castExprType = castExpr->getType(); 4336 4337 // For the purposes of the classification, we assume reference types 4338 // will bind to temporaries. 4339 QualType effCastType = castType; 4340 if (const ReferenceType *ref = castType->getAs<ReferenceType>()) 4341 effCastType = ref->getPointeeType(); 4342 4343 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); 4344 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); 4345 if (exprACTC == castACTC) { 4346 // Check for viability and report error if casting an rvalue to a 4347 // life-time qualifier. 4348 if (castACTC == ACTC_retainable && 4349 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) && 4350 castType != castExprType) { 4351 const Type *DT = castType.getTypePtr(); 4352 QualType QDT = castType; 4353 // We desugar some types but not others. We ignore those 4354 // that cannot happen in a cast; i.e. auto, and those which 4355 // should not be de-sugared; i.e typedef. 4356 if (const ParenType *PT = dyn_cast<ParenType>(DT)) 4357 QDT = PT->desugar(); 4358 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT)) 4359 QDT = TP->desugar(); 4360 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT)) 4361 QDT = AT->desugar(); 4362 if (QDT != castType && 4363 QDT.getObjCLifetime() != Qualifiers::OCL_None) { 4364 if (Diagnose) { 4365 SourceLocation loc = (castRange.isValid() ? castRange.getBegin() 4366 : castExpr->getExprLoc()); 4367 Diag(loc, diag::err_arc_nolifetime_behavior); 4368 } 4369 return ACR_error; 4370 } 4371 } 4372 return ACR_okay; 4373 } 4374 4375 // The life-time qualifier cast check above is all we need for ObjCWeak. 4376 // ObjCAutoRefCount has more restrictions on what is legal. 4377 if (!getLangOpts().ObjCAutoRefCount) 4378 return ACR_okay; 4379 4380 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay; 4381 4382 // Allow all of these types to be cast to integer types (but not 4383 // vice-versa). 4384 if (castACTC == ACTC_none && castType->isIntegralType(Context)) 4385 return ACR_okay; 4386 4387 // Allow casts between pointers to lifetime types (e.g., __strong id*) 4388 // and pointers to void (e.g., cv void *). Casting from void* to lifetime* 4389 // must be explicit. 4390 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr) 4391 return ACR_okay; 4392 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr && 4393 isCast(CCK)) 4394 return ACR_okay; 4395 4396 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) { 4397 // For invalid casts, fall through. 4398 case ACC_invalid: 4399 break; 4400 4401 // Do nothing for both bottom and +0. 4402 case ACC_bottom: 4403 case ACC_plusZero: 4404 return ACR_okay; 4405 4406 // If the result is +1, consume it here. 4407 case ACC_plusOne: 4408 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(), 4409 CK_ARCConsumeObject, castExpr, 4410 nullptr, VK_RValue); 4411 Cleanup.setExprNeedsCleanups(true); 4412 return ACR_okay; 4413 } 4414 4415 // If this is a non-implicit cast from id or block type to a 4416 // CoreFoundation type, delay complaining in case the cast is used 4417 // in an acceptable context. 4418 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && isCast(CCK)) 4419 return ACR_unbridged; 4420 4421 // Issue a diagnostic about a missing @-sign when implicit casting a cstring 4422 // to 'NSString *', instead of falling through to report a "bridge cast" 4423 // diagnostic. 4424 if (castACTC == ACTC_retainable && exprACTC == ACTC_none && 4425 CheckConversionToObjCLiteral(castType, castExpr, Diagnose)) 4426 return ACR_error; 4427 4428 // Do not issue "bridge cast" diagnostic when implicit casting 4429 // a retainable object to a CF type parameter belonging to an audited 4430 // CF API function. Let caller issue a normal type mismatched diagnostic 4431 // instead. 4432 if ((!DiagnoseCFAudited || exprACTC != ACTC_retainable || 4433 castACTC != ACTC_coreFoundation) && 4434 !(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable && 4435 (Opc == BO_NE || Opc == BO_EQ))) { 4436 if (Diagnose) 4437 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr, 4438 castExpr, exprACTC, CCK); 4439 return ACR_error; 4440 } 4441 return ACR_okay; 4442 } 4443 4444 /// Given that we saw an expression with the ARCUnbridgedCastTy 4445 /// placeholder type, complain bitterly. 4446 void Sema::diagnoseARCUnbridgedCast(Expr *e) { 4447 // We expect the spurious ImplicitCastExpr to already have been stripped. 4448 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 4449 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens()); 4450 4451 SourceRange castRange; 4452 QualType castType; 4453 CheckedConversionKind CCK; 4454 4455 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) { 4456 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc()); 4457 castType = cast->getTypeAsWritten(); 4458 CCK = CCK_CStyleCast; 4459 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) { 4460 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange(); 4461 castType = cast->getTypeAsWritten(); 4462 CCK = CCK_OtherCast; 4463 } else { 4464 llvm_unreachable("Unexpected ImplicitCastExpr"); 4465 } 4466 4467 ARCConversionTypeClass castACTC = 4468 classifyTypeForARCConversion(castType.getNonReferenceType()); 4469 4470 Expr *castExpr = realCast->getSubExpr(); 4471 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable); 4472 4473 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, 4474 castExpr, realCast, ACTC_retainable, CCK); 4475 } 4476 4477 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast 4478 /// type, remove the placeholder cast. 4479 Expr *Sema::stripARCUnbridgedCast(Expr *e) { 4480 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 4481 4482 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) { 4483 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr()); 4484 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub); 4485 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) { 4486 assert(uo->getOpcode() == UO_Extension); 4487 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr()); 4488 return UnaryOperator::Create(Context, sub, UO_Extension, sub->getType(), 4489 sub->getValueKind(), sub->getObjectKind(), 4490 uo->getOperatorLoc(), false, CurFPFeatures); 4491 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { 4492 assert(!gse->isResultDependent()); 4493 4494 unsigned n = gse->getNumAssocs(); 4495 SmallVector<Expr *, 4> subExprs; 4496 SmallVector<TypeSourceInfo *, 4> subTypes; 4497 subExprs.reserve(n); 4498 subTypes.reserve(n); 4499 for (const GenericSelectionExpr::Association assoc : gse->associations()) { 4500 subTypes.push_back(assoc.getTypeSourceInfo()); 4501 Expr *sub = assoc.getAssociationExpr(); 4502 if (assoc.isSelected()) 4503 sub = stripARCUnbridgedCast(sub); 4504 subExprs.push_back(sub); 4505 } 4506 4507 return GenericSelectionExpr::Create( 4508 Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes, 4509 subExprs, gse->getDefaultLoc(), gse->getRParenLoc(), 4510 gse->containsUnexpandedParameterPack(), gse->getResultIndex()); 4511 } else { 4512 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!"); 4513 return cast<ImplicitCastExpr>(e)->getSubExpr(); 4514 } 4515 } 4516 4517 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, 4518 QualType exprType) { 4519 QualType canCastType = 4520 Context.getCanonicalType(castType).getUnqualifiedType(); 4521 QualType canExprType = 4522 Context.getCanonicalType(exprType).getUnqualifiedType(); 4523 if (isa<ObjCObjectPointerType>(canCastType) && 4524 castType.getObjCLifetime() == Qualifiers::OCL_Weak && 4525 canExprType->isObjCObjectPointerType()) { 4526 if (const ObjCObjectPointerType *ObjT = 4527 canExprType->getAs<ObjCObjectPointerType>()) 4528 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl()) 4529 return !ObjI->isArcWeakrefUnavailable(); 4530 } 4531 return true; 4532 } 4533 4534 /// Look for an ObjCReclaimReturnedObject cast and destroy it. 4535 static Expr *maybeUndoReclaimObject(Expr *e) { 4536 Expr *curExpr = e, *prevExpr = nullptr; 4537 4538 // Walk down the expression until we hit an implicit cast of kind 4539 // ARCReclaimReturnedObject or an Expr that is neither a Paren nor a Cast. 4540 while (true) { 4541 if (auto *pe = dyn_cast<ParenExpr>(curExpr)) { 4542 prevExpr = curExpr; 4543 curExpr = pe->getSubExpr(); 4544 continue; 4545 } 4546 4547 if (auto *ce = dyn_cast<CastExpr>(curExpr)) { 4548 if (auto *ice = dyn_cast<ImplicitCastExpr>(ce)) 4549 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) { 4550 if (!prevExpr) 4551 return ice->getSubExpr(); 4552 if (auto *pe = dyn_cast<ParenExpr>(prevExpr)) 4553 pe->setSubExpr(ice->getSubExpr()); 4554 else 4555 cast<CastExpr>(prevExpr)->setSubExpr(ice->getSubExpr()); 4556 return e; 4557 } 4558 4559 prevExpr = curExpr; 4560 curExpr = ce->getSubExpr(); 4561 continue; 4562 } 4563 4564 // Break out of the loop if curExpr is neither a Paren nor a Cast. 4565 break; 4566 } 4567 4568 return e; 4569 } 4570 4571 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, 4572 ObjCBridgeCastKind Kind, 4573 SourceLocation BridgeKeywordLoc, 4574 TypeSourceInfo *TSInfo, 4575 Expr *SubExpr) { 4576 ExprResult SubResult = UsualUnaryConversions(SubExpr); 4577 if (SubResult.isInvalid()) return ExprError(); 4578 SubExpr = SubResult.get(); 4579 4580 QualType T = TSInfo->getType(); 4581 QualType FromType = SubExpr->getType(); 4582 4583 CastKind CK; 4584 4585 bool MustConsume = false; 4586 if (T->isDependentType() || SubExpr->isTypeDependent()) { 4587 // Okay: we'll build a dependent expression type. 4588 CK = CK_Dependent; 4589 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) { 4590 // Casting CF -> id 4591 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast 4592 : CK_CPointerToObjCPointerCast); 4593 switch (Kind) { 4594 case OBC_Bridge: 4595 break; 4596 4597 case OBC_BridgeRetained: { 4598 bool br = isKnownName("CFBridgingRelease"); 4599 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 4600 << 2 4601 << FromType 4602 << (T->isBlockPointerType()? 1 : 0) 4603 << T 4604 << SubExpr->getSourceRange() 4605 << Kind; 4606 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 4607 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); 4608 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) 4609 << FromType << br 4610 << FixItHint::CreateReplacement(BridgeKeywordLoc, 4611 br ? "CFBridgingRelease " 4612 : "__bridge_transfer "); 4613 4614 Kind = OBC_Bridge; 4615 break; 4616 } 4617 4618 case OBC_BridgeTransfer: 4619 // We must consume the Objective-C object produced by the cast. 4620 MustConsume = true; 4621 break; 4622 } 4623 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) { 4624 // Okay: id -> CF 4625 CK = CK_BitCast; 4626 switch (Kind) { 4627 case OBC_Bridge: 4628 // Reclaiming a value that's going to be __bridge-casted to CF 4629 // is very dangerous, so we don't do it. 4630 SubExpr = maybeUndoReclaimObject(SubExpr); 4631 break; 4632 4633 case OBC_BridgeRetained: 4634 // Produce the object before casting it. 4635 SubExpr = ImplicitCastExpr::Create(Context, FromType, 4636 CK_ARCProduceObject, 4637 SubExpr, nullptr, VK_RValue); 4638 break; 4639 4640 case OBC_BridgeTransfer: { 4641 bool br = isKnownName("CFBridgingRetain"); 4642 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 4643 << (FromType->isBlockPointerType()? 1 : 0) 4644 << FromType 4645 << 2 4646 << T 4647 << SubExpr->getSourceRange() 4648 << Kind; 4649 4650 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 4651 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); 4652 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) 4653 << T << br 4654 << FixItHint::CreateReplacement(BridgeKeywordLoc, 4655 br ? "CFBridgingRetain " : "__bridge_retained"); 4656 4657 Kind = OBC_Bridge; 4658 break; 4659 } 4660 } 4661 } else { 4662 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible) 4663 << FromType << T << Kind 4664 << SubExpr->getSourceRange() 4665 << TSInfo->getTypeLoc().getSourceRange(); 4666 return ExprError(); 4667 } 4668 4669 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, 4670 BridgeKeywordLoc, 4671 TSInfo, SubExpr); 4672 4673 if (MustConsume) { 4674 Cleanup.setExprNeedsCleanups(true); 4675 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 4676 nullptr, VK_RValue); 4677 } 4678 4679 return Result; 4680 } 4681 4682 ExprResult Sema::ActOnObjCBridgedCast(Scope *S, 4683 SourceLocation LParenLoc, 4684 ObjCBridgeCastKind Kind, 4685 SourceLocation BridgeKeywordLoc, 4686 ParsedType Type, 4687 SourceLocation RParenLoc, 4688 Expr *SubExpr) { 4689 TypeSourceInfo *TSInfo = nullptr; 4690 QualType T = GetTypeFromParser(Type, &TSInfo); 4691 if (Kind == OBC_Bridge) 4692 CheckTollFreeBridgeCast(T, SubExpr); 4693 if (!TSInfo) 4694 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); 4695 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, 4696 SubExpr); 4697 } 4698