1 //===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===// 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 expressions involving 11 // pseudo-object references. Pseudo-objects are conceptual objects 12 // whose storage is entirely abstract and all accesses to which are 13 // translated through some sort of abstraction barrier. 14 // 15 // For example, Objective-C objects can have "properties", either 16 // declared or undeclared. A property may be accessed by writing 17 // expr.prop 18 // where 'expr' is an r-value of Objective-C pointer type and 'prop' 19 // is the name of the property. If this expression is used in a context 20 // needing an r-value, it is treated as if it were a message-send 21 // of the associated 'getter' selector, typically: 22 // [expr prop] 23 // If it is used as the LHS of a simple assignment, it is treated 24 // as a message-send of the associated 'setter' selector, typically: 25 // [expr setProp: RHS] 26 // If it is used as the LHS of a compound assignment, or the operand 27 // of a unary increment or decrement, both are required; for example, 28 // 'expr.prop *= 100' would be translated to: 29 // [expr setProp: [expr prop] * 100] 30 // 31 //===----------------------------------------------------------------------===// 32 33 #include "clang/Sema/SemaInternal.h" 34 #include "clang/AST/ExprCXX.h" 35 #include "clang/AST/ExprObjC.h" 36 #include "clang/Basic/CharInfo.h" 37 #include "clang/Lex/Preprocessor.h" 38 #include "clang/Sema/Initialization.h" 39 #include "clang/Sema/ScopeInfo.h" 40 #include "llvm/ADT/SmallString.h" 41 42 using namespace clang; 43 using namespace sema; 44 45 namespace { 46 // Basically just a very focused copy of TreeTransform. 47 template <class T> struct Rebuilder { 48 Sema &S; 49 Rebuilder(Sema &S) : S(S) {} 50 51 T &getDerived() { return static_cast<T&>(*this); } 52 53 Expr *rebuild(Expr *e) { 54 // Fast path: nothing to look through. 55 if (typename T::specific_type *specific 56 = dyn_cast<typename T::specific_type>(e)) 57 return getDerived().rebuildSpecific(specific); 58 59 // Otherwise, we should look through and rebuild anything that 60 // IgnoreParens would. 61 62 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) { 63 e = rebuild(parens->getSubExpr()); 64 return new (S.Context) ParenExpr(parens->getLParen(), 65 parens->getRParen(), 66 e); 67 } 68 69 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) { 70 assert(uop->getOpcode() == UO_Extension); 71 e = rebuild(uop->getSubExpr()); 72 return new (S.Context) UnaryOperator(e, uop->getOpcode(), 73 uop->getType(), 74 uop->getValueKind(), 75 uop->getObjectKind(), 76 uop->getOperatorLoc()); 77 } 78 79 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { 80 assert(!gse->isResultDependent()); 81 unsigned resultIndex = gse->getResultIndex(); 82 unsigned numAssocs = gse->getNumAssocs(); 83 84 SmallVector<Expr*, 8> assocs(numAssocs); 85 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs); 86 87 for (unsigned i = 0; i != numAssocs; ++i) { 88 Expr *assoc = gse->getAssocExpr(i); 89 if (i == resultIndex) assoc = rebuild(assoc); 90 assocs[i] = assoc; 91 assocTypes[i] = gse->getAssocTypeSourceInfo(i); 92 } 93 94 return new (S.Context) GenericSelectionExpr(S.Context, 95 gse->getGenericLoc(), 96 gse->getControllingExpr(), 97 assocTypes, 98 assocs, 99 gse->getDefaultLoc(), 100 gse->getRParenLoc(), 101 gse->containsUnexpandedParameterPack(), 102 resultIndex); 103 } 104 105 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) { 106 assert(!ce->isConditionDependent()); 107 108 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS(); 109 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS; 110 rebuiltExpr = rebuild(rebuiltExpr); 111 112 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(), 113 ce->getCond(), 114 LHS, RHS, 115 rebuiltExpr->getType(), 116 rebuiltExpr->getValueKind(), 117 rebuiltExpr->getObjectKind(), 118 ce->getRParenLoc(), 119 ce->isConditionTrue(), 120 rebuiltExpr->isTypeDependent(), 121 rebuiltExpr->isValueDependent()); 122 } 123 124 llvm_unreachable("bad expression to rebuild!"); 125 } 126 }; 127 128 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> { 129 Expr *NewBase; 130 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase) 131 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {} 132 133 typedef ObjCPropertyRefExpr specific_type; 134 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) { 135 // Fortunately, the constraint that we're rebuilding something 136 // with a base limits the number of cases here. 137 assert(refExpr->isObjectReceiver()); 138 139 if (refExpr->isExplicitProperty()) { 140 return new (S.Context) 141 ObjCPropertyRefExpr(refExpr->getExplicitProperty(), 142 refExpr->getType(), refExpr->getValueKind(), 143 refExpr->getObjectKind(), refExpr->getLocation(), 144 NewBase); 145 } 146 return new (S.Context) 147 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(), 148 refExpr->getImplicitPropertySetter(), 149 refExpr->getType(), refExpr->getValueKind(), 150 refExpr->getObjectKind(),refExpr->getLocation(), 151 NewBase); 152 } 153 }; 154 155 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> { 156 Expr *NewBase; 157 Expr *NewKeyExpr; 158 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr) 159 : Rebuilder<ObjCSubscriptRefRebuilder>(S), 160 NewBase(newBase), NewKeyExpr(newKeyExpr) {} 161 162 typedef ObjCSubscriptRefExpr specific_type; 163 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) { 164 assert(refExpr->getBaseExpr()); 165 assert(refExpr->getKeyExpr()); 166 167 return new (S.Context) 168 ObjCSubscriptRefExpr(NewBase, 169 NewKeyExpr, 170 refExpr->getType(), refExpr->getValueKind(), 171 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(), 172 refExpr->setAtIndexMethodDecl(), 173 refExpr->getRBracket()); 174 } 175 }; 176 177 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> { 178 Expr *NewBase; 179 MSPropertyRefRebuilder(Sema &S, Expr *newBase) 180 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {} 181 182 typedef MSPropertyRefExpr specific_type; 183 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) { 184 assert(refExpr->getBaseExpr()); 185 186 return new (S.Context) 187 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(), 188 refExpr->isArrow(), refExpr->getType(), 189 refExpr->getValueKind(), refExpr->getQualifierLoc(), 190 refExpr->getMemberLoc()); 191 } 192 }; 193 194 class PseudoOpBuilder { 195 public: 196 Sema &S; 197 unsigned ResultIndex; 198 SourceLocation GenericLoc; 199 SmallVector<Expr *, 4> Semantics; 200 201 PseudoOpBuilder(Sema &S, SourceLocation genericLoc) 202 : S(S), ResultIndex(PseudoObjectExpr::NoResult), 203 GenericLoc(genericLoc) {} 204 205 virtual ~PseudoOpBuilder() {} 206 207 /// Add a normal semantic expression. 208 void addSemanticExpr(Expr *semantic) { 209 Semantics.push_back(semantic); 210 } 211 212 /// Add the 'result' semantic expression. 213 void addResultSemanticExpr(Expr *resultExpr) { 214 assert(ResultIndex == PseudoObjectExpr::NoResult); 215 ResultIndex = Semantics.size(); 216 Semantics.push_back(resultExpr); 217 } 218 219 ExprResult buildRValueOperation(Expr *op); 220 ExprResult buildAssignmentOperation(Scope *Sc, 221 SourceLocation opLoc, 222 BinaryOperatorKind opcode, 223 Expr *LHS, Expr *RHS); 224 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc, 225 UnaryOperatorKind opcode, 226 Expr *op); 227 228 virtual ExprResult complete(Expr *syntacticForm); 229 230 OpaqueValueExpr *capture(Expr *op); 231 OpaqueValueExpr *captureValueAsResult(Expr *op); 232 233 void setResultToLastSemantic() { 234 assert(ResultIndex == PseudoObjectExpr::NoResult); 235 ResultIndex = Semantics.size() - 1; 236 } 237 238 /// Return true if assignments have a non-void result. 239 bool CanCaptureValue(Expr *exp) { 240 if (exp->isGLValue()) 241 return true; 242 QualType ty = exp->getType(); 243 assert(!ty->isIncompleteType()); 244 assert(!ty->isDependentType()); 245 246 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl()) 247 return ClassDecl->isTriviallyCopyable(); 248 return true; 249 } 250 251 virtual Expr *rebuildAndCaptureObject(Expr *) = 0; 252 virtual ExprResult buildGet() = 0; 253 virtual ExprResult buildSet(Expr *, SourceLocation, 254 bool captureSetValueAsResult) = 0; 255 }; 256 257 /// A PseudoOpBuilder for Objective-C \@properties. 258 class ObjCPropertyOpBuilder : public PseudoOpBuilder { 259 ObjCPropertyRefExpr *RefExpr; 260 ObjCPropertyRefExpr *SyntacticRefExpr; 261 OpaqueValueExpr *InstanceReceiver; 262 ObjCMethodDecl *Getter; 263 264 ObjCMethodDecl *Setter; 265 Selector SetterSelector; 266 Selector GetterSelector; 267 268 public: 269 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) : 270 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr), 271 SyntacticRefExpr(nullptr), InstanceReceiver(nullptr), Getter(nullptr), 272 Setter(nullptr) { 273 } 274 275 ExprResult buildRValueOperation(Expr *op); 276 ExprResult buildAssignmentOperation(Scope *Sc, 277 SourceLocation opLoc, 278 BinaryOperatorKind opcode, 279 Expr *LHS, Expr *RHS); 280 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc, 281 UnaryOperatorKind opcode, 282 Expr *op); 283 284 bool tryBuildGetOfReference(Expr *op, ExprResult &result); 285 bool findSetter(bool warn=true); 286 bool findGetter(); 287 void DiagnoseUnsupportedPropertyUse(); 288 289 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override; 290 ExprResult buildGet() override; 291 ExprResult buildSet(Expr *op, SourceLocation, bool) override; 292 ExprResult complete(Expr *SyntacticForm) override; 293 294 bool isWeakProperty() const; 295 }; 296 297 /// A PseudoOpBuilder for Objective-C array/dictionary indexing. 298 class ObjCSubscriptOpBuilder : public PseudoOpBuilder { 299 ObjCSubscriptRefExpr *RefExpr; 300 OpaqueValueExpr *InstanceBase; 301 OpaqueValueExpr *InstanceKey; 302 ObjCMethodDecl *AtIndexGetter; 303 Selector AtIndexGetterSelector; 304 305 ObjCMethodDecl *AtIndexSetter; 306 Selector AtIndexSetterSelector; 307 308 public: 309 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) : 310 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()), 311 RefExpr(refExpr), 312 InstanceBase(nullptr), InstanceKey(nullptr), 313 AtIndexGetter(nullptr), AtIndexSetter(nullptr) {} 314 315 ExprResult buildRValueOperation(Expr *op); 316 ExprResult buildAssignmentOperation(Scope *Sc, 317 SourceLocation opLoc, 318 BinaryOperatorKind opcode, 319 Expr *LHS, Expr *RHS); 320 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override; 321 322 bool findAtIndexGetter(); 323 bool findAtIndexSetter(); 324 325 ExprResult buildGet() override; 326 ExprResult buildSet(Expr *op, SourceLocation, bool) override; 327 }; 328 329 class MSPropertyOpBuilder : public PseudoOpBuilder { 330 MSPropertyRefExpr *RefExpr; 331 332 public: 333 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) : 334 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()), 335 RefExpr(refExpr) {} 336 337 Expr *rebuildAndCaptureObject(Expr *) override; 338 ExprResult buildGet() override; 339 ExprResult buildSet(Expr *op, SourceLocation, bool) override; 340 }; 341 } 342 343 /// Capture the given expression in an OpaqueValueExpr. 344 OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) { 345 // Make a new OVE whose source is the given expression. 346 OpaqueValueExpr *captured = 347 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(), 348 e->getValueKind(), e->getObjectKind(), 349 e); 350 351 // Make sure we bind that in the semantics. 352 addSemanticExpr(captured); 353 return captured; 354 } 355 356 /// Capture the given expression as the result of this pseudo-object 357 /// operation. This routine is safe against expressions which may 358 /// already be captured. 359 /// 360 /// \returns the captured expression, which will be the 361 /// same as the input if the input was already captured 362 OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) { 363 assert(ResultIndex == PseudoObjectExpr::NoResult); 364 365 // If the expression hasn't already been captured, just capture it 366 // and set the new semantic 367 if (!isa<OpaqueValueExpr>(e)) { 368 OpaqueValueExpr *cap = capture(e); 369 setResultToLastSemantic(); 370 return cap; 371 } 372 373 // Otherwise, it must already be one of our semantic expressions; 374 // set ResultIndex to its index. 375 unsigned index = 0; 376 for (;; ++index) { 377 assert(index < Semantics.size() && 378 "captured expression not found in semantics!"); 379 if (e == Semantics[index]) break; 380 } 381 ResultIndex = index; 382 return cast<OpaqueValueExpr>(e); 383 } 384 385 /// The routine which creates the final PseudoObjectExpr. 386 ExprResult PseudoOpBuilder::complete(Expr *syntactic) { 387 return PseudoObjectExpr::Create(S.Context, syntactic, 388 Semantics, ResultIndex); 389 } 390 391 /// The main skeleton for building an r-value operation. 392 ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) { 393 Expr *syntacticBase = rebuildAndCaptureObject(op); 394 395 ExprResult getExpr = buildGet(); 396 if (getExpr.isInvalid()) return ExprError(); 397 addResultSemanticExpr(getExpr.get()); 398 399 return complete(syntacticBase); 400 } 401 402 /// The basic skeleton for building a simple or compound 403 /// assignment operation. 404 ExprResult 405 PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc, 406 BinaryOperatorKind opcode, 407 Expr *LHS, Expr *RHS) { 408 assert(BinaryOperator::isAssignmentOp(opcode)); 409 410 Expr *syntacticLHS = rebuildAndCaptureObject(LHS); 411 OpaqueValueExpr *capturedRHS = capture(RHS); 412 413 // In some very specific cases, semantic analysis of the RHS as an 414 // expression may require it to be rewritten. In these cases, we 415 // cannot safely keep the OVE around. Fortunately, we don't really 416 // need to: we don't use this particular OVE in multiple places, and 417 // no clients rely that closely on matching up expressions in the 418 // semantic expression with expressions from the syntactic form. 419 Expr *semanticRHS = capturedRHS; 420 if (RHS->hasPlaceholderType() || isa<InitListExpr>(RHS)) { 421 semanticRHS = RHS; 422 Semantics.pop_back(); 423 } 424 425 Expr *syntactic; 426 427 ExprResult result; 428 if (opcode == BO_Assign) { 429 result = semanticRHS; 430 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS, 431 opcode, capturedRHS->getType(), 432 capturedRHS->getValueKind(), 433 OK_Ordinary, opcLoc, false); 434 } else { 435 ExprResult opLHS = buildGet(); 436 if (opLHS.isInvalid()) return ExprError(); 437 438 // Build an ordinary, non-compound operation. 439 BinaryOperatorKind nonCompound = 440 BinaryOperator::getOpForCompoundAssignment(opcode); 441 result = S.BuildBinOp(Sc, opcLoc, nonCompound, opLHS.get(), semanticRHS); 442 if (result.isInvalid()) return ExprError(); 443 444 syntactic = 445 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode, 446 result.get()->getType(), 447 result.get()->getValueKind(), 448 OK_Ordinary, 449 opLHS.get()->getType(), 450 result.get()->getType(), 451 opcLoc, false); 452 } 453 454 // The result of the assignment, if not void, is the value set into 455 // the l-value. 456 result = buildSet(result.get(), opcLoc, /*captureSetValueAsResult*/ true); 457 if (result.isInvalid()) return ExprError(); 458 addSemanticExpr(result.get()); 459 460 return complete(syntactic); 461 } 462 463 /// The basic skeleton for building an increment or decrement 464 /// operation. 465 ExprResult 466 PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc, 467 UnaryOperatorKind opcode, 468 Expr *op) { 469 assert(UnaryOperator::isIncrementDecrementOp(opcode)); 470 471 Expr *syntacticOp = rebuildAndCaptureObject(op); 472 473 // Load the value. 474 ExprResult result = buildGet(); 475 if (result.isInvalid()) return ExprError(); 476 477 QualType resultType = result.get()->getType(); 478 479 // That's the postfix result. 480 if (UnaryOperator::isPostfix(opcode) && 481 (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) { 482 result = capture(result.get()); 483 setResultToLastSemantic(); 484 } 485 486 // Add or subtract a literal 1. 487 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1); 488 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy, 489 GenericLoc); 490 491 if (UnaryOperator::isIncrementOp(opcode)) { 492 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.get(), one); 493 } else { 494 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.get(), one); 495 } 496 if (result.isInvalid()) return ExprError(); 497 498 // Store that back into the result. The value stored is the result 499 // of a prefix operation. 500 result = buildSet(result.get(), opcLoc, UnaryOperator::isPrefix(opcode)); 501 if (result.isInvalid()) return ExprError(); 502 addSemanticExpr(result.get()); 503 504 UnaryOperator *syntactic = 505 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType, 506 VK_LValue, OK_Ordinary, opcLoc); 507 return complete(syntactic); 508 } 509 510 511 //===----------------------------------------------------------------------===// 512 // Objective-C @property and implicit property references 513 //===----------------------------------------------------------------------===// 514 515 /// Look up a method in the receiver type of an Objective-C property 516 /// reference. 517 static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel, 518 const ObjCPropertyRefExpr *PRE) { 519 if (PRE->isObjectReceiver()) { 520 const ObjCObjectPointerType *PT = 521 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>(); 522 523 // Special case for 'self' in class method implementations. 524 if (PT->isObjCClassType() && 525 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) { 526 // This cast is safe because isSelfExpr is only true within 527 // methods. 528 ObjCMethodDecl *method = 529 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor()); 530 return S.LookupMethodInObjectType(sel, 531 S.Context.getObjCInterfaceType(method->getClassInterface()), 532 /*instance*/ false); 533 } 534 535 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true); 536 } 537 538 if (PRE->isSuperReceiver()) { 539 if (const ObjCObjectPointerType *PT = 540 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>()) 541 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true); 542 543 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false); 544 } 545 546 assert(PRE->isClassReceiver() && "Invalid expression"); 547 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver()); 548 return S.LookupMethodInObjectType(sel, IT, false); 549 } 550 551 bool ObjCPropertyOpBuilder::isWeakProperty() const { 552 QualType T; 553 if (RefExpr->isExplicitProperty()) { 554 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty(); 555 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) 556 return !Prop->hasAttr<IBOutletAttr>(); 557 558 T = Prop->getType(); 559 } else if (Getter) { 560 T = Getter->getReturnType(); 561 } else { 562 return false; 563 } 564 565 return T.getObjCLifetime() == Qualifiers::OCL_Weak; 566 } 567 568 bool ObjCPropertyOpBuilder::findGetter() { 569 if (Getter) return true; 570 571 // For implicit properties, just trust the lookup we already did. 572 if (RefExpr->isImplicitProperty()) { 573 if ((Getter = RefExpr->getImplicitPropertyGetter())) { 574 GetterSelector = Getter->getSelector(); 575 return true; 576 } 577 else { 578 // Must build the getter selector the hard way. 579 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter(); 580 assert(setter && "both setter and getter are null - cannot happen"); 581 IdentifierInfo *setterName = 582 setter->getSelector().getIdentifierInfoForSlot(0); 583 IdentifierInfo *getterName = 584 &S.Context.Idents.get(setterName->getName().substr(3)); 585 GetterSelector = 586 S.PP.getSelectorTable().getNullarySelector(getterName); 587 return false; 588 } 589 } 590 591 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty(); 592 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr); 593 return (Getter != nullptr); 594 } 595 596 /// Try to find the most accurate setter declaration for the property 597 /// reference. 598 /// 599 /// \return true if a setter was found, in which case Setter 600 bool ObjCPropertyOpBuilder::findSetter(bool warn) { 601 // For implicit properties, just trust the lookup we already did. 602 if (RefExpr->isImplicitProperty()) { 603 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) { 604 Setter = setter; 605 SetterSelector = setter->getSelector(); 606 return true; 607 } else { 608 IdentifierInfo *getterName = 609 RefExpr->getImplicitPropertyGetter()->getSelector() 610 .getIdentifierInfoForSlot(0); 611 SetterSelector = 612 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(), 613 S.PP.getSelectorTable(), 614 getterName); 615 return false; 616 } 617 } 618 619 // For explicit properties, this is more involved. 620 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty(); 621 SetterSelector = prop->getSetterName(); 622 623 // Do a normal method lookup first. 624 if (ObjCMethodDecl *setter = 625 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) { 626 if (setter->isPropertyAccessor() && warn) 627 if (const ObjCInterfaceDecl *IFace = 628 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) { 629 StringRef thisPropertyName = prop->getName(); 630 // Try flipping the case of the first character. 631 char front = thisPropertyName.front(); 632 front = isLowercase(front) ? toUppercase(front) : toLowercase(front); 633 SmallString<100> PropertyName = thisPropertyName; 634 PropertyName[0] = front; 635 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName); 636 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember)) 637 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) { 638 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use) 639 << prop << prop1 << setter->getSelector(); 640 S.Diag(prop->getLocation(), diag::note_property_declare); 641 S.Diag(prop1->getLocation(), diag::note_property_declare); 642 } 643 } 644 Setter = setter; 645 return true; 646 } 647 648 // That can fail in the somewhat crazy situation that we're 649 // type-checking a message send within the @interface declaration 650 // that declared the @property. But it's not clear that that's 651 // valuable to support. 652 653 return false; 654 } 655 656 void ObjCPropertyOpBuilder::DiagnoseUnsupportedPropertyUse() { 657 if (S.getCurLexicalContext()->isObjCContainer() && 658 S.getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl && 659 S.getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation) { 660 if (ObjCPropertyDecl *prop = RefExpr->getExplicitProperty()) { 661 S.Diag(RefExpr->getLocation(), 662 diag::err_property_function_in_objc_container); 663 S.Diag(prop->getLocation(), diag::note_property_declare); 664 } 665 } 666 } 667 668 /// Capture the base object of an Objective-C property expression. 669 Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { 670 assert(InstanceReceiver == nullptr); 671 672 // If we have a base, capture it in an OVE and rebuild the syntactic 673 // form to use the OVE as its base. 674 if (RefExpr->isObjectReceiver()) { 675 InstanceReceiver = capture(RefExpr->getBase()); 676 677 syntacticBase = 678 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase); 679 } 680 681 if (ObjCPropertyRefExpr * 682 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens())) 683 SyntacticRefExpr = refE; 684 685 return syntacticBase; 686 } 687 688 /// Load from an Objective-C property reference. 689 ExprResult ObjCPropertyOpBuilder::buildGet() { 690 findGetter(); 691 if (!Getter) { 692 DiagnoseUnsupportedPropertyUse(); 693 return ExprError(); 694 } 695 696 if (SyntacticRefExpr) 697 SyntacticRefExpr->setIsMessagingGetter(); 698 699 QualType receiverType = RefExpr->getReceiverType(S.Context); 700 if (!Getter->isImplicit()) 701 S.DiagnoseUseOfDecl(Getter, GenericLoc, nullptr, true); 702 // Build a message-send. 703 ExprResult msg; 704 if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) || 705 RefExpr->isObjectReceiver()) { 706 assert(InstanceReceiver || RefExpr->isSuperReceiver()); 707 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType, 708 GenericLoc, Getter->getSelector(), 709 Getter, None); 710 } else { 711 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(), 712 GenericLoc, Getter->getSelector(), 713 Getter, None); 714 } 715 return msg; 716 } 717 718 /// Store to an Objective-C property reference. 719 /// 720 /// \param captureSetValueAsResult If true, capture the actual 721 /// value being set as the value of the property operation. 722 ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, 723 bool captureSetValueAsResult) { 724 if (!findSetter(false)) { 725 DiagnoseUnsupportedPropertyUse(); 726 return ExprError(); 727 } 728 729 if (SyntacticRefExpr) 730 SyntacticRefExpr->setIsMessagingSetter(); 731 732 QualType receiverType = RefExpr->getReceiverType(S.Context); 733 734 // Use assignment constraints when possible; they give us better 735 // diagnostics. "When possible" basically means anything except a 736 // C++ class type. 737 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) { 738 QualType paramType = (*Setter->param_begin())->getType() 739 .substObjCMemberType( 740 receiverType, 741 Setter->getDeclContext(), 742 ObjCSubstitutionContext::Parameter); 743 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) { 744 ExprResult opResult = op; 745 Sema::AssignConvertType assignResult 746 = S.CheckSingleAssignmentConstraints(paramType, opResult); 747 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType, 748 op->getType(), opResult.get(), 749 Sema::AA_Assigning)) 750 return ExprError(); 751 752 op = opResult.get(); 753 assert(op && "successful assignment left argument invalid?"); 754 } 755 } 756 757 // Arguments. 758 Expr *args[] = { op }; 759 760 // Build a message-send. 761 ExprResult msg; 762 if (!Setter->isImplicit()) 763 S.DiagnoseUseOfDecl(Setter, GenericLoc, nullptr, true); 764 if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) || 765 RefExpr->isObjectReceiver()) { 766 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType, 767 GenericLoc, SetterSelector, Setter, 768 MultiExprArg(args, 1)); 769 } else { 770 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(), 771 GenericLoc, 772 SetterSelector, Setter, 773 MultiExprArg(args, 1)); 774 } 775 776 if (!msg.isInvalid() && captureSetValueAsResult) { 777 ObjCMessageExpr *msgExpr = 778 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit()); 779 Expr *arg = msgExpr->getArg(0); 780 if (CanCaptureValue(arg)) 781 msgExpr->setArg(0, captureValueAsResult(arg)); 782 } 783 784 return msg; 785 } 786 787 /// @property-specific behavior for doing lvalue-to-rvalue conversion. 788 ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) { 789 // Explicit properties always have getters, but implicit ones don't. 790 // Check that before proceeding. 791 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) { 792 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found) 793 << RefExpr->getSourceRange(); 794 return ExprError(); 795 } 796 797 ExprResult result = PseudoOpBuilder::buildRValueOperation(op); 798 if (result.isInvalid()) return ExprError(); 799 800 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType()) 801 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(), 802 Getter, RefExpr->getLocation()); 803 804 // As a special case, if the method returns 'id', try to get 805 // a better type from the property. 806 if (RefExpr->isExplicitProperty() && result.get()->isRValue()) { 807 QualType receiverType = RefExpr->getReceiverType(S.Context); 808 QualType propType = RefExpr->getExplicitProperty() 809 ->getUsageType(receiverType); 810 if (result.get()->getType()->isObjCIdType()) { 811 if (const ObjCObjectPointerType *ptr 812 = propType->getAs<ObjCObjectPointerType>()) { 813 if (!ptr->isObjCIdType()) 814 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast); 815 } 816 } 817 if (S.getLangOpts().ObjCAutoRefCount) { 818 Qualifiers::ObjCLifetime LT = propType.getObjCLifetime(); 819 if (LT == Qualifiers::OCL_Weak) 820 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, RefExpr->getLocation())) 821 S.getCurFunction()->markSafeWeakUse(RefExpr); 822 } 823 } 824 825 return result; 826 } 827 828 /// Try to build this as a call to a getter that returns a reference. 829 /// 830 /// \return true if it was possible, whether or not it actually 831 /// succeeded 832 bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op, 833 ExprResult &result) { 834 if (!S.getLangOpts().CPlusPlus) return false; 835 836 findGetter(); 837 if (!Getter) { 838 // The property has no setter and no getter! This can happen if the type is 839 // invalid. Error have already been reported. 840 result = ExprError(); 841 return true; 842 } 843 844 // Only do this if the getter returns an l-value reference type. 845 QualType resultType = Getter->getReturnType(); 846 if (!resultType->isLValueReferenceType()) return false; 847 848 result = buildRValueOperation(op); 849 return true; 850 } 851 852 /// @property-specific behavior for doing assignments. 853 ExprResult 854 ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc, 855 SourceLocation opcLoc, 856 BinaryOperatorKind opcode, 857 Expr *LHS, Expr *RHS) { 858 assert(BinaryOperator::isAssignmentOp(opcode)); 859 860 // If there's no setter, we have no choice but to try to assign to 861 // the result of the getter. 862 if (!findSetter()) { 863 ExprResult result; 864 if (tryBuildGetOfReference(LHS, result)) { 865 if (result.isInvalid()) return ExprError(); 866 return S.BuildBinOp(Sc, opcLoc, opcode, result.get(), RHS); 867 } 868 869 // Otherwise, it's an error. 870 S.Diag(opcLoc, diag::err_nosetter_property_assignment) 871 << unsigned(RefExpr->isImplicitProperty()) 872 << SetterSelector 873 << LHS->getSourceRange() << RHS->getSourceRange(); 874 return ExprError(); 875 } 876 877 // If there is a setter, we definitely want to use it. 878 879 // Verify that we can do a compound assignment. 880 if (opcode != BO_Assign && !findGetter()) { 881 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment) 882 << LHS->getSourceRange() << RHS->getSourceRange(); 883 return ExprError(); 884 } 885 886 ExprResult result = 887 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS); 888 if (result.isInvalid()) return ExprError(); 889 890 // Various warnings about property assignments in ARC. 891 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) { 892 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS); 893 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS); 894 } 895 896 return result; 897 } 898 899 /// @property-specific behavior for doing increments and decrements. 900 ExprResult 901 ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc, 902 UnaryOperatorKind opcode, 903 Expr *op) { 904 // If there's no setter, we have no choice but to try to assign to 905 // the result of the getter. 906 if (!findSetter()) { 907 ExprResult result; 908 if (tryBuildGetOfReference(op, result)) { 909 if (result.isInvalid()) return ExprError(); 910 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.get()); 911 } 912 913 // Otherwise, it's an error. 914 S.Diag(opcLoc, diag::err_nosetter_property_incdec) 915 << unsigned(RefExpr->isImplicitProperty()) 916 << unsigned(UnaryOperator::isDecrementOp(opcode)) 917 << SetterSelector 918 << op->getSourceRange(); 919 return ExprError(); 920 } 921 922 // If there is a setter, we definitely want to use it. 923 924 // We also need a getter. 925 if (!findGetter()) { 926 assert(RefExpr->isImplicitProperty()); 927 S.Diag(opcLoc, diag::err_nogetter_property_incdec) 928 << unsigned(UnaryOperator::isDecrementOp(opcode)) 929 << GetterSelector 930 << op->getSourceRange(); 931 return ExprError(); 932 } 933 934 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op); 935 } 936 937 ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) { 938 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty() && 939 !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, 940 SyntacticForm->getLocStart())) 941 S.recordUseOfEvaluatedWeak(SyntacticRefExpr, 942 SyntacticRefExpr->isMessagingGetter()); 943 944 return PseudoOpBuilder::complete(SyntacticForm); 945 } 946 947 // ObjCSubscript build stuff. 948 // 949 950 /// objective-c subscripting-specific behavior for doing lvalue-to-rvalue 951 /// conversion. 952 /// FIXME. Remove this routine if it is proven that no additional 953 /// specifity is needed. 954 ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) { 955 ExprResult result = PseudoOpBuilder::buildRValueOperation(op); 956 if (result.isInvalid()) return ExprError(); 957 return result; 958 } 959 960 /// objective-c subscripting-specific behavior for doing assignments. 961 ExprResult 962 ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc, 963 SourceLocation opcLoc, 964 BinaryOperatorKind opcode, 965 Expr *LHS, Expr *RHS) { 966 assert(BinaryOperator::isAssignmentOp(opcode)); 967 // There must be a method to do the Index'ed assignment. 968 if (!findAtIndexSetter()) 969 return ExprError(); 970 971 // Verify that we can do a compound assignment. 972 if (opcode != BO_Assign && !findAtIndexGetter()) 973 return ExprError(); 974 975 ExprResult result = 976 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS); 977 if (result.isInvalid()) return ExprError(); 978 979 // Various warnings about objc Index'ed assignments in ARC. 980 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) { 981 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS); 982 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS); 983 } 984 985 return result; 986 } 987 988 /// Capture the base object of an Objective-C Index'ed expression. 989 Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { 990 assert(InstanceBase == nullptr); 991 992 // Capture base expression in an OVE and rebuild the syntactic 993 // form to use the OVE as its base expression. 994 InstanceBase = capture(RefExpr->getBaseExpr()); 995 InstanceKey = capture(RefExpr->getKeyExpr()); 996 997 syntacticBase = 998 ObjCSubscriptRefRebuilder(S, InstanceBase, 999 InstanceKey).rebuild(syntacticBase); 1000 1001 return syntacticBase; 1002 } 1003 1004 /// CheckSubscriptingKind - This routine decide what type 1005 /// of indexing represented by "FromE" is being done. 1006 Sema::ObjCSubscriptKind 1007 Sema::CheckSubscriptingKind(Expr *FromE) { 1008 // If the expression already has integral or enumeration type, we're golden. 1009 QualType T = FromE->getType(); 1010 if (T->isIntegralOrEnumerationType()) 1011 return OS_Array; 1012 1013 // If we don't have a class type in C++, there's no way we can get an 1014 // expression of integral or enumeration type. 1015 const RecordType *RecordTy = T->getAs<RecordType>(); 1016 if (!RecordTy && 1017 (T->isObjCObjectPointerType() || T->isVoidPointerType())) 1018 // All other scalar cases are assumed to be dictionary indexing which 1019 // caller handles, with diagnostics if needed. 1020 return OS_Dictionary; 1021 if (!getLangOpts().CPlusPlus || 1022 !RecordTy || RecordTy->isIncompleteType()) { 1023 // No indexing can be done. Issue diagnostics and quit. 1024 const Expr *IndexExpr = FromE->IgnoreParenImpCasts(); 1025 if (isa<StringLiteral>(IndexExpr)) 1026 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer) 1027 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@"); 1028 else 1029 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion) 1030 << T; 1031 return OS_Error; 1032 } 1033 1034 // We must have a complete class type. 1035 if (RequireCompleteType(FromE->getExprLoc(), T, 1036 diag::err_objc_index_incomplete_class_type, FromE)) 1037 return OS_Error; 1038 1039 // Look for a conversion to an integral, enumeration type, or 1040 // objective-C pointer type. 1041 int NoIntegrals=0, NoObjCIdPointers=0; 1042 SmallVector<CXXConversionDecl *, 4> ConversionDecls; 1043 1044 for (NamedDecl *D : cast<CXXRecordDecl>(RecordTy->getDecl()) 1045 ->getVisibleConversionFunctions()) { 1046 if (CXXConversionDecl *Conversion = 1047 dyn_cast<CXXConversionDecl>(D->getUnderlyingDecl())) { 1048 QualType CT = Conversion->getConversionType().getNonReferenceType(); 1049 if (CT->isIntegralOrEnumerationType()) { 1050 ++NoIntegrals; 1051 ConversionDecls.push_back(Conversion); 1052 } 1053 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) { 1054 ++NoObjCIdPointers; 1055 ConversionDecls.push_back(Conversion); 1056 } 1057 } 1058 } 1059 if (NoIntegrals ==1 && NoObjCIdPointers == 0) 1060 return OS_Array; 1061 if (NoIntegrals == 0 && NoObjCIdPointers == 1) 1062 return OS_Dictionary; 1063 if (NoIntegrals == 0 && NoObjCIdPointers == 0) { 1064 // No conversion function was found. Issue diagnostic and return. 1065 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion) 1066 << FromE->getType(); 1067 return OS_Error; 1068 } 1069 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion) 1070 << FromE->getType(); 1071 for (unsigned int i = 0; i < ConversionDecls.size(); i++) 1072 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at); 1073 1074 return OS_Error; 1075 } 1076 1077 /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF 1078 /// objects used as dictionary subscript key objects. 1079 static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT, 1080 Expr *Key) { 1081 if (ContainerT.isNull()) 1082 return; 1083 // dictionary subscripting. 1084 // - (id)objectForKeyedSubscript:(id)key; 1085 IdentifierInfo *KeyIdents[] = { 1086 &S.Context.Idents.get("objectForKeyedSubscript") 1087 }; 1088 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); 1089 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT, 1090 true /*instance*/); 1091 if (!Getter) 1092 return; 1093 QualType T = Getter->parameters()[0]->getType(); 1094 S.CheckObjCARCConversion(Key->getSourceRange(), 1095 T, Key, Sema::CCK_ImplicitConversion); 1096 } 1097 1098 bool ObjCSubscriptOpBuilder::findAtIndexGetter() { 1099 if (AtIndexGetter) 1100 return true; 1101 1102 Expr *BaseExpr = RefExpr->getBaseExpr(); 1103 QualType BaseT = BaseExpr->getType(); 1104 1105 QualType ResultType; 1106 if (const ObjCObjectPointerType *PTy = 1107 BaseT->getAs<ObjCObjectPointerType>()) { 1108 ResultType = PTy->getPointeeType(); 1109 } 1110 Sema::ObjCSubscriptKind Res = 1111 S.CheckSubscriptingKind(RefExpr->getKeyExpr()); 1112 if (Res == Sema::OS_Error) { 1113 if (S.getLangOpts().ObjCAutoRefCount) 1114 CheckKeyForObjCARCConversion(S, ResultType, 1115 RefExpr->getKeyExpr()); 1116 return false; 1117 } 1118 bool arrayRef = (Res == Sema::OS_Array); 1119 1120 if (ResultType.isNull()) { 1121 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) 1122 << BaseExpr->getType() << arrayRef; 1123 return false; 1124 } 1125 if (!arrayRef) { 1126 // dictionary subscripting. 1127 // - (id)objectForKeyedSubscript:(id)key; 1128 IdentifierInfo *KeyIdents[] = { 1129 &S.Context.Idents.get("objectForKeyedSubscript") 1130 }; 1131 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); 1132 } 1133 else { 1134 // - (id)objectAtIndexedSubscript:(size_t)index; 1135 IdentifierInfo *KeyIdents[] = { 1136 &S.Context.Idents.get("objectAtIndexedSubscript") 1137 }; 1138 1139 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents); 1140 } 1141 1142 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType, 1143 true /*instance*/); 1144 bool receiverIdType = (BaseT->isObjCIdType() || 1145 BaseT->isObjCQualifiedIdType()); 1146 1147 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) { 1148 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(), 1149 SourceLocation(), AtIndexGetterSelector, 1150 S.Context.getObjCIdType() /*ReturnType*/, 1151 nullptr /*TypeSourceInfo */, 1152 S.Context.getTranslationUnitDecl(), 1153 true /*Instance*/, false/*isVariadic*/, 1154 /*isPropertyAccessor=*/false, 1155 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 1156 ObjCMethodDecl::Required, 1157 false); 1158 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter, 1159 SourceLocation(), SourceLocation(), 1160 arrayRef ? &S.Context.Idents.get("index") 1161 : &S.Context.Idents.get("key"), 1162 arrayRef ? S.Context.UnsignedLongTy 1163 : S.Context.getObjCIdType(), 1164 /*TInfo=*/nullptr, 1165 SC_None, 1166 nullptr); 1167 AtIndexGetter->setMethodParams(S.Context, Argument, None); 1168 } 1169 1170 if (!AtIndexGetter) { 1171 if (!receiverIdType) { 1172 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found) 1173 << BaseExpr->getType() << 0 << arrayRef; 1174 return false; 1175 } 1176 AtIndexGetter = 1177 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector, 1178 RefExpr->getSourceRange(), 1179 true); 1180 } 1181 1182 if (AtIndexGetter) { 1183 QualType T = AtIndexGetter->parameters()[0]->getType(); 1184 if ((arrayRef && !T->isIntegralOrEnumerationType()) || 1185 (!arrayRef && !T->isObjCObjectPointerType())) { 1186 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1187 arrayRef ? diag::err_objc_subscript_index_type 1188 : diag::err_objc_subscript_key_type) << T; 1189 S.Diag(AtIndexGetter->parameters()[0]->getLocation(), 1190 diag::note_parameter_type) << T; 1191 return false; 1192 } 1193 QualType R = AtIndexGetter->getReturnType(); 1194 if (!R->isObjCObjectPointerType()) { 1195 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1196 diag::err_objc_indexing_method_result_type) << R << arrayRef; 1197 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) << 1198 AtIndexGetter->getDeclName(); 1199 } 1200 } 1201 return true; 1202 } 1203 1204 bool ObjCSubscriptOpBuilder::findAtIndexSetter() { 1205 if (AtIndexSetter) 1206 return true; 1207 1208 Expr *BaseExpr = RefExpr->getBaseExpr(); 1209 QualType BaseT = BaseExpr->getType(); 1210 1211 QualType ResultType; 1212 if (const ObjCObjectPointerType *PTy = 1213 BaseT->getAs<ObjCObjectPointerType>()) { 1214 ResultType = PTy->getPointeeType(); 1215 } 1216 1217 Sema::ObjCSubscriptKind Res = 1218 S.CheckSubscriptingKind(RefExpr->getKeyExpr()); 1219 if (Res == Sema::OS_Error) { 1220 if (S.getLangOpts().ObjCAutoRefCount) 1221 CheckKeyForObjCARCConversion(S, ResultType, 1222 RefExpr->getKeyExpr()); 1223 return false; 1224 } 1225 bool arrayRef = (Res == Sema::OS_Array); 1226 1227 if (ResultType.isNull()) { 1228 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type) 1229 << BaseExpr->getType() << arrayRef; 1230 return false; 1231 } 1232 1233 if (!arrayRef) { 1234 // dictionary subscripting. 1235 // - (void)setObject:(id)object forKeyedSubscript:(id)key; 1236 IdentifierInfo *KeyIdents[] = { 1237 &S.Context.Idents.get("setObject"), 1238 &S.Context.Idents.get("forKeyedSubscript") 1239 }; 1240 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents); 1241 } 1242 else { 1243 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index; 1244 IdentifierInfo *KeyIdents[] = { 1245 &S.Context.Idents.get("setObject"), 1246 &S.Context.Idents.get("atIndexedSubscript") 1247 }; 1248 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents); 1249 } 1250 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType, 1251 true /*instance*/); 1252 1253 bool receiverIdType = (BaseT->isObjCIdType() || 1254 BaseT->isObjCQualifiedIdType()); 1255 1256 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) { 1257 TypeSourceInfo *ReturnTInfo = nullptr; 1258 QualType ReturnType = S.Context.VoidTy; 1259 AtIndexSetter = ObjCMethodDecl::Create( 1260 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector, 1261 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(), 1262 true /*Instance*/, false /*isVariadic*/, 1263 /*isPropertyAccessor=*/false, 1264 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 1265 ObjCMethodDecl::Required, false); 1266 SmallVector<ParmVarDecl *, 2> Params; 1267 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter, 1268 SourceLocation(), SourceLocation(), 1269 &S.Context.Idents.get("object"), 1270 S.Context.getObjCIdType(), 1271 /*TInfo=*/nullptr, 1272 SC_None, 1273 nullptr); 1274 Params.push_back(object); 1275 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter, 1276 SourceLocation(), SourceLocation(), 1277 arrayRef ? &S.Context.Idents.get("index") 1278 : &S.Context.Idents.get("key"), 1279 arrayRef ? S.Context.UnsignedLongTy 1280 : S.Context.getObjCIdType(), 1281 /*TInfo=*/nullptr, 1282 SC_None, 1283 nullptr); 1284 Params.push_back(key); 1285 AtIndexSetter->setMethodParams(S.Context, Params, None); 1286 } 1287 1288 if (!AtIndexSetter) { 1289 if (!receiverIdType) { 1290 S.Diag(BaseExpr->getExprLoc(), 1291 diag::err_objc_subscript_method_not_found) 1292 << BaseExpr->getType() << 1 << arrayRef; 1293 return false; 1294 } 1295 AtIndexSetter = 1296 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector, 1297 RefExpr->getSourceRange(), 1298 true); 1299 } 1300 1301 bool err = false; 1302 if (AtIndexSetter && arrayRef) { 1303 QualType T = AtIndexSetter->parameters()[1]->getType(); 1304 if (!T->isIntegralOrEnumerationType()) { 1305 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1306 diag::err_objc_subscript_index_type) << T; 1307 S.Diag(AtIndexSetter->parameters()[1]->getLocation(), 1308 diag::note_parameter_type) << T; 1309 err = true; 1310 } 1311 T = AtIndexSetter->parameters()[0]->getType(); 1312 if (!T->isObjCObjectPointerType()) { 1313 S.Diag(RefExpr->getBaseExpr()->getExprLoc(), 1314 diag::err_objc_subscript_object_type) << T << arrayRef; 1315 S.Diag(AtIndexSetter->parameters()[0]->getLocation(), 1316 diag::note_parameter_type) << T; 1317 err = true; 1318 } 1319 } 1320 else if (AtIndexSetter && !arrayRef) 1321 for (unsigned i=0; i <2; i++) { 1322 QualType T = AtIndexSetter->parameters()[i]->getType(); 1323 if (!T->isObjCObjectPointerType()) { 1324 if (i == 1) 1325 S.Diag(RefExpr->getKeyExpr()->getExprLoc(), 1326 diag::err_objc_subscript_key_type) << T; 1327 else 1328 S.Diag(RefExpr->getBaseExpr()->getExprLoc(), 1329 diag::err_objc_subscript_dic_object_type) << T; 1330 S.Diag(AtIndexSetter->parameters()[i]->getLocation(), 1331 diag::note_parameter_type) << T; 1332 err = true; 1333 } 1334 } 1335 1336 return !err; 1337 } 1338 1339 // Get the object at "Index" position in the container. 1340 // [BaseExpr objectAtIndexedSubscript : IndexExpr]; 1341 ExprResult ObjCSubscriptOpBuilder::buildGet() { 1342 if (!findAtIndexGetter()) 1343 return ExprError(); 1344 1345 QualType receiverType = InstanceBase->getType(); 1346 1347 // Build a message-send. 1348 ExprResult msg; 1349 Expr *Index = InstanceKey; 1350 1351 // Arguments. 1352 Expr *args[] = { Index }; 1353 assert(InstanceBase); 1354 if (AtIndexGetter) 1355 S.DiagnoseUseOfDecl(AtIndexGetter, GenericLoc); 1356 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType, 1357 GenericLoc, 1358 AtIndexGetterSelector, AtIndexGetter, 1359 MultiExprArg(args, 1)); 1360 return msg; 1361 } 1362 1363 /// Store into the container the "op" object at "Index"'ed location 1364 /// by building this messaging expression: 1365 /// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index; 1366 /// \param captureSetValueAsResult If true, capture the actual 1367 /// value being set as the value of the property operation. 1368 ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc, 1369 bool captureSetValueAsResult) { 1370 if (!findAtIndexSetter()) 1371 return ExprError(); 1372 if (AtIndexSetter) 1373 S.DiagnoseUseOfDecl(AtIndexSetter, GenericLoc); 1374 QualType receiverType = InstanceBase->getType(); 1375 Expr *Index = InstanceKey; 1376 1377 // Arguments. 1378 Expr *args[] = { op, Index }; 1379 1380 // Build a message-send. 1381 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType, 1382 GenericLoc, 1383 AtIndexSetterSelector, 1384 AtIndexSetter, 1385 MultiExprArg(args, 2)); 1386 1387 if (!msg.isInvalid() && captureSetValueAsResult) { 1388 ObjCMessageExpr *msgExpr = 1389 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit()); 1390 Expr *arg = msgExpr->getArg(0); 1391 if (CanCaptureValue(arg)) 1392 msgExpr->setArg(0, captureValueAsResult(arg)); 1393 } 1394 1395 return msg; 1396 } 1397 1398 //===----------------------------------------------------------------------===// 1399 // MSVC __declspec(property) references 1400 //===----------------------------------------------------------------------===// 1401 1402 Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) { 1403 Expr *NewBase = capture(RefExpr->getBaseExpr()); 1404 1405 syntacticBase = 1406 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase); 1407 1408 return syntacticBase; 1409 } 1410 1411 ExprResult MSPropertyOpBuilder::buildGet() { 1412 if (!RefExpr->getPropertyDecl()->hasGetter()) { 1413 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property) 1414 << 0 /* getter */ << RefExpr->getPropertyDecl(); 1415 return ExprError(); 1416 } 1417 1418 UnqualifiedId GetterName; 1419 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId(); 1420 GetterName.setIdentifier(II, RefExpr->getMemberLoc()); 1421 CXXScopeSpec SS; 1422 SS.Adopt(RefExpr->getQualifierLoc()); 1423 ExprResult GetterExpr = S.ActOnMemberAccessExpr( 1424 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(), 1425 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(), 1426 GetterName, nullptr); 1427 if (GetterExpr.isInvalid()) { 1428 S.Diag(RefExpr->getMemberLoc(), 1429 diag::error_cannot_find_suitable_accessor) << 0 /* getter */ 1430 << RefExpr->getPropertyDecl(); 1431 return ExprError(); 1432 } 1433 1434 MultiExprArg ArgExprs; 1435 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.get(), 1436 RefExpr->getSourceRange().getBegin(), ArgExprs, 1437 RefExpr->getSourceRange().getEnd()); 1438 } 1439 1440 ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl, 1441 bool captureSetValueAsResult) { 1442 if (!RefExpr->getPropertyDecl()->hasSetter()) { 1443 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property) 1444 << 1 /* setter */ << RefExpr->getPropertyDecl(); 1445 return ExprError(); 1446 } 1447 1448 UnqualifiedId SetterName; 1449 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId(); 1450 SetterName.setIdentifier(II, RefExpr->getMemberLoc()); 1451 CXXScopeSpec SS; 1452 SS.Adopt(RefExpr->getQualifierLoc()); 1453 ExprResult SetterExpr = S.ActOnMemberAccessExpr( 1454 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(), 1455 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(), 1456 SetterName, nullptr); 1457 if (SetterExpr.isInvalid()) { 1458 S.Diag(RefExpr->getMemberLoc(), 1459 diag::error_cannot_find_suitable_accessor) << 1 /* setter */ 1460 << RefExpr->getPropertyDecl(); 1461 return ExprError(); 1462 } 1463 1464 SmallVector<Expr*, 1> ArgExprs; 1465 ArgExprs.push_back(op); 1466 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.get(), 1467 RefExpr->getSourceRange().getBegin(), ArgExprs, 1468 op->getSourceRange().getEnd()); 1469 } 1470 1471 //===----------------------------------------------------------------------===// 1472 // General Sema routines. 1473 //===----------------------------------------------------------------------===// 1474 1475 ExprResult Sema::checkPseudoObjectRValue(Expr *E) { 1476 Expr *opaqueRef = E->IgnoreParens(); 1477 if (ObjCPropertyRefExpr *refExpr 1478 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1479 ObjCPropertyOpBuilder builder(*this, refExpr); 1480 return builder.buildRValueOperation(E); 1481 } 1482 else if (ObjCSubscriptRefExpr *refExpr 1483 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) { 1484 ObjCSubscriptOpBuilder builder(*this, refExpr); 1485 return builder.buildRValueOperation(E); 1486 } else if (MSPropertyRefExpr *refExpr 1487 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1488 MSPropertyOpBuilder builder(*this, refExpr); 1489 return builder.buildRValueOperation(E); 1490 } else { 1491 llvm_unreachable("unknown pseudo-object kind!"); 1492 } 1493 } 1494 1495 /// Check an increment or decrement of a pseudo-object expression. 1496 ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc, 1497 UnaryOperatorKind opcode, Expr *op) { 1498 // Do nothing if the operand is dependent. 1499 if (op->isTypeDependent()) 1500 return new (Context) UnaryOperator(op, opcode, Context.DependentTy, 1501 VK_RValue, OK_Ordinary, opcLoc); 1502 1503 assert(UnaryOperator::isIncrementDecrementOp(opcode)); 1504 Expr *opaqueRef = op->IgnoreParens(); 1505 if (ObjCPropertyRefExpr *refExpr 1506 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1507 ObjCPropertyOpBuilder builder(*this, refExpr); 1508 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op); 1509 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) { 1510 Diag(opcLoc, diag::err_illegal_container_subscripting_op); 1511 return ExprError(); 1512 } else if (MSPropertyRefExpr *refExpr 1513 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1514 MSPropertyOpBuilder builder(*this, refExpr); 1515 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op); 1516 } else { 1517 llvm_unreachable("unknown pseudo-object kind!"); 1518 } 1519 } 1520 1521 ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc, 1522 BinaryOperatorKind opcode, 1523 Expr *LHS, Expr *RHS) { 1524 // Do nothing if either argument is dependent. 1525 if (LHS->isTypeDependent() || RHS->isTypeDependent()) 1526 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy, 1527 VK_RValue, OK_Ordinary, opcLoc, false); 1528 1529 // Filter out non-overload placeholder types in the RHS. 1530 if (RHS->getType()->isNonOverloadPlaceholderType()) { 1531 ExprResult result = CheckPlaceholderExpr(RHS); 1532 if (result.isInvalid()) return ExprError(); 1533 RHS = result.get(); 1534 } 1535 1536 Expr *opaqueRef = LHS->IgnoreParens(); 1537 if (ObjCPropertyRefExpr *refExpr 1538 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1539 ObjCPropertyOpBuilder builder(*this, refExpr); 1540 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS); 1541 } else if (ObjCSubscriptRefExpr *refExpr 1542 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) { 1543 ObjCSubscriptOpBuilder builder(*this, refExpr); 1544 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS); 1545 } else if (MSPropertyRefExpr *refExpr 1546 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1547 MSPropertyOpBuilder builder(*this, refExpr); 1548 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS); 1549 } else { 1550 llvm_unreachable("unknown pseudo-object kind!"); 1551 } 1552 } 1553 1554 /// Given a pseudo-object reference, rebuild it without the opaque 1555 /// values. Basically, undo the behavior of rebuildAndCaptureObject. 1556 /// This should never operate in-place. 1557 static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) { 1558 Expr *opaqueRef = E->IgnoreParens(); 1559 if (ObjCPropertyRefExpr *refExpr 1560 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) { 1561 // Class and super property references don't have opaque values in them. 1562 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver()) 1563 return E; 1564 1565 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?"); 1566 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase()); 1567 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E); 1568 } else if (ObjCSubscriptRefExpr *refExpr 1569 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) { 1570 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr()); 1571 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr()); 1572 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(), 1573 keyOVE->getSourceExpr()).rebuild(E); 1574 } else if (MSPropertyRefExpr *refExpr 1575 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) { 1576 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr()); 1577 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E); 1578 } else { 1579 llvm_unreachable("unknown pseudo-object kind!"); 1580 } 1581 } 1582 1583 /// Given a pseudo-object expression, recreate what it looks like 1584 /// syntactically without the attendant OpaqueValueExprs. 1585 /// 1586 /// This is a hack which should be removed when TreeTransform is 1587 /// capable of rebuilding a tree without stripping implicit 1588 /// operations. 1589 Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) { 1590 Expr *syntax = E->getSyntacticForm(); 1591 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) { 1592 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr()); 1593 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(), 1594 uop->getValueKind(), uop->getObjectKind(), 1595 uop->getOperatorLoc()); 1596 } else if (CompoundAssignOperator *cop 1597 = dyn_cast<CompoundAssignOperator>(syntax)) { 1598 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS()); 1599 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr(); 1600 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(), 1601 cop->getType(), 1602 cop->getValueKind(), 1603 cop->getObjectKind(), 1604 cop->getComputationLHSType(), 1605 cop->getComputationResultType(), 1606 cop->getOperatorLoc(), false); 1607 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) { 1608 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS()); 1609 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr(); 1610 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(), 1611 bop->getType(), bop->getValueKind(), 1612 bop->getObjectKind(), 1613 bop->getOperatorLoc(), false); 1614 } else { 1615 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject)); 1616 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax); 1617 } 1618 } 1619