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