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