1 //===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
15 // For example, Objective-C objects can have "properties", either
16 // declared or undeclared. A property may be accessed by writing
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:
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]
31 //===----------------------------------------------------------------------===//
33 #include "clang/Sema/SemaInternal.h"
34 #include "clang/AST/ExprObjC.h"
35 #include "clang/Basic/CharInfo.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/ScopeInfo.h"
39 #include "llvm/ADT/SmallString.h"
41 using namespace clang;
45 // Basically just a very focused copy of TreeTransform.
46 template <class T> struct Rebuilder {
48 Rebuilder(Sema &S) : S(S) {}
50 T &getDerived() { return static_cast<T&>(*this); }
52 Expr *rebuild(Expr *e) {
53 // Fast path: nothing to look through.
54 if (typename T::specific_type *specific
55 = dyn_cast<typename T::specific_type>(e))
56 return getDerived().rebuildSpecific(specific);
58 // Otherwise, we should look through and rebuild anything that
59 // IgnoreParens would.
61 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
62 e = rebuild(parens->getSubExpr());
63 return new (S.Context) ParenExpr(parens->getLParen(),
68 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
69 assert(uop->getOpcode() == UO_Extension);
70 e = rebuild(uop->getSubExpr());
71 return new (S.Context) UnaryOperator(e, uop->getOpcode(),
75 uop->getOperatorLoc());
78 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
79 assert(!gse->isResultDependent());
80 unsigned resultIndex = gse->getResultIndex();
81 unsigned numAssocs = gse->getNumAssocs();
83 SmallVector<Expr*, 8> assocs(numAssocs);
84 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
86 for (unsigned i = 0; i != numAssocs; ++i) {
87 Expr *assoc = gse->getAssocExpr(i);
88 if (i == resultIndex) assoc = rebuild(assoc);
90 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
93 return new (S.Context) GenericSelectionExpr(S.Context,
95 gse->getControllingExpr(),
100 gse->containsUnexpandedParameterPack(),
104 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
105 assert(!ce->isConditionDependent());
107 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
108 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
109 rebuiltExpr = rebuild(rebuiltExpr);
111 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(),
114 rebuiltExpr->getType(),
115 rebuiltExpr->getValueKind(),
116 rebuiltExpr->getObjectKind(),
118 ce->isConditionTrue(),
119 rebuiltExpr->isTypeDependent(),
120 rebuiltExpr->isValueDependent());
123 llvm_unreachable("bad expression to rebuild!");
127 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> {
129 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase)
130 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {}
132 typedef ObjCPropertyRefExpr specific_type;
133 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) {
134 // Fortunately, the constraint that we're rebuilding something
135 // with a base limits the number of cases here.
136 assert(refExpr->isObjectReceiver());
138 if (refExpr->isExplicitProperty()) {
139 return new (S.Context)
140 ObjCPropertyRefExpr(refExpr->getExplicitProperty(),
141 refExpr->getType(), refExpr->getValueKind(),
142 refExpr->getObjectKind(), refExpr->getLocation(),
145 return new (S.Context)
146 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(),
147 refExpr->getImplicitPropertySetter(),
148 refExpr->getType(), refExpr->getValueKind(),
149 refExpr->getObjectKind(),refExpr->getLocation(),
154 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> {
157 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr)
158 : Rebuilder<ObjCSubscriptRefRebuilder>(S),
159 NewBase(newBase), NewKeyExpr(newKeyExpr) {}
161 typedef ObjCSubscriptRefExpr specific_type;
162 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) {
163 assert(refExpr->getBaseExpr());
164 assert(refExpr->getKeyExpr());
166 return new (S.Context)
167 ObjCSubscriptRefExpr(NewBase,
169 refExpr->getType(), refExpr->getValueKind(),
170 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(),
171 refExpr->setAtIndexMethodDecl(),
172 refExpr->getRBracket());
176 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> {
178 MSPropertyRefRebuilder(Sema &S, Expr *newBase)
179 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {}
181 typedef MSPropertyRefExpr specific_type;
182 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) {
183 assert(refExpr->getBaseExpr());
185 return new (S.Context)
186 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(),
187 refExpr->isArrow(), refExpr->getType(),
188 refExpr->getValueKind(), refExpr->getQualifierLoc(),
189 refExpr->getMemberLoc());
193 class PseudoOpBuilder {
196 unsigned ResultIndex;
197 SourceLocation GenericLoc;
198 SmallVector<Expr *, 4> Semantics;
200 PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
201 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
202 GenericLoc(genericLoc) {}
204 virtual ~PseudoOpBuilder() {}
206 /// Add a normal semantic expression.
207 void addSemanticExpr(Expr *semantic) {
208 Semantics.push_back(semantic);
211 /// Add the 'result' semantic expression.
212 void addResultSemanticExpr(Expr *resultExpr) {
213 assert(ResultIndex == PseudoObjectExpr::NoResult);
214 ResultIndex = Semantics.size();
215 Semantics.push_back(resultExpr);
218 ExprResult buildRValueOperation(Expr *op);
219 ExprResult buildAssignmentOperation(Scope *Sc,
220 SourceLocation opLoc,
221 BinaryOperatorKind opcode,
222 Expr *LHS, Expr *RHS);
223 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
224 UnaryOperatorKind opcode,
227 virtual ExprResult complete(Expr *syntacticForm);
229 OpaqueValueExpr *capture(Expr *op);
230 OpaqueValueExpr *captureValueAsResult(Expr *op);
232 void setResultToLastSemantic() {
233 assert(ResultIndex == PseudoObjectExpr::NoResult);
234 ResultIndex = Semantics.size() - 1;
237 /// Return true if assignments have a non-void result.
238 bool CanCaptureValueOfType(QualType ty) {
239 assert(!ty->isIncompleteType());
240 assert(!ty->isDependentType());
242 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
243 return ClassDecl->isTriviallyCopyable();
247 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
248 virtual ExprResult buildGet() = 0;
249 virtual ExprResult buildSet(Expr *, SourceLocation,
250 bool captureSetValueAsResult) = 0;
253 /// A PseudoOpBuilder for Objective-C \@properties.
254 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
255 ObjCPropertyRefExpr *RefExpr;
256 ObjCPropertyRefExpr *SyntacticRefExpr;
257 OpaqueValueExpr *InstanceReceiver;
258 ObjCMethodDecl *Getter;
260 ObjCMethodDecl *Setter;
261 Selector SetterSelector;
262 Selector GetterSelector;
265 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
266 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
267 SyntacticRefExpr(0), InstanceReceiver(0), Getter(0), Setter(0) {
270 ExprResult buildRValueOperation(Expr *op);
271 ExprResult buildAssignmentOperation(Scope *Sc,
272 SourceLocation opLoc,
273 BinaryOperatorKind opcode,
274 Expr *LHS, Expr *RHS);
275 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
276 UnaryOperatorKind opcode,
279 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
280 bool findSetter(bool warn=true);
283 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
284 ExprResult buildGet();
285 ExprResult buildSet(Expr *op, SourceLocation, bool);
286 ExprResult complete(Expr *SyntacticForm);
288 bool isWeakProperty() const;
291 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
292 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
293 ObjCSubscriptRefExpr *RefExpr;
294 OpaqueValueExpr *InstanceBase;
295 OpaqueValueExpr *InstanceKey;
296 ObjCMethodDecl *AtIndexGetter;
297 Selector AtIndexGetterSelector;
299 ObjCMethodDecl *AtIndexSetter;
300 Selector AtIndexSetterSelector;
303 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
304 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
306 InstanceBase(0), InstanceKey(0),
307 AtIndexGetter(0), AtIndexSetter(0) { }
309 ExprResult buildRValueOperation(Expr *op);
310 ExprResult buildAssignmentOperation(Scope *Sc,
311 SourceLocation opLoc,
312 BinaryOperatorKind opcode,
313 Expr *LHS, Expr *RHS);
314 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
316 bool findAtIndexGetter();
317 bool findAtIndexSetter();
319 ExprResult buildGet();
320 ExprResult buildSet(Expr *op, SourceLocation, bool);
323 class MSPropertyOpBuilder : public PseudoOpBuilder {
324 MSPropertyRefExpr *RefExpr;
327 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) :
328 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
331 Expr *rebuildAndCaptureObject(Expr *);
332 ExprResult buildGet();
333 ExprResult buildSet(Expr *op, SourceLocation, bool);
337 /// Capture the given expression in an OpaqueValueExpr.
338 OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
339 // Make a new OVE whose source is the given expression.
340 OpaqueValueExpr *captured =
341 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
342 e->getValueKind(), e->getObjectKind(),
345 // Make sure we bind that in the semantics.
346 addSemanticExpr(captured);
350 /// Capture the given expression as the result of this pseudo-object
351 /// operation. This routine is safe against expressions which may
352 /// already be captured.
354 /// \returns the captured expression, which will be the
355 /// same as the input if the input was already captured
356 OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
357 assert(ResultIndex == PseudoObjectExpr::NoResult);
359 // If the expression hasn't already been captured, just capture it
360 // and set the new semantic
361 if (!isa<OpaqueValueExpr>(e)) {
362 OpaqueValueExpr *cap = capture(e);
363 setResultToLastSemantic();
367 // Otherwise, it must already be one of our semantic expressions;
368 // set ResultIndex to its index.
371 assert(index < Semantics.size() &&
372 "captured expression not found in semantics!");
373 if (e == Semantics[index]) break;
376 return cast<OpaqueValueExpr>(e);
379 /// The routine which creates the final PseudoObjectExpr.
380 ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
381 return PseudoObjectExpr::Create(S.Context, syntactic,
382 Semantics, ResultIndex);
385 /// The main skeleton for building an r-value operation.
386 ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
387 Expr *syntacticBase = rebuildAndCaptureObject(op);
389 ExprResult getExpr = buildGet();
390 if (getExpr.isInvalid()) return ExprError();
391 addResultSemanticExpr(getExpr.take());
393 return complete(syntacticBase);
396 /// The basic skeleton for building a simple or compound
397 /// assignment operation.
399 PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
400 BinaryOperatorKind opcode,
401 Expr *LHS, Expr *RHS) {
402 assert(BinaryOperator::isAssignmentOp(opcode));
404 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
405 OpaqueValueExpr *capturedRHS = capture(RHS);
410 if (opcode == BO_Assign) {
411 result = capturedRHS;
412 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
413 opcode, capturedRHS->getType(),
414 capturedRHS->getValueKind(),
415 OK_Ordinary, opcLoc, false);
417 ExprResult opLHS = buildGet();
418 if (opLHS.isInvalid()) return ExprError();
420 // Build an ordinary, non-compound operation.
421 BinaryOperatorKind nonCompound =
422 BinaryOperator::getOpForCompoundAssignment(opcode);
423 result = S.BuildBinOp(Sc, opcLoc, nonCompound,
424 opLHS.take(), capturedRHS);
425 if (result.isInvalid()) return ExprError();
428 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
429 result.get()->getType(),
430 result.get()->getValueKind(),
432 opLHS.get()->getType(),
433 result.get()->getType(),
437 // The result of the assignment, if not void, is the value set into
439 result = buildSet(result.take(), opcLoc, /*captureSetValueAsResult*/ true);
440 if (result.isInvalid()) return ExprError();
441 addSemanticExpr(result.take());
443 return complete(syntactic);
446 /// The basic skeleton for building an increment or decrement
449 PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
450 UnaryOperatorKind opcode,
452 assert(UnaryOperator::isIncrementDecrementOp(opcode));
454 Expr *syntacticOp = rebuildAndCaptureObject(op);
457 ExprResult result = buildGet();
458 if (result.isInvalid()) return ExprError();
460 QualType resultType = result.get()->getType();
462 // That's the postfix result.
463 if (UnaryOperator::isPostfix(opcode) &&
464 (result.get()->isTypeDependent() || CanCaptureValueOfType(resultType))) {
465 result = capture(result.take());
466 setResultToLastSemantic();
469 // Add or subtract a literal 1.
470 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
471 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
474 if (UnaryOperator::isIncrementOp(opcode)) {
475 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one);
477 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one);
479 if (result.isInvalid()) return ExprError();
481 // Store that back into the result. The value stored is the result
482 // of a prefix operation.
483 result = buildSet(result.take(), opcLoc, UnaryOperator::isPrefix(opcode));
484 if (result.isInvalid()) return ExprError();
485 addSemanticExpr(result.take());
487 UnaryOperator *syntactic =
488 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
489 VK_LValue, OK_Ordinary, opcLoc);
490 return complete(syntactic);
494 //===----------------------------------------------------------------------===//
495 // Objective-C @property and implicit property references
496 //===----------------------------------------------------------------------===//
498 /// Look up a method in the receiver type of an Objective-C property
500 static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
501 const ObjCPropertyRefExpr *PRE) {
502 if (PRE->isObjectReceiver()) {
503 const ObjCObjectPointerType *PT =
504 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
506 // Special case for 'self' in class method implementations.
507 if (PT->isObjCClassType() &&
508 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
509 // This cast is safe because isSelfExpr is only true within
511 ObjCMethodDecl *method =
512 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
513 return S.LookupMethodInObjectType(sel,
514 S.Context.getObjCInterfaceType(method->getClassInterface()),
518 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
521 if (PRE->isSuperReceiver()) {
522 if (const ObjCObjectPointerType *PT =
523 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
524 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
526 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
529 assert(PRE->isClassReceiver() && "Invalid expression");
530 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
531 return S.LookupMethodInObjectType(sel, IT, false);
534 bool ObjCPropertyOpBuilder::isWeakProperty() const {
536 if (RefExpr->isExplicitProperty()) {
537 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
538 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
543 T = Getter->getResultType();
548 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
551 bool ObjCPropertyOpBuilder::findGetter() {
552 if (Getter) return true;
554 // For implicit properties, just trust the lookup we already did.
555 if (RefExpr->isImplicitProperty()) {
556 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
557 GetterSelector = Getter->getSelector();
561 // Must build the getter selector the hard way.
562 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
563 assert(setter && "both setter and getter are null - cannot happen");
564 IdentifierInfo *setterName =
565 setter->getSelector().getIdentifierInfoForSlot(0);
566 const char *compStr = setterName->getNameStart();
568 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
570 S.PP.getSelectorTable().getNullarySelector(getterName);
576 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
577 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
578 return (Getter != 0);
581 /// Try to find the most accurate setter declaration for the property
584 /// \return true if a setter was found, in which case Setter
585 bool ObjCPropertyOpBuilder::findSetter(bool warn) {
586 // For implicit properties, just trust the lookup we already did.
587 if (RefExpr->isImplicitProperty()) {
588 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
590 SetterSelector = setter->getSelector();
593 IdentifierInfo *getterName =
594 RefExpr->getImplicitPropertyGetter()->getSelector()
595 .getIdentifierInfoForSlot(0);
597 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
598 S.PP.getSelectorTable(),
604 // For explicit properties, this is more involved.
605 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
606 SetterSelector = prop->getSetterName();
608 // Do a normal method lookup first.
609 if (ObjCMethodDecl *setter =
610 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
611 if (setter->isPropertyAccessor() && warn)
612 if (const ObjCInterfaceDecl *IFace =
613 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
614 const StringRef thisPropertyName(prop->getName());
615 // Try flipping the case of the first character.
616 char front = thisPropertyName.front();
617 front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
618 SmallString<100> PropertyName = thisPropertyName;
619 PropertyName[0] = front;
620 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
621 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember))
622 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
623 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use)
624 << prop->getName() << prop1->getName() << setter->getSelector();
625 S.Diag(prop->getLocation(), diag::note_property_declare);
626 S.Diag(prop1->getLocation(), diag::note_property_declare);
633 // That can fail in the somewhat crazy situation that we're
634 // type-checking a message send within the @interface declaration
635 // that declared the @property. But it's not clear that that's
636 // valuable to support.
641 /// Capture the base object of an Objective-C property expression.
642 Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
643 assert(InstanceReceiver == 0);
645 // If we have a base, capture it in an OVE and rebuild the syntactic
646 // form to use the OVE as its base.
647 if (RefExpr->isObjectReceiver()) {
648 InstanceReceiver = capture(RefExpr->getBase());
651 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
654 if (ObjCPropertyRefExpr *
655 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
656 SyntacticRefExpr = refE;
658 return syntacticBase;
661 /// Load from an Objective-C property reference.
662 ExprResult ObjCPropertyOpBuilder::buildGet() {
666 if (SyntacticRefExpr)
667 SyntacticRefExpr->setIsMessagingGetter();
669 QualType receiverType;
670 if (RefExpr->isClassReceiver()) {
671 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
672 } else if (RefExpr->isSuperReceiver()) {
673 receiverType = RefExpr->getSuperReceiverType();
675 assert(InstanceReceiver);
676 receiverType = InstanceReceiver->getType();
679 // Build a message-send.
681 if (Getter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
682 assert(InstanceReceiver || RefExpr->isSuperReceiver());
683 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
684 GenericLoc, Getter->getSelector(),
687 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
688 GenericLoc, Getter->getSelector(),
694 /// Store to an Objective-C property reference.
696 /// \param captureSetValueAsResult If true, capture the actual
697 /// value being set as the value of the property operation.
698 ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
699 bool captureSetValueAsResult) {
700 bool hasSetter = findSetter(false);
701 assert(hasSetter); (void) hasSetter;
703 if (SyntacticRefExpr)
704 SyntacticRefExpr->setIsMessagingSetter();
706 QualType receiverType;
707 if (RefExpr->isClassReceiver()) {
708 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
709 } else if (RefExpr->isSuperReceiver()) {
710 receiverType = RefExpr->getSuperReceiverType();
712 assert(InstanceReceiver);
713 receiverType = InstanceReceiver->getType();
716 // Use assignment constraints when possible; they give us better
717 // diagnostics. "When possible" basically means anything except a
719 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
720 QualType paramType = (*Setter->param_begin())->getType();
721 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
722 ExprResult opResult = op;
723 Sema::AssignConvertType assignResult
724 = S.CheckSingleAssignmentConstraints(paramType, opResult);
725 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
726 op->getType(), opResult.get(),
730 op = opResult.take();
731 assert(op && "successful assignment left argument invalid?");
733 else if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(op)) {
734 Expr *Initializer = OVE->getSourceExpr();
735 // passing C++11 style initialized temporaries to objc++ properties
736 // requires special treatment by removing OpaqueValueExpr so type
737 // conversion takes place and adding the OpaqueValueExpr later on.
738 if (isa<InitListExpr>(Initializer) &&
739 Initializer->getType()->isVoidType()) {
746 Expr *args[] = { op };
748 // Build a message-send.
750 if (Setter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
751 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
752 GenericLoc, SetterSelector, Setter,
753 MultiExprArg(args, 1));
755 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
757 SetterSelector, Setter,
758 MultiExprArg(args, 1));
761 if (!msg.isInvalid() && captureSetValueAsResult) {
762 ObjCMessageExpr *msgExpr =
763 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
764 Expr *arg = msgExpr->getArg(0);
765 if (CanCaptureValueOfType(arg->getType()))
766 msgExpr->setArg(0, captureValueAsResult(arg));
772 /// @property-specific behavior for doing lvalue-to-rvalue conversion.
773 ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
774 // Explicit properties always have getters, but implicit ones don't.
775 // Check that before proceeding.
776 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
777 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
778 << RefExpr->getSourceRange();
782 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
783 if (result.isInvalid()) return ExprError();
785 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
786 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
787 Getter, RefExpr->getLocation());
789 // As a special case, if the method returns 'id', try to get
790 // a better type from the property.
791 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
792 result.get()->getType()->isObjCIdType()) {
793 QualType propType = RefExpr->getExplicitProperty()->getType();
794 if (const ObjCObjectPointerType *ptr
795 = propType->getAs<ObjCObjectPointerType>()) {
796 if (!ptr->isObjCIdType())
797 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
804 /// Try to build this as a call to a getter that returns a reference.
806 /// \return true if it was possible, whether or not it actually
808 bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
809 ExprResult &result) {
810 if (!S.getLangOpts().CPlusPlus) return false;
813 assert(Getter && "property has no setter and no getter!");
815 // Only do this if the getter returns an l-value reference type.
816 QualType resultType = Getter->getResultType();
817 if (!resultType->isLValueReferenceType()) return false;
819 result = buildRValueOperation(op);
823 /// @property-specific behavior for doing assignments.
825 ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
826 SourceLocation opcLoc,
827 BinaryOperatorKind opcode,
828 Expr *LHS, Expr *RHS) {
829 assert(BinaryOperator::isAssignmentOp(opcode));
831 // If there's no setter, we have no choice but to try to assign to
832 // the result of the getter.
835 if (tryBuildGetOfReference(LHS, result)) {
836 if (result.isInvalid()) return ExprError();
837 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
840 // Otherwise, it's an error.
841 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
842 << unsigned(RefExpr->isImplicitProperty())
844 << LHS->getSourceRange() << RHS->getSourceRange();
848 // If there is a setter, we definitely want to use it.
850 // Verify that we can do a compound assignment.
851 if (opcode != BO_Assign && !findGetter()) {
852 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
853 << LHS->getSourceRange() << RHS->getSourceRange();
858 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
859 if (result.isInvalid()) return ExprError();
861 // Various warnings about property assignments in ARC.
862 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
863 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
864 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
870 /// @property-specific behavior for doing increments and decrements.
872 ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
873 UnaryOperatorKind opcode,
875 // If there's no setter, we have no choice but to try to assign to
876 // the result of the getter.
879 if (tryBuildGetOfReference(op, result)) {
880 if (result.isInvalid()) return ExprError();
881 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
884 // Otherwise, it's an error.
885 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
886 << unsigned(RefExpr->isImplicitProperty())
887 << unsigned(UnaryOperator::isDecrementOp(opcode))
889 << op->getSourceRange();
893 // If there is a setter, we definitely want to use it.
895 // We also need a getter.
897 assert(RefExpr->isImplicitProperty());
898 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
899 << unsigned(UnaryOperator::isDecrementOp(opcode))
901 << op->getSourceRange();
905 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
908 ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
909 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) {
910 DiagnosticsEngine::Level Level =
911 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
912 SyntacticForm->getLocStart());
913 if (Level != DiagnosticsEngine::Ignored)
914 S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
915 SyntacticRefExpr->isMessagingGetter());
918 return PseudoOpBuilder::complete(SyntacticForm);
921 // ObjCSubscript build stuff.
924 /// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
926 /// FIXME. Remove this routine if it is proven that no additional
927 /// specifity is needed.
928 ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
929 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
930 if (result.isInvalid()) return ExprError();
934 /// objective-c subscripting-specific behavior for doing assignments.
936 ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
937 SourceLocation opcLoc,
938 BinaryOperatorKind opcode,
939 Expr *LHS, Expr *RHS) {
940 assert(BinaryOperator::isAssignmentOp(opcode));
941 // There must be a method to do the Index'ed assignment.
942 if (!findAtIndexSetter())
945 // Verify that we can do a compound assignment.
946 if (opcode != BO_Assign && !findAtIndexGetter())
950 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
951 if (result.isInvalid()) return ExprError();
953 // Various warnings about objc Index'ed assignments in ARC.
954 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
955 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
956 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
962 /// Capture the base object of an Objective-C Index'ed expression.
963 Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
964 assert(InstanceBase == 0);
966 // Capture base expression in an OVE and rebuild the syntactic
967 // form to use the OVE as its base expression.
968 InstanceBase = capture(RefExpr->getBaseExpr());
969 InstanceKey = capture(RefExpr->getKeyExpr());
972 ObjCSubscriptRefRebuilder(S, InstanceBase,
973 InstanceKey).rebuild(syntacticBase);
975 return syntacticBase;
978 /// CheckSubscriptingKind - This routine decide what type
979 /// of indexing represented by "FromE" is being done.
980 Sema::ObjCSubscriptKind
981 Sema::CheckSubscriptingKind(Expr *FromE) {
982 // If the expression already has integral or enumeration type, we're golden.
983 QualType T = FromE->getType();
984 if (T->isIntegralOrEnumerationType())
987 // If we don't have a class type in C++, there's no way we can get an
988 // expression of integral or enumeration type.
989 const RecordType *RecordTy = T->getAs<RecordType>();
990 if (!RecordTy && T->isObjCObjectPointerType())
991 // All other scalar cases are assumed to be dictionary indexing which
992 // caller handles, with diagnostics if needed.
993 return OS_Dictionary;
994 if (!getLangOpts().CPlusPlus ||
995 !RecordTy || RecordTy->isIncompleteType()) {
996 // No indexing can be done. Issue diagnostics and quit.
997 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
998 if (isa<StringLiteral>(IndexExpr))
999 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1000 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1002 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1007 // We must have a complete class type.
1008 if (RequireCompleteType(FromE->getExprLoc(), T,
1009 diag::err_objc_index_incomplete_class_type, FromE))
1012 // Look for a conversion to an integral, enumeration type, or
1013 // objective-C pointer type.
1014 UnresolvedSet<4> ViableConversions;
1015 UnresolvedSet<4> ExplicitConversions;
1016 std::pair<CXXRecordDecl::conversion_iterator,
1017 CXXRecordDecl::conversion_iterator> Conversions
1018 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
1020 int NoIntegrals=0, NoObjCIdPointers=0;
1021 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1023 for (CXXRecordDecl::conversion_iterator
1024 I = Conversions.first, E = Conversions.second; I != E; ++I) {
1025 if (CXXConversionDecl *Conversion
1026 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
1027 QualType CT = Conversion->getConversionType().getNonReferenceType();
1028 if (CT->isIntegralOrEnumerationType()) {
1030 ConversionDecls.push_back(Conversion);
1032 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1034 ConversionDecls.push_back(Conversion);
1038 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1040 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1041 return OS_Dictionary;
1042 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1043 // No conversion function was found. Issue diagnostic and return.
1044 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1045 << FromE->getType();
1048 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1049 << FromE->getType();
1050 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1051 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
1056 /// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1057 /// objects used as dictionary subscript key objects.
1058 static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1060 if (ContainerT.isNull())
1062 // dictionary subscripting.
1063 // - (id)objectForKeyedSubscript:(id)key;
1064 IdentifierInfo *KeyIdents[] = {
1065 &S.Context.Idents.get("objectForKeyedSubscript")
1067 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1068 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1072 QualType T = Getter->param_begin()[0]->getType();
1073 S.CheckObjCARCConversion(Key->getSourceRange(),
1074 T, Key, Sema::CCK_ImplicitConversion);
1077 bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1081 Expr *BaseExpr = RefExpr->getBaseExpr();
1082 QualType BaseT = BaseExpr->getType();
1084 QualType ResultType;
1085 if (const ObjCObjectPointerType *PTy =
1086 BaseT->getAs<ObjCObjectPointerType>()) {
1087 ResultType = PTy->getPointeeType();
1088 if (const ObjCObjectType *iQFaceTy =
1089 ResultType->getAsObjCQualifiedInterfaceType())
1090 ResultType = iQFaceTy->getBaseType();
1092 Sema::ObjCSubscriptKind Res =
1093 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
1094 if (Res == Sema::OS_Error) {
1095 if (S.getLangOpts().ObjCAutoRefCount)
1096 CheckKeyForObjCARCConversion(S, ResultType,
1097 RefExpr->getKeyExpr());
1100 bool arrayRef = (Res == Sema::OS_Array);
1102 if (ResultType.isNull()) {
1103 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1104 << BaseExpr->getType() << arrayRef;
1108 // dictionary subscripting.
1109 // - (id)objectForKeyedSubscript:(id)key;
1110 IdentifierInfo *KeyIdents[] = {
1111 &S.Context.Idents.get("objectForKeyedSubscript")
1113 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1116 // - (id)objectAtIndexedSubscript:(size_t)index;
1117 IdentifierInfo *KeyIdents[] = {
1118 &S.Context.Idents.get("objectAtIndexedSubscript")
1121 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1124 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1126 bool receiverIdType = (BaseT->isObjCIdType() ||
1127 BaseT->isObjCQualifiedIdType());
1129 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
1130 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1131 SourceLocation(), AtIndexGetterSelector,
1132 S.Context.getObjCIdType() /*ReturnType*/,
1133 0 /*TypeSourceInfo */,
1134 S.Context.getTranslationUnitDecl(),
1135 true /*Instance*/, false/*isVariadic*/,
1136 /*isPropertyAccessor=*/false,
1137 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1138 ObjCMethodDecl::Required,
1140 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1141 SourceLocation(), SourceLocation(),
1142 arrayRef ? &S.Context.Idents.get("index")
1143 : &S.Context.Idents.get("key"),
1144 arrayRef ? S.Context.UnsignedLongTy
1145 : S.Context.getObjCIdType(),
1149 AtIndexGetter->setMethodParams(S.Context, Argument, None);
1152 if (!AtIndexGetter) {
1153 if (!receiverIdType) {
1154 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1155 << BaseExpr->getType() << 0 << arrayRef;
1159 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1160 RefExpr->getSourceRange(),
1164 if (AtIndexGetter) {
1165 QualType T = AtIndexGetter->param_begin()[0]->getType();
1166 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1167 (!arrayRef && !T->isObjCObjectPointerType())) {
1168 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1169 arrayRef ? diag::err_objc_subscript_index_type
1170 : diag::err_objc_subscript_key_type) << T;
1171 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1172 diag::note_parameter_type) << T;
1175 QualType R = AtIndexGetter->getResultType();
1176 if (!R->isObjCObjectPointerType()) {
1177 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1178 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1179 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1180 AtIndexGetter->getDeclName();
1186 bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1190 Expr *BaseExpr = RefExpr->getBaseExpr();
1191 QualType BaseT = BaseExpr->getType();
1193 QualType ResultType;
1194 if (const ObjCObjectPointerType *PTy =
1195 BaseT->getAs<ObjCObjectPointerType>()) {
1196 ResultType = PTy->getPointeeType();
1197 if (const ObjCObjectType *iQFaceTy =
1198 ResultType->getAsObjCQualifiedInterfaceType())
1199 ResultType = iQFaceTy->getBaseType();
1202 Sema::ObjCSubscriptKind Res =
1203 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
1204 if (Res == Sema::OS_Error) {
1205 if (S.getLangOpts().ObjCAutoRefCount)
1206 CheckKeyForObjCARCConversion(S, ResultType,
1207 RefExpr->getKeyExpr());
1210 bool arrayRef = (Res == Sema::OS_Array);
1212 if (ResultType.isNull()) {
1213 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1214 << BaseExpr->getType() << arrayRef;
1219 // dictionary subscripting.
1220 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1221 IdentifierInfo *KeyIdents[] = {
1222 &S.Context.Idents.get("setObject"),
1223 &S.Context.Idents.get("forKeyedSubscript")
1225 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1228 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1229 IdentifierInfo *KeyIdents[] = {
1230 &S.Context.Idents.get("setObject"),
1231 &S.Context.Idents.get("atIndexedSubscript")
1233 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1235 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1238 bool receiverIdType = (BaseT->isObjCIdType() ||
1239 BaseT->isObjCQualifiedIdType());
1241 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
1242 TypeSourceInfo *ResultTInfo = 0;
1243 QualType ReturnType = S.Context.VoidTy;
1244 AtIndexSetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1245 SourceLocation(), AtIndexSetterSelector,
1248 S.Context.getTranslationUnitDecl(),
1249 true /*Instance*/, false/*isVariadic*/,
1250 /*isPropertyAccessor=*/false,
1251 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1252 ObjCMethodDecl::Required,
1254 SmallVector<ParmVarDecl *, 2> Params;
1255 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1256 SourceLocation(), SourceLocation(),
1257 &S.Context.Idents.get("object"),
1258 S.Context.getObjCIdType(),
1262 Params.push_back(object);
1263 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1264 SourceLocation(), SourceLocation(),
1265 arrayRef ? &S.Context.Idents.get("index")
1266 : &S.Context.Idents.get("key"),
1267 arrayRef ? S.Context.UnsignedLongTy
1268 : S.Context.getObjCIdType(),
1272 Params.push_back(key);
1273 AtIndexSetter->setMethodParams(S.Context, Params, None);
1276 if (!AtIndexSetter) {
1277 if (!receiverIdType) {
1278 S.Diag(BaseExpr->getExprLoc(),
1279 diag::err_objc_subscript_method_not_found)
1280 << BaseExpr->getType() << 1 << arrayRef;
1284 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1285 RefExpr->getSourceRange(),
1290 if (AtIndexSetter && arrayRef) {
1291 QualType T = AtIndexSetter->param_begin()[1]->getType();
1292 if (!T->isIntegralOrEnumerationType()) {
1293 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1294 diag::err_objc_subscript_index_type) << T;
1295 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1296 diag::note_parameter_type) << T;
1299 T = AtIndexSetter->param_begin()[0]->getType();
1300 if (!T->isObjCObjectPointerType()) {
1301 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1302 diag::err_objc_subscript_object_type) << T << arrayRef;
1303 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1304 diag::note_parameter_type) << T;
1308 else if (AtIndexSetter && !arrayRef)
1309 for (unsigned i=0; i <2; i++) {
1310 QualType T = AtIndexSetter->param_begin()[i]->getType();
1311 if (!T->isObjCObjectPointerType()) {
1313 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1314 diag::err_objc_subscript_key_type) << T;
1316 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1317 diag::err_objc_subscript_dic_object_type) << T;
1318 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1319 diag::note_parameter_type) << T;
1327 // Get the object at "Index" position in the container.
1328 // [BaseExpr objectAtIndexedSubscript : IndexExpr];
1329 ExprResult ObjCSubscriptOpBuilder::buildGet() {
1330 if (!findAtIndexGetter())
1333 QualType receiverType = InstanceBase->getType();
1335 // Build a message-send.
1337 Expr *Index = InstanceKey;
1340 Expr *args[] = { Index };
1341 assert(InstanceBase);
1342 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1344 AtIndexGetterSelector, AtIndexGetter,
1345 MultiExprArg(args, 1));
1349 /// Store into the container the "op" object at "Index"'ed location
1350 /// by building this messaging expression:
1351 /// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1352 /// \param captureSetValueAsResult If true, capture the actual
1353 /// value being set as the value of the property operation.
1354 ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1355 bool captureSetValueAsResult) {
1356 if (!findAtIndexSetter())
1359 QualType receiverType = InstanceBase->getType();
1360 Expr *Index = InstanceKey;
1363 Expr *args[] = { op, Index };
1365 // Build a message-send.
1366 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1368 AtIndexSetterSelector,
1370 MultiExprArg(args, 2));
1372 if (!msg.isInvalid() && captureSetValueAsResult) {
1373 ObjCMessageExpr *msgExpr =
1374 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1375 Expr *arg = msgExpr->getArg(0);
1376 if (CanCaptureValueOfType(arg->getType()))
1377 msgExpr->setArg(0, captureValueAsResult(arg));
1383 //===----------------------------------------------------------------------===//
1384 // MSVC __declspec(property) references
1385 //===----------------------------------------------------------------------===//
1387 Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1388 Expr *NewBase = capture(RefExpr->getBaseExpr());
1391 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase);
1393 return syntacticBase;
1396 ExprResult MSPropertyOpBuilder::buildGet() {
1397 if (!RefExpr->getPropertyDecl()->hasGetter()) {
1398 S.Diag(RefExpr->getMemberLoc(), diag::err_no_getter_for_property)
1399 << RefExpr->getPropertyDecl()->getName();
1403 UnqualifiedId GetterName;
1404 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1405 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1407 SS.Adopt(RefExpr->getQualifierLoc());
1408 ExprResult GetterExpr = S.ActOnMemberAccessExpr(
1409 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1410 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1411 GetterName, 0, true);
1412 if (GetterExpr.isInvalid()) {
1413 S.Diag(RefExpr->getMemberLoc(), diag::error_cannot_find_suitable_getter)
1414 << RefExpr->getPropertyDecl()->getName();
1418 MultiExprArg ArgExprs;
1419 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.take(),
1420 RefExpr->getSourceRange().getBegin(), ArgExprs,
1421 RefExpr->getSourceRange().getEnd());
1424 ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1425 bool captureSetValueAsResult) {
1426 if (!RefExpr->getPropertyDecl()->hasSetter()) {
1427 S.Diag(RefExpr->getMemberLoc(), diag::err_no_setter_for_property)
1428 << RefExpr->getPropertyDecl()->getName();
1432 UnqualifiedId SetterName;
1433 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1434 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1436 SS.Adopt(RefExpr->getQualifierLoc());
1437 ExprResult SetterExpr = S.ActOnMemberAccessExpr(
1438 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1439 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1440 SetterName, 0, true);
1441 if (SetterExpr.isInvalid()) {
1442 S.Diag(RefExpr->getMemberLoc(), diag::error_cannot_find_suitable_setter)
1443 << RefExpr->getPropertyDecl()->getName();
1447 SmallVector<Expr*, 1> ArgExprs;
1448 ArgExprs.push_back(op);
1449 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.take(),
1450 RefExpr->getSourceRange().getBegin(), ArgExprs,
1451 op->getSourceRange().getEnd());
1454 //===----------------------------------------------------------------------===//
1455 // General Sema routines.
1456 //===----------------------------------------------------------------------===//
1458 ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1459 Expr *opaqueRef = E->IgnoreParens();
1460 if (ObjCPropertyRefExpr *refExpr
1461 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1462 ObjCPropertyOpBuilder builder(*this, refExpr);
1463 return builder.buildRValueOperation(E);
1465 else if (ObjCSubscriptRefExpr *refExpr
1466 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1467 ObjCSubscriptOpBuilder builder(*this, refExpr);
1468 return builder.buildRValueOperation(E);
1469 } else if (MSPropertyRefExpr *refExpr
1470 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1471 MSPropertyOpBuilder builder(*this, refExpr);
1472 return builder.buildRValueOperation(E);
1474 llvm_unreachable("unknown pseudo-object kind!");
1478 /// Check an increment or decrement of a pseudo-object expression.
1479 ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1480 UnaryOperatorKind opcode, Expr *op) {
1481 // Do nothing if the operand is dependent.
1482 if (op->isTypeDependent())
1483 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1484 VK_RValue, OK_Ordinary, opcLoc);
1486 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1487 Expr *opaqueRef = op->IgnoreParens();
1488 if (ObjCPropertyRefExpr *refExpr
1489 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1490 ObjCPropertyOpBuilder builder(*this, refExpr);
1491 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1492 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1493 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1495 } else if (MSPropertyRefExpr *refExpr
1496 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1497 MSPropertyOpBuilder builder(*this, refExpr);
1498 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
1500 llvm_unreachable("unknown pseudo-object kind!");
1504 ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1505 BinaryOperatorKind opcode,
1506 Expr *LHS, Expr *RHS) {
1507 // Do nothing if either argument is dependent.
1508 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1509 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
1510 VK_RValue, OK_Ordinary, opcLoc, false);
1512 // Filter out non-overload placeholder types in the RHS.
1513 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1514 ExprResult result = CheckPlaceholderExpr(RHS);
1515 if (result.isInvalid()) return ExprError();
1516 RHS = result.take();
1519 Expr *opaqueRef = LHS->IgnoreParens();
1520 if (ObjCPropertyRefExpr *refExpr
1521 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1522 ObjCPropertyOpBuilder builder(*this, refExpr);
1523 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1524 } else if (ObjCSubscriptRefExpr *refExpr
1525 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1526 ObjCSubscriptOpBuilder builder(*this, refExpr);
1527 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1528 } else if (MSPropertyRefExpr *refExpr
1529 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1530 MSPropertyOpBuilder builder(*this, refExpr);
1531 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
1533 llvm_unreachable("unknown pseudo-object kind!");
1537 /// Given a pseudo-object reference, rebuild it without the opaque
1538 /// values. Basically, undo the behavior of rebuildAndCaptureObject.
1539 /// This should never operate in-place.
1540 static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1541 Expr *opaqueRef = E->IgnoreParens();
1542 if (ObjCPropertyRefExpr *refExpr
1543 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1544 // Class and super property references don't have opaque values in them.
1545 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1548 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1549 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1550 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
1551 } else if (ObjCSubscriptRefExpr *refExpr
1552 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1553 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1554 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1555 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1556 keyOVE->getSourceExpr()).rebuild(E);
1557 } else if (MSPropertyRefExpr *refExpr
1558 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1559 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1560 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
1562 llvm_unreachable("unknown pseudo-object kind!");
1566 /// Given a pseudo-object expression, recreate what it looks like
1567 /// syntactically without the attendant OpaqueValueExprs.
1569 /// This is a hack which should be removed when TreeTransform is
1570 /// capable of rebuilding a tree without stripping implicit
1572 Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1573 Expr *syntax = E->getSyntacticForm();
1574 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1575 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1576 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1577 uop->getValueKind(), uop->getObjectKind(),
1578 uop->getOperatorLoc());
1579 } else if (CompoundAssignOperator *cop
1580 = dyn_cast<CompoundAssignOperator>(syntax)) {
1581 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1582 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1583 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1585 cop->getValueKind(),
1586 cop->getObjectKind(),
1587 cop->getComputationLHSType(),
1588 cop->getComputationResultType(),
1589 cop->getOperatorLoc(), false);
1590 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1591 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1592 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1593 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1594 bop->getType(), bop->getValueKind(),
1595 bop->getObjectKind(),
1596 bop->getOperatorLoc(), false);
1598 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1599 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);