1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis for Objective-C expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/ExprObjC.h" 18 #include "clang/AST/StmtVisitor.h" 19 #include "clang/AST/TypeLoc.h" 20 #include "clang/Analysis/DomainSpecific/CocoaConventions.h" 21 #include "clang/Edit/Commit.h" 22 #include "clang/Edit/Rewriters.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Sema/Initialization.h" 25 #include "clang/Sema/Lookup.h" 26 #include "clang/Sema/Scope.h" 27 #include "clang/Sema/ScopeInfo.h" 28 #include "llvm/ADT/SmallString.h" 29 30 using namespace clang; 31 using namespace sema; 32 using llvm::makeArrayRef; 33 34 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, 35 Expr **strings, 36 unsigned NumStrings) { 37 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); 38 39 // Most ObjC strings are formed out of a single piece. However, we *can* 40 // have strings formed out of multiple @ strings with multiple pptokens in 41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one 42 // StringLiteral for ObjCStringLiteral to hold onto. 43 StringLiteral *S = Strings[0]; 44 45 // If we have a multi-part string, merge it all together. 46 if (NumStrings != 1) { 47 // Concatenate objc strings. 48 SmallString<128> StrBuf; 49 SmallVector<SourceLocation, 8> StrLocs; 50 51 for (unsigned i = 0; i != NumStrings; ++i) { 52 S = Strings[i]; 53 54 // ObjC strings can't be wide or UTF. 55 if (!S->isAscii()) { 56 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant) 57 << S->getSourceRange(); 58 return true; 59 } 60 61 // Append the string. 62 StrBuf += S->getString(); 63 64 // Get the locations of the string tokens. 65 StrLocs.append(S->tokloc_begin(), S->tokloc_end()); 66 } 67 68 // Create the aggregate string with the appropriate content and location 69 // information. 70 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); 71 assert(CAT && "String literal not of constant array type!"); 72 QualType StrTy = Context.getConstantArrayType( 73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), 74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers()); 75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii, 76 /*Pascal=*/false, StrTy, &StrLocs[0], 77 StrLocs.size()); 78 } 79 80 return BuildObjCStringLiteral(AtLocs[0], S); 81 } 82 83 ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ 84 // Verify that this composite string is acceptable for ObjC strings. 85 if (CheckObjCString(S)) 86 return true; 87 88 // Initialize the constant string interface lazily. This assumes 89 // the NSString interface is seen in this translation unit. Note: We 90 // don't use NSConstantString, since the runtime team considers this 91 // interface private (even though it appears in the header files). 92 QualType Ty = Context.getObjCConstantStringInterface(); 93 if (!Ty.isNull()) { 94 Ty = Context.getObjCObjectPointerType(Ty); 95 } else if (getLangOpts().NoConstantCFStrings) { 96 IdentifierInfo *NSIdent=nullptr; 97 std::string StringClass(getLangOpts().ObjCConstantStringClass); 98 99 if (StringClass.empty()) 100 NSIdent = &Context.Idents.get("NSConstantString"); 101 else 102 NSIdent = &Context.Idents.get(StringClass); 103 104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 105 LookupOrdinaryName); 106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 107 Context.setObjCConstantStringInterface(StrIF); 108 Ty = Context.getObjCConstantStringInterface(); 109 Ty = Context.getObjCObjectPointerType(Ty); 110 } else { 111 // If there is no NSConstantString interface defined then treat this 112 // as error and recover from it. 113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent 114 << S->getSourceRange(); 115 Ty = Context.getObjCIdType(); 116 } 117 } else { 118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); 119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, 120 LookupOrdinaryName); 121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 122 Context.setObjCConstantStringInterface(StrIF); 123 Ty = Context.getObjCConstantStringInterface(); 124 Ty = Context.getObjCObjectPointerType(Ty); 125 } else { 126 // If there is no NSString interface defined, implicitly declare 127 // a @class NSString; and use that instead. This is to make sure 128 // type of an NSString literal is represented correctly, instead of 129 // being an 'id' type. 130 Ty = Context.getObjCNSStringType(); 131 if (Ty.isNull()) { 132 ObjCInterfaceDecl *NSStringIDecl = 133 ObjCInterfaceDecl::Create (Context, 134 Context.getTranslationUnitDecl(), 135 SourceLocation(), NSIdent, 136 nullptr, SourceLocation()); 137 Ty = Context.getObjCInterfaceType(NSStringIDecl); 138 Context.setObjCNSStringType(Ty); 139 } 140 Ty = Context.getObjCObjectPointerType(Ty); 141 } 142 } 143 144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc); 145 } 146 147 /// \brief Emits an error if the given method does not exist, or if the return 148 /// type is not an Objective-C object. 149 static bool validateBoxingMethod(Sema &S, SourceLocation Loc, 150 const ObjCInterfaceDecl *Class, 151 Selector Sel, const ObjCMethodDecl *Method) { 152 if (!Method) { 153 // FIXME: Is there a better way to avoid quotes than using getName()? 154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName(); 155 return false; 156 } 157 158 // Make sure the return type is reasonable. 159 QualType ReturnType = Method->getReturnType(); 160 if (!ReturnType->isObjCObjectPointerType()) { 161 S.Diag(Loc, diag::err_objc_literal_method_sig) 162 << Sel; 163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return) 164 << ReturnType; 165 return false; 166 } 167 168 return true; 169 } 170 171 /// \brief Retrieve the NSNumber factory method that should be used to create 172 /// an Objective-C literal for the given type. 173 static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, 174 QualType NumberType, 175 bool isLiteral = false, 176 SourceRange R = SourceRange()) { 177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind = 178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType); 179 180 if (!Kind) { 181 if (isLiteral) { 182 S.Diag(Loc, diag::err_invalid_nsnumber_type) 183 << NumberType << R; 184 } 185 return nullptr; 186 } 187 188 // If we already looked up this method, we're done. 189 if (S.NSNumberLiteralMethods[*Kind]) 190 return S.NSNumberLiteralMethods[*Kind]; 191 192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, 193 /*Instance=*/false); 194 195 ASTContext &CX = S.Context; 196 197 // Look up the NSNumber class, if we haven't done so already. It's cached 198 // in the Sema instance. 199 if (!S.NSNumberDecl) { 200 IdentifierInfo *NSNumberId = 201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber); 202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId, 203 Loc, Sema::LookupOrdinaryName); 204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 205 if (!S.NSNumberDecl) { 206 if (S.getLangOpts().DebuggerObjCLiteral) { 207 // Create a stub definition of NSNumber. 208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX, 209 CX.getTranslationUnitDecl(), 210 SourceLocation(), NSNumberId, 211 nullptr, SourceLocation()); 212 } else { 213 // Otherwise, require a declaration of NSNumber. 214 S.Diag(Loc, diag::err_undeclared_nsnumber); 215 return nullptr; 216 } 217 } else if (!S.NSNumberDecl->hasDefinition()) { 218 S.Diag(Loc, diag::err_undeclared_nsnumber); 219 return nullptr; 220 } 221 222 // generate the pointer to NSNumber type. 223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl); 224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject); 225 } 226 227 // Look for the appropriate method within NSNumber. 228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel); 229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) { 230 // create a stub definition this NSNumber factory method. 231 TypeSourceInfo *ReturnTInfo = nullptr; 232 Method = 233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel, 234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl, 235 /*isInstance=*/false, /*isVariadic=*/false, 236 /*isPropertyAccessor=*/false, 237 /*isImplicitlyDeclared=*/true, 238 /*isDefined=*/false, ObjCMethodDecl::Required, 239 /*HasRelatedResultType=*/false); 240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method, 241 SourceLocation(), SourceLocation(), 242 &CX.Idents.get("value"), 243 NumberType, /*TInfo=*/nullptr, 244 SC_None, nullptr); 245 Method->setMethodParams(S.Context, value, None); 246 } 247 248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method)) 249 return nullptr; 250 251 // Note: if the parameter type is out-of-line, we'll catch it later in the 252 // implicit conversion. 253 254 S.NSNumberLiteralMethods[*Kind] = Method; 255 return Method; 256 } 257 258 /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the 259 /// numeric literal expression. Type of the expression will be "NSNumber *". 260 ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { 261 // Determine the type of the literal. 262 QualType NumberType = Number->getType(); 263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) { 264 // In C, character literals have type 'int'. That's not the type we want 265 // to use to determine the Objective-c literal kind. 266 switch (Char->getKind()) { 267 case CharacterLiteral::Ascii: 268 NumberType = Context.CharTy; 269 break; 270 271 case CharacterLiteral::Wide: 272 NumberType = Context.getWideCharType(); 273 break; 274 275 case CharacterLiteral::UTF16: 276 NumberType = Context.Char16Ty; 277 break; 278 279 case CharacterLiteral::UTF32: 280 NumberType = Context.Char32Ty; 281 break; 282 } 283 } 284 285 // Look for the appropriate method within NSNumber. 286 // Construct the literal. 287 SourceRange NR(Number->getSourceRange()); 288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType, 289 true, NR); 290 if (!Method) 291 return ExprError(); 292 293 // Convert the number to the type that the parameter expects. 294 ParmVarDecl *ParamDecl = Method->param_begin()[0]; 295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 296 ParamDecl); 297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity, 298 SourceLocation(), 299 Number); 300 if (ConvertedNumber.isInvalid()) 301 return ExprError(); 302 Number = ConvertedNumber.get(); 303 304 // Use the effective source range of the literal, including the leading '@'. 305 return MaybeBindToTemporary( 306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, 307 SourceRange(AtLoc, NR.getEnd()))); 308 } 309 310 ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, 311 SourceLocation ValueLoc, 312 bool Value) { 313 ExprResult Inner; 314 if (getLangOpts().CPlusPlus) { 315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); 316 } else { 317 // C doesn't actually have a way to represent literal values of type 318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool. 319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); 320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, 321 CK_IntegralToBoolean); 322 } 323 324 return BuildObjCNumericLiteral(AtLoc, Inner.get()); 325 } 326 327 /// \brief Check that the given expression is a valid element of an Objective-C 328 /// collection literal. 329 static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, 330 QualType T, 331 bool ArrayLiteral = false) { 332 // If the expression is type-dependent, there's nothing for us to do. 333 if (Element->isTypeDependent()) 334 return Element; 335 336 ExprResult Result = S.CheckPlaceholderExpr(Element); 337 if (Result.isInvalid()) 338 return ExprError(); 339 Element = Result.get(); 340 341 // In C++, check for an implicit conversion to an Objective-C object pointer 342 // type. 343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { 344 InitializedEntity Entity 345 = InitializedEntity::InitializeParameter(S.Context, T, 346 /*Consumed=*/false); 347 InitializationKind Kind 348 = InitializationKind::CreateCopy(Element->getLocStart(), 349 SourceLocation()); 350 InitializationSequence Seq(S, Entity, Kind, Element); 351 if (!Seq.Failed()) 352 return Seq.Perform(S, Entity, Kind, Element); 353 } 354 355 Expr *OrigElement = Element; 356 357 // Perform lvalue-to-rvalue conversion. 358 Result = S.DefaultLvalueConversion(Element); 359 if (Result.isInvalid()) 360 return ExprError(); 361 Element = Result.get(); 362 363 // Make sure that we have an Objective-C pointer type or block. 364 if (!Element->getType()->isObjCObjectPointerType() && 365 !Element->getType()->isBlockPointerType()) { 366 bool Recovered = false; 367 368 // If this is potentially an Objective-C numeric literal, add the '@'. 369 if (isa<IntegerLiteral>(OrigElement) || 370 isa<CharacterLiteral>(OrigElement) || 371 isa<FloatingLiteral>(OrigElement) || 372 isa<ObjCBoolLiteralExpr>(OrigElement) || 373 isa<CXXBoolLiteralExpr>(OrigElement)) { 374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) { 375 int Which = isa<CharacterLiteral>(OrigElement) ? 1 376 : (isa<CXXBoolLiteralExpr>(OrigElement) || 377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2 378 : 3; 379 380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) 381 << Which << OrigElement->getSourceRange() 382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); 383 384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(), 385 OrigElement); 386 if (Result.isInvalid()) 387 return ExprError(); 388 389 Element = Result.get(); 390 Recovered = true; 391 } 392 } 393 // If this is potentially an Objective-C string literal, add the '@'. 394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) { 395 if (String->isAscii()) { 396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) 397 << 0 << OrigElement->getSourceRange() 398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); 399 400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String); 401 if (Result.isInvalid()) 402 return ExprError(); 403 404 Element = Result.get(); 405 Recovered = true; 406 } 407 } 408 409 if (!Recovered) { 410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element) 411 << Element->getType(); 412 return ExprError(); 413 } 414 } 415 if (ArrayLiteral) 416 if (ObjCStringLiteral *getString = 417 dyn_cast<ObjCStringLiteral>(OrigElement)) { 418 if (StringLiteral *SL = getString->getString()) { 419 unsigned numConcat = SL->getNumConcatenated(); 420 if (numConcat > 1) { 421 // Only warn if the concatenated string doesn't come from a macro. 422 bool hasMacro = false; 423 for (unsigned i = 0; i < numConcat ; ++i) 424 if (SL->getStrTokenLoc(i).isMacroID()) { 425 hasMacro = true; 426 break; 427 } 428 if (!hasMacro) 429 S.Diag(Element->getLocStart(), 430 diag::warn_concatenated_nsarray_literal) 431 << Element->getType(); 432 } 433 } 434 } 435 436 // Make sure that the element has the type that the container factory 437 // function expects. 438 return S.PerformCopyInitialization( 439 InitializedEntity::InitializeParameter(S.Context, T, 440 /*Consumed=*/false), 441 Element->getLocStart(), Element); 442 } 443 444 ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { 445 if (ValueExpr->isTypeDependent()) { 446 ObjCBoxedExpr *BoxedExpr = 447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR); 448 return BoxedExpr; 449 } 450 ObjCMethodDecl *BoxingMethod = nullptr; 451 QualType BoxedType; 452 // Convert the expression to an RValue, so we can check for pointer types... 453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr); 454 if (RValue.isInvalid()) { 455 return ExprError(); 456 } 457 ValueExpr = RValue.get(); 458 QualType ValueType(ValueExpr->getType()); 459 if (const PointerType *PT = ValueType->getAs<PointerType>()) { 460 QualType PointeeType = PT->getPointeeType(); 461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) { 462 463 if (!NSStringDecl) { 464 IdentifierInfo *NSStringId = 465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); 466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId, 467 SR.getBegin(), LookupOrdinaryName); 468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl); 469 if (!NSStringDecl) { 470 if (getLangOpts().DebuggerObjCLiteral) { 471 // Support boxed expressions in the debugger w/o NSString declaration. 472 DeclContext *TU = Context.getTranslationUnitDecl(); 473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU, 474 SourceLocation(), 475 NSStringId, 476 nullptr, SourceLocation()); 477 } else { 478 Diag(SR.getBegin(), diag::err_undeclared_nsstring); 479 return ExprError(); 480 } 481 } else if (!NSStringDecl->hasDefinition()) { 482 Diag(SR.getBegin(), diag::err_undeclared_nsstring); 483 return ExprError(); 484 } 485 assert(NSStringDecl && "NSStringDecl should not be NULL"); 486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); 487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); 488 } 489 490 if (!StringWithUTF8StringMethod) { 491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); 492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); 493 494 // Look for the appropriate method within NSString. 495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String); 496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { 497 // Debugger needs to work even if NSString hasn't been defined. 498 TypeSourceInfo *ReturnTInfo = nullptr; 499 ObjCMethodDecl *M = ObjCMethodDecl::Create( 500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String, 501 NSStringPointer, ReturnTInfo, NSStringDecl, 502 /*isInstance=*/false, /*isVariadic=*/false, 503 /*isPropertyAccessor=*/false, 504 /*isImplicitlyDeclared=*/true, 505 /*isDefined=*/false, ObjCMethodDecl::Required, 506 /*HasRelatedResultType=*/false); 507 QualType ConstCharType = Context.CharTy.withConst(); 508 ParmVarDecl *value = 509 ParmVarDecl::Create(Context, M, 510 SourceLocation(), SourceLocation(), 511 &Context.Idents.get("value"), 512 Context.getPointerType(ConstCharType), 513 /*TInfo=*/nullptr, 514 SC_None, nullptr); 515 M->setMethodParams(Context, value, None); 516 BoxingMethod = M; 517 } 518 519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl, 520 stringWithUTF8String, BoxingMethod)) 521 return ExprError(); 522 523 StringWithUTF8StringMethod = BoxingMethod; 524 } 525 526 BoxingMethod = StringWithUTF8StringMethod; 527 BoxedType = NSStringPointer; 528 } 529 } else if (ValueType->isBuiltinType()) { 530 // The other types we support are numeric, char and BOOL/bool. We could also 531 // provide limited support for structure types, such as NSRange, NSRect, and 532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h> 533 // for more details. 534 535 // Check for a top-level character literal. 536 if (const CharacterLiteral *Char = 537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) { 538 // In C, character literals have type 'int'. That's not the type we want 539 // to use to determine the Objective-c literal kind. 540 switch (Char->getKind()) { 541 case CharacterLiteral::Ascii: 542 ValueType = Context.CharTy; 543 break; 544 545 case CharacterLiteral::Wide: 546 ValueType = Context.getWideCharType(); 547 break; 548 549 case CharacterLiteral::UTF16: 550 ValueType = Context.Char16Ty; 551 break; 552 553 case CharacterLiteral::UTF32: 554 ValueType = Context.Char32Ty; 555 break; 556 } 557 } 558 CheckForIntOverflow(ValueExpr); 559 // FIXME: Do I need to do anything special with BoolTy expressions? 560 561 // Look for the appropriate method within NSNumber. 562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType); 563 BoxedType = NSNumberPointer; 564 565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) { 566 if (!ET->getDecl()->isComplete()) { 567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type) 568 << ValueType << ValueExpr->getSourceRange(); 569 return ExprError(); 570 } 571 572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), 573 ET->getDecl()->getIntegerType()); 574 BoxedType = NSNumberPointer; 575 } 576 577 if (!BoxingMethod) { 578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type) 579 << ValueType << ValueExpr->getSourceRange(); 580 return ExprError(); 581 } 582 583 // Convert the expression to the type that the parameter requires. 584 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0]; 585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 586 ParamDecl); 587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity, 588 SourceLocation(), 589 ValueExpr); 590 if (ConvertedValueExpr.isInvalid()) 591 return ExprError(); 592 ValueExpr = ConvertedValueExpr.get(); 593 594 ObjCBoxedExpr *BoxedExpr = 595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, 596 BoxingMethod, SR); 597 return MaybeBindToTemporary(BoxedExpr); 598 } 599 600 /// Build an ObjC subscript pseudo-object expression, given that 601 /// that's supported by the runtime. 602 ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, 603 Expr *IndexExpr, 604 ObjCMethodDecl *getterMethod, 605 ObjCMethodDecl *setterMethod) { 606 assert(!LangOpts.isSubscriptPointerArithmetic()); 607 608 // We can't get dependent types here; our callers should have 609 // filtered them out. 610 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) && 611 "base or index cannot have dependent type here"); 612 613 // Filter out placeholders in the index. In theory, overloads could 614 // be preserved here, although that might not actually work correctly. 615 ExprResult Result = CheckPlaceholderExpr(IndexExpr); 616 if (Result.isInvalid()) 617 return ExprError(); 618 IndexExpr = Result.get(); 619 620 // Perform lvalue-to-rvalue conversion on the base. 621 Result = DefaultLvalueConversion(BaseExpr); 622 if (Result.isInvalid()) 623 return ExprError(); 624 BaseExpr = Result.get(); 625 626 // Build the pseudo-object expression. 627 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr, 628 Context.PseudoObjectTy, getterMethod, 629 setterMethod, RB); 630 } 631 632 ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { 633 // Look up the NSArray class, if we haven't done so already. 634 if (!NSArrayDecl) { 635 NamedDecl *IF = LookupSingleName(TUScope, 636 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), 637 SR.getBegin(), 638 LookupOrdinaryName); 639 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 640 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral) 641 NSArrayDecl = ObjCInterfaceDecl::Create (Context, 642 Context.getTranslationUnitDecl(), 643 SourceLocation(), 644 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), 645 nullptr, SourceLocation()); 646 647 if (!NSArrayDecl) { 648 Diag(SR.getBegin(), diag::err_undeclared_nsarray); 649 return ExprError(); 650 } 651 } 652 653 // Find the arrayWithObjects:count: method, if we haven't done so already. 654 QualType IdT = Context.getObjCIdType(); 655 if (!ArrayWithObjectsMethod) { 656 Selector 657 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount); 658 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel); 659 if (!Method && getLangOpts().DebuggerObjCLiteral) { 660 TypeSourceInfo *ReturnTInfo = nullptr; 661 Method = ObjCMethodDecl::Create( 662 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo, 663 Context.getTranslationUnitDecl(), false /*Instance*/, 664 false /*isVariadic*/, 665 /*isPropertyAccessor=*/false, 666 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 667 ObjCMethodDecl::Required, false); 668 SmallVector<ParmVarDecl *, 2> Params; 669 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, 670 SourceLocation(), 671 SourceLocation(), 672 &Context.Idents.get("objects"), 673 Context.getPointerType(IdT), 674 /*TInfo=*/nullptr, 675 SC_None, nullptr); 676 Params.push_back(objects); 677 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 678 SourceLocation(), 679 SourceLocation(), 680 &Context.Idents.get("cnt"), 681 Context.UnsignedLongTy, 682 /*TInfo=*/nullptr, SC_None, 683 nullptr); 684 Params.push_back(cnt); 685 Method->setMethodParams(Context, Params, None); 686 } 687 688 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method)) 689 return ExprError(); 690 691 // Dig out the type that all elements should be converted to. 692 QualType T = Method->param_begin()[0]->getType(); 693 const PointerType *PtrT = T->getAs<PointerType>(); 694 if (!PtrT || 695 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { 696 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 697 << Sel; 698 Diag(Method->param_begin()[0]->getLocation(), 699 diag::note_objc_literal_method_param) 700 << 0 << T 701 << Context.getPointerType(IdT.withConst()); 702 return ExprError(); 703 } 704 705 // Check that the 'count' parameter is integral. 706 if (!Method->param_begin()[1]->getType()->isIntegerType()) { 707 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 708 << Sel; 709 Diag(Method->param_begin()[1]->getLocation(), 710 diag::note_objc_literal_method_param) 711 << 1 712 << Method->param_begin()[1]->getType() 713 << "integral"; 714 return ExprError(); 715 } 716 717 // We've found a good +arrayWithObjects:count: method. Save it! 718 ArrayWithObjectsMethod = Method; 719 } 720 721 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType(); 722 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType(); 723 724 // Check that each of the elements provided is valid in a collection literal, 725 // performing conversions as necessary. 726 Expr **ElementsBuffer = Elements.data(); 727 for (unsigned I = 0, N = Elements.size(); I != N; ++I) { 728 ExprResult Converted = CheckObjCCollectionLiteralElement(*this, 729 ElementsBuffer[I], 730 RequiredType, true); 731 if (Converted.isInvalid()) 732 return ExprError(); 733 734 ElementsBuffer[I] = Converted.get(); 735 } 736 737 QualType Ty 738 = Context.getObjCObjectPointerType( 739 Context.getObjCInterfaceType(NSArrayDecl)); 740 741 return MaybeBindToTemporary( 742 ObjCArrayLiteral::Create(Context, Elements, Ty, 743 ArrayWithObjectsMethod, SR)); 744 } 745 746 ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, 747 ObjCDictionaryElement *Elements, 748 unsigned NumElements) { 749 // Look up the NSDictionary class, if we haven't done so already. 750 if (!NSDictionaryDecl) { 751 NamedDecl *IF = LookupSingleName(TUScope, 752 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), 753 SR.getBegin(), LookupOrdinaryName); 754 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 755 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral) 756 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context, 757 Context.getTranslationUnitDecl(), 758 SourceLocation(), 759 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), 760 nullptr, SourceLocation()); 761 762 if (!NSDictionaryDecl) { 763 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary); 764 return ExprError(); 765 } 766 } 767 768 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done 769 // so already. 770 QualType IdT = Context.getObjCIdType(); 771 if (!DictionaryWithObjectsMethod) { 772 Selector Sel = NSAPIObj->getNSDictionarySelector( 773 NSAPI::NSDict_dictionaryWithObjectsForKeysCount); 774 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel); 775 if (!Method && getLangOpts().DebuggerObjCLiteral) { 776 Method = ObjCMethodDecl::Create(Context, 777 SourceLocation(), SourceLocation(), Sel, 778 IdT, 779 nullptr /*TypeSourceInfo */, 780 Context.getTranslationUnitDecl(), 781 false /*Instance*/, false/*isVariadic*/, 782 /*isPropertyAccessor=*/false, 783 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 784 ObjCMethodDecl::Required, 785 false); 786 SmallVector<ParmVarDecl *, 3> Params; 787 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, 788 SourceLocation(), 789 SourceLocation(), 790 &Context.Idents.get("objects"), 791 Context.getPointerType(IdT), 792 /*TInfo=*/nullptr, SC_None, 793 nullptr); 794 Params.push_back(objects); 795 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method, 796 SourceLocation(), 797 SourceLocation(), 798 &Context.Idents.get("keys"), 799 Context.getPointerType(IdT), 800 /*TInfo=*/nullptr, SC_None, 801 nullptr); 802 Params.push_back(keys); 803 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, 804 SourceLocation(), 805 SourceLocation(), 806 &Context.Idents.get("cnt"), 807 Context.UnsignedLongTy, 808 /*TInfo=*/nullptr, SC_None, 809 nullptr); 810 Params.push_back(cnt); 811 Method->setMethodParams(Context, Params, None); 812 } 813 814 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel, 815 Method)) 816 return ExprError(); 817 818 // Dig out the type that all values should be converted to. 819 QualType ValueT = Method->param_begin()[0]->getType(); 820 const PointerType *PtrValue = ValueT->getAs<PointerType>(); 821 if (!PtrValue || 822 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { 823 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 824 << Sel; 825 Diag(Method->param_begin()[0]->getLocation(), 826 diag::note_objc_literal_method_param) 827 << 0 << ValueT 828 << Context.getPointerType(IdT.withConst()); 829 return ExprError(); 830 } 831 832 // Dig out the type that all keys should be converted to. 833 QualType KeyT = Method->param_begin()[1]->getType(); 834 const PointerType *PtrKey = KeyT->getAs<PointerType>(); 835 if (!PtrKey || 836 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 837 IdT)) { 838 bool err = true; 839 if (PtrKey) { 840 if (QIDNSCopying.isNull()) { 841 // key argument of selector is id<NSCopying>? 842 if (ObjCProtocolDecl *NSCopyingPDecl = 843 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) { 844 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl}; 845 QIDNSCopying = 846 Context.getObjCObjectType(Context.ObjCBuiltinIdTy, 847 (ObjCProtocolDecl**) PQ,1); 848 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying); 849 } 850 } 851 if (!QIDNSCopying.isNull()) 852 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), 853 QIDNSCopying); 854 } 855 856 if (err) { 857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 858 << Sel; 859 Diag(Method->param_begin()[1]->getLocation(), 860 diag::note_objc_literal_method_param) 861 << 1 << KeyT 862 << Context.getPointerType(IdT.withConst()); 863 return ExprError(); 864 } 865 } 866 867 // Check that the 'count' parameter is integral. 868 QualType CountType = Method->param_begin()[2]->getType(); 869 if (!CountType->isIntegerType()) { 870 Diag(SR.getBegin(), diag::err_objc_literal_method_sig) 871 << Sel; 872 Diag(Method->param_begin()[2]->getLocation(), 873 diag::note_objc_literal_method_param) 874 << 2 << CountType 875 << "integral"; 876 return ExprError(); 877 } 878 879 // We've found a good +dictionaryWithObjects:keys:count: method; save it! 880 DictionaryWithObjectsMethod = Method; 881 } 882 883 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType(); 884 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType(); 885 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType(); 886 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType(); 887 888 // Check that each of the keys and values provided is valid in a collection 889 // literal, performing conversions as necessary. 890 bool HasPackExpansions = false; 891 for (unsigned I = 0, N = NumElements; I != N; ++I) { 892 // Check the key. 893 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key, 894 KeyT); 895 if (Key.isInvalid()) 896 return ExprError(); 897 898 // Check the value. 899 ExprResult Value 900 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT); 901 if (Value.isInvalid()) 902 return ExprError(); 903 904 Elements[I].Key = Key.get(); 905 Elements[I].Value = Value.get(); 906 907 if (Elements[I].EllipsisLoc.isInvalid()) 908 continue; 909 910 if (!Elements[I].Key->containsUnexpandedParameterPack() && 911 !Elements[I].Value->containsUnexpandedParameterPack()) { 912 Diag(Elements[I].EllipsisLoc, 913 diag::err_pack_expansion_without_parameter_packs) 914 << SourceRange(Elements[I].Key->getLocStart(), 915 Elements[I].Value->getLocEnd()); 916 return ExprError(); 917 } 918 919 HasPackExpansions = true; 920 } 921 922 923 QualType Ty 924 = Context.getObjCObjectPointerType( 925 Context.getObjCInterfaceType(NSDictionaryDecl)); 926 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create( 927 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty, 928 DictionaryWithObjectsMethod, SR)); 929 } 930 931 ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, 932 TypeSourceInfo *EncodedTypeInfo, 933 SourceLocation RParenLoc) { 934 QualType EncodedType = EncodedTypeInfo->getType(); 935 QualType StrTy; 936 if (EncodedType->isDependentType()) 937 StrTy = Context.DependentTy; 938 else { 939 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled. 940 !EncodedType->isVoidType()) // void is handled too. 941 if (RequireCompleteType(AtLoc, EncodedType, 942 diag::err_incomplete_type_objc_at_encode, 943 EncodedTypeInfo->getTypeLoc())) 944 return ExprError(); 945 946 std::string Str; 947 Context.getObjCEncodingForType(EncodedType, Str); 948 949 // The type of @encode is the same as the type of the corresponding string, 950 // which is an array type. 951 StrTy = Context.CharTy; 952 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 953 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) 954 StrTy.addConst(); 955 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), 956 ArrayType::Normal, 0); 957 } 958 959 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc); 960 } 961 962 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, 963 SourceLocation EncodeLoc, 964 SourceLocation LParenLoc, 965 ParsedType ty, 966 SourceLocation RParenLoc) { 967 // FIXME: Preserve type source info ? 968 TypeSourceInfo *TInfo; 969 QualType EncodedType = GetTypeFromParser(ty, &TInfo); 970 if (!TInfo) 971 TInfo = Context.getTrivialTypeSourceInfo(EncodedType, 972 PP.getLocForEndOfToken(LParenLoc)); 973 974 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc); 975 } 976 977 static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S, 978 SourceLocation AtLoc, 979 ObjCMethodDecl *Method, 980 ObjCMethodList &MethList) { 981 ObjCMethodList *M = &MethList; 982 bool Warned = false; 983 for (M = M->getNext(); M; M=M->getNext()) { 984 ObjCMethodDecl *MatchingMethodDecl = M->Method; 985 if (MatchingMethodDecl == Method || 986 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) || 987 MatchingMethodDecl->getSelector() != Method->getSelector()) 988 continue; 989 if (!S.MatchTwoMethodDeclarations(Method, 990 MatchingMethodDecl, Sema::MMS_loose)) { 991 if (!Warned) { 992 Warned = true; 993 S.Diag(AtLoc, diag::warning_multiple_selectors) 994 << Method->getSelector(); 995 S.Diag(Method->getLocation(), diag::note_method_declared_at) 996 << Method->getDeclName(); 997 } 998 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at) 999 << MatchingMethodDecl->getDeclName(); 1000 } 1001 } 1002 return Warned; 1003 } 1004 1005 static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc, 1006 ObjCMethodDecl *Method) { 1007 if (S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation())) 1008 return; 1009 bool Warned = false; 1010 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(), 1011 e = S.MethodPool.end(); b != e; b++) { 1012 // first, instance methods 1013 ObjCMethodList &InstMethList = b->second.first; 1014 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, 1015 Method, InstMethList)) 1016 Warned = true; 1017 1018 // second, class methods 1019 ObjCMethodList &ClsMethList = b->second.second; 1020 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, 1021 Method, ClsMethList) || 1022 Warned) 1023 return; 1024 } 1025 } 1026 1027 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, 1028 SourceLocation AtLoc, 1029 SourceLocation SelLoc, 1030 SourceLocation LParenLoc, 1031 SourceLocation RParenLoc) { 1032 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, 1033 SourceRange(LParenLoc, RParenLoc), false, false); 1034 if (!Method) 1035 Method = LookupFactoryMethodInGlobalPool(Sel, 1036 SourceRange(LParenLoc, RParenLoc)); 1037 if (!Method) { 1038 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) { 1039 Selector MatchedSel = OM->getSelector(); 1040 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1), 1041 RParenLoc.getLocWithOffset(-1)); 1042 Diag(SelLoc, diag::warn_undeclared_selector_with_typo) 1043 << Sel << MatchedSel 1044 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 1045 1046 } else 1047 Diag(SelLoc, diag::warn_undeclared_selector) << Sel; 1048 } else 1049 DiagnoseMismatchedSelectors(*this, AtLoc, Method); 1050 1051 if (Method && 1052 Method->getImplementationControl() != ObjCMethodDecl::Optional && 1053 !getSourceManager().isInSystemHeader(Method->getLocation())) { 1054 llvm::DenseMap<Selector, SourceLocation>::iterator Pos 1055 = ReferencedSelectors.find(Sel); 1056 if (Pos == ReferencedSelectors.end()) 1057 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); 1058 } 1059 1060 // In ARC, forbid the user from using @selector for 1061 // retain/release/autorelease/dealloc/retainCount. 1062 if (getLangOpts().ObjCAutoRefCount) { 1063 switch (Sel.getMethodFamily()) { 1064 case OMF_retain: 1065 case OMF_release: 1066 case OMF_autorelease: 1067 case OMF_retainCount: 1068 case OMF_dealloc: 1069 Diag(AtLoc, diag::err_arc_illegal_selector) << 1070 Sel << SourceRange(LParenLoc, RParenLoc); 1071 break; 1072 1073 case OMF_None: 1074 case OMF_alloc: 1075 case OMF_copy: 1076 case OMF_finalize: 1077 case OMF_init: 1078 case OMF_mutableCopy: 1079 case OMF_new: 1080 case OMF_self: 1081 case OMF_performSelector: 1082 break; 1083 } 1084 } 1085 QualType Ty = Context.getObjCSelType(); 1086 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); 1087 } 1088 1089 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, 1090 SourceLocation AtLoc, 1091 SourceLocation ProtoLoc, 1092 SourceLocation LParenLoc, 1093 SourceLocation ProtoIdLoc, 1094 SourceLocation RParenLoc) { 1095 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc); 1096 if (!PDecl) { 1097 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; 1098 return true; 1099 } 1100 1101 QualType Ty = Context.getObjCProtoType(); 1102 if (Ty.isNull()) 1103 return true; 1104 Ty = Context.getObjCObjectPointerType(Ty); 1105 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc); 1106 } 1107 1108 /// Try to capture an implicit reference to 'self'. 1109 ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) { 1110 DeclContext *DC = getFunctionLevelDeclContext(); 1111 1112 // If we're not in an ObjC method, error out. Note that, unlike the 1113 // C++ case, we don't require an instance method --- class methods 1114 // still have a 'self', and we really do still need to capture it! 1115 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC); 1116 if (!method) 1117 return nullptr; 1118 1119 tryCaptureVariable(method->getSelfDecl(), Loc); 1120 1121 return method; 1122 } 1123 1124 static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { 1125 if (T == Context.getObjCInstanceType()) 1126 return Context.getObjCIdType(); 1127 1128 return T; 1129 } 1130 1131 QualType Sema::getMessageSendResultType(QualType ReceiverType, 1132 ObjCMethodDecl *Method, 1133 bool isClassMessage, bool isSuperMessage) { 1134 assert(Method && "Must have a method"); 1135 if (!Method->hasRelatedResultType()) 1136 return Method->getSendResultType(); 1137 1138 // If a method has a related return type: 1139 // - if the method found is an instance method, but the message send 1140 // was a class message send, T is the declared return type of the method 1141 // found 1142 if (Method->isInstanceMethod() && isClassMessage) 1143 return stripObjCInstanceType(Context, Method->getSendResultType()); 1144 1145 // - if the receiver is super, T is a pointer to the class of the 1146 // enclosing method definition 1147 if (isSuperMessage) { 1148 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 1149 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) 1150 return Context.getObjCObjectPointerType( 1151 Context.getObjCInterfaceType(Class)); 1152 } 1153 1154 // - if the receiver is the name of a class U, T is a pointer to U 1155 if (ReceiverType->getAs<ObjCInterfaceType>() || 1156 ReceiverType->isObjCQualifiedInterfaceType()) 1157 return Context.getObjCObjectPointerType(ReceiverType); 1158 // - if the receiver is of type Class or qualified Class type, 1159 // T is the declared return type of the method. 1160 if (ReceiverType->isObjCClassType() || 1161 ReceiverType->isObjCQualifiedClassType()) 1162 return stripObjCInstanceType(Context, Method->getSendResultType()); 1163 1164 // - if the receiver is id, qualified id, Class, or qualified Class, T 1165 // is the receiver type, otherwise 1166 // - T is the type of the receiver expression. 1167 return ReceiverType; 1168 } 1169 1170 /// Look for an ObjC method whose result type exactly matches the given type. 1171 static const ObjCMethodDecl * 1172 findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, 1173 QualType instancetype) { 1174 if (MD->getReturnType() == instancetype) 1175 return MD; 1176 1177 // For these purposes, a method in an @implementation overrides a 1178 // declaration in the @interface. 1179 if (const ObjCImplDecl *impl = 1180 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { 1181 const ObjCContainerDecl *iface; 1182 if (const ObjCCategoryImplDecl *catImpl = 1183 dyn_cast<ObjCCategoryImplDecl>(impl)) { 1184 iface = catImpl->getCategoryDecl(); 1185 } else { 1186 iface = impl->getClassInterface(); 1187 } 1188 1189 const ObjCMethodDecl *ifaceMD = 1190 iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); 1191 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); 1192 } 1193 1194 SmallVector<const ObjCMethodDecl *, 4> overrides; 1195 MD->getOverriddenMethods(overrides); 1196 for (unsigned i = 0, e = overrides.size(); i != e; ++i) { 1197 if (const ObjCMethodDecl *result = 1198 findExplicitInstancetypeDeclarer(overrides[i], instancetype)) 1199 return result; 1200 } 1201 1202 return nullptr; 1203 } 1204 1205 void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) { 1206 // Only complain if we're in an ObjC method and the required return 1207 // type doesn't match the method's declared return type. 1208 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext); 1209 if (!MD || !MD->hasRelatedResultType() || 1210 Context.hasSameUnqualifiedType(destType, MD->getReturnType())) 1211 return; 1212 1213 // Look for a method overridden by this method which explicitly uses 1214 // 'instancetype'. 1215 if (const ObjCMethodDecl *overridden = 1216 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) { 1217 SourceLocation loc; 1218 SourceRange range; 1219 if (TypeSourceInfo *TSI = overridden->getReturnTypeSourceInfo()) { 1220 range = TSI->getTypeLoc().getSourceRange(); 1221 loc = range.getBegin(); 1222 } 1223 if (loc.isInvalid()) 1224 loc = overridden->getLocation(); 1225 Diag(loc, diag::note_related_result_type_explicit) 1226 << /*current method*/ 1 << range; 1227 return; 1228 } 1229 1230 // Otherwise, if we have an interesting method family, note that. 1231 // This should always trigger if the above didn't. 1232 if (ObjCMethodFamily family = MD->getMethodFamily()) 1233 Diag(MD->getLocation(), diag::note_related_result_type_family) 1234 << /*current method*/ 1 1235 << family; 1236 } 1237 1238 void Sema::EmitRelatedResultTypeNote(const Expr *E) { 1239 E = E->IgnoreParenImpCasts(); 1240 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); 1241 if (!MsgSend) 1242 return; 1243 1244 const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); 1245 if (!Method) 1246 return; 1247 1248 if (!Method->hasRelatedResultType()) 1249 return; 1250 1251 if (Context.hasSameUnqualifiedType( 1252 Method->getReturnType().getNonReferenceType(), MsgSend->getType())) 1253 return; 1254 1255 if (!Context.hasSameUnqualifiedType(Method->getReturnType(), 1256 Context.getObjCInstanceType())) 1257 return; 1258 1259 Diag(Method->getLocation(), diag::note_related_result_type_inferred) 1260 << Method->isInstanceMethod() << Method->getSelector() 1261 << MsgSend->getType(); 1262 } 1263 1264 bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, 1265 MultiExprArg Args, 1266 Selector Sel, 1267 ArrayRef<SourceLocation> SelectorLocs, 1268 ObjCMethodDecl *Method, 1269 bool isClassMessage, bool isSuperMessage, 1270 SourceLocation lbrac, SourceLocation rbrac, 1271 QualType &ReturnType, ExprValueKind &VK) { 1272 SourceLocation SelLoc; 1273 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 1274 SelLoc = SelectorLocs.front(); 1275 else 1276 SelLoc = lbrac; 1277 1278 if (!Method) { 1279 // Apply default argument promotion as for (C99 6.5.2.2p6). 1280 for (unsigned i = 0, e = Args.size(); i != e; i++) { 1281 if (Args[i]->isTypeDependent()) 1282 continue; 1283 1284 ExprResult result; 1285 if (getLangOpts().DebuggerSupport) { 1286 QualType paramTy; // ignored 1287 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy); 1288 } else { 1289 result = DefaultArgumentPromotion(Args[i]); 1290 } 1291 if (result.isInvalid()) 1292 return true; 1293 Args[i] = result.get(); 1294 } 1295 1296 unsigned DiagID; 1297 if (getLangOpts().ObjCAutoRefCount) 1298 DiagID = diag::err_arc_method_not_found; 1299 else 1300 DiagID = isClassMessage ? diag::warn_class_method_not_found 1301 : diag::warn_inst_method_not_found; 1302 if (!getLangOpts().DebuggerSupport) { 1303 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType); 1304 if (OMD && !OMD->isInvalidDecl()) { 1305 if (getLangOpts().ObjCAutoRefCount) 1306 DiagID = diag::error_method_not_found_with_typo; 1307 else 1308 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo 1309 : diag::warn_instance_method_not_found_with_typo; 1310 Selector MatchedSel = OMD->getSelector(); 1311 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back()); 1312 Diag(SelLoc, DiagID) 1313 << Sel<< isClassMessage << MatchedSel 1314 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); 1315 } 1316 else 1317 Diag(SelLoc, DiagID) 1318 << Sel << isClassMessage << SourceRange(SelectorLocs.front(), 1319 SelectorLocs.back()); 1320 // Find the class to which we are sending this message. 1321 if (ReceiverType->isObjCObjectPointerType()) { 1322 if (ObjCInterfaceDecl *Class = 1323 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) 1324 Diag(Class->getLocation(), diag::note_receiver_class_declared); 1325 } 1326 } 1327 1328 // In debuggers, we want to use __unknown_anytype for these 1329 // results so that clients can cast them. 1330 if (getLangOpts().DebuggerSupport) { 1331 ReturnType = Context.UnknownAnyTy; 1332 } else { 1333 ReturnType = Context.getObjCIdType(); 1334 } 1335 VK = VK_RValue; 1336 return false; 1337 } 1338 1339 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, 1340 isSuperMessage); 1341 VK = Expr::getValueKindForType(Method->getReturnType()); 1342 1343 unsigned NumNamedArgs = Sel.getNumArgs(); 1344 // Method might have more arguments than selector indicates. This is due 1345 // to addition of c-style arguments in method. 1346 if (Method->param_size() > Sel.getNumArgs()) 1347 NumNamedArgs = Method->param_size(); 1348 // FIXME. This need be cleaned up. 1349 if (Args.size() < NumNamedArgs) { 1350 Diag(SelLoc, diag::err_typecheck_call_too_few_args) 1351 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size()); 1352 return false; 1353 } 1354 1355 bool IsError = false; 1356 for (unsigned i = 0; i < NumNamedArgs; i++) { 1357 // We can't do any type-checking on a type-dependent argument. 1358 if (Args[i]->isTypeDependent()) 1359 continue; 1360 1361 Expr *argExpr = Args[i]; 1362 1363 ParmVarDecl *param = Method->param_begin()[i]; 1364 assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); 1365 1366 // Strip the unbridged-cast placeholder expression off unless it's 1367 // a consumed argument. 1368 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 1369 !param->hasAttr<CFConsumedAttr>()) 1370 argExpr = stripARCUnbridgedCast(argExpr); 1371 1372 // If the parameter is __unknown_anytype, infer its type 1373 // from the argument. 1374 if (param->getType() == Context.UnknownAnyTy) { 1375 QualType paramType; 1376 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType); 1377 if (argE.isInvalid()) { 1378 IsError = true; 1379 } else { 1380 Args[i] = argE.get(); 1381 1382 // Update the parameter type in-place. 1383 param->setType(paramType); 1384 } 1385 continue; 1386 } 1387 1388 if (RequireCompleteType(argExpr->getSourceRange().getBegin(), 1389 param->getType(), 1390 diag::err_call_incomplete_argument, argExpr)) 1391 return true; 1392 1393 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 1394 param); 1395 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, argExpr); 1396 if (ArgE.isInvalid()) 1397 IsError = true; 1398 else 1399 Args[i] = ArgE.getAs<Expr>(); 1400 } 1401 1402 // Promote additional arguments to variadic methods. 1403 if (Method->isVariadic()) { 1404 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 1405 if (Args[i]->isTypeDependent()) 1406 continue; 1407 1408 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 1409 nullptr); 1410 IsError |= Arg.isInvalid(); 1411 Args[i] = Arg.get(); 1412 } 1413 } else { 1414 // Check for extra arguments to non-variadic methods. 1415 if (Args.size() != NumNamedArgs) { 1416 Diag(Args[NumNamedArgs]->getLocStart(), 1417 diag::err_typecheck_call_too_many_args) 1418 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size()) 1419 << Method->getSourceRange() 1420 << SourceRange(Args[NumNamedArgs]->getLocStart(), 1421 Args.back()->getLocEnd()); 1422 } 1423 } 1424 1425 DiagnoseSentinelCalls(Method, SelLoc, Args); 1426 1427 // Do additional checkings on method. 1428 IsError |= CheckObjCMethodCall( 1429 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size())); 1430 1431 return IsError; 1432 } 1433 1434 bool Sema::isSelfExpr(Expr *RExpr) { 1435 // 'self' is objc 'self' in an objc method only. 1436 ObjCMethodDecl *Method = 1437 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor()); 1438 return isSelfExpr(RExpr, Method); 1439 } 1440 1441 bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) { 1442 if (!method) return false; 1443 1444 receiver = receiver->IgnoreParenLValueCasts(); 1445 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver)) 1446 if (DRE->getDecl() == method->getSelfDecl()) 1447 return true; 1448 return false; 1449 } 1450 1451 /// LookupMethodInType - Look up a method in an ObjCObjectType. 1452 ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, 1453 bool isInstance) { 1454 const ObjCObjectType *objType = type->castAs<ObjCObjectType>(); 1455 if (ObjCInterfaceDecl *iface = objType->getInterface()) { 1456 // Look it up in the main interface (and categories, etc.) 1457 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance)) 1458 return method; 1459 1460 // Okay, look for "private" methods declared in any 1461 // @implementations we've seen. 1462 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance)) 1463 return method; 1464 } 1465 1466 // Check qualifiers. 1467 for (const auto *I : objType->quals()) 1468 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance)) 1469 return method; 1470 1471 return nullptr; 1472 } 1473 1474 /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier 1475 /// list of a qualified objective pointer type. 1476 ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, 1477 const ObjCObjectPointerType *OPT, 1478 bool Instance) 1479 { 1480 ObjCMethodDecl *MD = nullptr; 1481 for (const auto *PROTO : OPT->quals()) { 1482 if ((MD = PROTO->lookupMethod(Sel, Instance))) { 1483 return MD; 1484 } 1485 } 1486 return nullptr; 1487 } 1488 1489 static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) { 1490 if (!Receiver) 1491 return; 1492 1493 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver)) 1494 Receiver = OVE->getSourceExpr(); 1495 1496 Expr *RExpr = Receiver->IgnoreParenImpCasts(); 1497 SourceLocation Loc = RExpr->getLocStart(); 1498 QualType T = RExpr->getType(); 1499 const ObjCPropertyDecl *PDecl = nullptr; 1500 const ObjCMethodDecl *GDecl = nullptr; 1501 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) { 1502 RExpr = POE->getSyntacticForm(); 1503 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) { 1504 if (PRE->isImplicitProperty()) { 1505 GDecl = PRE->getImplicitPropertyGetter(); 1506 if (GDecl) { 1507 T = GDecl->getReturnType(); 1508 } 1509 } 1510 else { 1511 PDecl = PRE->getExplicitProperty(); 1512 if (PDecl) { 1513 T = PDecl->getType(); 1514 } 1515 } 1516 } 1517 } 1518 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) { 1519 // See if receiver is a method which envokes a synthesized getter 1520 // backing a 'weak' property. 1521 ObjCMethodDecl *Method = ME->getMethodDecl(); 1522 if (Method && Method->getSelector().getNumArgs() == 0) { 1523 PDecl = Method->findPropertyDecl(); 1524 if (PDecl) 1525 T = PDecl->getType(); 1526 } 1527 } 1528 1529 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) { 1530 if (!PDecl) 1531 return; 1532 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) 1533 return; 1534 } 1535 1536 S.Diag(Loc, diag::warn_receiver_is_weak) 1537 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2)); 1538 1539 if (PDecl) 1540 S.Diag(PDecl->getLocation(), diag::note_property_declare); 1541 else if (GDecl) 1542 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl; 1543 1544 S.Diag(Loc, diag::note_arc_assign_to_strong); 1545 } 1546 1547 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an 1548 /// objective C interface. This is a property reference expression. 1549 ExprResult Sema:: 1550 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 1551 Expr *BaseExpr, SourceLocation OpLoc, 1552 DeclarationName MemberName, 1553 SourceLocation MemberLoc, 1554 SourceLocation SuperLoc, QualType SuperType, 1555 bool Super) { 1556 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 1557 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 1558 1559 if (!MemberName.isIdentifier()) { 1560 Diag(MemberLoc, diag::err_invalid_property_name) 1561 << MemberName << QualType(OPT, 0); 1562 return ExprError(); 1563 } 1564 1565 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1566 1567 SourceRange BaseRange = Super? SourceRange(SuperLoc) 1568 : BaseExpr->getSourceRange(); 1569 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), 1570 diag::err_property_not_found_forward_class, 1571 MemberName, BaseRange)) 1572 return ExprError(); 1573 1574 // Search for a declared property first. 1575 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { 1576 // Check whether we can reference this property. 1577 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1578 return ExprError(); 1579 if (Super) 1580 return new (Context) 1581 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 1582 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); 1583 else 1584 return new (Context) 1585 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 1586 OK_ObjCProperty, MemberLoc, BaseExpr); 1587 } 1588 // Check protocols on qualified interfaces. 1589 for (const auto *I : OPT->quals()) 1590 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) { 1591 // Check whether we can reference this property. 1592 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1593 return ExprError(); 1594 1595 if (Super) 1596 return new (Context) ObjCPropertyRefExpr( 1597 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, 1598 SuperLoc, SuperType); 1599 else 1600 return new (Context) 1601 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, 1602 OK_ObjCProperty, MemberLoc, BaseExpr); 1603 } 1604 // If that failed, look for an "implicit" property by seeing if the nullary 1605 // selector is implemented. 1606 1607 // FIXME: The logic for looking up nullary and unary selectors should be 1608 // shared with the code in ActOnInstanceMessage. 1609 1610 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1611 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 1612 1613 // May be founf in property's qualified list. 1614 if (!Getter) 1615 Getter = LookupMethodInQualifiedType(Sel, OPT, true); 1616 1617 // If this reference is in an @implementation, check for 'private' methods. 1618 if (!Getter) 1619 Getter = IFace->lookupPrivateMethod(Sel); 1620 1621 if (Getter) { 1622 // Check if we can reference this property. 1623 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1624 return ExprError(); 1625 } 1626 // If we found a getter then this may be a valid dot-reference, we 1627 // will look for the matching setter, in case it is needed. 1628 Selector SetterSel = 1629 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1630 PP.getSelectorTable(), Member); 1631 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 1632 1633 // May be founf in property's qualified list. 1634 if (!Setter) 1635 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); 1636 1637 if (!Setter) { 1638 // If this reference is in an @implementation, also check for 'private' 1639 // methods. 1640 Setter = IFace->lookupPrivateMethod(SetterSel); 1641 } 1642 1643 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1644 return ExprError(); 1645 1646 if (Getter || Setter) { 1647 if (Super) 1648 return new (Context) 1649 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 1650 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType); 1651 else 1652 return new (Context) 1653 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 1654 OK_ObjCProperty, MemberLoc, BaseExpr); 1655 1656 } 1657 1658 // Attempt to correct for typos in property names. 1659 DeclFilterCCC<ObjCPropertyDecl> Validator; 1660 if (TypoCorrection Corrected = CorrectTypo( 1661 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, 1662 nullptr, nullptr, Validator, CTK_ErrorRecovery, IFace, false, OPT)) { 1663 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest) 1664 << MemberName << QualType(OPT, 0)); 1665 DeclarationName TypoResult = Corrected.getCorrection(); 1666 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc, 1667 TypoResult, MemberLoc, 1668 SuperLoc, SuperType, Super); 1669 } 1670 ObjCInterfaceDecl *ClassDeclared; 1671 if (ObjCIvarDecl *Ivar = 1672 IFace->lookupInstanceVariable(Member, ClassDeclared)) { 1673 QualType T = Ivar->getType(); 1674 if (const ObjCObjectPointerType * OBJPT = 1675 T->getAsObjCInterfacePointerType()) { 1676 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), 1677 diag::err_property_not_as_forward_class, 1678 MemberName, BaseExpr)) 1679 return ExprError(); 1680 } 1681 Diag(MemberLoc, 1682 diag::err_ivar_access_using_property_syntax_suggest) 1683 << MemberName << QualType(OPT, 0) << Ivar->getDeclName() 1684 << FixItHint::CreateReplacement(OpLoc, "->"); 1685 return ExprError(); 1686 } 1687 1688 Diag(MemberLoc, diag::err_property_not_found) 1689 << MemberName << QualType(OPT, 0); 1690 if (Setter) 1691 Diag(Setter->getLocation(), diag::note_getter_unavailable) 1692 << MemberName << BaseExpr->getSourceRange(); 1693 return ExprError(); 1694 } 1695 1696 1697 1698 ExprResult Sema:: 1699 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 1700 IdentifierInfo &propertyName, 1701 SourceLocation receiverNameLoc, 1702 SourceLocation propertyNameLoc) { 1703 1704 IdentifierInfo *receiverNamePtr = &receiverName; 1705 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr, 1706 receiverNameLoc); 1707 1708 bool IsSuper = false; 1709 if (!IFace) { 1710 // If the "receiver" is 'super' in a method, handle it as an expression-like 1711 // property reference. 1712 if (receiverNamePtr->isStr("super")) { 1713 IsSuper = true; 1714 1715 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) { 1716 if (CurMethod->isInstanceMethod()) { 1717 ObjCInterfaceDecl *Super = 1718 CurMethod->getClassInterface()->getSuperClass(); 1719 if (!Super) { 1720 // The current class does not have a superclass. 1721 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super) 1722 << CurMethod->getClassInterface()->getIdentifier(); 1723 return ExprError(); 1724 } 1725 QualType T = Context.getObjCInterfaceType(Super); 1726 T = Context.getObjCObjectPointerType(T); 1727 1728 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(), 1729 /*BaseExpr*/nullptr, 1730 SourceLocation()/*OpLoc*/, 1731 &propertyName, 1732 propertyNameLoc, 1733 receiverNameLoc, T, true); 1734 } 1735 1736 // Otherwise, if this is a class method, try dispatching to our 1737 // superclass. 1738 IFace = CurMethod->getClassInterface()->getSuperClass(); 1739 } 1740 } 1741 1742 if (!IFace) { 1743 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier 1744 << tok::l_paren; 1745 return ExprError(); 1746 } 1747 } 1748 1749 // Search for a declared property first. 1750 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); 1751 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel); 1752 1753 // If this reference is in an @implementation, check for 'private' methods. 1754 if (!Getter) 1755 Getter = IFace->lookupPrivateClassMethod(Sel); 1756 1757 if (Getter) { 1758 // FIXME: refactor/share with ActOnMemberReference(). 1759 // Check if we can reference this property. 1760 if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) 1761 return ExprError(); 1762 } 1763 1764 // Look for the matching setter, in case it is needed. 1765 Selector SetterSel = 1766 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1767 PP.getSelectorTable(), 1768 &propertyName); 1769 1770 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 1771 if (!Setter) { 1772 // If this reference is in an @implementation, also check for 'private' 1773 // methods. 1774 Setter = IFace->lookupPrivateClassMethod(SetterSel); 1775 } 1776 // Look through local category implementations associated with the class. 1777 if (!Setter) 1778 Setter = IFace->getCategoryClassMethod(SetterSel); 1779 1780 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) 1781 return ExprError(); 1782 1783 if (Getter || Setter) { 1784 if (IsSuper) 1785 return new (Context) 1786 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, 1787 OK_ObjCProperty, propertyNameLoc, receiverNameLoc, 1788 Context.getObjCInterfaceType(IFace)); 1789 1790 return new (Context) ObjCPropertyRefExpr( 1791 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, 1792 propertyNameLoc, receiverNameLoc, IFace); 1793 } 1794 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) 1795 << &propertyName << Context.getObjCInterfaceType(IFace)); 1796 } 1797 1798 namespace { 1799 1800 class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback { 1801 public: 1802 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) { 1803 // Determine whether "super" is acceptable in the current context. 1804 if (Method && Method->getClassInterface()) 1805 WantObjCSuper = Method->getClassInterface()->getSuperClass(); 1806 } 1807 1808 bool ValidateCandidate(const TypoCorrection &candidate) override { 1809 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() || 1810 candidate.isKeyword("super"); 1811 } 1812 }; 1813 1814 } 1815 1816 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, 1817 IdentifierInfo *Name, 1818 SourceLocation NameLoc, 1819 bool IsSuper, 1820 bool HasTrailingDot, 1821 ParsedType &ReceiverType) { 1822 ReceiverType = ParsedType(); 1823 1824 // If the identifier is "super" and there is no trailing dot, we're 1825 // messaging super. If the identifier is "super" and there is a 1826 // trailing dot, it's an instance message. 1827 if (IsSuper && S->isInObjcMethodScope()) 1828 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; 1829 1830 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 1831 LookupName(Result, S); 1832 1833 switch (Result.getResultKind()) { 1834 case LookupResult::NotFound: 1835 // Normal name lookup didn't find anything. If we're in an 1836 // Objective-C method, look for ivars. If we find one, we're done! 1837 // FIXME: This is a hack. Ivar lookup should be part of normal 1838 // lookup. 1839 if (ObjCMethodDecl *Method = getCurMethodDecl()) { 1840 if (!Method->getClassInterface()) { 1841 // Fall back: let the parser try to parse it as an instance message. 1842 return ObjCInstanceMessage; 1843 } 1844 1845 ObjCInterfaceDecl *ClassDeclared; 1846 if (Method->getClassInterface()->lookupInstanceVariable(Name, 1847 ClassDeclared)) 1848 return ObjCInstanceMessage; 1849 } 1850 1851 // Break out; we'll perform typo correction below. 1852 break; 1853 1854 case LookupResult::NotFoundInCurrentInstantiation: 1855 case LookupResult::FoundOverloaded: 1856 case LookupResult::FoundUnresolvedValue: 1857 case LookupResult::Ambiguous: 1858 Result.suppressDiagnostics(); 1859 return ObjCInstanceMessage; 1860 1861 case LookupResult::Found: { 1862 // If the identifier is a class or not, and there is a trailing dot, 1863 // it's an instance message. 1864 if (HasTrailingDot) 1865 return ObjCInstanceMessage; 1866 // We found something. If it's a type, then we have a class 1867 // message. Otherwise, it's an instance message. 1868 NamedDecl *ND = Result.getFoundDecl(); 1869 QualType T; 1870 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) 1871 T = Context.getObjCInterfaceType(Class); 1872 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) { 1873 T = Context.getTypeDeclType(Type); 1874 DiagnoseUseOfDecl(Type, NameLoc); 1875 } 1876 else 1877 return ObjCInstanceMessage; 1878 1879 // We have a class message, and T is the type we're 1880 // messaging. Build source-location information for it. 1881 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 1882 ReceiverType = CreateParsedType(T, TSInfo); 1883 return ObjCClassMessage; 1884 } 1885 } 1886 1887 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl()); 1888 if (TypoCorrection Corrected = 1889 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, 1890 nullptr, Validator, CTK_ErrorRecovery, nullptr, false, 1891 nullptr, false)) { 1892 if (Corrected.isKeyword()) { 1893 // If we've found the keyword "super" (the only keyword that would be 1894 // returned by CorrectTypo), this is a send to super. 1895 diagnoseTypo(Corrected, 1896 PDiag(diag::err_unknown_receiver_suggest) << Name); 1897 return ObjCSuperMessage; 1898 } else if (ObjCInterfaceDecl *Class = 1899 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1900 // If we found a declaration, correct when it refers to an Objective-C 1901 // class. 1902 diagnoseTypo(Corrected, 1903 PDiag(diag::err_unknown_receiver_suggest) << Name); 1904 QualType T = Context.getObjCInterfaceType(Class); 1905 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 1906 ReceiverType = CreateParsedType(T, TSInfo); 1907 return ObjCClassMessage; 1908 } 1909 } 1910 1911 // Fall back: let the parser try to parse it as an instance message. 1912 return ObjCInstanceMessage; 1913 } 1914 1915 ExprResult Sema::ActOnSuperMessage(Scope *S, 1916 SourceLocation SuperLoc, 1917 Selector Sel, 1918 SourceLocation LBracLoc, 1919 ArrayRef<SourceLocation> SelectorLocs, 1920 SourceLocation RBracLoc, 1921 MultiExprArg Args) { 1922 // Determine whether we are inside a method or not. 1923 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc); 1924 if (!Method) { 1925 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super); 1926 return ExprError(); 1927 } 1928 1929 ObjCInterfaceDecl *Class = Method->getClassInterface(); 1930 if (!Class) { 1931 Diag(SuperLoc, diag::error_no_super_class_message) 1932 << Method->getDeclName(); 1933 return ExprError(); 1934 } 1935 1936 ObjCInterfaceDecl *Super = Class->getSuperClass(); 1937 if (!Super) { 1938 // The current class does not have a superclass. 1939 Diag(SuperLoc, diag::error_root_class_cannot_use_super) 1940 << Class->getIdentifier(); 1941 return ExprError(); 1942 } 1943 1944 // We are in a method whose class has a superclass, so 'super' 1945 // is acting as a keyword. 1946 if (Method->getSelector() == Sel) 1947 getCurFunction()->ObjCShouldCallSuper = false; 1948 1949 if (Method->isInstanceMethod()) { 1950 // Since we are in an instance method, this is an instance 1951 // message to the superclass instance. 1952 QualType SuperTy = Context.getObjCInterfaceType(Super); 1953 SuperTy = Context.getObjCObjectPointerType(SuperTy); 1954 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc, 1955 Sel, /*Method=*/nullptr, 1956 LBracLoc, SelectorLocs, RBracLoc, Args); 1957 } 1958 1959 // Since we are in a class method, this is a class message to 1960 // the superclass. 1961 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr, 1962 Context.getObjCInterfaceType(Super), 1963 SuperLoc, Sel, /*Method=*/nullptr, 1964 LBracLoc, SelectorLocs, RBracLoc, Args); 1965 } 1966 1967 1968 ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType, 1969 bool isSuperReceiver, 1970 SourceLocation Loc, 1971 Selector Sel, 1972 ObjCMethodDecl *Method, 1973 MultiExprArg Args) { 1974 TypeSourceInfo *receiverTypeInfo = nullptr; 1975 if (!ReceiverType.isNull()) 1976 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType); 1977 1978 return BuildClassMessage(receiverTypeInfo, ReceiverType, 1979 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(), 1980 Sel, Method, Loc, Loc, Loc, Args, 1981 /*isImplicit=*/true); 1982 1983 } 1984 1985 static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg, 1986 unsigned DiagID, 1987 bool (*refactor)(const ObjCMessageExpr *, 1988 const NSAPI &, edit::Commit &)) { 1989 SourceLocation MsgLoc = Msg->getExprLoc(); 1990 if (S.Diags.isIgnored(DiagID, MsgLoc)) 1991 return; 1992 1993 SourceManager &SM = S.SourceMgr; 1994 edit::Commit ECommit(SM, S.LangOpts); 1995 if (refactor(Msg,*S.NSAPIObj, ECommit)) { 1996 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID) 1997 << Msg->getSelector() << Msg->getSourceRange(); 1998 // FIXME: Don't emit diagnostic at all if fixits are non-commitable. 1999 if (!ECommit.isCommitable()) 2000 return; 2001 for (edit::Commit::edit_iterator 2002 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) { 2003 const edit::Commit::Edit &Edit = *I; 2004 switch (Edit.Kind) { 2005 case edit::Commit::Act_Insert: 2006 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc, 2007 Edit.Text, 2008 Edit.BeforePrev)); 2009 break; 2010 case edit::Commit::Act_InsertFromRange: 2011 Builder.AddFixItHint( 2012 FixItHint::CreateInsertionFromRange(Edit.OrigLoc, 2013 Edit.getInsertFromRange(SM), 2014 Edit.BeforePrev)); 2015 break; 2016 case edit::Commit::Act_Remove: 2017 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM))); 2018 break; 2019 } 2020 } 2021 } 2022 } 2023 2024 static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) { 2025 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use, 2026 edit::rewriteObjCRedundantCallWithLiteral); 2027 } 2028 2029 /// \brief Build an Objective-C class message expression. 2030 /// 2031 /// This routine takes care of both normal class messages and 2032 /// class messages to the superclass. 2033 /// 2034 /// \param ReceiverTypeInfo Type source information that describes the 2035 /// receiver of this message. This may be NULL, in which case we are 2036 /// sending to the superclass and \p SuperLoc must be a valid source 2037 /// location. 2038 2039 /// \param ReceiverType The type of the object receiving the 2040 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same 2041 /// type as that refers to. For a superclass send, this is the type of 2042 /// the superclass. 2043 /// 2044 /// \param SuperLoc The location of the "super" keyword in a 2045 /// superclass message. 2046 /// 2047 /// \param Sel The selector to which the message is being sent. 2048 /// 2049 /// \param Method The method that this class message is invoking, if 2050 /// already known. 2051 /// 2052 /// \param LBracLoc The location of the opening square bracket ']'. 2053 /// 2054 /// \param RBracLoc The location of the closing square bracket ']'. 2055 /// 2056 /// \param ArgsIn The message arguments. 2057 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 2058 QualType ReceiverType, 2059 SourceLocation SuperLoc, 2060 Selector Sel, 2061 ObjCMethodDecl *Method, 2062 SourceLocation LBracLoc, 2063 ArrayRef<SourceLocation> SelectorLocs, 2064 SourceLocation RBracLoc, 2065 MultiExprArg ArgsIn, 2066 bool isImplicit) { 2067 SourceLocation Loc = SuperLoc.isValid()? SuperLoc 2068 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin(); 2069 if (LBracLoc.isInvalid()) { 2070 Diag(Loc, diag::err_missing_open_square_message_send) 2071 << FixItHint::CreateInsertion(Loc, "["); 2072 LBracLoc = Loc; 2073 } 2074 SourceLocation SelLoc; 2075 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 2076 SelLoc = SelectorLocs.front(); 2077 else 2078 SelLoc = Loc; 2079 2080 if (ReceiverType->isDependentType()) { 2081 // If the receiver type is dependent, we can't type-check anything 2082 // at this point. Build a dependent expression. 2083 unsigned NumArgs = ArgsIn.size(); 2084 Expr **Args = ArgsIn.data(); 2085 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 2086 return ObjCMessageExpr::Create( 2087 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel, 2088 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc, 2089 isImplicit); 2090 } 2091 2092 // Find the class to which we are sending this message. 2093 ObjCInterfaceDecl *Class = nullptr; 2094 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); 2095 if (!ClassType || !(Class = ClassType->getInterface())) { 2096 Diag(Loc, diag::err_invalid_receiver_class_message) 2097 << ReceiverType; 2098 return ExprError(); 2099 } 2100 assert(Class && "We don't know which class we're messaging?"); 2101 // objc++ diagnoses during typename annotation. 2102 if (!getLangOpts().CPlusPlus) 2103 (void)DiagnoseUseOfDecl(Class, SelLoc); 2104 // Find the method we are messaging. 2105 if (!Method) { 2106 SourceRange TypeRange 2107 = SuperLoc.isValid()? SourceRange(SuperLoc) 2108 : ReceiverTypeInfo->getTypeLoc().getSourceRange(); 2109 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), 2110 (getLangOpts().ObjCAutoRefCount 2111 ? diag::err_arc_receiver_forward_class 2112 : diag::warn_receiver_forward_class), 2113 TypeRange)) { 2114 // A forward class used in messaging is treated as a 'Class' 2115 Method = LookupFactoryMethodInGlobalPool(Sel, 2116 SourceRange(LBracLoc, RBracLoc)); 2117 if (Method && !getLangOpts().ObjCAutoRefCount) 2118 Diag(Method->getLocation(), diag::note_method_sent_forward_class) 2119 << Method->getDeclName(); 2120 } 2121 if (!Method) 2122 Method = Class->lookupClassMethod(Sel); 2123 2124 // If we have an implementation in scope, check "private" methods. 2125 if (!Method) 2126 Method = Class->lookupPrivateClassMethod(Sel); 2127 2128 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 2129 return ExprError(); 2130 } 2131 2132 // Check the argument types and determine the result type. 2133 QualType ReturnType; 2134 ExprValueKind VK = VK_RValue; 2135 2136 unsigned NumArgs = ArgsIn.size(); 2137 Expr **Args = ArgsIn.data(); 2138 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), 2139 Sel, SelectorLocs, 2140 Method, true, 2141 SuperLoc.isValid(), LBracLoc, RBracLoc, 2142 ReturnType, VK)) 2143 return ExprError(); 2144 2145 if (Method && !Method->getReturnType()->isVoidType() && 2146 RequireCompleteType(LBracLoc, Method->getReturnType(), 2147 diag::err_illegal_message_expr_incomplete_type)) 2148 return ExprError(); 2149 2150 // Construct the appropriate ObjCMessageExpr. 2151 ObjCMessageExpr *Result; 2152 if (SuperLoc.isValid()) 2153 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2154 SuperLoc, /*IsInstanceSuper=*/false, 2155 ReceiverType, Sel, SelectorLocs, 2156 Method, makeArrayRef(Args, NumArgs), 2157 RBracLoc, isImplicit); 2158 else { 2159 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2160 ReceiverTypeInfo, Sel, SelectorLocs, 2161 Method, makeArrayRef(Args, NumArgs), 2162 RBracLoc, isImplicit); 2163 if (!isImplicit) 2164 checkCocoaAPI(*this, Result); 2165 } 2166 return MaybeBindToTemporary(Result); 2167 } 2168 2169 // ActOnClassMessage - used for both unary and keyword messages. 2170 // ArgExprs is optional - if it is present, the number of expressions 2171 // is obtained from Sel.getNumArgs(). 2172 ExprResult Sema::ActOnClassMessage(Scope *S, 2173 ParsedType Receiver, 2174 Selector Sel, 2175 SourceLocation LBracLoc, 2176 ArrayRef<SourceLocation> SelectorLocs, 2177 SourceLocation RBracLoc, 2178 MultiExprArg Args) { 2179 TypeSourceInfo *ReceiverTypeInfo; 2180 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo); 2181 if (ReceiverType.isNull()) 2182 return ExprError(); 2183 2184 2185 if (!ReceiverTypeInfo) 2186 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); 2187 2188 return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 2189 /*SuperLoc=*/SourceLocation(), Sel, 2190 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc, 2191 Args); 2192 } 2193 2194 ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver, 2195 QualType ReceiverType, 2196 SourceLocation Loc, 2197 Selector Sel, 2198 ObjCMethodDecl *Method, 2199 MultiExprArg Args) { 2200 return BuildInstanceMessage(Receiver, ReceiverType, 2201 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(), 2202 Sel, Method, Loc, Loc, Loc, Args, 2203 /*isImplicit=*/true); 2204 } 2205 2206 /// \brief Build an Objective-C instance message expression. 2207 /// 2208 /// This routine takes care of both normal instance messages and 2209 /// instance messages to the superclass instance. 2210 /// 2211 /// \param Receiver The expression that computes the object that will 2212 /// receive this message. This may be empty, in which case we are 2213 /// sending to the superclass instance and \p SuperLoc must be a valid 2214 /// source location. 2215 /// 2216 /// \param ReceiverType The (static) type of the object receiving the 2217 /// message. When a \p Receiver expression is provided, this is the 2218 /// same type as that expression. For a superclass instance send, this 2219 /// is a pointer to the type of the superclass. 2220 /// 2221 /// \param SuperLoc The location of the "super" keyword in a 2222 /// superclass instance message. 2223 /// 2224 /// \param Sel The selector to which the message is being sent. 2225 /// 2226 /// \param Method The method that this instance message is invoking, if 2227 /// already known. 2228 /// 2229 /// \param LBracLoc The location of the opening square bracket ']'. 2230 /// 2231 /// \param RBracLoc The location of the closing square bracket ']'. 2232 /// 2233 /// \param ArgsIn The message arguments. 2234 ExprResult Sema::BuildInstanceMessage(Expr *Receiver, 2235 QualType ReceiverType, 2236 SourceLocation SuperLoc, 2237 Selector Sel, 2238 ObjCMethodDecl *Method, 2239 SourceLocation LBracLoc, 2240 ArrayRef<SourceLocation> SelectorLocs, 2241 SourceLocation RBracLoc, 2242 MultiExprArg ArgsIn, 2243 bool isImplicit) { 2244 // The location of the receiver. 2245 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart(); 2246 SourceRange RecRange = 2247 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange(); 2248 SourceLocation SelLoc; 2249 if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) 2250 SelLoc = SelectorLocs.front(); 2251 else 2252 SelLoc = Loc; 2253 2254 if (LBracLoc.isInvalid()) { 2255 Diag(Loc, diag::err_missing_open_square_message_send) 2256 << FixItHint::CreateInsertion(Loc, "["); 2257 LBracLoc = Loc; 2258 } 2259 2260 // If we have a receiver expression, perform appropriate promotions 2261 // and determine receiver type. 2262 if (Receiver) { 2263 if (Receiver->hasPlaceholderType()) { 2264 ExprResult Result; 2265 if (Receiver->getType() == Context.UnknownAnyTy) 2266 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType()); 2267 else 2268 Result = CheckPlaceholderExpr(Receiver); 2269 if (Result.isInvalid()) return ExprError(); 2270 Receiver = Result.get(); 2271 } 2272 2273 if (Receiver->isTypeDependent()) { 2274 // If the receiver is type-dependent, we can't type-check anything 2275 // at this point. Build a dependent expression. 2276 unsigned NumArgs = ArgsIn.size(); 2277 Expr **Args = ArgsIn.data(); 2278 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 2279 return ObjCMessageExpr::Create( 2280 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel, 2281 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), 2282 RBracLoc, isImplicit); 2283 } 2284 2285 // If necessary, apply function/array conversion to the receiver. 2286 // C99 6.7.5.3p[7,8]. 2287 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver); 2288 if (Result.isInvalid()) 2289 return ExprError(); 2290 Receiver = Result.get(); 2291 ReceiverType = Receiver->getType(); 2292 2293 // If the receiver is an ObjC pointer, a block pointer, or an 2294 // __attribute__((NSObject)) pointer, we don't need to do any 2295 // special conversion in order to look up a receiver. 2296 if (ReceiverType->isObjCRetainableType()) { 2297 // do nothing 2298 } else if (!getLangOpts().ObjCAutoRefCount && 2299 !Context.getObjCIdType().isNull() && 2300 (ReceiverType->isPointerType() || 2301 ReceiverType->isIntegerType())) { 2302 // Implicitly convert integers and pointers to 'id' but emit a warning. 2303 // But not in ARC. 2304 Diag(Loc, diag::warn_bad_receiver_type) 2305 << ReceiverType 2306 << Receiver->getSourceRange(); 2307 if (ReceiverType->isPointerType()) { 2308 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 2309 CK_CPointerToObjCPointerCast).get(); 2310 } else { 2311 // TODO: specialized warning on null receivers? 2312 bool IsNull = Receiver->isNullPointerConstant(Context, 2313 Expr::NPC_ValueDependentIsNull); 2314 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer; 2315 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), 2316 Kind).get(); 2317 } 2318 ReceiverType = Receiver->getType(); 2319 } else if (getLangOpts().CPlusPlus) { 2320 // The receiver must be a complete type. 2321 if (RequireCompleteType(Loc, Receiver->getType(), 2322 diag::err_incomplete_receiver_type)) 2323 return ExprError(); 2324 2325 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver); 2326 if (result.isUsable()) { 2327 Receiver = result.get(); 2328 ReceiverType = Receiver->getType(); 2329 } 2330 } 2331 } 2332 2333 // There's a somewhat weird interaction here where we assume that we 2334 // won't actually have a method unless we also don't need to do some 2335 // of the more detailed type-checking on the receiver. 2336 2337 if (!Method) { 2338 // Handle messages to id. 2339 bool receiverIsId = ReceiverType->isObjCIdType(); 2340 if (receiverIsId || ReceiverType->isBlockPointerType() || 2341 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) { 2342 Method = LookupInstanceMethodInGlobalPool(Sel, 2343 SourceRange(LBracLoc, RBracLoc), 2344 receiverIsId); 2345 if (!Method) 2346 Method = LookupFactoryMethodInGlobalPool(Sel, 2347 SourceRange(LBracLoc,RBracLoc), 2348 receiverIsId); 2349 } else if (ReceiverType->isObjCClassType() || 2350 ReceiverType->isObjCQualifiedClassType()) { 2351 // Handle messages to Class. 2352 // We allow sending a message to a qualified Class ("Class<foo>"), which 2353 // is ok as long as one of the protocols implements the selector (if not, warn). 2354 if (const ObjCObjectPointerType *QClassTy 2355 = ReceiverType->getAsObjCQualifiedClassType()) { 2356 // Search protocols for class methods. 2357 Method = LookupMethodInQualifiedType(Sel, QClassTy, false); 2358 if (!Method) { 2359 Method = LookupMethodInQualifiedType(Sel, QClassTy, true); 2360 // warn if instance method found for a Class message. 2361 if (Method) { 2362 Diag(SelLoc, diag::warn_instance_method_on_class_found) 2363 << Method->getSelector() << Sel; 2364 Diag(Method->getLocation(), diag::note_method_declared_at) 2365 << Method->getDeclName(); 2366 } 2367 } 2368 } else { 2369 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 2370 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { 2371 // First check the public methods in the class interface. 2372 Method = ClassDecl->lookupClassMethod(Sel); 2373 2374 if (!Method) 2375 Method = ClassDecl->lookupPrivateClassMethod(Sel); 2376 } 2377 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 2378 return ExprError(); 2379 } 2380 if (!Method) { 2381 // If not messaging 'self', look for any factory method named 'Sel'. 2382 if (!Receiver || !isSelfExpr(Receiver)) { 2383 Method = LookupFactoryMethodInGlobalPool(Sel, 2384 SourceRange(LBracLoc, RBracLoc), 2385 true); 2386 if (!Method) { 2387 // If no class (factory) method was found, check if an _instance_ 2388 // method of the same name exists in the root class only. 2389 Method = LookupInstanceMethodInGlobalPool(Sel, 2390 SourceRange(LBracLoc, RBracLoc), 2391 true); 2392 if (Method) 2393 if (const ObjCInterfaceDecl *ID = 2394 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { 2395 if (ID->getSuperClass()) 2396 Diag(SelLoc, diag::warn_root_inst_method_not_found) 2397 << Sel << SourceRange(LBracLoc, RBracLoc); 2398 } 2399 } 2400 } 2401 } 2402 } 2403 } else { 2404 ObjCInterfaceDecl *ClassDecl = nullptr; 2405 2406 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as 2407 // long as one of the protocols implements the selector (if not, warn). 2408 // And as long as message is not deprecated/unavailable (warn if it is). 2409 if (const ObjCObjectPointerType *QIdTy 2410 = ReceiverType->getAsObjCQualifiedIdType()) { 2411 // Search protocols for instance methods. 2412 Method = LookupMethodInQualifiedType(Sel, QIdTy, true); 2413 if (!Method) 2414 Method = LookupMethodInQualifiedType(Sel, QIdTy, false); 2415 if (Method && DiagnoseUseOfDecl(Method, SelLoc)) 2416 return ExprError(); 2417 } else if (const ObjCObjectPointerType *OCIType 2418 = ReceiverType->getAsObjCInterfacePointerType()) { 2419 // We allow sending a message to a pointer to an interface (an object). 2420 ClassDecl = OCIType->getInterfaceDecl(); 2421 2422 // Try to complete the type. Under ARC, this is a hard error from which 2423 // we don't try to recover. 2424 const ObjCInterfaceDecl *forwardClass = nullptr; 2425 if (RequireCompleteType(Loc, OCIType->getPointeeType(), 2426 getLangOpts().ObjCAutoRefCount 2427 ? diag::err_arc_receiver_forward_instance 2428 : diag::warn_receiver_forward_instance, 2429 Receiver? Receiver->getSourceRange() 2430 : SourceRange(SuperLoc))) { 2431 if (getLangOpts().ObjCAutoRefCount) 2432 return ExprError(); 2433 2434 forwardClass = OCIType->getInterfaceDecl(); 2435 Diag(Receiver ? Receiver->getLocStart() 2436 : SuperLoc, diag::note_receiver_is_id); 2437 Method = nullptr; 2438 } else { 2439 Method = ClassDecl->lookupInstanceMethod(Sel); 2440 } 2441 2442 if (!Method) 2443 // Search protocol qualifiers. 2444 Method = LookupMethodInQualifiedType(Sel, OCIType, true); 2445 2446 if (!Method) { 2447 // If we have implementations in scope, check "private" methods. 2448 Method = ClassDecl->lookupPrivateMethod(Sel); 2449 2450 if (!Method && getLangOpts().ObjCAutoRefCount) { 2451 Diag(SelLoc, diag::err_arc_may_not_respond) 2452 << OCIType->getPointeeType() << Sel << RecRange 2453 << SourceRange(SelectorLocs.front(), SelectorLocs.back()); 2454 return ExprError(); 2455 } 2456 2457 if (!Method && (!Receiver || !isSelfExpr(Receiver))) { 2458 // If we still haven't found a method, look in the global pool. This 2459 // behavior isn't very desirable, however we need it for GCC 2460 // compatibility. FIXME: should we deviate?? 2461 if (OCIType->qual_empty()) { 2462 Method = LookupInstanceMethodInGlobalPool(Sel, 2463 SourceRange(LBracLoc, RBracLoc)); 2464 if (Method && !forwardClass) 2465 Diag(SelLoc, diag::warn_maynot_respond) 2466 << OCIType->getInterfaceDecl()->getIdentifier() 2467 << Sel << RecRange; 2468 } 2469 } 2470 } 2471 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass)) 2472 return ExprError(); 2473 } else { 2474 // Reject other random receiver types (e.g. structs). 2475 Diag(Loc, diag::err_bad_receiver_type) 2476 << ReceiverType << Receiver->getSourceRange(); 2477 return ExprError(); 2478 } 2479 } 2480 } 2481 2482 FunctionScopeInfo *DIFunctionScopeInfo = 2483 (Method && Method->getMethodFamily() == OMF_init) 2484 ? getEnclosingFunction() : nullptr; 2485 2486 if (DIFunctionScopeInfo && 2487 DIFunctionScopeInfo->ObjCIsDesignatedInit && 2488 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 2489 bool isDesignatedInitChain = false; 2490 if (SuperLoc.isValid()) { 2491 if (const ObjCObjectPointerType * 2492 OCIType = ReceiverType->getAsObjCInterfacePointerType()) { 2493 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) { 2494 // Either we know this is a designated initializer or we 2495 // conservatively assume it because we don't know for sure. 2496 if (!ID->declaresOrInheritsDesignatedInitializers() || 2497 ID->isDesignatedInitializer(Sel)) { 2498 isDesignatedInitChain = true; 2499 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false; 2500 } 2501 } 2502 } 2503 } 2504 if (!isDesignatedInitChain) { 2505 const ObjCMethodDecl *InitMethod = nullptr; 2506 bool isDesignated = 2507 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod); 2508 assert(isDesignated && InitMethod); 2509 (void)isDesignated; 2510 Diag(SelLoc, SuperLoc.isValid() ? 2511 diag::warn_objc_designated_init_non_designated_init_call : 2512 diag::warn_objc_designated_init_non_super_designated_init_call); 2513 Diag(InitMethod->getLocation(), 2514 diag::note_objc_designated_init_marked_here); 2515 } 2516 } 2517 2518 if (DIFunctionScopeInfo && 2519 DIFunctionScopeInfo->ObjCIsSecondaryInit && 2520 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 2521 if (SuperLoc.isValid()) { 2522 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call); 2523 } else { 2524 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false; 2525 } 2526 } 2527 2528 // Check the message arguments. 2529 unsigned NumArgs = ArgsIn.size(); 2530 Expr **Args = ArgsIn.data(); 2531 QualType ReturnType; 2532 ExprValueKind VK = VK_RValue; 2533 bool ClassMessage = (ReceiverType->isObjCClassType() || 2534 ReceiverType->isObjCQualifiedClassType()); 2535 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), 2536 Sel, SelectorLocs, Method, 2537 ClassMessage, SuperLoc.isValid(), 2538 LBracLoc, RBracLoc, ReturnType, VK)) 2539 return ExprError(); 2540 2541 if (Method && !Method->getReturnType()->isVoidType() && 2542 RequireCompleteType(LBracLoc, Method->getReturnType(), 2543 diag::err_illegal_message_expr_incomplete_type)) 2544 return ExprError(); 2545 2546 // In ARC, forbid the user from sending messages to 2547 // retain/release/autorelease/dealloc/retainCount explicitly. 2548 if (getLangOpts().ObjCAutoRefCount) { 2549 ObjCMethodFamily family = 2550 (Method ? Method->getMethodFamily() : Sel.getMethodFamily()); 2551 switch (family) { 2552 case OMF_init: 2553 if (Method) 2554 checkInitMethod(Method, ReceiverType); 2555 2556 case OMF_None: 2557 case OMF_alloc: 2558 case OMF_copy: 2559 case OMF_finalize: 2560 case OMF_mutableCopy: 2561 case OMF_new: 2562 case OMF_self: 2563 break; 2564 2565 case OMF_dealloc: 2566 case OMF_retain: 2567 case OMF_release: 2568 case OMF_autorelease: 2569 case OMF_retainCount: 2570 Diag(SelLoc, diag::err_arc_illegal_explicit_message) 2571 << Sel << RecRange; 2572 break; 2573 2574 case OMF_performSelector: 2575 if (Method && NumArgs >= 1) { 2576 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) { 2577 Selector ArgSel = SelExp->getSelector(); 2578 ObjCMethodDecl *SelMethod = 2579 LookupInstanceMethodInGlobalPool(ArgSel, 2580 SelExp->getSourceRange()); 2581 if (!SelMethod) 2582 SelMethod = 2583 LookupFactoryMethodInGlobalPool(ArgSel, 2584 SelExp->getSourceRange()); 2585 if (SelMethod) { 2586 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily(); 2587 switch (SelFamily) { 2588 case OMF_alloc: 2589 case OMF_copy: 2590 case OMF_mutableCopy: 2591 case OMF_new: 2592 case OMF_self: 2593 case OMF_init: 2594 // Issue error, unless ns_returns_not_retained. 2595 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { 2596 // selector names a +1 method 2597 Diag(SelLoc, 2598 diag::err_arc_perform_selector_retains); 2599 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 2600 << SelMethod->getDeclName(); 2601 } 2602 break; 2603 default: 2604 // +0 call. OK. unless ns_returns_retained. 2605 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { 2606 // selector names a +1 method 2607 Diag(SelLoc, 2608 diag::err_arc_perform_selector_retains); 2609 Diag(SelMethod->getLocation(), diag::note_method_declared_at) 2610 << SelMethod->getDeclName(); 2611 } 2612 break; 2613 } 2614 } 2615 } else { 2616 // error (may leak). 2617 Diag(SelLoc, diag::warn_arc_perform_selector_leaks); 2618 Diag(Args[0]->getExprLoc(), diag::note_used_here); 2619 } 2620 } 2621 break; 2622 } 2623 } 2624 2625 // Construct the appropriate ObjCMessageExpr instance. 2626 ObjCMessageExpr *Result; 2627 if (SuperLoc.isValid()) 2628 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2629 SuperLoc, /*IsInstanceSuper=*/true, 2630 ReceiverType, Sel, SelectorLocs, Method, 2631 makeArrayRef(Args, NumArgs), RBracLoc, 2632 isImplicit); 2633 else { 2634 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, 2635 Receiver, Sel, SelectorLocs, Method, 2636 makeArrayRef(Args, NumArgs), RBracLoc, 2637 isImplicit); 2638 if (!isImplicit) 2639 checkCocoaAPI(*this, Result); 2640 } 2641 2642 if (getLangOpts().ObjCAutoRefCount) { 2643 // Do not warn about IBOutlet weak property receivers being set to null 2644 // as this cannot asynchronously happen. 2645 bool WarnWeakReceiver = true; 2646 if (isImplicit && Method) 2647 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl()) 2648 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>(); 2649 if (WarnWeakReceiver) 2650 DiagnoseARCUseOfWeakReceiver(*this, Receiver); 2651 2652 // In ARC, annotate delegate init calls. 2653 if (Result->getMethodFamily() == OMF_init && 2654 (SuperLoc.isValid() || isSelfExpr(Receiver))) { 2655 // Only consider init calls *directly* in init implementations, 2656 // not within blocks. 2657 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext); 2658 if (method && method->getMethodFamily() == OMF_init) { 2659 // The implicit assignment to self means we also don't want to 2660 // consume the result. 2661 Result->setDelegateInitCall(true); 2662 return Result; 2663 } 2664 } 2665 2666 // In ARC, check for message sends which are likely to introduce 2667 // retain cycles. 2668 checkRetainCycles(Result); 2669 2670 if (!isImplicit && Method) { 2671 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) { 2672 bool IsWeak = 2673 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak; 2674 if (!IsWeak && Sel.isUnarySelector()) 2675 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak; 2676 if (IsWeak && 2677 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc)) 2678 getCurFunction()->recordUseOfWeak(Result, Prop); 2679 } 2680 } 2681 } 2682 2683 return MaybeBindToTemporary(Result); 2684 } 2685 2686 static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { 2687 if (ObjCSelectorExpr *OSE = 2688 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) { 2689 Selector Sel = OSE->getSelector(); 2690 SourceLocation Loc = OSE->getAtLoc(); 2691 llvm::DenseMap<Selector, SourceLocation>::iterator Pos 2692 = S.ReferencedSelectors.find(Sel); 2693 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc) 2694 S.ReferencedSelectors.erase(Pos); 2695 } 2696 } 2697 2698 // ActOnInstanceMessage - used for both unary and keyword messages. 2699 // ArgExprs is optional - if it is present, the number of expressions 2700 // is obtained from Sel.getNumArgs(). 2701 ExprResult Sema::ActOnInstanceMessage(Scope *S, 2702 Expr *Receiver, 2703 Selector Sel, 2704 SourceLocation LBracLoc, 2705 ArrayRef<SourceLocation> SelectorLocs, 2706 SourceLocation RBracLoc, 2707 MultiExprArg Args) { 2708 if (!Receiver) 2709 return ExprError(); 2710 2711 // A ParenListExpr can show up while doing error recovery with invalid code. 2712 if (isa<ParenListExpr>(Receiver)) { 2713 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver); 2714 if (Result.isInvalid()) return ExprError(); 2715 Receiver = Result.get(); 2716 } 2717 2718 if (RespondsToSelectorSel.isNull()) { 2719 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); 2720 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); 2721 } 2722 if (Sel == RespondsToSelectorSel) 2723 RemoveSelectorFromWarningCache(*this, Args[0]); 2724 2725 return BuildInstanceMessage(Receiver, Receiver->getType(), 2726 /*SuperLoc=*/SourceLocation(), Sel, 2727 /*Method=*/nullptr, LBracLoc, SelectorLocs, 2728 RBracLoc, Args); 2729 } 2730 2731 enum ARCConversionTypeClass { 2732 /// int, void, struct A 2733 ACTC_none, 2734 2735 /// id, void (^)() 2736 ACTC_retainable, 2737 2738 /// id*, id***, void (^*)(), 2739 ACTC_indirectRetainable, 2740 2741 /// void* might be a normal C type, or it might a CF type. 2742 ACTC_voidPtr, 2743 2744 /// struct A* 2745 ACTC_coreFoundation 2746 }; 2747 static bool isAnyRetainable(ARCConversionTypeClass ACTC) { 2748 return (ACTC == ACTC_retainable || 2749 ACTC == ACTC_coreFoundation || 2750 ACTC == ACTC_voidPtr); 2751 } 2752 static bool isAnyCLike(ARCConversionTypeClass ACTC) { 2753 return ACTC == ACTC_none || 2754 ACTC == ACTC_voidPtr || 2755 ACTC == ACTC_coreFoundation; 2756 } 2757 2758 static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { 2759 bool isIndirect = false; 2760 2761 // Ignore an outermost reference type. 2762 if (const ReferenceType *ref = type->getAs<ReferenceType>()) { 2763 type = ref->getPointeeType(); 2764 isIndirect = true; 2765 } 2766 2767 // Drill through pointers and arrays recursively. 2768 while (true) { 2769 if (const PointerType *ptr = type->getAs<PointerType>()) { 2770 type = ptr->getPointeeType(); 2771 2772 // The first level of pointer may be the innermost pointer on a CF type. 2773 if (!isIndirect) { 2774 if (type->isVoidType()) return ACTC_voidPtr; 2775 if (type->isRecordType()) return ACTC_coreFoundation; 2776 } 2777 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) { 2778 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0); 2779 } else { 2780 break; 2781 } 2782 isIndirect = true; 2783 } 2784 2785 if (isIndirect) { 2786 if (type->isObjCARCBridgableType()) 2787 return ACTC_indirectRetainable; 2788 return ACTC_none; 2789 } 2790 2791 if (type->isObjCARCBridgableType()) 2792 return ACTC_retainable; 2793 2794 return ACTC_none; 2795 } 2796 2797 namespace { 2798 /// A result from the cast checker. 2799 enum ACCResult { 2800 /// Cannot be casted. 2801 ACC_invalid, 2802 2803 /// Can be safely retained or not retained. 2804 ACC_bottom, 2805 2806 /// Can be casted at +0. 2807 ACC_plusZero, 2808 2809 /// Can be casted at +1. 2810 ACC_plusOne 2811 }; 2812 ACCResult merge(ACCResult left, ACCResult right) { 2813 if (left == right) return left; 2814 if (left == ACC_bottom) return right; 2815 if (right == ACC_bottom) return left; 2816 return ACC_invalid; 2817 } 2818 2819 /// A checker which white-lists certain expressions whose conversion 2820 /// to or from retainable type would otherwise be forbidden in ARC. 2821 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> { 2822 typedef StmtVisitor<ARCCastChecker, ACCResult> super; 2823 2824 ASTContext &Context; 2825 ARCConversionTypeClass SourceClass; 2826 ARCConversionTypeClass TargetClass; 2827 bool Diagnose; 2828 2829 static bool isCFType(QualType type) { 2830 // Someday this can use ns_bridged. For now, it has to do this. 2831 return type->isCARCBridgableType(); 2832 } 2833 2834 public: 2835 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source, 2836 ARCConversionTypeClass target, bool diagnose) 2837 : Context(Context), SourceClass(source), TargetClass(target), 2838 Diagnose(diagnose) {} 2839 2840 using super::Visit; 2841 ACCResult Visit(Expr *e) { 2842 return super::Visit(e->IgnoreParens()); 2843 } 2844 2845 ACCResult VisitStmt(Stmt *s) { 2846 return ACC_invalid; 2847 } 2848 2849 /// Null pointer constants can be casted however you please. 2850 ACCResult VisitExpr(Expr *e) { 2851 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 2852 return ACC_bottom; 2853 return ACC_invalid; 2854 } 2855 2856 /// Objective-C string literals can be safely casted. 2857 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) { 2858 // If we're casting to any retainable type, go ahead. Global 2859 // strings are immune to retains, so this is bottom. 2860 if (isAnyRetainable(TargetClass)) return ACC_bottom; 2861 2862 return ACC_invalid; 2863 } 2864 2865 /// Look through certain implicit and explicit casts. 2866 ACCResult VisitCastExpr(CastExpr *e) { 2867 switch (e->getCastKind()) { 2868 case CK_NullToPointer: 2869 return ACC_bottom; 2870 2871 case CK_NoOp: 2872 case CK_LValueToRValue: 2873 case CK_BitCast: 2874 case CK_CPointerToObjCPointerCast: 2875 case CK_BlockPointerToObjCPointerCast: 2876 case CK_AnyPointerToBlockPointerCast: 2877 return Visit(e->getSubExpr()); 2878 2879 default: 2880 return ACC_invalid; 2881 } 2882 } 2883 2884 /// Look through unary extension. 2885 ACCResult VisitUnaryExtension(UnaryOperator *e) { 2886 return Visit(e->getSubExpr()); 2887 } 2888 2889 /// Ignore the LHS of a comma operator. 2890 ACCResult VisitBinComma(BinaryOperator *e) { 2891 return Visit(e->getRHS()); 2892 } 2893 2894 /// Conditional operators are okay if both sides are okay. 2895 ACCResult VisitConditionalOperator(ConditionalOperator *e) { 2896 ACCResult left = Visit(e->getTrueExpr()); 2897 if (left == ACC_invalid) return ACC_invalid; 2898 return merge(left, Visit(e->getFalseExpr())); 2899 } 2900 2901 /// Look through pseudo-objects. 2902 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) { 2903 // If we're getting here, we should always have a result. 2904 return Visit(e->getResultExpr()); 2905 } 2906 2907 /// Statement expressions are okay if their result expression is okay. 2908 ACCResult VisitStmtExpr(StmtExpr *e) { 2909 return Visit(e->getSubStmt()->body_back()); 2910 } 2911 2912 /// Some declaration references are okay. 2913 ACCResult VisitDeclRefExpr(DeclRefExpr *e) { 2914 // References to global constants from system headers are okay. 2915 // These are things like 'kCFStringTransformToLatin'. They are 2916 // can also be assumed to be immune to retains. 2917 VarDecl *var = dyn_cast<VarDecl>(e->getDecl()); 2918 if (isAnyRetainable(TargetClass) && 2919 isAnyRetainable(SourceClass) && 2920 var && 2921 var->getStorageClass() == SC_Extern && 2922 var->getType().isConstQualified() && 2923 Context.getSourceManager().isInSystemHeader(var->getLocation())) { 2924 return ACC_bottom; 2925 } 2926 2927 // Nothing else. 2928 return ACC_invalid; 2929 } 2930 2931 /// Some calls are okay. 2932 ACCResult VisitCallExpr(CallExpr *e) { 2933 if (FunctionDecl *fn = e->getDirectCallee()) 2934 if (ACCResult result = checkCallToFunction(fn)) 2935 return result; 2936 2937 return super::VisitCallExpr(e); 2938 } 2939 2940 ACCResult checkCallToFunction(FunctionDecl *fn) { 2941 // Require a CF*Ref return type. 2942 if (!isCFType(fn->getReturnType())) 2943 return ACC_invalid; 2944 2945 if (!isAnyRetainable(TargetClass)) 2946 return ACC_invalid; 2947 2948 // Honor an explicit 'not retained' attribute. 2949 if (fn->hasAttr<CFReturnsNotRetainedAttr>()) 2950 return ACC_plusZero; 2951 2952 // Honor an explicit 'retained' attribute, except that for 2953 // now we're not going to permit implicit handling of +1 results, 2954 // because it's a bit frightening. 2955 if (fn->hasAttr<CFReturnsRetainedAttr>()) 2956 return Diagnose ? ACC_plusOne 2957 : ACC_invalid; // ACC_plusOne if we start accepting this 2958 2959 // Recognize this specific builtin function, which is used by CFSTR. 2960 unsigned builtinID = fn->getBuiltinID(); 2961 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString) 2962 return ACC_bottom; 2963 2964 // Otherwise, don't do anything implicit with an unaudited function. 2965 if (!fn->hasAttr<CFAuditedTransferAttr>()) 2966 return ACC_invalid; 2967 2968 // Otherwise, it's +0 unless it follows the create convention. 2969 if (ento::coreFoundation::followsCreateRule(fn)) 2970 return Diagnose ? ACC_plusOne 2971 : ACC_invalid; // ACC_plusOne if we start accepting this 2972 2973 return ACC_plusZero; 2974 } 2975 2976 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) { 2977 return checkCallToMethod(e->getMethodDecl()); 2978 } 2979 2980 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) { 2981 ObjCMethodDecl *method; 2982 if (e->isExplicitProperty()) 2983 method = e->getExplicitProperty()->getGetterMethodDecl(); 2984 else 2985 method = e->getImplicitPropertyGetter(); 2986 return checkCallToMethod(method); 2987 } 2988 2989 ACCResult checkCallToMethod(ObjCMethodDecl *method) { 2990 if (!method) return ACC_invalid; 2991 2992 // Check for message sends to functions returning CF types. We 2993 // just obey the Cocoa conventions with these, even though the 2994 // return type is CF. 2995 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType())) 2996 return ACC_invalid; 2997 2998 // If the method is explicitly marked not-retained, it's +0. 2999 if (method->hasAttr<CFReturnsNotRetainedAttr>()) 3000 return ACC_plusZero; 3001 3002 // If the method is explicitly marked as returning retained, or its 3003 // selector follows a +1 Cocoa convention, treat it as +1. 3004 if (method->hasAttr<CFReturnsRetainedAttr>()) 3005 return ACC_plusOne; 3006 3007 switch (method->getSelector().getMethodFamily()) { 3008 case OMF_alloc: 3009 case OMF_copy: 3010 case OMF_mutableCopy: 3011 case OMF_new: 3012 return ACC_plusOne; 3013 3014 default: 3015 // Otherwise, treat it as +0. 3016 return ACC_plusZero; 3017 } 3018 } 3019 }; 3020 } 3021 3022 bool Sema::isKnownName(StringRef name) { 3023 if (name.empty()) 3024 return false; 3025 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(), 3026 Sema::LookupOrdinaryName); 3027 return LookupName(R, TUScope, false); 3028 } 3029 3030 static void addFixitForObjCARCConversion(Sema &S, 3031 DiagnosticBuilder &DiagB, 3032 Sema::CheckedConversionKind CCK, 3033 SourceLocation afterLParen, 3034 QualType castType, 3035 Expr *castExpr, 3036 Expr *realCast, 3037 const char *bridgeKeyword, 3038 const char *CFBridgeName) { 3039 // We handle C-style and implicit casts here. 3040 switch (CCK) { 3041 case Sema::CCK_ImplicitConversion: 3042 case Sema::CCK_CStyleCast: 3043 case Sema::CCK_OtherCast: 3044 break; 3045 case Sema::CCK_FunctionalCast: 3046 return; 3047 } 3048 3049 if (CFBridgeName) { 3050 if (CCK == Sema::CCK_OtherCast) { 3051 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 3052 SourceRange range(NCE->getOperatorLoc(), 3053 NCE->getAngleBrackets().getEnd()); 3054 SmallString<32> BridgeCall; 3055 3056 SourceManager &SM = S.getSourceManager(); 3057 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 3058 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 3059 BridgeCall += ' '; 3060 3061 BridgeCall += CFBridgeName; 3062 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); 3063 } 3064 return; 3065 } 3066 Expr *castedE = castExpr; 3067 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE)) 3068 castedE = CCE->getSubExpr(); 3069 castedE = castedE->IgnoreImpCasts(); 3070 SourceRange range = castedE->getSourceRange(); 3071 3072 SmallString<32> BridgeCall; 3073 3074 SourceManager &SM = S.getSourceManager(); 3075 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); 3076 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) 3077 BridgeCall += ' '; 3078 3079 BridgeCall += CFBridgeName; 3080 3081 if (isa<ParenExpr>(castedE)) { 3082 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3083 BridgeCall)); 3084 } else { 3085 BridgeCall += '('; 3086 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3087 BridgeCall)); 3088 DiagB.AddFixItHint(FixItHint::CreateInsertion( 3089 S.PP.getLocForEndOfToken(range.getEnd()), 3090 ")")); 3091 } 3092 return; 3093 } 3094 3095 if (CCK == Sema::CCK_CStyleCast) { 3096 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword)); 3097 } else if (CCK == Sema::CCK_OtherCast) { 3098 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { 3099 std::string castCode = "("; 3100 castCode += bridgeKeyword; 3101 castCode += castType.getAsString(); 3102 castCode += ")"; 3103 SourceRange Range(NCE->getOperatorLoc(), 3104 NCE->getAngleBrackets().getEnd()); 3105 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode)); 3106 } 3107 } else { 3108 std::string castCode = "("; 3109 castCode += bridgeKeyword; 3110 castCode += castType.getAsString(); 3111 castCode += ")"; 3112 Expr *castedE = castExpr->IgnoreImpCasts(); 3113 SourceRange range = castedE->getSourceRange(); 3114 if (isa<ParenExpr>(castedE)) { 3115 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3116 castCode)); 3117 } else { 3118 castCode += "("; 3119 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), 3120 castCode)); 3121 DiagB.AddFixItHint(FixItHint::CreateInsertion( 3122 S.PP.getLocForEndOfToken(range.getEnd()), 3123 ")")); 3124 } 3125 } 3126 } 3127 3128 template <typename T> 3129 static inline T *getObjCBridgeAttr(const TypedefType *TD) { 3130 TypedefNameDecl *TDNDecl = TD->getDecl(); 3131 QualType QT = TDNDecl->getUnderlyingType(); 3132 if (QT->isPointerType()) { 3133 QT = QT->getPointeeType(); 3134 if (const RecordType *RT = QT->getAs<RecordType>()) 3135 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl()) 3136 return RD->getAttr<T>(); 3137 } 3138 return nullptr; 3139 } 3140 3141 static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T, 3142 TypedefNameDecl *&TDNDecl) { 3143 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 3144 TDNDecl = TD->getDecl(); 3145 if (ObjCBridgeRelatedAttr *ObjCBAttr = 3146 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD)) 3147 return ObjCBAttr; 3148 T = TDNDecl->getUnderlyingType(); 3149 } 3150 return nullptr; 3151 } 3152 3153 static void 3154 diagnoseObjCARCConversion(Sema &S, SourceRange castRange, 3155 QualType castType, ARCConversionTypeClass castACTC, 3156 Expr *castExpr, Expr *realCast, 3157 ARCConversionTypeClass exprACTC, 3158 Sema::CheckedConversionKind CCK) { 3159 SourceLocation loc = 3160 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); 3161 3162 if (S.makeUnavailableInSystemHeader(loc, 3163 "converts between Objective-C and C pointers in -fobjc-arc")) 3164 return; 3165 3166 QualType castExprType = castExpr->getType(); 3167 TypedefNameDecl *TDNDecl = nullptr; 3168 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable && 3169 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) || 3170 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable && 3171 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl))) 3172 return; 3173 3174 unsigned srcKind = 0; 3175 switch (exprACTC) { 3176 case ACTC_none: 3177 case ACTC_coreFoundation: 3178 case ACTC_voidPtr: 3179 srcKind = (castExprType->isPointerType() ? 1 : 0); 3180 break; 3181 case ACTC_retainable: 3182 srcKind = (castExprType->isBlockPointerType() ? 2 : 3); 3183 break; 3184 case ACTC_indirectRetainable: 3185 srcKind = 4; 3186 break; 3187 } 3188 3189 // Check whether this could be fixed with a bridge cast. 3190 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin()); 3191 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; 3192 3193 // Bridge from an ARC type to a CF type. 3194 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) { 3195 3196 S.Diag(loc, diag::err_arc_cast_requires_bridge) 3197 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit 3198 << 2 // of C pointer type 3199 << castExprType 3200 << unsigned(castType->isBlockPointerType()) // to ObjC|block type 3201 << castType 3202 << castRange 3203 << castExpr->getSourceRange(); 3204 bool br = S.isKnownName("CFBridgingRelease"); 3205 ACCResult CreateRule = 3206 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 3207 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 3208 if (CreateRule != ACC_plusOne) 3209 { 3210 DiagnosticBuilder DiagB = 3211 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 3212 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 3213 3214 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3215 castType, castExpr, realCast, "__bridge ", 3216 nullptr); 3217 } 3218 if (CreateRule != ACC_plusZero) 3219 { 3220 DiagnosticBuilder DiagB = 3221 (CCK == Sema::CCK_OtherCast && !br) ? 3222 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType : 3223 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 3224 diag::note_arc_bridge_transfer) 3225 << castExprType << br; 3226 3227 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3228 castType, castExpr, realCast, "__bridge_transfer ", 3229 br ? "CFBridgingRelease" : nullptr); 3230 } 3231 3232 return; 3233 } 3234 3235 // Bridge from a CF type to an ARC type. 3236 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { 3237 bool br = S.isKnownName("CFBridgingRetain"); 3238 S.Diag(loc, diag::err_arc_cast_requires_bridge) 3239 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit 3240 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type 3241 << castExprType 3242 << 2 // to C pointer type 3243 << castType 3244 << castRange 3245 << castExpr->getSourceRange(); 3246 ACCResult CreateRule = 3247 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); 3248 assert(CreateRule != ACC_bottom && "This cast should already be accepted."); 3249 if (CreateRule != ACC_plusOne) 3250 { 3251 DiagnosticBuilder DiagB = 3252 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) 3253 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); 3254 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3255 castType, castExpr, realCast, "__bridge ", 3256 nullptr); 3257 } 3258 if (CreateRule != ACC_plusZero) 3259 { 3260 DiagnosticBuilder DiagB = 3261 (CCK == Sema::CCK_OtherCast && !br) ? 3262 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType : 3263 S.Diag(br ? castExpr->getExprLoc() : noteLoc, 3264 diag::note_arc_bridge_retained) 3265 << castType << br; 3266 3267 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, 3268 castType, castExpr, realCast, "__bridge_retained ", 3269 br ? "CFBridgingRetain" : nullptr); 3270 } 3271 3272 return; 3273 } 3274 3275 S.Diag(loc, diag::err_arc_mismatched_cast) 3276 << (CCK != Sema::CCK_ImplicitConversion) 3277 << srcKind << castExprType << castType 3278 << castRange << castExpr->getSourceRange(); 3279 } 3280 3281 template <typename TB> 3282 static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr, 3283 bool &HadTheAttribute, bool warn) { 3284 QualType T = castExpr->getType(); 3285 HadTheAttribute = false; 3286 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 3287 TypedefNameDecl *TDNDecl = TD->getDecl(); 3288 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { 3289 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { 3290 HadTheAttribute = true; 3291 NamedDecl *Target = nullptr; 3292 // Check for an existing type with this name. 3293 LookupResult R(S, DeclarationName(Parm), SourceLocation(), 3294 Sema::LookupOrdinaryName); 3295 if (S.LookupName(R, S.TUScope)) { 3296 Target = R.getFoundDecl(); 3297 if (Target && isa<ObjCInterfaceDecl>(Target)) { 3298 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target); 3299 if (const ObjCObjectPointerType *InterfacePointerType = 3300 castType->getAsObjCInterfacePointerType()) { 3301 ObjCInterfaceDecl *CastClass 3302 = InterfacePointerType->getObjectType()->getInterface(); 3303 if ((CastClass == ExprClass) || 3304 (CastClass && ExprClass->isSuperClassOf(CastClass))) 3305 return true; 3306 if (warn) 3307 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) 3308 << T << Target->getName() << castType->getPointeeType(); 3309 return false; 3310 } else if (castType->isObjCIdType() || 3311 (S.Context.ObjCObjectAdoptsQTypeProtocols( 3312 castType, ExprClass))) 3313 // ok to cast to 'id'. 3314 // casting to id<p-list> is ok if bridge type adopts all of 3315 // p-list protocols. 3316 return true; 3317 else { 3318 if (warn) { 3319 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) 3320 << T << Target->getName() << castType; 3321 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3322 S.Diag(Target->getLocStart(), diag::note_declared_at); 3323 } 3324 return false; 3325 } 3326 } 3327 } 3328 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface) 3329 << castExpr->getType() << Parm; 3330 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3331 if (Target) 3332 S.Diag(Target->getLocStart(), diag::note_declared_at); 3333 return true; 3334 } 3335 return false; 3336 } 3337 T = TDNDecl->getUnderlyingType(); 3338 } 3339 return true; 3340 } 3341 3342 template <typename TB> 3343 static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr, 3344 bool &HadTheAttribute, bool warn) { 3345 QualType T = castType; 3346 HadTheAttribute = false; 3347 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { 3348 TypedefNameDecl *TDNDecl = TD->getDecl(); 3349 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { 3350 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { 3351 HadTheAttribute = true; 3352 NamedDecl *Target = nullptr; 3353 // Check for an existing type with this name. 3354 LookupResult R(S, DeclarationName(Parm), SourceLocation(), 3355 Sema::LookupOrdinaryName); 3356 if (S.LookupName(R, S.TUScope)) { 3357 Target = R.getFoundDecl(); 3358 if (Target && isa<ObjCInterfaceDecl>(Target)) { 3359 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target); 3360 if (const ObjCObjectPointerType *InterfacePointerType = 3361 castExpr->getType()->getAsObjCInterfacePointerType()) { 3362 ObjCInterfaceDecl *ExprClass 3363 = InterfacePointerType->getObjectType()->getInterface(); 3364 if ((CastClass == ExprClass) || 3365 (ExprClass && CastClass->isSuperClassOf(ExprClass))) 3366 return true; 3367 if (warn) { 3368 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) 3369 << castExpr->getType()->getPointeeType() << T; 3370 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3371 } 3372 return false; 3373 } else if (castExpr->getType()->isObjCIdType() || 3374 (S.Context.QIdProtocolsAdoptObjCObjectProtocols( 3375 castExpr->getType(), CastClass))) 3376 // ok to cast an 'id' expression to a CFtype. 3377 // ok to cast an 'id<plist>' expression to CFtype provided plist 3378 // adopts all of CFtype's ObjetiveC's class plist. 3379 return true; 3380 else { 3381 if (warn) { 3382 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) 3383 << castExpr->getType() << castType; 3384 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3385 S.Diag(Target->getLocStart(), diag::note_declared_at); 3386 } 3387 return false; 3388 } 3389 } 3390 } 3391 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject) 3392 << castExpr->getType() << castType; 3393 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3394 if (Target) 3395 S.Diag(Target->getLocStart(), diag::note_declared_at); 3396 return true; 3397 } 3398 return false; 3399 } 3400 T = TDNDecl->getUnderlyingType(); 3401 } 3402 return true; 3403 } 3404 3405 void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { 3406 if (!getLangOpts().ObjC1) 3407 return; 3408 // warn in presence of __bridge casting to or from a toll free bridge cast. 3409 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType()); 3410 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); 3411 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) { 3412 bool HasObjCBridgeAttr; 3413 bool ObjCBridgeAttrWillNotWarn = 3414 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 3415 false); 3416 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) 3417 return; 3418 bool HasObjCBridgeMutableAttr; 3419 bool ObjCBridgeMutableAttrWillNotWarn = 3420 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 3421 HasObjCBridgeMutableAttr, false); 3422 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) 3423 return; 3424 3425 if (HasObjCBridgeAttr) 3426 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 3427 true); 3428 else if (HasObjCBridgeMutableAttr) 3429 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 3430 HasObjCBridgeMutableAttr, true); 3431 } 3432 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) { 3433 bool HasObjCBridgeAttr; 3434 bool ObjCBridgeAttrWillNotWarn = 3435 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 3436 false); 3437 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr) 3438 return; 3439 bool HasObjCBridgeMutableAttr; 3440 bool ObjCBridgeMutableAttrWillNotWarn = 3441 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 3442 HasObjCBridgeMutableAttr, false); 3443 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr) 3444 return; 3445 3446 if (HasObjCBridgeAttr) 3447 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr, 3448 true); 3449 else if (HasObjCBridgeMutableAttr) 3450 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr, 3451 HasObjCBridgeMutableAttr, true); 3452 } 3453 } 3454 3455 bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, 3456 CastKind &Kind) { 3457 if (!getLangOpts().ObjC1) 3458 return false; 3459 ARCConversionTypeClass exprACTC = 3460 classifyTypeForARCConversion(castExpr->getType()); 3461 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); 3462 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) || 3463 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) { 3464 CheckTollFreeBridgeCast(castType, castExpr); 3465 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast 3466 : CK_CPointerToObjCPointerCast; 3467 return true; 3468 } 3469 return false; 3470 } 3471 3472 bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, 3473 QualType DestType, QualType SrcType, 3474 ObjCInterfaceDecl *&RelatedClass, 3475 ObjCMethodDecl *&ClassMethod, 3476 ObjCMethodDecl *&InstanceMethod, 3477 TypedefNameDecl *&TDNDecl, 3478 bool CfToNs) { 3479 QualType T = CfToNs ? SrcType : DestType; 3480 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl); 3481 if (!ObjCBAttr) 3482 return false; 3483 3484 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass(); 3485 IdentifierInfo *CMId = ObjCBAttr->getClassMethod(); 3486 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod(); 3487 if (!RCId) 3488 return false; 3489 NamedDecl *Target = nullptr; 3490 // Check for an existing type with this name. 3491 LookupResult R(*this, DeclarationName(RCId), SourceLocation(), 3492 Sema::LookupOrdinaryName); 3493 if (!LookupName(R, TUScope)) { 3494 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId 3495 << SrcType << DestType; 3496 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3497 return false; 3498 } 3499 Target = R.getFoundDecl(); 3500 if (Target && isa<ObjCInterfaceDecl>(Target)) 3501 RelatedClass = cast<ObjCInterfaceDecl>(Target); 3502 else { 3503 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId 3504 << SrcType << DestType; 3505 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3506 if (Target) 3507 Diag(Target->getLocStart(), diag::note_declared_at); 3508 return false; 3509 } 3510 3511 // Check for an existing class method with the given selector name. 3512 if (CfToNs && CMId) { 3513 Selector Sel = Context.Selectors.getUnarySelector(CMId); 3514 ClassMethod = RelatedClass->lookupMethod(Sel, false); 3515 if (!ClassMethod) { 3516 Diag(Loc, diag::err_objc_bridged_related_known_method) 3517 << SrcType << DestType << Sel << false; 3518 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3519 return false; 3520 } 3521 } 3522 3523 // Check for an existing instance method with the given selector name. 3524 if (!CfToNs && IMId) { 3525 Selector Sel = Context.Selectors.getNullarySelector(IMId); 3526 InstanceMethod = RelatedClass->lookupMethod(Sel, true); 3527 if (!InstanceMethod) { 3528 Diag(Loc, diag::err_objc_bridged_related_known_method) 3529 << SrcType << DestType << Sel << true; 3530 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3531 return false; 3532 } 3533 } 3534 return true; 3535 } 3536 3537 bool 3538 Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, 3539 QualType DestType, QualType SrcType, 3540 Expr *&SrcExpr) { 3541 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType); 3542 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType); 3543 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable); 3544 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation); 3545 if (!CfToNs && !NsToCf) 3546 return false; 3547 3548 ObjCInterfaceDecl *RelatedClass; 3549 ObjCMethodDecl *ClassMethod = nullptr; 3550 ObjCMethodDecl *InstanceMethod = nullptr; 3551 TypedefNameDecl *TDNDecl = nullptr; 3552 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass, 3553 ClassMethod, InstanceMethod, TDNDecl, CfToNs)) 3554 return false; 3555 3556 if (CfToNs) { 3557 // Implicit conversion from CF to ObjC object is needed. 3558 if (ClassMethod) { 3559 std::string ExpressionString = "["; 3560 ExpressionString += RelatedClass->getNameAsString(); 3561 ExpressionString += " "; 3562 ExpressionString += ClassMethod->getSelector().getAsString(); 3563 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); 3564 // Provide a fixit: [RelatedClass ClassMethod SrcExpr] 3565 Diag(Loc, diag::err_objc_bridged_related_known_method) 3566 << SrcType << DestType << ClassMethod->getSelector() << false 3567 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString) 3568 << FixItHint::CreateInsertion(SrcExprEndLoc, "]"); 3569 Diag(RelatedClass->getLocStart(), diag::note_declared_at); 3570 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3571 3572 QualType receiverType = 3573 Context.getObjCInterfaceType(RelatedClass); 3574 // Argument. 3575 Expr *args[] = { SrcExpr }; 3576 ExprResult msg = BuildClassMessageImplicit(receiverType, false, 3577 ClassMethod->getLocation(), 3578 ClassMethod->getSelector(), ClassMethod, 3579 MultiExprArg(args, 1)); 3580 SrcExpr = msg.get(); 3581 return true; 3582 } 3583 } 3584 else { 3585 // Implicit conversion from ObjC type to CF object is needed. 3586 if (InstanceMethod) { 3587 std::string ExpressionString; 3588 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); 3589 if (InstanceMethod->isPropertyAccessor()) 3590 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) { 3591 // fixit: ObjectExpr.propertyname when it is aproperty accessor. 3592 ExpressionString = "."; 3593 ExpressionString += PDecl->getNameAsString(); 3594 Diag(Loc, diag::err_objc_bridged_related_known_method) 3595 << SrcType << DestType << InstanceMethod->getSelector() << true 3596 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); 3597 } 3598 if (ExpressionString.empty()) { 3599 // Provide a fixit: [ObjectExpr InstanceMethod] 3600 ExpressionString = " "; 3601 ExpressionString += InstanceMethod->getSelector().getAsString(); 3602 ExpressionString += "]"; 3603 3604 Diag(Loc, diag::err_objc_bridged_related_known_method) 3605 << SrcType << DestType << InstanceMethod->getSelector() << true 3606 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[") 3607 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); 3608 } 3609 Diag(RelatedClass->getLocStart(), diag::note_declared_at); 3610 Diag(TDNDecl->getLocStart(), diag::note_declared_at); 3611 3612 ExprResult msg = 3613 BuildInstanceMessageImplicit(SrcExpr, SrcType, 3614 InstanceMethod->getLocation(), 3615 InstanceMethod->getSelector(), 3616 InstanceMethod, None); 3617 SrcExpr = msg.get(); 3618 return true; 3619 } 3620 } 3621 return false; 3622 } 3623 3624 Sema::ARCConversionResult 3625 Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType, 3626 Expr *&castExpr, CheckedConversionKind CCK, 3627 bool DiagnoseCFAudited, 3628 BinaryOperatorKind Opc) { 3629 QualType castExprType = castExpr->getType(); 3630 3631 // For the purposes of the classification, we assume reference types 3632 // will bind to temporaries. 3633 QualType effCastType = castType; 3634 if (const ReferenceType *ref = castType->getAs<ReferenceType>()) 3635 effCastType = ref->getPointeeType(); 3636 3637 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); 3638 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); 3639 if (exprACTC == castACTC) { 3640 // check for viablity and report error if casting an rvalue to a 3641 // life-time qualifier. 3642 if ((castACTC == ACTC_retainable) && 3643 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) && 3644 (castType != castExprType)) { 3645 const Type *DT = castType.getTypePtr(); 3646 QualType QDT = castType; 3647 // We desugar some types but not others. We ignore those 3648 // that cannot happen in a cast; i.e. auto, and those which 3649 // should not be de-sugared; i.e typedef. 3650 if (const ParenType *PT = dyn_cast<ParenType>(DT)) 3651 QDT = PT->desugar(); 3652 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT)) 3653 QDT = TP->desugar(); 3654 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT)) 3655 QDT = AT->desugar(); 3656 if (QDT != castType && 3657 QDT.getObjCLifetime() != Qualifiers::OCL_None) { 3658 SourceLocation loc = 3659 (castRange.isValid() ? castRange.getBegin() 3660 : castExpr->getExprLoc()); 3661 Diag(loc, diag::err_arc_nolifetime_behavior); 3662 } 3663 } 3664 return ACR_okay; 3665 } 3666 3667 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay; 3668 3669 // Allow all of these types to be cast to integer types (but not 3670 // vice-versa). 3671 if (castACTC == ACTC_none && castType->isIntegralType(Context)) 3672 return ACR_okay; 3673 3674 // Allow casts between pointers to lifetime types (e.g., __strong id*) 3675 // and pointers to void (e.g., cv void *). Casting from void* to lifetime* 3676 // must be explicit. 3677 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr) 3678 return ACR_okay; 3679 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr && 3680 CCK != CCK_ImplicitConversion) 3681 return ACR_okay; 3682 3683 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) { 3684 // For invalid casts, fall through. 3685 case ACC_invalid: 3686 break; 3687 3688 // Do nothing for both bottom and +0. 3689 case ACC_bottom: 3690 case ACC_plusZero: 3691 return ACR_okay; 3692 3693 // If the result is +1, consume it here. 3694 case ACC_plusOne: 3695 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(), 3696 CK_ARCConsumeObject, castExpr, 3697 nullptr, VK_RValue); 3698 ExprNeedsCleanups = true; 3699 return ACR_okay; 3700 } 3701 3702 // If this is a non-implicit cast from id or block type to a 3703 // CoreFoundation type, delay complaining in case the cast is used 3704 // in an acceptable context. 3705 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && 3706 CCK != CCK_ImplicitConversion) 3707 return ACR_unbridged; 3708 3709 // Do not issue bridge cast" diagnostic when implicit casting a cstring 3710 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with 3711 // suitable fix-it. 3712 if (castACTC == ACTC_retainable && exprACTC == ACTC_none && 3713 ConversionToObjCStringLiteralCheck(castType, castExpr)) 3714 return ACR_okay; 3715 3716 // Do not issue "bridge cast" diagnostic when implicit casting 3717 // a retainable object to a CF type parameter belonging to an audited 3718 // CF API function. Let caller issue a normal type mismatched diagnostic 3719 // instead. 3720 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable || 3721 castACTC != ACTC_coreFoundation) 3722 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable && 3723 (Opc == BO_NE || Opc == BO_EQ))) 3724 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, 3725 castExpr, castExpr, exprACTC, CCK); 3726 return ACR_okay; 3727 } 3728 3729 /// Given that we saw an expression with the ARCUnbridgedCastTy 3730 /// placeholder type, complain bitterly. 3731 void Sema::diagnoseARCUnbridgedCast(Expr *e) { 3732 // We expect the spurious ImplicitCastExpr to already have been stripped. 3733 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 3734 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens()); 3735 3736 SourceRange castRange; 3737 QualType castType; 3738 CheckedConversionKind CCK; 3739 3740 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) { 3741 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc()); 3742 castType = cast->getTypeAsWritten(); 3743 CCK = CCK_CStyleCast; 3744 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) { 3745 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange(); 3746 castType = cast->getTypeAsWritten(); 3747 CCK = CCK_OtherCast; 3748 } else { 3749 castType = cast->getType(); 3750 CCK = CCK_ImplicitConversion; 3751 } 3752 3753 ARCConversionTypeClass castACTC = 3754 classifyTypeForARCConversion(castType.getNonReferenceType()); 3755 3756 Expr *castExpr = realCast->getSubExpr(); 3757 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable); 3758 3759 diagnoseObjCARCConversion(*this, castRange, castType, castACTC, 3760 castExpr, realCast, ACTC_retainable, CCK); 3761 } 3762 3763 /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast 3764 /// type, remove the placeholder cast. 3765 Expr *Sema::stripARCUnbridgedCast(Expr *e) { 3766 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 3767 3768 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) { 3769 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr()); 3770 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub); 3771 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) { 3772 assert(uo->getOpcode() == UO_Extension); 3773 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr()); 3774 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(), 3775 sub->getValueKind(), sub->getObjectKind(), 3776 uo->getOperatorLoc()); 3777 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { 3778 assert(!gse->isResultDependent()); 3779 3780 unsigned n = gse->getNumAssocs(); 3781 SmallVector<Expr*, 4> subExprs(n); 3782 SmallVector<TypeSourceInfo*, 4> subTypes(n); 3783 for (unsigned i = 0; i != n; ++i) { 3784 subTypes[i] = gse->getAssocTypeSourceInfo(i); 3785 Expr *sub = gse->getAssocExpr(i); 3786 if (i == gse->getResultIndex()) 3787 sub = stripARCUnbridgedCast(sub); 3788 subExprs[i] = sub; 3789 } 3790 3791 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(), 3792 gse->getControllingExpr(), 3793 subTypes, subExprs, 3794 gse->getDefaultLoc(), 3795 gse->getRParenLoc(), 3796 gse->containsUnexpandedParameterPack(), 3797 gse->getResultIndex()); 3798 } else { 3799 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!"); 3800 return cast<ImplicitCastExpr>(e)->getSubExpr(); 3801 } 3802 } 3803 3804 bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, 3805 QualType exprType) { 3806 QualType canCastType = 3807 Context.getCanonicalType(castType).getUnqualifiedType(); 3808 QualType canExprType = 3809 Context.getCanonicalType(exprType).getUnqualifiedType(); 3810 if (isa<ObjCObjectPointerType>(canCastType) && 3811 castType.getObjCLifetime() == Qualifiers::OCL_Weak && 3812 canExprType->isObjCObjectPointerType()) { 3813 if (const ObjCObjectPointerType *ObjT = 3814 canExprType->getAs<ObjCObjectPointerType>()) 3815 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl()) 3816 return !ObjI->isArcWeakrefUnavailable(); 3817 } 3818 return true; 3819 } 3820 3821 /// Look for an ObjCReclaimReturnedObject cast and destroy it. 3822 static Expr *maybeUndoReclaimObject(Expr *e) { 3823 // For now, we just undo operands that are *immediately* reclaim 3824 // expressions, which prevents the vast majority of potential 3825 // problems here. To catch them all, we'd need to rebuild arbitrary 3826 // value-propagating subexpressions --- we can't reliably rebuild 3827 // in-place because of expression sharing. 3828 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) 3829 if (ice->getCastKind() == CK_ARCReclaimReturnedObject) 3830 return ice->getSubExpr(); 3831 3832 return e; 3833 } 3834 3835 ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, 3836 ObjCBridgeCastKind Kind, 3837 SourceLocation BridgeKeywordLoc, 3838 TypeSourceInfo *TSInfo, 3839 Expr *SubExpr) { 3840 ExprResult SubResult = UsualUnaryConversions(SubExpr); 3841 if (SubResult.isInvalid()) return ExprError(); 3842 SubExpr = SubResult.get(); 3843 3844 QualType T = TSInfo->getType(); 3845 QualType FromType = SubExpr->getType(); 3846 3847 CastKind CK; 3848 3849 bool MustConsume = false; 3850 if (T->isDependentType() || SubExpr->isTypeDependent()) { 3851 // Okay: we'll build a dependent expression type. 3852 CK = CK_Dependent; 3853 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) { 3854 // Casting CF -> id 3855 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast 3856 : CK_CPointerToObjCPointerCast); 3857 switch (Kind) { 3858 case OBC_Bridge: 3859 break; 3860 3861 case OBC_BridgeRetained: { 3862 bool br = isKnownName("CFBridgingRelease"); 3863 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 3864 << 2 3865 << FromType 3866 << (T->isBlockPointerType()? 1 : 0) 3867 << T 3868 << SubExpr->getSourceRange() 3869 << Kind; 3870 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 3871 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); 3872 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) 3873 << FromType << br 3874 << FixItHint::CreateReplacement(BridgeKeywordLoc, 3875 br ? "CFBridgingRelease " 3876 : "__bridge_transfer "); 3877 3878 Kind = OBC_Bridge; 3879 break; 3880 } 3881 3882 case OBC_BridgeTransfer: 3883 // We must consume the Objective-C object produced by the cast. 3884 MustConsume = true; 3885 break; 3886 } 3887 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) { 3888 // Okay: id -> CF 3889 CK = CK_BitCast; 3890 switch (Kind) { 3891 case OBC_Bridge: 3892 // Reclaiming a value that's going to be __bridge-casted to CF 3893 // is very dangerous, so we don't do it. 3894 SubExpr = maybeUndoReclaimObject(SubExpr); 3895 break; 3896 3897 case OBC_BridgeRetained: 3898 // Produce the object before casting it. 3899 SubExpr = ImplicitCastExpr::Create(Context, FromType, 3900 CK_ARCProduceObject, 3901 SubExpr, nullptr, VK_RValue); 3902 break; 3903 3904 case OBC_BridgeTransfer: { 3905 bool br = isKnownName("CFBridgingRetain"); 3906 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) 3907 << (FromType->isBlockPointerType()? 1 : 0) 3908 << FromType 3909 << 2 3910 << T 3911 << SubExpr->getSourceRange() 3912 << Kind; 3913 3914 Diag(BridgeKeywordLoc, diag::note_arc_bridge) 3915 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); 3916 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) 3917 << T << br 3918 << FixItHint::CreateReplacement(BridgeKeywordLoc, 3919 br ? "CFBridgingRetain " : "__bridge_retained"); 3920 3921 Kind = OBC_Bridge; 3922 break; 3923 } 3924 } 3925 } else { 3926 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible) 3927 << FromType << T << Kind 3928 << SubExpr->getSourceRange() 3929 << TSInfo->getTypeLoc().getSourceRange(); 3930 return ExprError(); 3931 } 3932 3933 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, 3934 BridgeKeywordLoc, 3935 TSInfo, SubExpr); 3936 3937 if (MustConsume) { 3938 ExprNeedsCleanups = true; 3939 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 3940 nullptr, VK_RValue); 3941 } 3942 3943 return Result; 3944 } 3945 3946 ExprResult Sema::ActOnObjCBridgedCast(Scope *S, 3947 SourceLocation LParenLoc, 3948 ObjCBridgeCastKind Kind, 3949 SourceLocation BridgeKeywordLoc, 3950 ParsedType Type, 3951 SourceLocation RParenLoc, 3952 Expr *SubExpr) { 3953 TypeSourceInfo *TSInfo = nullptr; 3954 QualType T = GetTypeFromParser(Type, &TSInfo); 3955 if (Kind == OBC_Bridge) 3956 CheckTollFreeBridgeCast(T, SubExpr); 3957 if (!TSInfo) 3958 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); 3959 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, 3960 SubExpr); 3961 } 3962