blob: af74f0d4a3e80a53009b6b9a5d7b83245a70c1ce [file] [log] [blame]
John McCall3c3b7f92011-10-25 17:37:35 +00001//===--- 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"
John McCall3c3b7f92011-10-25 17:37:35 +000034#include "clang/AST/ExprObjC.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000035#include "clang/Basic/CharInfo.h"
John McCall3c3b7f92011-10-25 17:37:35 +000036#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000037#include "clang/Sema/Initialization.h"
38#include "clang/Sema/ScopeInfo.h"
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +000039#include "llvm/ADT/SmallString.h"
John McCall3c3b7f92011-10-25 17:37:35 +000040
41using namespace clang;
42using namespace sema;
43
John McCall4b9c2d22011-11-06 09:01:30 +000044namespace {
45 // Basically just a very focused copy of TreeTransform.
46 template <class T> struct Rebuilder {
47 Sema &S;
48 Rebuilder(Sema &S) : S(S) {}
49
50 T &getDerived() { return static_cast<T&>(*this); }
51
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);
57
58 // Otherwise, we should look through and rebuild anything that
59 // IgnoreParens would.
60
61 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
62 e = rebuild(parens->getSubExpr());
63 return new (S.Context) ParenExpr(parens->getLParen(),
64 parens->getRParen(),
65 e);
66 }
67
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(),
72 uop->getType(),
73 uop->getValueKind(),
74 uop->getObjectKind(),
75 uop->getOperatorLoc());
76 }
77
78 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
79 assert(!gse->isResultDependent());
80 unsigned resultIndex = gse->getResultIndex();
81 unsigned numAssocs = gse->getNumAssocs();
82
83 SmallVector<Expr*, 8> assocs(numAssocs);
84 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
85
86 for (unsigned i = 0; i != numAssocs; ++i) {
87 Expr *assoc = gse->getAssocExpr(i);
88 if (i == resultIndex) assoc = rebuild(assoc);
89 assocs[i] = assoc;
90 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
91 }
92
93 return new (S.Context) GenericSelectionExpr(S.Context,
94 gse->getGenericLoc(),
95 gse->getControllingExpr(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000096 assocTypes,
97 assocs,
John McCall4b9c2d22011-11-06 09:01:30 +000098 gse->getDefaultLoc(),
99 gse->getRParenLoc(),
100 gse->containsUnexpandedParameterPack(),
101 resultIndex);
102 }
103
Eli Friedmana5e66012013-07-20 00:40:58 +0000104 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
105 assert(!ce->isConditionDependent());
106
107 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
108 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
109 rebuiltExpr = rebuild(rebuiltExpr);
110
111 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(),
112 ce->getCond(),
113 LHS, RHS,
114 rebuiltExpr->getType(),
115 rebuiltExpr->getValueKind(),
116 rebuiltExpr->getObjectKind(),
117 ce->getRParenLoc(),
118 ce->isConditionTrue(),
119 rebuiltExpr->isTypeDependent(),
120 rebuiltExpr->isValueDependent());
121 }
122
John McCall4b9c2d22011-11-06 09:01:30 +0000123 llvm_unreachable("bad expression to rebuild!");
124 }
125 };
126
127 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> {
128 Expr *NewBase;
129 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase)
Benjamin Krameracf9e822011-11-06 09:50:13 +0000130 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {}
John McCall4b9c2d22011-11-06 09:01:30 +0000131
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.
Eli Friedmana70779f2012-11-29 03:13:49 +0000136 assert(refExpr->isObjectReceiver());
John McCall4b9c2d22011-11-06 09:01:30 +0000137
138 if (refExpr->isExplicitProperty()) {
139 return new (S.Context)
140 ObjCPropertyRefExpr(refExpr->getExplicitProperty(),
141 refExpr->getType(), refExpr->getValueKind(),
142 refExpr->getObjectKind(), refExpr->getLocation(),
143 NewBase);
144 }
145 return new (S.Context)
146 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(),
147 refExpr->getImplicitPropertySetter(),
148 refExpr->getType(), refExpr->getValueKind(),
149 refExpr->getObjectKind(),refExpr->getLocation(),
150 NewBase);
151 }
152 };
153
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000154 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> {
155 Expr *NewBase;
156 Expr *NewKeyExpr;
157 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr)
158 : Rebuilder<ObjCSubscriptRefRebuilder>(S),
159 NewBase(newBase), NewKeyExpr(newKeyExpr) {}
160
161 typedef ObjCSubscriptRefExpr specific_type;
162 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) {
163 assert(refExpr->getBaseExpr());
164 assert(refExpr->getKeyExpr());
165
166 return new (S.Context)
167 ObjCSubscriptRefExpr(NewBase,
168 NewKeyExpr,
169 refExpr->getType(), refExpr->getValueKind(),
170 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(),
171 refExpr->setAtIndexMethodDecl(),
172 refExpr->getRBracket());
173 }
174 };
John McCall76da55d2013-04-16 07:28:30 +0000175
176 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> {
177 Expr *NewBase;
178 MSPropertyRefRebuilder(Sema &S, Expr *newBase)
179 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {}
180
181 typedef MSPropertyRefExpr specific_type;
182 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) {
183 assert(refExpr->getBaseExpr());
184
185 return new (S.Context)
186 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(),
187 refExpr->isArrow(), refExpr->getType(),
188 refExpr->getValueKind(), refExpr->getQualifierLoc(),
189 refExpr->getMemberLoc());
190 }
191 };
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000192
John McCall4b9c2d22011-11-06 09:01:30 +0000193 class PseudoOpBuilder {
194 public:
195 Sema &S;
196 unsigned ResultIndex;
197 SourceLocation GenericLoc;
198 SmallVector<Expr *, 4> Semantics;
199
200 PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
201 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
202 GenericLoc(genericLoc) {}
203
Matt Beaumont-Gay1aa17212011-11-08 01:53:17 +0000204 virtual ~PseudoOpBuilder() {}
205
John McCall4b9c2d22011-11-06 09:01:30 +0000206 /// Add a normal semantic expression.
207 void addSemanticExpr(Expr *semantic) {
208 Semantics.push_back(semantic);
209 }
210
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);
216 }
217
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,
225 Expr *op);
226
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000227 virtual ExprResult complete(Expr *syntacticForm);
John McCall4b9c2d22011-11-06 09:01:30 +0000228
229 OpaqueValueExpr *capture(Expr *op);
230 OpaqueValueExpr *captureValueAsResult(Expr *op);
231
232 void setResultToLastSemantic() {
233 assert(ResultIndex == PseudoObjectExpr::NoResult);
234 ResultIndex = Semantics.size() - 1;
235 }
236
237 /// Return true if assignments have a non-void result.
Eli Friedman25f071e2012-11-13 23:16:33 +0000238 bool CanCaptureValueOfType(QualType ty) {
239 assert(!ty->isIncompleteType());
240 assert(!ty->isDependentType());
241
242 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
243 return ClassDecl->isTriviallyCopyable();
244 return true;
245 }
John McCall4b9c2d22011-11-06 09:01:30 +0000246
247 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
248 virtual ExprResult buildGet() = 0;
249 virtual ExprResult buildSet(Expr *, SourceLocation,
250 bool captureSetValueAsResult) = 0;
251 };
252
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000253 /// A PseudoOpBuilder for Objective-C \@properties.
John McCall4b9c2d22011-11-06 09:01:30 +0000254 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
255 ObjCPropertyRefExpr *RefExpr;
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000256 ObjCPropertyRefExpr *SyntacticRefExpr;
John McCall4b9c2d22011-11-06 09:01:30 +0000257 OpaqueValueExpr *InstanceReceiver;
258 ObjCMethodDecl *Getter;
259
260 ObjCMethodDecl *Setter;
261 Selector SetterSelector;
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000262 Selector GetterSelector;
John McCall4b9c2d22011-11-06 09:01:30 +0000263
264 public:
265 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
266 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000267 SyntacticRefExpr(0), InstanceReceiver(0), Getter(0), Setter(0) {
John McCall4b9c2d22011-11-06 09:01:30 +0000268 }
269
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,
277 Expr *op);
278
279 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000280 bool findSetter(bool warn=true);
John McCall4b9c2d22011-11-06 09:01:30 +0000281 bool findGetter();
282
283 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
284 ExprResult buildGet();
285 ExprResult buildSet(Expr *op, SourceLocation, bool);
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000286 ExprResult complete(Expr *SyntacticForm);
287
288 bool isWeakProperty() const;
John McCall4b9c2d22011-11-06 09:01:30 +0000289 };
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000290
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;
298
299 ObjCMethodDecl *AtIndexSetter;
300 Selector AtIndexSetterSelector;
301
302 public:
303 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
304 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
305 RefExpr(refExpr),
306 InstanceBase(0), InstanceKey(0),
307 AtIndexGetter(0), AtIndexSetter(0) { }
308
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);
315
316 bool findAtIndexGetter();
317 bool findAtIndexSetter();
318
319 ExprResult buildGet();
320 ExprResult buildSet(Expr *op, SourceLocation, bool);
321 };
322
John McCall76da55d2013-04-16 07:28:30 +0000323 class MSPropertyOpBuilder : public PseudoOpBuilder {
324 MSPropertyRefExpr *RefExpr;
325
326 public:
327 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) :
328 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
329 RefExpr(refExpr) {}
330
331 Expr *rebuildAndCaptureObject(Expr *);
332 ExprResult buildGet();
333 ExprResult buildSet(Expr *op, SourceLocation, bool);
334 };
John McCall4b9c2d22011-11-06 09:01:30 +0000335}
336
337/// Capture the given expression in an OpaqueValueExpr.
338OpaqueValueExpr *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(),
Douglas Gregor97df54e2012-02-23 22:17:26 +0000342 e->getValueKind(), e->getObjectKind(),
343 e);
John McCall4b9c2d22011-11-06 09:01:30 +0000344
345 // Make sure we bind that in the semantics.
346 addSemanticExpr(captured);
347 return captured;
348}
349
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.
353///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000354/// \returns the captured expression, which will be the
John McCall4b9c2d22011-11-06 09:01:30 +0000355/// same as the input if the input was already captured
356OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
357 assert(ResultIndex == PseudoObjectExpr::NoResult);
358
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();
364 return cap;
365 }
366
367 // Otherwise, it must already be one of our semantic expressions;
368 // set ResultIndex to its index.
369 unsigned index = 0;
370 for (;; ++index) {
371 assert(index < Semantics.size() &&
372 "captured expression not found in semantics!");
373 if (e == Semantics[index]) break;
374 }
375 ResultIndex = index;
376 return cast<OpaqueValueExpr>(e);
377}
378
379/// The routine which creates the final PseudoObjectExpr.
380ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
381 return PseudoObjectExpr::Create(S.Context, syntactic,
382 Semantics, ResultIndex);
383}
384
385/// The main skeleton for building an r-value operation.
386ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
387 Expr *syntacticBase = rebuildAndCaptureObject(op);
388
389 ExprResult getExpr = buildGet();
390 if (getExpr.isInvalid()) return ExprError();
391 addResultSemanticExpr(getExpr.take());
392
393 return complete(syntacticBase);
394}
395
396/// The basic skeleton for building a simple or compound
397/// assignment operation.
398ExprResult
399PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
400 BinaryOperatorKind opcode,
401 Expr *LHS, Expr *RHS) {
402 assert(BinaryOperator::isAssignmentOp(opcode));
403
404 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
405 OpaqueValueExpr *capturedRHS = capture(RHS);
406
407 Expr *syntactic;
408
409 ExprResult result;
410 if (opcode == BO_Assign) {
411 result = capturedRHS;
412 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
413 opcode, capturedRHS->getType(),
414 capturedRHS->getValueKind(),
Lang Hamesbe9af122012-10-02 04:45:10 +0000415 OK_Ordinary, opcLoc, false);
John McCall4b9c2d22011-11-06 09:01:30 +0000416 } else {
417 ExprResult opLHS = buildGet();
418 if (opLHS.isInvalid()) return ExprError();
419
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();
426
427 syntactic =
428 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
429 result.get()->getType(),
430 result.get()->getValueKind(),
431 OK_Ordinary,
432 opLHS.get()->getType(),
433 result.get()->getType(),
Lang Hamesbe9af122012-10-02 04:45:10 +0000434 opcLoc, false);
John McCall4b9c2d22011-11-06 09:01:30 +0000435 }
436
437 // The result of the assignment, if not void, is the value set into
438 // the l-value.
Eli Friedman25f071e2012-11-13 23:16:33 +0000439 result = buildSet(result.take(), opcLoc, /*captureSetValueAsResult*/ true);
John McCall4b9c2d22011-11-06 09:01:30 +0000440 if (result.isInvalid()) return ExprError();
441 addSemanticExpr(result.take());
442
443 return complete(syntactic);
444}
445
446/// The basic skeleton for building an increment or decrement
447/// operation.
448ExprResult
449PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
450 UnaryOperatorKind opcode,
451 Expr *op) {
452 assert(UnaryOperator::isIncrementDecrementOp(opcode));
453
454 Expr *syntacticOp = rebuildAndCaptureObject(op);
455
456 // Load the value.
457 ExprResult result = buildGet();
458 if (result.isInvalid()) return ExprError();
459
460 QualType resultType = result.get()->getType();
461
462 // That's the postfix result.
John McCalld314abe2013-04-16 22:32:04 +0000463 if (UnaryOperator::isPostfix(opcode) &&
464 (result.get()->isTypeDependent() || CanCaptureValueOfType(resultType))) {
John McCall4b9c2d22011-11-06 09:01:30 +0000465 result = capture(result.take());
466 setResultToLastSemantic();
467 }
468
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,
472 GenericLoc);
473
474 if (UnaryOperator::isIncrementOp(opcode)) {
475 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one);
476 } else {
477 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one);
478 }
479 if (result.isInvalid()) return ExprError();
480
481 // Store that back into the result. The value stored is the result
482 // of a prefix operation.
Eli Friedman25f071e2012-11-13 23:16:33 +0000483 result = buildSet(result.take(), opcLoc, UnaryOperator::isPrefix(opcode));
John McCall4b9c2d22011-11-06 09:01:30 +0000484 if (result.isInvalid()) return ExprError();
485 addSemanticExpr(result.take());
486
487 UnaryOperator *syntactic =
488 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
489 VK_LValue, OK_Ordinary, opcLoc);
490 return complete(syntactic);
491}
492
493
494//===----------------------------------------------------------------------===//
495// Objective-C @property and implicit property references
496//===----------------------------------------------------------------------===//
497
498/// Look up a method in the receiver type of an Objective-C property
499/// reference.
John McCall3c3b7f92011-10-25 17:37:35 +0000500static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
501 const ObjCPropertyRefExpr *PRE) {
John McCall3c3b7f92011-10-25 17:37:35 +0000502 if (PRE->isObjectReceiver()) {
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000503 const ObjCObjectPointerType *PT =
504 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +0000505
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
510 // methods.
511 ObjCMethodDecl *method =
512 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
513 return S.LookupMethodInObjectType(sel,
514 S.Context.getObjCInterfaceType(method->getClassInterface()),
515 /*instance*/ false);
516 }
517
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000518 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
John McCall3c3b7f92011-10-25 17:37:35 +0000519 }
520
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000521 if (PRE->isSuperReceiver()) {
522 if (const ObjCObjectPointerType *PT =
523 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
524 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
525
526 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
527 }
528
529 assert(PRE->isClassReceiver() && "Invalid expression");
530 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
531 return S.LookupMethodInObjectType(sel, IT, false);
John McCall3c3b7f92011-10-25 17:37:35 +0000532}
533
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000534bool ObjCPropertyOpBuilder::isWeakProperty() const {
535 QualType T;
536 if (RefExpr->isExplicitProperty()) {
537 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
538 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
539 return true;
540
541 T = Prop->getType();
542 } else if (Getter) {
543 T = Getter->getResultType();
544 } else {
545 return false;
546 }
547
548 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
549}
550
John McCall4b9c2d22011-11-06 09:01:30 +0000551bool ObjCPropertyOpBuilder::findGetter() {
552 if (Getter) return true;
John McCall3c3b7f92011-10-25 17:37:35 +0000553
John McCalldc4df512011-11-07 22:49:50 +0000554 // For implicit properties, just trust the lookup we already did.
555 if (RefExpr->isImplicitProperty()) {
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000556 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
557 GetterSelector = Getter->getSelector();
558 return true;
559 }
560 else {
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();
567 compStr += 3;
568 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
569 GetterSelector =
570 S.PP.getSelectorTable().getNullarySelector(getterName);
571 return false;
572
573 }
John McCalldc4df512011-11-07 22:49:50 +0000574 }
575
576 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
577 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
John McCall4b9c2d22011-11-06 09:01:30 +0000578 return (Getter != 0);
579}
580
581/// Try to find the most accurate setter declaration for the property
582/// reference.
583///
584/// \return true if a setter was found, in which case Setter
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000585bool ObjCPropertyOpBuilder::findSetter(bool warn) {
John McCall4b9c2d22011-11-06 09:01:30 +0000586 // For implicit properties, just trust the lookup we already did.
587 if (RefExpr->isImplicitProperty()) {
588 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
589 Setter = setter;
590 SetterSelector = setter->getSelector();
591 return true;
John McCall3c3b7f92011-10-25 17:37:35 +0000592 } else {
John McCall4b9c2d22011-11-06 09:01:30 +0000593 IdentifierInfo *getterName =
594 RefExpr->getImplicitPropertyGetter()->getSelector()
595 .getIdentifierInfoForSlot(0);
596 SetterSelector =
Adrian Prantl80e8ea92013-06-07 22:29:12 +0000597 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
598 S.PP.getSelectorTable(),
599 getterName);
John McCall4b9c2d22011-11-06 09:01:30 +0000600 return false;
John McCall3c3b7f92011-10-25 17:37:35 +0000601 }
John McCall4b9c2d22011-11-06 09:01:30 +0000602 }
603
604 // For explicit properties, this is more involved.
605 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
606 SetterSelector = prop->getSetterName();
607
608 // Do a normal method lookup first.
609 if (ObjCMethodDecl *setter =
610 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
Jordan Rose1e4691b2012-10-10 16:42:25 +0000611 if (setter->isPropertyAccessor() && warn)
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000612 if (const ObjCInterfaceDecl *IFace =
613 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
614 const StringRef thisPropertyName(prop->getName());
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000615 // Try flipping the case of the first character.
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000616 char front = thisPropertyName.front();
Jordan Rose3f6f51e2013-02-08 22:30:41 +0000617 front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000618 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)) {
Fariborz Jahaniancba0ebc2012-05-26 16:10:06 +0000623 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use)
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000624 << prop->getName() << prop1->getName() << setter->getSelector();
625 S.Diag(prop->getLocation(), diag::note_property_declare);
626 S.Diag(prop1->getLocation(), diag::note_property_declare);
627 }
628 }
John McCall4b9c2d22011-11-06 09:01:30 +0000629 Setter = setter;
630 return true;
631 }
632
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.
637
638 return false;
639}
640
641/// Capture the base object of an Objective-C property expression.
642Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
643 assert(InstanceReceiver == 0);
644
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());
649
650 syntacticBase =
651 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
652 }
653
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000654 if (ObjCPropertyRefExpr *
655 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
656 SyntacticRefExpr = refE;
657
John McCall4b9c2d22011-11-06 09:01:30 +0000658 return syntacticBase;
659}
660
661/// Load from an Objective-C property reference.
662ExprResult ObjCPropertyOpBuilder::buildGet() {
663 findGetter();
664 assert(Getter);
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000665
666 if (SyntacticRefExpr)
667 SyntacticRefExpr->setIsMessagingGetter();
668
John McCall4b9c2d22011-11-06 09:01:30 +0000669 QualType receiverType;
John McCall4b9c2d22011-11-06 09:01:30 +0000670 if (RefExpr->isClassReceiver()) {
671 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
672 } else if (RefExpr->isSuperReceiver()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000673 receiverType = RefExpr->getSuperReceiverType();
John McCall3c3b7f92011-10-25 17:37:35 +0000674 } else {
John McCall4b9c2d22011-11-06 09:01:30 +0000675 assert(InstanceReceiver);
676 receiverType = InstanceReceiver->getType();
677 }
John McCall3c3b7f92011-10-25 17:37:35 +0000678
John McCall4b9c2d22011-11-06 09:01:30 +0000679 // Build a message-send.
680 ExprResult msg;
681 if (Getter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
682 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000683 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
684 GenericLoc, Getter->getSelector(),
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000685 Getter, None);
John McCall4b9c2d22011-11-06 09:01:30 +0000686 } else {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000687 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
Dmitri Gribenko62ed8892013-05-05 20:40:26 +0000688 GenericLoc, Getter->getSelector(),
689 Getter, None);
John McCall4b9c2d22011-11-06 09:01:30 +0000690 }
691 return msg;
692}
John McCall3c3b7f92011-10-25 17:37:35 +0000693
John McCall4b9c2d22011-11-06 09:01:30 +0000694/// Store to an Objective-C property reference.
695///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000696/// \param captureSetValueAsResult If true, capture the actual
John McCall4b9c2d22011-11-06 09:01:30 +0000697/// value being set as the value of the property operation.
698ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
699 bool captureSetValueAsResult) {
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000700 bool hasSetter = findSetter(false);
John McCall4b9c2d22011-11-06 09:01:30 +0000701 assert(hasSetter); (void) hasSetter;
702
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000703 if (SyntacticRefExpr)
704 SyntacticRefExpr->setIsMessagingSetter();
705
John McCall4b9c2d22011-11-06 09:01:30 +0000706 QualType receiverType;
John McCall4b9c2d22011-11-06 09:01:30 +0000707 if (RefExpr->isClassReceiver()) {
708 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
709 } else if (RefExpr->isSuperReceiver()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000710 receiverType = RefExpr->getSuperReceiverType();
711 } else {
712 assert(InstanceReceiver);
713 receiverType = InstanceReceiver->getType();
714 }
715
716 // Use assignment constraints when possible; they give us better
717 // diagnostics. "When possible" basically means anything except a
718 // C++ class type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000719 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000720 QualType paramType = (*Setter->param_begin())->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +0000721 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000722 ExprResult opResult = op;
723 Sema::AssignConvertType assignResult
724 = S.CheckSingleAssignmentConstraints(paramType, opResult);
725 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
726 op->getType(), opResult.get(),
727 Sema::AA_Assigning))
728 return ExprError();
729
730 op = opResult.take();
731 assert(op && "successful assignment left argument invalid?");
John McCall3c3b7f92011-10-25 17:37:35 +0000732 }
Fariborz Jahanian289a0d82013-10-16 17:51:43 +0000733 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()) {
740 op = Initializer;
741 }
742 }
John McCall3c3b7f92011-10-25 17:37:35 +0000743 }
744
John McCall4b9c2d22011-11-06 09:01:30 +0000745 // Arguments.
746 Expr *args[] = { op };
John McCall3c3b7f92011-10-25 17:37:35 +0000747
John McCall4b9c2d22011-11-06 09:01:30 +0000748 // Build a message-send.
749 ExprResult msg;
750 if (Setter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000751 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
752 GenericLoc, SetterSelector, Setter,
753 MultiExprArg(args, 1));
John McCall4b9c2d22011-11-06 09:01:30 +0000754 } else {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000755 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
756 GenericLoc,
757 SetterSelector, Setter,
758 MultiExprArg(args, 1));
John McCall4b9c2d22011-11-06 09:01:30 +0000759 }
760
761 if (!msg.isInvalid() && captureSetValueAsResult) {
762 ObjCMessageExpr *msgExpr =
763 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
764 Expr *arg = msgExpr->getArg(0);
Eli Friedman25f071e2012-11-13 23:16:33 +0000765 if (CanCaptureValueOfType(arg->getType()))
766 msgExpr->setArg(0, captureValueAsResult(arg));
John McCall4b9c2d22011-11-06 09:01:30 +0000767 }
768
769 return msg;
John McCall3c3b7f92011-10-25 17:37:35 +0000770}
771
John McCall4b9c2d22011-11-06 09:01:30 +0000772/// @property-specific behavior for doing lvalue-to-rvalue conversion.
773ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
774 // Explicit properties always have getters, but implicit ones don't.
775 // Check that before proceeding.
Eli Friedmana70779f2012-11-29 03:13:49 +0000776 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000777 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
Eli Friedmana70779f2012-11-29 03:13:49 +0000778 << RefExpr->getSourceRange();
John McCall3c3b7f92011-10-25 17:37:35 +0000779 return ExprError();
780 }
781
John McCall4b9c2d22011-11-06 09:01:30 +0000782 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall3c3b7f92011-10-25 17:37:35 +0000783 if (result.isInvalid()) return ExprError();
784
John McCall4b9c2d22011-11-06 09:01:30 +0000785 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
786 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
787 Getter, RefExpr->getLocation());
788
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);
798 }
799 }
800
John McCall3c3b7f92011-10-25 17:37:35 +0000801 return result;
802}
803
John McCall4b9c2d22011-11-06 09:01:30 +0000804/// Try to build this as a call to a getter that returns a reference.
805///
806/// \return true if it was possible, whether or not it actually
807/// succeeded
808bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
809 ExprResult &result) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000810 if (!S.getLangOpts().CPlusPlus) return false;
John McCall4b9c2d22011-11-06 09:01:30 +0000811
812 findGetter();
813 assert(Getter && "property has no setter and no getter!");
814
815 // Only do this if the getter returns an l-value reference type.
816 QualType resultType = Getter->getResultType();
817 if (!resultType->isLValueReferenceType()) return false;
818
819 result = buildRValueOperation(op);
820 return true;
821}
822
823/// @property-specific behavior for doing assignments.
824ExprResult
825ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
826 SourceLocation opcLoc,
827 BinaryOperatorKind opcode,
828 Expr *LHS, Expr *RHS) {
John McCall3c3b7f92011-10-25 17:37:35 +0000829 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall3c3b7f92011-10-25 17:37:35 +0000830
831 // If there's no setter, we have no choice but to try to assign to
832 // the result of the getter.
John McCall4b9c2d22011-11-06 09:01:30 +0000833 if (!findSetter()) {
834 ExprResult result;
835 if (tryBuildGetOfReference(LHS, result)) {
836 if (result.isInvalid()) return ExprError();
837 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
John McCall3c3b7f92011-10-25 17:37:35 +0000838 }
839
840 // Otherwise, it's an error.
John McCall4b9c2d22011-11-06 09:01:30 +0000841 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
842 << unsigned(RefExpr->isImplicitProperty())
843 << SetterSelector
John McCall3c3b7f92011-10-25 17:37:35 +0000844 << LHS->getSourceRange() << RHS->getSourceRange();
845 return ExprError();
846 }
847
848 // If there is a setter, we definitely want to use it.
849
John McCall4b9c2d22011-11-06 09:01:30 +0000850 // Verify that we can do a compound assignment.
851 if (opcode != BO_Assign && !findGetter()) {
852 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall3c3b7f92011-10-25 17:37:35 +0000853 << LHS->getSourceRange() << RHS->getSourceRange();
854 return ExprError();
855 }
856
John McCall4b9c2d22011-11-06 09:01:30 +0000857 ExprResult result =
858 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall3c3b7f92011-10-25 17:37:35 +0000859 if (result.isInvalid()) return ExprError();
860
John McCall4b9c2d22011-11-06 09:01:30 +0000861 // Various warnings about property assignments in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +0000862 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCall4b9c2d22011-11-06 09:01:30 +0000863 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
864 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
865 }
866
John McCall3c3b7f92011-10-25 17:37:35 +0000867 return result;
868}
John McCall4b9c2d22011-11-06 09:01:30 +0000869
870/// @property-specific behavior for doing increments and decrements.
871ExprResult
872ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
873 UnaryOperatorKind opcode,
874 Expr *op) {
875 // If there's no setter, we have no choice but to try to assign to
876 // the result of the getter.
877 if (!findSetter()) {
878 ExprResult result;
879 if (tryBuildGetOfReference(op, result)) {
880 if (result.isInvalid()) return ExprError();
881 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
882 }
883
884 // Otherwise, it's an error.
885 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
886 << unsigned(RefExpr->isImplicitProperty())
887 << unsigned(UnaryOperator::isDecrementOp(opcode))
888 << SetterSelector
889 << op->getSourceRange();
890 return ExprError();
891 }
892
893 // If there is a setter, we definitely want to use it.
894
895 // We also need a getter.
896 if (!findGetter()) {
897 assert(RefExpr->isImplicitProperty());
898 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
899 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000900 << GetterSelector
John McCall4b9c2d22011-11-06 09:01:30 +0000901 << op->getSourceRange();
902 return ExprError();
903 }
904
905 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
906}
907
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000908ExprResult 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)
Fariborz Jahanian569b4ad2013-05-21 21:20:26 +0000914 S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
915 SyntacticRefExpr->isMessagingGetter());
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000916 }
917
918 return PseudoOpBuilder::complete(SyntacticForm);
919}
920
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000921// ObjCSubscript build stuff.
922//
923
924/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
925/// conversion.
926/// FIXME. Remove this routine if it is proven that no additional
927/// specifity is needed.
928ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
929 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
930 if (result.isInvalid()) return ExprError();
931 return result;
932}
933
934/// objective-c subscripting-specific behavior for doing assignments.
935ExprResult
936ObjCSubscriptOpBuilder::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())
943 return ExprError();
944
945 // Verify that we can do a compound assignment.
946 if (opcode != BO_Assign && !findAtIndexGetter())
947 return ExprError();
948
949 ExprResult result =
950 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
951 if (result.isInvalid()) return ExprError();
952
953 // Various warnings about objc Index'ed assignments in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +0000954 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000955 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
956 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
957 }
958
959 return result;
960}
961
962/// Capture the base object of an Objective-C Index'ed expression.
963Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
964 assert(InstanceBase == 0);
965
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());
970
971 syntacticBase =
972 ObjCSubscriptRefRebuilder(S, InstanceBase,
973 InstanceKey).rebuild(syntacticBase);
974
975 return syntacticBase;
976}
977
978/// CheckSubscriptingKind - This routine decide what type
979/// of indexing represented by "FromE" is being done.
980Sema::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())
985 return OS_Array;
986
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>();
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000990 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000991 // All other scalar cases are assumed to be dictionary indexing which
992 // caller handles, with diagnostics if needed.
993 return OS_Dictionary;
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000994 if (!getLangOpts().CPlusPlus ||
995 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000996 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000997 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(), "@");
1001 else
1002 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1003 << T;
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001004 return OS_Error;
1005 }
1006
1007 // We must have a complete class type.
1008 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregord10099e2012-05-04 16:32:21 +00001009 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001010 return OS_Error;
1011
1012 // Look for a conversion to an integral, enumeration type, or
1013 // objective-C pointer type.
1014 UnresolvedSet<4> ViableConversions;
1015 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00001016 std::pair<CXXRecordDecl::conversion_iterator,
1017 CXXRecordDecl::conversion_iterator> Conversions
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001018 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
1019
1020 int NoIntegrals=0, NoObjCIdPointers=0;
1021 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1022
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00001023 for (CXXRecordDecl::conversion_iterator
1024 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001025 if (CXXConversionDecl *Conversion
1026 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
1027 QualType CT = Conversion->getConversionType().getNonReferenceType();
1028 if (CT->isIntegralOrEnumerationType()) {
1029 ++NoIntegrals;
1030 ConversionDecls.push_back(Conversion);
1031 }
1032 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1033 ++NoObjCIdPointers;
1034 ConversionDecls.push_back(Conversion);
1035 }
1036 }
1037 }
1038 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1039 return OS_Array;
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();
1046 return OS_Error;
1047 }
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);
1052
1053 return OS_Error;
1054}
1055
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001056/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1057/// objects used as dictionary subscript key objects.
1058static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1059 Expr *Key) {
1060 if (ContainerT.isNull())
1061 return;
1062 // dictionary subscripting.
1063 // - (id)objectForKeyedSubscript:(id)key;
1064 IdentifierInfo *KeyIdents[] = {
1065 &S.Context.Idents.get("objectForKeyedSubscript")
1066 };
1067 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1068 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1069 true /*instance*/);
1070 if (!Getter)
1071 return;
1072 QualType T = Getter->param_begin()[0]->getType();
1073 S.CheckObjCARCConversion(Key->getSourceRange(),
1074 T, Key, Sema::CCK_ImplicitConversion);
1075}
1076
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001077bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1078 if (AtIndexGetter)
1079 return true;
1080
1081 Expr *BaseExpr = RefExpr->getBaseExpr();
1082 QualType BaseT = BaseExpr->getType();
1083
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();
1091 }
1092 Sema::ObjCSubscriptKind Res =
1093 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001094 if (Res == Sema::OS_Error) {
1095 if (S.getLangOpts().ObjCAutoRefCount)
1096 CheckKeyForObjCARCConversion(S, ResultType,
1097 RefExpr->getKeyExpr());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001098 return false;
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001099 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001100 bool arrayRef = (Res == Sema::OS_Array);
1101
1102 if (ResultType.isNull()) {
1103 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1104 << BaseExpr->getType() << arrayRef;
1105 return false;
1106 }
1107 if (!arrayRef) {
1108 // dictionary subscripting.
1109 // - (id)objectForKeyedSubscript:(id)key;
1110 IdentifierInfo *KeyIdents[] = {
1111 &S.Context.Idents.get("objectForKeyedSubscript")
1112 };
1113 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1114 }
1115 else {
1116 // - (id)objectAtIndexedSubscript:(size_t)index;
1117 IdentifierInfo *KeyIdents[] = {
1118 &S.Context.Idents.get("objectAtIndexedSubscript")
1119 };
1120
1121 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1122 }
1123
1124 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1125 true /*instance*/);
1126 bool receiverIdType = (BaseT->isObjCIdType() ||
1127 BaseT->isObjCQualifiedIdType());
1128
David Blaikie4e4d0842012-03-11 07:00:24 +00001129 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001130 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*/,
Jordan Rose1e4691b2012-10-10 16:42:25 +00001136 /*isPropertyAccessor=*/false,
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001137 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1138 ObjCMethodDecl::Required,
1139 false);
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(),
1146 /*TInfo=*/0,
1147 SC_None,
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001148 0);
Dmitri Gribenko55431692013-05-05 00:41:58 +00001149 AtIndexGetter->setMethodParams(S.Context, Argument, None);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001150 }
1151
1152 if (!AtIndexGetter) {
1153 if (!receiverIdType) {
1154 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1155 << BaseExpr->getType() << 0 << arrayRef;
1156 return false;
1157 }
1158 AtIndexGetter =
1159 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1160 RefExpr->getSourceRange(),
1161 true, false);
1162 }
1163
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;
1173 return false;
1174 }
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();
1181 }
1182 }
1183 return true;
1184}
1185
1186bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1187 if (AtIndexSetter)
1188 return true;
1189
1190 Expr *BaseExpr = RefExpr->getBaseExpr();
1191 QualType BaseT = BaseExpr->getType();
1192
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();
1200 }
1201
1202 Sema::ObjCSubscriptKind Res =
1203 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001204 if (Res == Sema::OS_Error) {
1205 if (S.getLangOpts().ObjCAutoRefCount)
1206 CheckKeyForObjCARCConversion(S, ResultType,
1207 RefExpr->getKeyExpr());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001208 return false;
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001209 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001210 bool arrayRef = (Res == Sema::OS_Array);
1211
1212 if (ResultType.isNull()) {
1213 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1214 << BaseExpr->getType() << arrayRef;
1215 return false;
1216 }
1217
1218 if (!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")
1224 };
1225 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1226 }
1227 else {
1228 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1229 IdentifierInfo *KeyIdents[] = {
1230 &S.Context.Idents.get("setObject"),
1231 &S.Context.Idents.get("atIndexedSubscript")
1232 };
1233 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1234 }
1235 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1236 true /*instance*/);
1237
1238 bool receiverIdType = (BaseT->isObjCIdType() ||
1239 BaseT->isObjCQualifiedIdType());
1240
David Blaikie4e4d0842012-03-11 07:00:24 +00001241 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001242 TypeSourceInfo *ResultTInfo = 0;
1243 QualType ReturnType = S.Context.VoidTy;
1244 AtIndexSetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1245 SourceLocation(), AtIndexSetterSelector,
1246 ReturnType,
1247 ResultTInfo,
1248 S.Context.getTranslationUnitDecl(),
1249 true /*Instance*/, false/*isVariadic*/,
Jordan Rose1e4691b2012-10-10 16:42:25 +00001250 /*isPropertyAccessor=*/false,
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001251 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1252 ObjCMethodDecl::Required,
1253 false);
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(),
1259 /*TInfo=*/0,
1260 SC_None,
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001261 0);
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(),
1269 /*TInfo=*/0,
1270 SC_None,
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001271 0);
1272 Params.push_back(key);
Dmitri Gribenko55431692013-05-05 00:41:58 +00001273 AtIndexSetter->setMethodParams(S.Context, Params, None);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001274 }
1275
1276 if (!AtIndexSetter) {
1277 if (!receiverIdType) {
1278 S.Diag(BaseExpr->getExprLoc(),
1279 diag::err_objc_subscript_method_not_found)
1280 << BaseExpr->getType() << 1 << arrayRef;
1281 return false;
1282 }
1283 AtIndexSetter =
1284 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1285 RefExpr->getSourceRange(),
1286 true, false);
1287 }
1288
1289 bool err = false;
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;
1297 err = true;
1298 }
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;
1305 err = true;
1306 }
1307 }
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()) {
1312 if (i == 1)
1313 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1314 diag::err_objc_subscript_key_type) << T;
1315 else
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;
1320 err = true;
1321 }
1322 }
1323
1324 return !err;
1325}
1326
1327// Get the object at "Index" position in the container.
1328// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1329ExprResult ObjCSubscriptOpBuilder::buildGet() {
1330 if (!findAtIndexGetter())
1331 return ExprError();
1332
1333 QualType receiverType = InstanceBase->getType();
1334
1335 // Build a message-send.
1336 ExprResult msg;
1337 Expr *Index = InstanceKey;
1338
1339 // Arguments.
1340 Expr *args[] = { Index };
1341 assert(InstanceBase);
1342 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1343 GenericLoc,
1344 AtIndexGetterSelector, AtIndexGetter,
1345 MultiExprArg(args, 1));
1346 return msg;
1347}
1348
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;
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001352/// \param captureSetValueAsResult If true, capture the actual
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001353/// value being set as the value of the property operation.
1354ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1355 bool captureSetValueAsResult) {
1356 if (!findAtIndexSetter())
1357 return ExprError();
1358
1359 QualType receiverType = InstanceBase->getType();
1360 Expr *Index = InstanceKey;
1361
1362 // Arguments.
1363 Expr *args[] = { op, Index };
1364
1365 // Build a message-send.
1366 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1367 GenericLoc,
1368 AtIndexSetterSelector,
1369 AtIndexSetter,
1370 MultiExprArg(args, 2));
1371
1372 if (!msg.isInvalid() && captureSetValueAsResult) {
1373 ObjCMessageExpr *msgExpr =
1374 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1375 Expr *arg = msgExpr->getArg(0);
Eli Friedman25f071e2012-11-13 23:16:33 +00001376 if (CanCaptureValueOfType(arg->getType()))
1377 msgExpr->setArg(0, captureValueAsResult(arg));
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001378 }
1379
1380 return msg;
1381}
1382
John McCall4b9c2d22011-11-06 09:01:30 +00001383//===----------------------------------------------------------------------===//
John McCall76da55d2013-04-16 07:28:30 +00001384// MSVC __declspec(property) references
1385//===----------------------------------------------------------------------===//
1386
1387Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1388 Expr *NewBase = capture(RefExpr->getBaseExpr());
1389
1390 syntacticBase =
1391 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase);
1392
1393 return syntacticBase;
1394}
1395
1396ExprResult MSPropertyOpBuilder::buildGet() {
1397 if (!RefExpr->getPropertyDecl()->hasGetter()) {
1398 S.Diag(RefExpr->getMemberLoc(), diag::err_no_getter_for_property)
1399 << RefExpr->getPropertyDecl()->getName();
1400 return ExprError();
1401 }
1402
1403 UnqualifiedId GetterName;
1404 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1405 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1406 CXXScopeSpec SS;
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();
1415 return ExprError();
1416 }
1417
1418 MultiExprArg ArgExprs;
1419 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.take(),
1420 RefExpr->getSourceRange().getBegin(), ArgExprs,
1421 RefExpr->getSourceRange().getEnd());
1422}
1423
1424ExprResult 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();
1429 return ExprError();
1430 }
1431
1432 UnqualifiedId SetterName;
1433 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1434 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1435 CXXScopeSpec SS;
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();
1444 return ExprError();
1445 }
1446
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());
1452}
1453
1454//===----------------------------------------------------------------------===//
John McCall4b9c2d22011-11-06 09:01:30 +00001455// General Sema routines.
1456//===----------------------------------------------------------------------===//
1457
1458ExprResult 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);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001464 }
1465 else if (ObjCSubscriptRefExpr *refExpr
1466 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1467 ObjCSubscriptOpBuilder builder(*this, refExpr);
1468 return builder.buildRValueOperation(E);
John McCall76da55d2013-04-16 07:28:30 +00001469 } else if (MSPropertyRefExpr *refExpr
1470 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1471 MSPropertyOpBuilder builder(*this, refExpr);
1472 return builder.buildRValueOperation(E);
John McCall4b9c2d22011-11-06 09:01:30 +00001473 } else {
1474 llvm_unreachable("unknown pseudo-object kind!");
1475 }
1476}
1477
1478/// Check an increment or decrement of a pseudo-object expression.
1479ExprResult 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);
1485
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);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001492 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1493 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1494 return ExprError();
John McCall76da55d2013-04-16 07:28:30 +00001495 } else if (MSPropertyRefExpr *refExpr
1496 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1497 MSPropertyOpBuilder builder(*this, refExpr);
1498 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
John McCall4b9c2d22011-11-06 09:01:30 +00001499 } else {
1500 llvm_unreachable("unknown pseudo-object kind!");
1501 }
1502}
1503
1504ExprResult 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,
Lang Hamesbe9af122012-10-02 04:45:10 +00001510 VK_RValue, OK_Ordinary, opcLoc, false);
John McCall4b9c2d22011-11-06 09:01:30 +00001511
1512 // Filter out non-overload placeholder types in the RHS.
John McCall32509f12011-11-15 01:35:18 +00001513 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1514 ExprResult result = CheckPlaceholderExpr(RHS);
1515 if (result.isInvalid()) return ExprError();
1516 RHS = result.take();
John McCall4b9c2d22011-11-06 09:01:30 +00001517 }
1518
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);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001524 } else if (ObjCSubscriptRefExpr *refExpr
1525 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1526 ObjCSubscriptOpBuilder builder(*this, refExpr);
1527 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall76da55d2013-04-16 07:28:30 +00001528 } else if (MSPropertyRefExpr *refExpr
1529 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1530 MSPropertyOpBuilder builder(*this, refExpr);
1531 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall4b9c2d22011-11-06 09:01:30 +00001532 } else {
1533 llvm_unreachable("unknown pseudo-object kind!");
1534 }
1535}
John McCall01e19be2011-11-30 04:42:31 +00001536
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.
1540static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1541 Expr *opaqueRef = E->IgnoreParens();
1542 if (ObjCPropertyRefExpr *refExpr
1543 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregor88507dd2012-04-13 16:05:42 +00001544 // Class and super property references don't have opaque values in them.
1545 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1546 return E;
1547
1548 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1549 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1550 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001551 } 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);
John McCall76da55d2013-04-16 07:28:30 +00001557 } else if (MSPropertyRefExpr *refExpr
1558 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1559 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1560 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
John McCall01e19be2011-11-30 04:42:31 +00001561 } else {
1562 llvm_unreachable("unknown pseudo-object kind!");
1563 }
1564}
1565
1566/// Given a pseudo-object expression, recreate what it looks like
1567/// syntactically without the attendant OpaqueValueExprs.
1568///
1569/// This is a hack which should be removed when TreeTransform is
1570/// capable of rebuilding a tree without stripping implicit
1571/// operations.
1572Expr *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(),
1584 cop->getType(),
1585 cop->getValueKind(),
1586 cop->getObjectKind(),
1587 cop->getComputationLHSType(),
1588 cop->getComputationResultType(),
Lang Hamesbe9af122012-10-02 04:45:10 +00001589 cop->getOperatorLoc(), false);
John McCall01e19be2011-11-30 04:42:31 +00001590 } 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(),
Lang Hamesbe9af122012-10-02 04:45:10 +00001596 bop->getOperatorLoc(), false);
John McCall01e19be2011-11-30 04:42:31 +00001597 } else {
1598 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1599 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1600 }
1601}