blob: 94b19431a3efebdd87fc29f6c96f641f1bc19f77 [file] [log] [blame]
John McCall526ab472011-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"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/AST/ExprCXX.h"
John McCall526ab472011-10-25 17:37:35 +000035#include "clang/AST/ExprObjC.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000036#include "clang/Basic/CharInfo.h"
John McCall526ab472011-10-25 17:37:35 +000037#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/Initialization.h"
39#include "clang/Sema/ScopeInfo.h"
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +000040#include "llvm/ADT/SmallString.h"
John McCall526ab472011-10-25 17:37:35 +000041
42using namespace clang;
43using namespace sema;
44
John McCallfe96e0b2011-11-06 09:01:30 +000045namespace {
46 // Basically just a very focused copy of TreeTransform.
47 template <class T> struct Rebuilder {
48 Sema &S;
49 Rebuilder(Sema &S) : S(S) {}
50
51 T &getDerived() { return static_cast<T&>(*this); }
52
53 Expr *rebuild(Expr *e) {
54 // Fast path: nothing to look through.
55 if (typename T::specific_type *specific
56 = dyn_cast<typename T::specific_type>(e))
57 return getDerived().rebuildSpecific(specific);
58
59 // Otherwise, we should look through and rebuild anything that
60 // IgnoreParens would.
61
62 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
63 e = rebuild(parens->getSubExpr());
64 return new (S.Context) ParenExpr(parens->getLParen(),
65 parens->getRParen(),
66 e);
67 }
68
69 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
70 assert(uop->getOpcode() == UO_Extension);
71 e = rebuild(uop->getSubExpr());
72 return new (S.Context) UnaryOperator(e, uop->getOpcode(),
73 uop->getType(),
74 uop->getValueKind(),
75 uop->getObjectKind(),
76 uop->getOperatorLoc());
77 }
78
79 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
80 assert(!gse->isResultDependent());
81 unsigned resultIndex = gse->getResultIndex();
82 unsigned numAssocs = gse->getNumAssocs();
83
84 SmallVector<Expr*, 8> assocs(numAssocs);
85 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
86
87 for (unsigned i = 0; i != numAssocs; ++i) {
88 Expr *assoc = gse->getAssocExpr(i);
89 if (i == resultIndex) assoc = rebuild(assoc);
90 assocs[i] = assoc;
91 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
92 }
93
94 return new (S.Context) GenericSelectionExpr(S.Context,
95 gse->getGenericLoc(),
96 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000097 assocTypes,
98 assocs,
John McCallfe96e0b2011-11-06 09:01:30 +000099 gse->getDefaultLoc(),
100 gse->getRParenLoc(),
101 gse->containsUnexpandedParameterPack(),
102 resultIndex);
103 }
104
Eli Friedman75807f22013-07-20 00:40:58 +0000105 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
106 assert(!ce->isConditionDependent());
107
108 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
109 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
110 rebuiltExpr = rebuild(rebuiltExpr);
111
112 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(),
113 ce->getCond(),
114 LHS, RHS,
115 rebuiltExpr->getType(),
116 rebuiltExpr->getValueKind(),
117 rebuiltExpr->getObjectKind(),
118 ce->getRParenLoc(),
119 ce->isConditionTrue(),
120 rebuiltExpr->isTypeDependent(),
121 rebuiltExpr->isValueDependent());
122 }
123
John McCallfe96e0b2011-11-06 09:01:30 +0000124 llvm_unreachable("bad expression to rebuild!");
125 }
126 };
127
128 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> {
129 Expr *NewBase;
130 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase)
Benjamin Kramer5c29d692011-11-06 09:50:13 +0000131 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {}
John McCallfe96e0b2011-11-06 09:01:30 +0000132
133 typedef ObjCPropertyRefExpr specific_type;
134 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) {
135 // Fortunately, the constraint that we're rebuilding something
136 // with a base limits the number of cases here.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000137 assert(refExpr->isObjectReceiver());
John McCallfe96e0b2011-11-06 09:01:30 +0000138
139 if (refExpr->isExplicitProperty()) {
140 return new (S.Context)
141 ObjCPropertyRefExpr(refExpr->getExplicitProperty(),
142 refExpr->getType(), refExpr->getValueKind(),
143 refExpr->getObjectKind(), refExpr->getLocation(),
144 NewBase);
145 }
146 return new (S.Context)
147 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(),
148 refExpr->getImplicitPropertySetter(),
149 refExpr->getType(), refExpr->getValueKind(),
150 refExpr->getObjectKind(),refExpr->getLocation(),
151 NewBase);
152 }
153 };
154
Ted Kremeneke65b0862012-03-06 20:05:56 +0000155 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> {
156 Expr *NewBase;
157 Expr *NewKeyExpr;
158 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr)
159 : Rebuilder<ObjCSubscriptRefRebuilder>(S),
160 NewBase(newBase), NewKeyExpr(newKeyExpr) {}
161
162 typedef ObjCSubscriptRefExpr specific_type;
163 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) {
164 assert(refExpr->getBaseExpr());
165 assert(refExpr->getKeyExpr());
166
167 return new (S.Context)
168 ObjCSubscriptRefExpr(NewBase,
169 NewKeyExpr,
170 refExpr->getType(), refExpr->getValueKind(),
171 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(),
172 refExpr->setAtIndexMethodDecl(),
173 refExpr->getRBracket());
174 }
175 };
John McCall5e77d762013-04-16 07:28:30 +0000176
177 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> {
178 Expr *NewBase;
179 MSPropertyRefRebuilder(Sema &S, Expr *newBase)
180 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {}
181
182 typedef MSPropertyRefExpr specific_type;
183 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) {
184 assert(refExpr->getBaseExpr());
185
186 return new (S.Context)
187 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(),
188 refExpr->isArrow(), refExpr->getType(),
189 refExpr->getValueKind(), refExpr->getQualifierLoc(),
190 refExpr->getMemberLoc());
191 }
192 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000193
John McCallfe96e0b2011-11-06 09:01:30 +0000194 class PseudoOpBuilder {
195 public:
196 Sema &S;
197 unsigned ResultIndex;
198 SourceLocation GenericLoc;
199 SmallVector<Expr *, 4> Semantics;
200
201 PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
202 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
203 GenericLoc(genericLoc) {}
204
Matt Beaumont-Gayfb3cb9a2011-11-08 01:53:17 +0000205 virtual ~PseudoOpBuilder() {}
206
John McCallfe96e0b2011-11-06 09:01:30 +0000207 /// Add a normal semantic expression.
208 void addSemanticExpr(Expr *semantic) {
209 Semantics.push_back(semantic);
210 }
211
212 /// Add the 'result' semantic expression.
213 void addResultSemanticExpr(Expr *resultExpr) {
214 assert(ResultIndex == PseudoObjectExpr::NoResult);
215 ResultIndex = Semantics.size();
216 Semantics.push_back(resultExpr);
217 }
218
219 ExprResult buildRValueOperation(Expr *op);
220 ExprResult buildAssignmentOperation(Scope *Sc,
221 SourceLocation opLoc,
222 BinaryOperatorKind opcode,
223 Expr *LHS, Expr *RHS);
224 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
225 UnaryOperatorKind opcode,
226 Expr *op);
227
Jordan Rosed3934582012-09-28 22:21:30 +0000228 virtual ExprResult complete(Expr *syntacticForm);
John McCallfe96e0b2011-11-06 09:01:30 +0000229
230 OpaqueValueExpr *capture(Expr *op);
231 OpaqueValueExpr *captureValueAsResult(Expr *op);
232
233 void setResultToLastSemantic() {
234 assert(ResultIndex == PseudoObjectExpr::NoResult);
235 ResultIndex = Semantics.size() - 1;
236 }
237
238 /// Return true if assignments have a non-void result.
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000239 bool CanCaptureValue(Expr *exp) {
240 if (exp->isGLValue())
241 return true;
242 QualType ty = exp->getType();
Eli Friedman00fa4292012-11-13 23:16:33 +0000243 assert(!ty->isIncompleteType());
244 assert(!ty->isDependentType());
245
246 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
247 return ClassDecl->isTriviallyCopyable();
248 return true;
249 }
John McCallfe96e0b2011-11-06 09:01:30 +0000250
251 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
252 virtual ExprResult buildGet() = 0;
253 virtual ExprResult buildSet(Expr *, SourceLocation,
254 bool captureSetValueAsResult) = 0;
255 };
256
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000257 /// A PseudoOpBuilder for Objective-C \@properties.
John McCallfe96e0b2011-11-06 09:01:30 +0000258 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
259 ObjCPropertyRefExpr *RefExpr;
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000260 ObjCPropertyRefExpr *SyntacticRefExpr;
John McCallfe96e0b2011-11-06 09:01:30 +0000261 OpaqueValueExpr *InstanceReceiver;
262 ObjCMethodDecl *Getter;
263
264 ObjCMethodDecl *Setter;
265 Selector SetterSelector;
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000266 Selector GetterSelector;
John McCallfe96e0b2011-11-06 09:01:30 +0000267
268 public:
269 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
270 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
Craig Topperc3ec1492014-05-26 06:22:03 +0000271 SyntacticRefExpr(nullptr), InstanceReceiver(nullptr), Getter(nullptr),
272 Setter(nullptr) {
John McCallfe96e0b2011-11-06 09:01:30 +0000273 }
274
275 ExprResult buildRValueOperation(Expr *op);
276 ExprResult buildAssignmentOperation(Scope *Sc,
277 SourceLocation opLoc,
278 BinaryOperatorKind opcode,
279 Expr *LHS, Expr *RHS);
280 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
281 UnaryOperatorKind opcode,
282 Expr *op);
283
284 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000285 bool findSetter(bool warn=true);
John McCallfe96e0b2011-11-06 09:01:30 +0000286 bool findGetter();
287
Craig Toppere14c0f82014-03-12 04:55:44 +0000288 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
289 ExprResult buildGet() override;
290 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
291 ExprResult complete(Expr *SyntacticForm) override;
Jordan Rosed3934582012-09-28 22:21:30 +0000292
293 bool isWeakProperty() const;
John McCallfe96e0b2011-11-06 09:01:30 +0000294 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000295
296 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
297 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
298 ObjCSubscriptRefExpr *RefExpr;
299 OpaqueValueExpr *InstanceBase;
300 OpaqueValueExpr *InstanceKey;
301 ObjCMethodDecl *AtIndexGetter;
302 Selector AtIndexGetterSelector;
303
304 ObjCMethodDecl *AtIndexSetter;
305 Selector AtIndexSetterSelector;
306
307 public:
308 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
309 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
310 RefExpr(refExpr),
Craig Topperc3ec1492014-05-26 06:22:03 +0000311 InstanceBase(nullptr), InstanceKey(nullptr),
312 AtIndexGetter(nullptr), AtIndexSetter(nullptr) {}
313
Ted Kremeneke65b0862012-03-06 20:05:56 +0000314 ExprResult buildRValueOperation(Expr *op);
315 ExprResult buildAssignmentOperation(Scope *Sc,
316 SourceLocation opLoc,
317 BinaryOperatorKind opcode,
318 Expr *LHS, Expr *RHS);
Craig Toppere14c0f82014-03-12 04:55:44 +0000319 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
320
Ted Kremeneke65b0862012-03-06 20:05:56 +0000321 bool findAtIndexGetter();
322 bool findAtIndexSetter();
Craig Toppere14c0f82014-03-12 04:55:44 +0000323
324 ExprResult buildGet() override;
325 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000326 };
327
John McCall5e77d762013-04-16 07:28:30 +0000328 class MSPropertyOpBuilder : public PseudoOpBuilder {
329 MSPropertyRefExpr *RefExpr;
330
331 public:
332 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) :
333 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
334 RefExpr(refExpr) {}
335
Craig Toppere14c0f82014-03-12 04:55:44 +0000336 Expr *rebuildAndCaptureObject(Expr *) override;
337 ExprResult buildGet() override;
338 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
John McCall5e77d762013-04-16 07:28:30 +0000339 };
John McCallfe96e0b2011-11-06 09:01:30 +0000340}
341
342/// Capture the given expression in an OpaqueValueExpr.
343OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
344 // Make a new OVE whose source is the given expression.
345 OpaqueValueExpr *captured =
346 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +0000347 e->getValueKind(), e->getObjectKind(),
348 e);
John McCallfe96e0b2011-11-06 09:01:30 +0000349
350 // Make sure we bind that in the semantics.
351 addSemanticExpr(captured);
352 return captured;
353}
354
355/// Capture the given expression as the result of this pseudo-object
356/// operation. This routine is safe against expressions which may
357/// already be captured.
358///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000359/// \returns the captured expression, which will be the
John McCallfe96e0b2011-11-06 09:01:30 +0000360/// same as the input if the input was already captured
361OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
362 assert(ResultIndex == PseudoObjectExpr::NoResult);
363
364 // If the expression hasn't already been captured, just capture it
365 // and set the new semantic
366 if (!isa<OpaqueValueExpr>(e)) {
367 OpaqueValueExpr *cap = capture(e);
368 setResultToLastSemantic();
369 return cap;
370 }
371
372 // Otherwise, it must already be one of our semantic expressions;
373 // set ResultIndex to its index.
374 unsigned index = 0;
375 for (;; ++index) {
376 assert(index < Semantics.size() &&
377 "captured expression not found in semantics!");
378 if (e == Semantics[index]) break;
379 }
380 ResultIndex = index;
381 return cast<OpaqueValueExpr>(e);
382}
383
384/// The routine which creates the final PseudoObjectExpr.
385ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
386 return PseudoObjectExpr::Create(S.Context, syntactic,
387 Semantics, ResultIndex);
388}
389
390/// The main skeleton for building an r-value operation.
391ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
392 Expr *syntacticBase = rebuildAndCaptureObject(op);
393
394 ExprResult getExpr = buildGet();
395 if (getExpr.isInvalid()) return ExprError();
396 addResultSemanticExpr(getExpr.take());
397
398 return complete(syntacticBase);
399}
400
401/// The basic skeleton for building a simple or compound
402/// assignment operation.
403ExprResult
404PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
405 BinaryOperatorKind opcode,
406 Expr *LHS, Expr *RHS) {
407 assert(BinaryOperator::isAssignmentOp(opcode));
408
409 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
410 OpaqueValueExpr *capturedRHS = capture(RHS);
411
412 Expr *syntactic;
413
414 ExprResult result;
415 if (opcode == BO_Assign) {
416 result = capturedRHS;
417 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
418 opcode, capturedRHS->getType(),
419 capturedRHS->getValueKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000420 OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000421 } else {
422 ExprResult opLHS = buildGet();
423 if (opLHS.isInvalid()) return ExprError();
424
425 // Build an ordinary, non-compound operation.
426 BinaryOperatorKind nonCompound =
427 BinaryOperator::getOpForCompoundAssignment(opcode);
428 result = S.BuildBinOp(Sc, opcLoc, nonCompound,
429 opLHS.take(), capturedRHS);
430 if (result.isInvalid()) return ExprError();
431
432 syntactic =
433 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
434 result.get()->getType(),
435 result.get()->getValueKind(),
436 OK_Ordinary,
437 opLHS.get()->getType(),
438 result.get()->getType(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000439 opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000440 }
441
442 // The result of the assignment, if not void, is the value set into
443 // the l-value.
Eli Friedman00fa4292012-11-13 23:16:33 +0000444 result = buildSet(result.take(), opcLoc, /*captureSetValueAsResult*/ true);
John McCallfe96e0b2011-11-06 09:01:30 +0000445 if (result.isInvalid()) return ExprError();
446 addSemanticExpr(result.take());
447
448 return complete(syntactic);
449}
450
451/// The basic skeleton for building an increment or decrement
452/// operation.
453ExprResult
454PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
455 UnaryOperatorKind opcode,
456 Expr *op) {
457 assert(UnaryOperator::isIncrementDecrementOp(opcode));
458
459 Expr *syntacticOp = rebuildAndCaptureObject(op);
460
461 // Load the value.
462 ExprResult result = buildGet();
463 if (result.isInvalid()) return ExprError();
464
465 QualType resultType = result.get()->getType();
466
467 // That's the postfix result.
John McCall0d9dd732013-04-16 22:32:04 +0000468 if (UnaryOperator::isPostfix(opcode) &&
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000469 (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
John McCallfe96e0b2011-11-06 09:01:30 +0000470 result = capture(result.take());
471 setResultToLastSemantic();
472 }
473
474 // Add or subtract a literal 1.
475 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
476 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
477 GenericLoc);
478
479 if (UnaryOperator::isIncrementOp(opcode)) {
480 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one);
481 } else {
482 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one);
483 }
484 if (result.isInvalid()) return ExprError();
485
486 // Store that back into the result. The value stored is the result
487 // of a prefix operation.
Eli Friedman00fa4292012-11-13 23:16:33 +0000488 result = buildSet(result.take(), opcLoc, UnaryOperator::isPrefix(opcode));
John McCallfe96e0b2011-11-06 09:01:30 +0000489 if (result.isInvalid()) return ExprError();
490 addSemanticExpr(result.take());
491
492 UnaryOperator *syntactic =
493 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
494 VK_LValue, OK_Ordinary, opcLoc);
495 return complete(syntactic);
496}
497
498
499//===----------------------------------------------------------------------===//
500// Objective-C @property and implicit property references
501//===----------------------------------------------------------------------===//
502
503/// Look up a method in the receiver type of an Objective-C property
504/// reference.
John McCall526ab472011-10-25 17:37:35 +0000505static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
506 const ObjCPropertyRefExpr *PRE) {
John McCall526ab472011-10-25 17:37:35 +0000507 if (PRE->isObjectReceiver()) {
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000508 const ObjCObjectPointerType *PT =
509 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +0000510
511 // Special case for 'self' in class method implementations.
512 if (PT->isObjCClassType() &&
513 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
514 // This cast is safe because isSelfExpr is only true within
515 // methods.
516 ObjCMethodDecl *method =
517 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
518 return S.LookupMethodInObjectType(sel,
519 S.Context.getObjCInterfaceType(method->getClassInterface()),
520 /*instance*/ false);
521 }
522
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000523 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
John McCall526ab472011-10-25 17:37:35 +0000524 }
525
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000526 if (PRE->isSuperReceiver()) {
527 if (const ObjCObjectPointerType *PT =
528 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
529 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
530
531 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
532 }
533
534 assert(PRE->isClassReceiver() && "Invalid expression");
535 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
536 return S.LookupMethodInObjectType(sel, IT, false);
John McCall526ab472011-10-25 17:37:35 +0000537}
538
Jordan Rosed3934582012-09-28 22:21:30 +0000539bool ObjCPropertyOpBuilder::isWeakProperty() const {
540 QualType T;
541 if (RefExpr->isExplicitProperty()) {
542 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
543 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
544 return true;
545
546 T = Prop->getType();
547 } else if (Getter) {
Alp Toker314cc812014-01-25 16:55:45 +0000548 T = Getter->getReturnType();
Jordan Rosed3934582012-09-28 22:21:30 +0000549 } else {
550 return false;
551 }
552
553 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
554}
555
John McCallfe96e0b2011-11-06 09:01:30 +0000556bool ObjCPropertyOpBuilder::findGetter() {
557 if (Getter) return true;
John McCall526ab472011-10-25 17:37:35 +0000558
John McCallcfef5462011-11-07 22:49:50 +0000559 // For implicit properties, just trust the lookup we already did.
560 if (RefExpr->isImplicitProperty()) {
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000561 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
562 GetterSelector = Getter->getSelector();
563 return true;
564 }
565 else {
566 // Must build the getter selector the hard way.
567 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
568 assert(setter && "both setter and getter are null - cannot happen");
569 IdentifierInfo *setterName =
570 setter->getSelector().getIdentifierInfoForSlot(0);
571 const char *compStr = setterName->getNameStart();
572 compStr += 3;
573 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
574 GetterSelector =
575 S.PP.getSelectorTable().getNullarySelector(getterName);
576 return false;
577
578 }
John McCallcfef5462011-11-07 22:49:50 +0000579 }
580
581 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
582 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
Craig Topperc3ec1492014-05-26 06:22:03 +0000583 return (Getter != nullptr);
John McCallfe96e0b2011-11-06 09:01:30 +0000584}
585
586/// Try to find the most accurate setter declaration for the property
587/// reference.
588///
589/// \return true if a setter was found, in which case Setter
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000590bool ObjCPropertyOpBuilder::findSetter(bool warn) {
John McCallfe96e0b2011-11-06 09:01:30 +0000591 // For implicit properties, just trust the lookup we already did.
592 if (RefExpr->isImplicitProperty()) {
593 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
594 Setter = setter;
595 SetterSelector = setter->getSelector();
596 return true;
John McCall526ab472011-10-25 17:37:35 +0000597 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000598 IdentifierInfo *getterName =
599 RefExpr->getImplicitPropertyGetter()->getSelector()
600 .getIdentifierInfoForSlot(0);
601 SetterSelector =
Adrian Prantla4ce9062013-06-07 22:29:12 +0000602 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
603 S.PP.getSelectorTable(),
604 getterName);
John McCallfe96e0b2011-11-06 09:01:30 +0000605 return false;
John McCall526ab472011-10-25 17:37:35 +0000606 }
John McCallfe96e0b2011-11-06 09:01:30 +0000607 }
608
609 // For explicit properties, this is more involved.
610 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
611 SetterSelector = prop->getSetterName();
612
613 // Do a normal method lookup first.
614 if (ObjCMethodDecl *setter =
615 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
Jordan Rosed01e83a2012-10-10 16:42:25 +0000616 if (setter->isPropertyAccessor() && warn)
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000617 if (const ObjCInterfaceDecl *IFace =
618 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
619 const StringRef thisPropertyName(prop->getName());
Jordan Rosea7d03842013-02-08 22:30:41 +0000620 // Try flipping the case of the first character.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000621 char front = thisPropertyName.front();
Jordan Rosea7d03842013-02-08 22:30:41 +0000622 front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000623 SmallString<100> PropertyName = thisPropertyName;
624 PropertyName[0] = front;
625 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
626 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember))
627 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
Fariborz Jahanianf3b76812012-05-26 16:10:06 +0000628 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use)
Aaron Ballman1fb39552014-01-03 14:23:03 +0000629 << prop << prop1 << setter->getSelector();
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000630 S.Diag(prop->getLocation(), diag::note_property_declare);
631 S.Diag(prop1->getLocation(), diag::note_property_declare);
632 }
633 }
John McCallfe96e0b2011-11-06 09:01:30 +0000634 Setter = setter;
635 return true;
636 }
637
638 // That can fail in the somewhat crazy situation that we're
639 // type-checking a message send within the @interface declaration
640 // that declared the @property. But it's not clear that that's
641 // valuable to support.
642
643 return false;
644}
645
646/// Capture the base object of an Objective-C property expression.
647Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000648 assert(InstanceReceiver == nullptr);
John McCallfe96e0b2011-11-06 09:01:30 +0000649
650 // If we have a base, capture it in an OVE and rebuild the syntactic
651 // form to use the OVE as its base.
652 if (RefExpr->isObjectReceiver()) {
653 InstanceReceiver = capture(RefExpr->getBase());
654
655 syntacticBase =
656 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
657 }
658
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000659 if (ObjCPropertyRefExpr *
660 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
661 SyntacticRefExpr = refE;
662
John McCallfe96e0b2011-11-06 09:01:30 +0000663 return syntacticBase;
664}
665
666/// Load from an Objective-C property reference.
667ExprResult ObjCPropertyOpBuilder::buildGet() {
668 findGetter();
669 assert(Getter);
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000670
671 if (SyntacticRefExpr)
672 SyntacticRefExpr->setIsMessagingGetter();
673
John McCallfe96e0b2011-11-06 09:01:30 +0000674 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000675 if (RefExpr->isClassReceiver()) {
676 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
677 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000678 receiverType = RefExpr->getSuperReceiverType();
John McCall526ab472011-10-25 17:37:35 +0000679 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000680 assert(InstanceReceiver);
681 receiverType = InstanceReceiver->getType();
682 }
John McCall526ab472011-10-25 17:37:35 +0000683
John McCallfe96e0b2011-11-06 09:01:30 +0000684 // Build a message-send.
685 ExprResult msg;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000686 if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
687 RefExpr->isObjectReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000688 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000689 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
690 GenericLoc, Getter->getSelector(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000691 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000692 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000693 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000694 GenericLoc, Getter->getSelector(),
695 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000696 }
697 return msg;
698}
John McCall526ab472011-10-25 17:37:35 +0000699
John McCallfe96e0b2011-11-06 09:01:30 +0000700/// Store to an Objective-C property reference.
701///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000702/// \param captureSetValueAsResult If true, capture the actual
John McCallfe96e0b2011-11-06 09:01:30 +0000703/// value being set as the value of the property operation.
704ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
705 bool captureSetValueAsResult) {
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000706 bool hasSetter = findSetter(false);
John McCallfe96e0b2011-11-06 09:01:30 +0000707 assert(hasSetter); (void) hasSetter;
708
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000709 if (SyntacticRefExpr)
710 SyntacticRefExpr->setIsMessagingSetter();
711
John McCallfe96e0b2011-11-06 09:01:30 +0000712 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000713 if (RefExpr->isClassReceiver()) {
714 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
715 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000716 receiverType = RefExpr->getSuperReceiverType();
717 } else {
718 assert(InstanceReceiver);
719 receiverType = InstanceReceiver->getType();
720 }
721
722 // Use assignment constraints when possible; they give us better
723 // diagnostics. "When possible" basically means anything except a
724 // C++ class type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000725 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000726 QualType paramType = (*Setter->param_begin())->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000727 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000728 ExprResult opResult = op;
729 Sema::AssignConvertType assignResult
730 = S.CheckSingleAssignmentConstraints(paramType, opResult);
731 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
732 op->getType(), opResult.get(),
733 Sema::AA_Assigning))
734 return ExprError();
735
736 op = opResult.take();
737 assert(op && "successful assignment left argument invalid?");
John McCall526ab472011-10-25 17:37:35 +0000738 }
Fariborz Jahanian2eaec612013-10-16 17:51:43 +0000739 else if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(op)) {
740 Expr *Initializer = OVE->getSourceExpr();
741 // passing C++11 style initialized temporaries to objc++ properties
742 // requires special treatment by removing OpaqueValueExpr so type
743 // conversion takes place and adding the OpaqueValueExpr later on.
744 if (isa<InitListExpr>(Initializer) &&
745 Initializer->getType()->isVoidType()) {
746 op = Initializer;
747 }
748 }
John McCall526ab472011-10-25 17:37:35 +0000749 }
750
John McCallfe96e0b2011-11-06 09:01:30 +0000751 // Arguments.
752 Expr *args[] = { op };
John McCall526ab472011-10-25 17:37:35 +0000753
John McCallfe96e0b2011-11-06 09:01:30 +0000754 // Build a message-send.
755 ExprResult msg;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000756 if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
757 RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000758 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
759 GenericLoc, SetterSelector, Setter,
760 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000761 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000762 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
763 GenericLoc,
764 SetterSelector, Setter,
765 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000766 }
767
768 if (!msg.isInvalid() && captureSetValueAsResult) {
769 ObjCMessageExpr *msgExpr =
770 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
771 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000772 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +0000773 msgExpr->setArg(0, captureValueAsResult(arg));
John McCallfe96e0b2011-11-06 09:01:30 +0000774 }
775
776 return msg;
John McCall526ab472011-10-25 17:37:35 +0000777}
778
John McCallfe96e0b2011-11-06 09:01:30 +0000779/// @property-specific behavior for doing lvalue-to-rvalue conversion.
780ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
781 // Explicit properties always have getters, but implicit ones don't.
782 // Check that before proceeding.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000783 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000784 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000785 << RefExpr->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +0000786 return ExprError();
787 }
788
John McCallfe96e0b2011-11-06 09:01:30 +0000789 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall526ab472011-10-25 17:37:35 +0000790 if (result.isInvalid()) return ExprError();
791
John McCallfe96e0b2011-11-06 09:01:30 +0000792 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
793 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
794 Getter, RefExpr->getLocation());
795
796 // As a special case, if the method returns 'id', try to get
797 // a better type from the property.
798 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
799 result.get()->getType()->isObjCIdType()) {
800 QualType propType = RefExpr->getExplicitProperty()->getType();
801 if (const ObjCObjectPointerType *ptr
802 = propType->getAs<ObjCObjectPointerType>()) {
803 if (!ptr->isObjCIdType())
804 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
805 }
806 }
807
John McCall526ab472011-10-25 17:37:35 +0000808 return result;
809}
810
John McCallfe96e0b2011-11-06 09:01:30 +0000811/// Try to build this as a call to a getter that returns a reference.
812///
813/// \return true if it was possible, whether or not it actually
814/// succeeded
815bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
816 ExprResult &result) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000817 if (!S.getLangOpts().CPlusPlus) return false;
John McCallfe96e0b2011-11-06 09:01:30 +0000818
819 findGetter();
820 assert(Getter && "property has no setter and no getter!");
821
822 // Only do this if the getter returns an l-value reference type.
Alp Toker314cc812014-01-25 16:55:45 +0000823 QualType resultType = Getter->getReturnType();
John McCallfe96e0b2011-11-06 09:01:30 +0000824 if (!resultType->isLValueReferenceType()) return false;
825
826 result = buildRValueOperation(op);
827 return true;
828}
829
830/// @property-specific behavior for doing assignments.
831ExprResult
832ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
833 SourceLocation opcLoc,
834 BinaryOperatorKind opcode,
835 Expr *LHS, Expr *RHS) {
John McCall526ab472011-10-25 17:37:35 +0000836 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall526ab472011-10-25 17:37:35 +0000837
838 // If there's no setter, we have no choice but to try to assign to
839 // the result of the getter.
John McCallfe96e0b2011-11-06 09:01:30 +0000840 if (!findSetter()) {
841 ExprResult result;
842 if (tryBuildGetOfReference(LHS, result)) {
843 if (result.isInvalid()) return ExprError();
844 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
John McCall526ab472011-10-25 17:37:35 +0000845 }
846
847 // Otherwise, it's an error.
John McCallfe96e0b2011-11-06 09:01:30 +0000848 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
849 << unsigned(RefExpr->isImplicitProperty())
850 << SetterSelector
John McCall526ab472011-10-25 17:37:35 +0000851 << LHS->getSourceRange() << RHS->getSourceRange();
852 return ExprError();
853 }
854
855 // If there is a setter, we definitely want to use it.
856
John McCallfe96e0b2011-11-06 09:01:30 +0000857 // Verify that we can do a compound assignment.
858 if (opcode != BO_Assign && !findGetter()) {
859 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall526ab472011-10-25 17:37:35 +0000860 << LHS->getSourceRange() << RHS->getSourceRange();
861 return ExprError();
862 }
863
John McCallfe96e0b2011-11-06 09:01:30 +0000864 ExprResult result =
865 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall526ab472011-10-25 17:37:35 +0000866 if (result.isInvalid()) return ExprError();
867
John McCallfe96e0b2011-11-06 09:01:30 +0000868 // Various warnings about property assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000869 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCallfe96e0b2011-11-06 09:01:30 +0000870 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
871 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
872 }
873
John McCall526ab472011-10-25 17:37:35 +0000874 return result;
875}
John McCallfe96e0b2011-11-06 09:01:30 +0000876
877/// @property-specific behavior for doing increments and decrements.
878ExprResult
879ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
880 UnaryOperatorKind opcode,
881 Expr *op) {
882 // If there's no setter, we have no choice but to try to assign to
883 // the result of the getter.
884 if (!findSetter()) {
885 ExprResult result;
886 if (tryBuildGetOfReference(op, result)) {
887 if (result.isInvalid()) return ExprError();
888 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
889 }
890
891 // Otherwise, it's an error.
892 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
893 << unsigned(RefExpr->isImplicitProperty())
894 << unsigned(UnaryOperator::isDecrementOp(opcode))
895 << SetterSelector
896 << op->getSourceRange();
897 return ExprError();
898 }
899
900 // If there is a setter, we definitely want to use it.
901
902 // We also need a getter.
903 if (!findGetter()) {
904 assert(RefExpr->isImplicitProperty());
905 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
906 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000907 << GetterSelector
John McCallfe96e0b2011-11-06 09:01:30 +0000908 << op->getSourceRange();
909 return ExprError();
910 }
911
912 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
913}
914
Jordan Rosed3934582012-09-28 22:21:30 +0000915ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
916 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) {
917 DiagnosticsEngine::Level Level =
918 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
919 SyntacticForm->getLocStart());
920 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +0000921 S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
922 SyntacticRefExpr->isMessagingGetter());
Jordan Rosed3934582012-09-28 22:21:30 +0000923 }
924
925 return PseudoOpBuilder::complete(SyntacticForm);
926}
927
Ted Kremeneke65b0862012-03-06 20:05:56 +0000928// ObjCSubscript build stuff.
929//
930
931/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
932/// conversion.
933/// FIXME. Remove this routine if it is proven that no additional
934/// specifity is needed.
935ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
936 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
937 if (result.isInvalid()) return ExprError();
938 return result;
939}
940
941/// objective-c subscripting-specific behavior for doing assignments.
942ExprResult
943ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
944 SourceLocation opcLoc,
945 BinaryOperatorKind opcode,
946 Expr *LHS, Expr *RHS) {
947 assert(BinaryOperator::isAssignmentOp(opcode));
948 // There must be a method to do the Index'ed assignment.
949 if (!findAtIndexSetter())
950 return ExprError();
951
952 // Verify that we can do a compound assignment.
953 if (opcode != BO_Assign && !findAtIndexGetter())
954 return ExprError();
955
956 ExprResult result =
957 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
958 if (result.isInvalid()) return ExprError();
959
960 // Various warnings about objc Index'ed assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000961 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000962 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
963 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
964 }
965
966 return result;
967}
968
969/// Capture the base object of an Objective-C Index'ed expression.
970Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000971 assert(InstanceBase == nullptr);
972
Ted Kremeneke65b0862012-03-06 20:05:56 +0000973 // Capture base expression in an OVE and rebuild the syntactic
974 // form to use the OVE as its base expression.
975 InstanceBase = capture(RefExpr->getBaseExpr());
976 InstanceKey = capture(RefExpr->getKeyExpr());
977
978 syntacticBase =
979 ObjCSubscriptRefRebuilder(S, InstanceBase,
980 InstanceKey).rebuild(syntacticBase);
981
982 return syntacticBase;
983}
984
985/// CheckSubscriptingKind - This routine decide what type
986/// of indexing represented by "FromE" is being done.
987Sema::ObjCSubscriptKind
988 Sema::CheckSubscriptingKind(Expr *FromE) {
989 // If the expression already has integral or enumeration type, we're golden.
990 QualType T = FromE->getType();
991 if (T->isIntegralOrEnumerationType())
992 return OS_Array;
993
994 // If we don't have a class type in C++, there's no way we can get an
995 // expression of integral or enumeration type.
996 const RecordType *RecordTy = T->getAs<RecordType>();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +0000997 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremeneke65b0862012-03-06 20:05:56 +0000998 // All other scalar cases are assumed to be dictionary indexing which
999 // caller handles, with diagnostics if needed.
1000 return OS_Dictionary;
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001001 if (!getLangOpts().CPlusPlus ||
1002 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001003 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001004 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1005 if (isa<StringLiteral>(IndexExpr))
1006 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1007 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1008 else
1009 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1010 << T;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001011 return OS_Error;
1012 }
1013
1014 // We must have a complete class type.
1015 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001016 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremeneke65b0862012-03-06 20:05:56 +00001017 return OS_Error;
1018
1019 // Look for a conversion to an integral, enumeration type, or
1020 // objective-C pointer type.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001021 std::pair<CXXRecordDecl::conversion_iterator,
1022 CXXRecordDecl::conversion_iterator> Conversions
Ted Kremeneke65b0862012-03-06 20:05:56 +00001023 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
1024
1025 int NoIntegrals=0, NoObjCIdPointers=0;
1026 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1027
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001028 for (CXXRecordDecl::conversion_iterator
1029 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001030 if (CXXConversionDecl *Conversion
1031 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
1032 QualType CT = Conversion->getConversionType().getNonReferenceType();
1033 if (CT->isIntegralOrEnumerationType()) {
1034 ++NoIntegrals;
1035 ConversionDecls.push_back(Conversion);
1036 }
1037 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1038 ++NoObjCIdPointers;
1039 ConversionDecls.push_back(Conversion);
1040 }
1041 }
1042 }
1043 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1044 return OS_Array;
1045 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1046 return OS_Dictionary;
1047 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1048 // No conversion function was found. Issue diagnostic and return.
1049 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1050 << FromE->getType();
1051 return OS_Error;
1052 }
1053 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1054 << FromE->getType();
1055 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1056 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
1057
1058 return OS_Error;
1059}
1060
Fariborz Jahanian90804912012-08-02 18:03:58 +00001061/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1062/// objects used as dictionary subscript key objects.
1063static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1064 Expr *Key) {
1065 if (ContainerT.isNull())
1066 return;
1067 // dictionary subscripting.
1068 // - (id)objectForKeyedSubscript:(id)key;
1069 IdentifierInfo *KeyIdents[] = {
1070 &S.Context.Idents.get("objectForKeyedSubscript")
1071 };
1072 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1073 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1074 true /*instance*/);
1075 if (!Getter)
1076 return;
1077 QualType T = Getter->param_begin()[0]->getType();
1078 S.CheckObjCARCConversion(Key->getSourceRange(),
1079 T, Key, Sema::CCK_ImplicitConversion);
1080}
1081
Ted Kremeneke65b0862012-03-06 20:05:56 +00001082bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1083 if (AtIndexGetter)
1084 return true;
1085
1086 Expr *BaseExpr = RefExpr->getBaseExpr();
1087 QualType BaseT = BaseExpr->getType();
1088
1089 QualType ResultType;
1090 if (const ObjCObjectPointerType *PTy =
1091 BaseT->getAs<ObjCObjectPointerType>()) {
1092 ResultType = PTy->getPointeeType();
1093 if (const ObjCObjectType *iQFaceTy =
1094 ResultType->getAsObjCQualifiedInterfaceType())
1095 ResultType = iQFaceTy->getBaseType();
1096 }
1097 Sema::ObjCSubscriptKind Res =
1098 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001099 if (Res == Sema::OS_Error) {
1100 if (S.getLangOpts().ObjCAutoRefCount)
1101 CheckKeyForObjCARCConversion(S, ResultType,
1102 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001103 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001104 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001105 bool arrayRef = (Res == Sema::OS_Array);
1106
1107 if (ResultType.isNull()) {
1108 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1109 << BaseExpr->getType() << arrayRef;
1110 return false;
1111 }
1112 if (!arrayRef) {
1113 // dictionary subscripting.
1114 // - (id)objectForKeyedSubscript:(id)key;
1115 IdentifierInfo *KeyIdents[] = {
1116 &S.Context.Idents.get("objectForKeyedSubscript")
1117 };
1118 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1119 }
1120 else {
1121 // - (id)objectAtIndexedSubscript:(size_t)index;
1122 IdentifierInfo *KeyIdents[] = {
1123 &S.Context.Idents.get("objectAtIndexedSubscript")
1124 };
1125
1126 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1127 }
1128
1129 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1130 true /*instance*/);
1131 bool receiverIdType = (BaseT->isObjCIdType() ||
1132 BaseT->isObjCQualifiedIdType());
1133
David Blaikiebbafb8a2012-03-11 07:00:24 +00001134 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001135 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1136 SourceLocation(), AtIndexGetterSelector,
1137 S.Context.getObjCIdType() /*ReturnType*/,
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001139 S.Context.getTranslationUnitDecl(),
1140 true /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +00001141 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001142 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1143 ObjCMethodDecl::Required,
1144 false);
1145 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1146 SourceLocation(), SourceLocation(),
1147 arrayRef ? &S.Context.Idents.get("index")
1148 : &S.Context.Idents.get("key"),
1149 arrayRef ? S.Context.UnsignedLongTy
1150 : S.Context.getObjCIdType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001151 /*TInfo=*/nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001152 SC_None,
Craig Topperc3ec1492014-05-26 06:22:03 +00001153 nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001154 AtIndexGetter->setMethodParams(S.Context, Argument, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001155 }
1156
1157 if (!AtIndexGetter) {
1158 if (!receiverIdType) {
1159 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1160 << BaseExpr->getType() << 0 << arrayRef;
1161 return false;
1162 }
1163 AtIndexGetter =
1164 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1165 RefExpr->getSourceRange(),
1166 true, false);
1167 }
1168
1169 if (AtIndexGetter) {
1170 QualType T = AtIndexGetter->param_begin()[0]->getType();
1171 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1172 (!arrayRef && !T->isObjCObjectPointerType())) {
1173 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1174 arrayRef ? diag::err_objc_subscript_index_type
1175 : diag::err_objc_subscript_key_type) << T;
1176 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1177 diag::note_parameter_type) << T;
1178 return false;
1179 }
Alp Toker314cc812014-01-25 16:55:45 +00001180 QualType R = AtIndexGetter->getReturnType();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001181 if (!R->isObjCObjectPointerType()) {
1182 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1183 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1184 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1185 AtIndexGetter->getDeclName();
1186 }
1187 }
1188 return true;
1189}
1190
1191bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1192 if (AtIndexSetter)
1193 return true;
1194
1195 Expr *BaseExpr = RefExpr->getBaseExpr();
1196 QualType BaseT = BaseExpr->getType();
1197
1198 QualType ResultType;
1199 if (const ObjCObjectPointerType *PTy =
1200 BaseT->getAs<ObjCObjectPointerType>()) {
1201 ResultType = PTy->getPointeeType();
1202 if (const ObjCObjectType *iQFaceTy =
1203 ResultType->getAsObjCQualifiedInterfaceType())
1204 ResultType = iQFaceTy->getBaseType();
1205 }
1206
1207 Sema::ObjCSubscriptKind Res =
1208 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001209 if (Res == Sema::OS_Error) {
1210 if (S.getLangOpts().ObjCAutoRefCount)
1211 CheckKeyForObjCARCConversion(S, ResultType,
1212 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001213 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001214 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001215 bool arrayRef = (Res == Sema::OS_Array);
1216
1217 if (ResultType.isNull()) {
1218 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1219 << BaseExpr->getType() << arrayRef;
1220 return false;
1221 }
1222
1223 if (!arrayRef) {
1224 // dictionary subscripting.
1225 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1226 IdentifierInfo *KeyIdents[] = {
1227 &S.Context.Idents.get("setObject"),
1228 &S.Context.Idents.get("forKeyedSubscript")
1229 };
1230 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1231 }
1232 else {
1233 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1234 IdentifierInfo *KeyIdents[] = {
1235 &S.Context.Idents.get("setObject"),
1236 &S.Context.Idents.get("atIndexedSubscript")
1237 };
1238 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1239 }
1240 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1241 true /*instance*/);
1242
1243 bool receiverIdType = (BaseT->isObjCIdType() ||
1244 BaseT->isObjCQualifiedIdType());
1245
David Blaikiebbafb8a2012-03-11 07:00:24 +00001246 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001247 TypeSourceInfo *ReturnTInfo = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001248 QualType ReturnType = S.Context.VoidTy;
Alp Toker314cc812014-01-25 16:55:45 +00001249 AtIndexSetter = ObjCMethodDecl::Create(
1250 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
1251 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
1252 true /*Instance*/, false /*isVariadic*/,
1253 /*isPropertyAccessor=*/false,
1254 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1255 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001256 SmallVector<ParmVarDecl *, 2> Params;
1257 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1258 SourceLocation(), SourceLocation(),
1259 &S.Context.Idents.get("object"),
1260 S.Context.getObjCIdType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001261 /*TInfo=*/nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001262 SC_None,
Craig Topperc3ec1492014-05-26 06:22:03 +00001263 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001264 Params.push_back(object);
1265 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1266 SourceLocation(), SourceLocation(),
1267 arrayRef ? &S.Context.Idents.get("index")
1268 : &S.Context.Idents.get("key"),
1269 arrayRef ? S.Context.UnsignedLongTy
1270 : S.Context.getObjCIdType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001271 /*TInfo=*/nullptr,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001272 SC_None,
Craig Topperc3ec1492014-05-26 06:22:03 +00001273 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001274 Params.push_back(key);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001275 AtIndexSetter->setMethodParams(S.Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001276 }
1277
1278 if (!AtIndexSetter) {
1279 if (!receiverIdType) {
1280 S.Diag(BaseExpr->getExprLoc(),
1281 diag::err_objc_subscript_method_not_found)
1282 << BaseExpr->getType() << 1 << arrayRef;
1283 return false;
1284 }
1285 AtIndexSetter =
1286 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1287 RefExpr->getSourceRange(),
1288 true, false);
1289 }
1290
1291 bool err = false;
1292 if (AtIndexSetter && arrayRef) {
1293 QualType T = AtIndexSetter->param_begin()[1]->getType();
1294 if (!T->isIntegralOrEnumerationType()) {
1295 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1296 diag::err_objc_subscript_index_type) << T;
1297 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1298 diag::note_parameter_type) << T;
1299 err = true;
1300 }
1301 T = AtIndexSetter->param_begin()[0]->getType();
1302 if (!T->isObjCObjectPointerType()) {
1303 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1304 diag::err_objc_subscript_object_type) << T << arrayRef;
1305 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1306 diag::note_parameter_type) << T;
1307 err = true;
1308 }
1309 }
1310 else if (AtIndexSetter && !arrayRef)
1311 for (unsigned i=0; i <2; i++) {
1312 QualType T = AtIndexSetter->param_begin()[i]->getType();
1313 if (!T->isObjCObjectPointerType()) {
1314 if (i == 1)
1315 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1316 diag::err_objc_subscript_key_type) << T;
1317 else
1318 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1319 diag::err_objc_subscript_dic_object_type) << T;
1320 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1321 diag::note_parameter_type) << T;
1322 err = true;
1323 }
1324 }
1325
1326 return !err;
1327}
1328
1329// Get the object at "Index" position in the container.
1330// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1331ExprResult ObjCSubscriptOpBuilder::buildGet() {
1332 if (!findAtIndexGetter())
1333 return ExprError();
1334
1335 QualType receiverType = InstanceBase->getType();
1336
1337 // Build a message-send.
1338 ExprResult msg;
1339 Expr *Index = InstanceKey;
1340
1341 // Arguments.
1342 Expr *args[] = { Index };
1343 assert(InstanceBase);
1344 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1345 GenericLoc,
1346 AtIndexGetterSelector, AtIndexGetter,
1347 MultiExprArg(args, 1));
1348 return msg;
1349}
1350
1351/// Store into the container the "op" object at "Index"'ed location
1352/// by building this messaging expression:
1353/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001354/// \param captureSetValueAsResult If true, capture the actual
Ted Kremeneke65b0862012-03-06 20:05:56 +00001355/// value being set as the value of the property operation.
1356ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1357 bool captureSetValueAsResult) {
1358 if (!findAtIndexSetter())
1359 return ExprError();
1360
1361 QualType receiverType = InstanceBase->getType();
1362 Expr *Index = InstanceKey;
1363
1364 // Arguments.
1365 Expr *args[] = { op, Index };
1366
1367 // Build a message-send.
1368 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1369 GenericLoc,
1370 AtIndexSetterSelector,
1371 AtIndexSetter,
1372 MultiExprArg(args, 2));
1373
1374 if (!msg.isInvalid() && captureSetValueAsResult) {
1375 ObjCMessageExpr *msgExpr =
1376 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1377 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +00001378 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +00001379 msgExpr->setArg(0, captureValueAsResult(arg));
Ted Kremeneke65b0862012-03-06 20:05:56 +00001380 }
1381
1382 return msg;
1383}
1384
John McCallfe96e0b2011-11-06 09:01:30 +00001385//===----------------------------------------------------------------------===//
John McCall5e77d762013-04-16 07:28:30 +00001386// MSVC __declspec(property) references
1387//===----------------------------------------------------------------------===//
1388
1389Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1390 Expr *NewBase = capture(RefExpr->getBaseExpr());
1391
1392 syntacticBase =
1393 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase);
1394
1395 return syntacticBase;
1396}
1397
1398ExprResult MSPropertyOpBuilder::buildGet() {
1399 if (!RefExpr->getPropertyDecl()->hasGetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001400 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001401 << 0 /* getter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001402 return ExprError();
1403 }
1404
1405 UnqualifiedId GetterName;
1406 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1407 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1408 CXXScopeSpec SS;
1409 SS.Adopt(RefExpr->getQualifierLoc());
1410 ExprResult GetterExpr = S.ActOnMemberAccessExpr(
1411 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1412 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001413 GetterName, nullptr, true);
John McCall5e77d762013-04-16 07:28:30 +00001414 if (GetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001415 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001416 diag::error_cannot_find_suitable_accessor) << 0 /* getter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001417 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001418 return ExprError();
1419 }
1420
1421 MultiExprArg ArgExprs;
1422 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.take(),
1423 RefExpr->getSourceRange().getBegin(), ArgExprs,
1424 RefExpr->getSourceRange().getEnd());
1425}
1426
1427ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1428 bool captureSetValueAsResult) {
1429 if (!RefExpr->getPropertyDecl()->hasSetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001430 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001431 << 1 /* setter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001432 return ExprError();
1433 }
1434
1435 UnqualifiedId SetterName;
1436 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1437 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1438 CXXScopeSpec SS;
1439 SS.Adopt(RefExpr->getQualifierLoc());
1440 ExprResult SetterExpr = S.ActOnMemberAccessExpr(
1441 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1442 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001443 SetterName, nullptr, true);
John McCall5e77d762013-04-16 07:28:30 +00001444 if (SetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001445 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001446 diag::error_cannot_find_suitable_accessor) << 1 /* setter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001447 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001448 return ExprError();
1449 }
1450
1451 SmallVector<Expr*, 1> ArgExprs;
1452 ArgExprs.push_back(op);
1453 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.take(),
1454 RefExpr->getSourceRange().getBegin(), ArgExprs,
1455 op->getSourceRange().getEnd());
1456}
1457
1458//===----------------------------------------------------------------------===//
John McCallfe96e0b2011-11-06 09:01:30 +00001459// General Sema routines.
1460//===----------------------------------------------------------------------===//
1461
1462ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1463 Expr *opaqueRef = E->IgnoreParens();
1464 if (ObjCPropertyRefExpr *refExpr
1465 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1466 ObjCPropertyOpBuilder builder(*this, refExpr);
1467 return builder.buildRValueOperation(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001468 }
1469 else if (ObjCSubscriptRefExpr *refExpr
1470 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1471 ObjCSubscriptOpBuilder builder(*this, refExpr);
1472 return builder.buildRValueOperation(E);
John McCall5e77d762013-04-16 07:28:30 +00001473 } else if (MSPropertyRefExpr *refExpr
1474 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1475 MSPropertyOpBuilder builder(*this, refExpr);
1476 return builder.buildRValueOperation(E);
John McCallfe96e0b2011-11-06 09:01:30 +00001477 } else {
1478 llvm_unreachable("unknown pseudo-object kind!");
1479 }
1480}
1481
1482/// Check an increment or decrement of a pseudo-object expression.
1483ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1484 UnaryOperatorKind opcode, Expr *op) {
1485 // Do nothing if the operand is dependent.
1486 if (op->isTypeDependent())
1487 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1488 VK_RValue, OK_Ordinary, opcLoc);
1489
1490 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1491 Expr *opaqueRef = op->IgnoreParens();
1492 if (ObjCPropertyRefExpr *refExpr
1493 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1494 ObjCPropertyOpBuilder builder(*this, refExpr);
1495 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001496 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1497 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1498 return ExprError();
John McCall5e77d762013-04-16 07:28:30 +00001499 } else if (MSPropertyRefExpr *refExpr
1500 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1501 MSPropertyOpBuilder builder(*this, refExpr);
1502 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
John McCallfe96e0b2011-11-06 09:01:30 +00001503 } else {
1504 llvm_unreachable("unknown pseudo-object kind!");
1505 }
1506}
1507
1508ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1509 BinaryOperatorKind opcode,
1510 Expr *LHS, Expr *RHS) {
1511 // Do nothing if either argument is dependent.
1512 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1513 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00001514 VK_RValue, OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +00001515
1516 // Filter out non-overload placeholder types in the RHS.
John McCalld5c98ae2011-11-15 01:35:18 +00001517 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1518 ExprResult result = CheckPlaceholderExpr(RHS);
1519 if (result.isInvalid()) return ExprError();
1520 RHS = result.take();
John McCallfe96e0b2011-11-06 09:01:30 +00001521 }
1522
1523 Expr *opaqueRef = LHS->IgnoreParens();
1524 if (ObjCPropertyRefExpr *refExpr
1525 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1526 ObjCPropertyOpBuilder builder(*this, refExpr);
1527 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001528 } else if (ObjCSubscriptRefExpr *refExpr
1529 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1530 ObjCSubscriptOpBuilder builder(*this, refExpr);
1531 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall5e77d762013-04-16 07:28:30 +00001532 } else if (MSPropertyRefExpr *refExpr
1533 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1534 MSPropertyOpBuilder builder(*this, refExpr);
1535 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCallfe96e0b2011-11-06 09:01:30 +00001536 } else {
1537 llvm_unreachable("unknown pseudo-object kind!");
1538 }
1539}
John McCalle9290822011-11-30 04:42:31 +00001540
1541/// Given a pseudo-object reference, rebuild it without the opaque
1542/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1543/// This should never operate in-place.
1544static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1545 Expr *opaqueRef = E->IgnoreParens();
1546 if (ObjCPropertyRefExpr *refExpr
1547 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregoraa0df2d2012-04-13 16:05:42 +00001548 // Class and super property references don't have opaque values in them.
1549 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1550 return E;
1551
1552 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1553 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1554 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001555 } else if (ObjCSubscriptRefExpr *refExpr
1556 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1557 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1558 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1559 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1560 keyOVE->getSourceExpr()).rebuild(E);
John McCall5e77d762013-04-16 07:28:30 +00001561 } else if (MSPropertyRefExpr *refExpr
1562 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1563 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1564 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
John McCalle9290822011-11-30 04:42:31 +00001565 } else {
1566 llvm_unreachable("unknown pseudo-object kind!");
1567 }
1568}
1569
1570/// Given a pseudo-object expression, recreate what it looks like
1571/// syntactically without the attendant OpaqueValueExprs.
1572///
1573/// This is a hack which should be removed when TreeTransform is
1574/// capable of rebuilding a tree without stripping implicit
1575/// operations.
1576Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1577 Expr *syntax = E->getSyntacticForm();
1578 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1579 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1580 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1581 uop->getValueKind(), uop->getObjectKind(),
1582 uop->getOperatorLoc());
1583 } else if (CompoundAssignOperator *cop
1584 = dyn_cast<CompoundAssignOperator>(syntax)) {
1585 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1586 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1587 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1588 cop->getType(),
1589 cop->getValueKind(),
1590 cop->getObjectKind(),
1591 cop->getComputationLHSType(),
1592 cop->getComputationResultType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001593 cop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001594 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1595 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1596 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1597 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1598 bop->getType(), bop->getValueKind(),
1599 bop->getObjectKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001600 bop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001601 } else {
1602 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1603 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1604 }
1605}