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