blob: e91ace36aadacdfbe724f9878deb3755c9a0592f [file] [log] [blame]
Douglas Gregor5476205b2011-06-23 00:49:38 +00001//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
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 member access expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/SemaInternal.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000014#include "clang/AST/ASTLambda.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000015#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000024
25using namespace clang;
26using namespace sema;
27
Richard Smithd80b2d52012-11-22 00:24:47 +000028typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
29static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
30 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
31 return !Bases.count(Base->getCanonicalDecl());
32}
33
Douglas Gregor5476205b2011-06-23 00:49:38 +000034/// Determines if the given class is provably not derived from all of
35/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000036static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
37 const BaseSet &Bases) {
38 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
39 return BaseIsNotInSet(Record, BasesPtr) &&
40 Record->forallBases(BaseIsNotInSet, BasesPtr);
Douglas Gregor5476205b2011-06-23 00:49:38 +000041}
42
43enum IMAKind {
44 /// The reference is definitely not an instance member access.
45 IMA_Static,
46
47 /// The reference may be an implicit instance member access.
48 IMA_Mixed,
49
Eli Friedman7bda7f72012-01-18 03:53:45 +000050 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000051 /// so, because the context is not an instance method.
52 IMA_Mixed_StaticContext,
53
54 /// The reference may be to an instance member, but it is invalid if
55 /// so, because the context is from an unrelated class.
56 IMA_Mixed_Unrelated,
57
58 /// The reference is definitely an implicit instance member access.
59 IMA_Instance,
60
61 /// The reference may be to an unresolved using declaration.
62 IMA_Unresolved,
63
John McCallf413f5e2013-05-03 00:10:13 +000064 /// The reference is a contextually-permitted abstract member reference.
65 IMA_Abstract,
66
Douglas Gregor5476205b2011-06-23 00:49:38 +000067 /// The reference may be to an unresolved using declaration and the
68 /// context is not an instance method.
69 IMA_Unresolved_StaticContext,
70
Eli Friedman456f0182012-01-20 01:26:23 +000071 // The reference refers to a field which is not a member of the containing
72 // class, which is allowed because we're in C++11 mode and the context is
73 // unevaluated.
74 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000075
Douglas Gregor5476205b2011-06-23 00:49:38 +000076 /// All possible referrents are instance members and the current
77 /// context is not an instance method.
78 IMA_Error_StaticContext,
79
80 /// All possible referrents are instance members of an unrelated
81 /// class.
82 IMA_Error_Unrelated
83};
84
85/// The given lookup names class member(s) and is not being used for
86/// an address-of-member expression. Classify the type of access
87/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000088/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000089/// conservatively answer "yes", in which case some errors will simply
90/// not be caught until template-instantiation.
91static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
92 Scope *CurScope,
93 const LookupResult &R) {
94 assert(!R.empty() && (*R.begin())->isCXXClassMember());
95
96 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
97
Douglas Gregor3024f072012-04-16 07:05:22 +000098 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
99 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000100
101 if (R.isUnresolvableResult())
102 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
103
104 // Collect all the declaring classes of instance members we find.
105 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000106 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000107 BaseSet Classes;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000108 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
109 NamedDecl *D = *I;
110
111 if (D->isCXXInstanceMember()) {
John McCall5e77d762013-04-16 07:28:30 +0000112 if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
113 || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman7bda7f72012-01-18 03:53:45 +0000114 isField = true;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000115
116 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
117 Classes.insert(R->getCanonicalDecl());
118 }
119 else
120 hasNonInstance = true;
121 }
122
123 // If we didn't find any instance members, it can't be an implicit
124 // member reference.
125 if (Classes.empty())
126 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000127
128 // C++11 [expr.prim.general]p12:
129 // An id-expression that denotes a non-static data member or non-static
130 // member function of a class can only be used:
131 // (...)
132 // - if that id-expression denotes a non-static data member and it
133 // appears in an unevaluated operand.
134 //
135 // This rule is specific to C++11. However, we also permit this form
136 // in unevaluated inline assembly operands, like the operand to a SIZE.
137 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
138 assert(!AbstractInstanceResult);
139 switch (SemaRef.ExprEvalContexts.back().Context) {
140 case Sema::Unevaluated:
141 if (isField && SemaRef.getLangOpts().CPlusPlus11)
142 AbstractInstanceResult = IMA_Field_Uneval_Context;
143 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000144
John McCallf413f5e2013-05-03 00:10:13 +0000145 case Sema::UnevaluatedAbstract:
146 AbstractInstanceResult = IMA_Abstract;
147 break;
148
149 case Sema::ConstantEvaluated:
150 case Sema::PotentiallyEvaluated:
151 case Sema::PotentiallyEvaluatedIfUsed:
152 break;
Richard Smitheae99682012-02-25 10:04:07 +0000153 }
154
Douglas Gregor5476205b2011-06-23 00:49:38 +0000155 // If the current context is not an instance method, it can't be
156 // an implicit member reference.
157 if (isStaticContext) {
158 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000159 return IMA_Mixed_StaticContext;
160
John McCallf413f5e2013-05-03 00:10:13 +0000161 return AbstractInstanceResult ? AbstractInstanceResult
162 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000163 }
164
165 CXXRecordDecl *contextClass;
166 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
167 contextClass = MD->getParent()->getCanonicalDecl();
168 else
169 contextClass = cast<CXXRecordDecl>(DC);
170
171 // [class.mfct.non-static]p3:
172 // ...is used in the body of a non-static member function of class X,
173 // if name lookup (3.4.1) resolves the name in the id-expression to a
174 // non-static non-type member of some class C [...]
175 // ...if C is not X or a base class of X, the class member access expression
176 // is ill-formed.
177 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000178 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000179 R.getNamingClass()->getCanonicalDecl()) {
180 // If the naming class is not the current context, this was a qualified
181 // member name lookup, and it's sufficient to check that we have the naming
182 // class as a base class.
183 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000184 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000185 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000186
187 // If we can prove that the current context is unrelated to all the
188 // declaring classes, it can't be an implicit member reference (in
189 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000190 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000191 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000192 AbstractInstanceResult ? AbstractInstanceResult :
193 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000194
195 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
196}
197
198/// Diagnose a reference to a field with no object available.
Richard Smithfa0a1f52012-04-05 01:13:04 +0000199static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000200 const CXXScopeSpec &SS,
Richard Smithfa0a1f52012-04-05 01:13:04 +0000201 NamedDecl *Rep,
Eli Friedman456f0182012-01-20 01:26:23 +0000202 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000203 SourceLocation Loc = nameInfo.getLoc();
204 SourceRange Range(Loc);
205 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000206
Richard Smithfa0a1f52012-04-05 01:13:04 +0000207 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000209 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000210 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
211
212 bool InStaticMethod = Method && Method->isStatic();
213 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
214
215 if (IsField && InStaticMethod)
216 // "invalid use of member 'x' in static member function"
217 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
218 << Range << nameInfo.getName();
219 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
220 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
221 // Unqualified lookup in a non-static member function found a member of an
222 // enclosing class.
223 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
224 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
225 else if (IsField)
Eli Friedman456f0182012-01-20 01:26:23 +0000226 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000227 << nameInfo.getName() << Range;
228 else
229 SemaRef.Diag(Loc, diag::err_member_call_without_object)
230 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000231}
232
233/// Builds an expression which might be an implicit member expression.
234ExprResult
235Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000236 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000237 LookupResult &R,
238 const TemplateArgumentListInfo *TemplateArgs) {
239 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
240 case IMA_Instance:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000241 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000242
243 case IMA_Mixed:
244 case IMA_Mixed_Unrelated:
245 case IMA_Unresolved:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000246 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000247
Richard Smith2a986112012-02-25 10:20:59 +0000248 case IMA_Field_Uneval_Context:
249 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
250 << R.getLookupNameInfo().getName();
251 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000252 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000253 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000254 case IMA_Mixed_StaticContext:
255 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000256 if (TemplateArgs || TemplateKWLoc.isValid())
257 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000258 return BuildDeclarationNameExpr(SS, R, false);
259
260 case IMA_Error_StaticContext:
261 case IMA_Error_Unrelated:
Richard Smithfa0a1f52012-04-05 01:13:04 +0000262 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000263 R.getLookupNameInfo());
264 return ExprError();
265 }
266
267 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000268}
269
270/// Check an ext-vector component access expression.
271///
272/// VK should be set in advance to the value kind of the base
273/// expression.
274static QualType
275CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
276 SourceLocation OpLoc, const IdentifierInfo *CompName,
277 SourceLocation CompLoc) {
278 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
279 // see FIXME there.
280 //
281 // FIXME: This logic can be greatly simplified by splitting it along
282 // halving/not halving and reworking the component checking.
283 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
284
285 // The vector accessor can't exceed the number of elements.
286 const char *compStr = CompName->getNameStart();
287
288 // This flag determines whether or not the component is one of the four
289 // special names that indicate a subset of exactly half the elements are
290 // to be selected.
291 bool HalvingSwizzle = false;
292
293 // This flag determines whether or not CompName has an 's' char prefix,
294 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000295 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000296
297 bool HasRepeated = false;
298 bool HasIndex[16] = {};
299
300 int Idx;
301
302 // Check that we've found one of the special components, or that the component
303 // names must come from the same set.
304 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
305 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
306 HalvingSwizzle = true;
307 } else if (!HexSwizzle &&
308 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
309 do {
310 if (HasIndex[Idx]) HasRepeated = true;
311 HasIndex[Idx] = true;
312 compStr++;
313 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
314 } else {
315 if (HexSwizzle) compStr++;
316 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
317 if (HasIndex[Idx]) HasRepeated = true;
318 HasIndex[Idx] = true;
319 compStr++;
320 }
321 }
322
323 if (!HalvingSwizzle && *compStr) {
324 // We didn't get to the end of the string. This means the component names
325 // didn't come from the same set *or* we encountered an illegal name.
326 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000327 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000328 return QualType();
329 }
330
331 // Ensure no component accessor exceeds the width of the vector type it
332 // operates on.
333 if (!HalvingSwizzle) {
334 compStr = CompName->getNameStart();
335
336 if (HexSwizzle)
337 compStr++;
338
339 while (*compStr) {
340 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
341 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
342 << baseType << SourceRange(CompLoc);
343 return QualType();
344 }
345 }
346 }
347
348 // The component accessor looks fine - now we need to compute the actual type.
349 // The vector type is implied by the component accessor. For example,
350 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
351 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
352 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
353 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
354 : CompName->getLength();
355 if (HexSwizzle)
356 CompSize--;
357
358 if (CompSize == 1)
359 return vecType->getElementType();
360
361 if (HasRepeated) VK = VK_RValue;
362
363 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
364 // Now look up the TypeDefDecl from the vector type. Without this,
365 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000366 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000367 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000368 E = S.ExtVectorDecls.end();
369 I != E; ++I) {
370 if ((*I)->getUnderlyingType() == VT)
371 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000372 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000373
Douglas Gregor5476205b2011-06-23 00:49:38 +0000374 return VT; // should never get here (a typedef type should always be found).
375}
376
377static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
378 IdentifierInfo *Member,
379 const Selector &Sel,
380 ASTContext &Context) {
381 if (Member)
382 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
383 return PD;
384 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
385 return OMD;
386
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000387 for (const auto *I : PDecl->protocols()) {
388 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000389 Context))
390 return D;
391 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000392 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000393}
394
395static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
396 IdentifierInfo *Member,
397 const Selector &Sel,
398 ASTContext &Context) {
399 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000400 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000401 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000402 if (Member)
Aaron Ballman83731462014-03-17 16:14:00 +0000403 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000404 GDecl = PD;
405 break;
406 }
407 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000408 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000409 GDecl = OMD;
410 break;
411 }
412 }
413 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000414 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000415 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000416 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000417 if (GDecl)
418 return GDecl;
419 }
420 }
421 return GDecl;
422}
423
424ExprResult
425Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
426 bool IsArrow, SourceLocation OpLoc,
427 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000428 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000429 NamedDecl *FirstQualifierInScope,
430 const DeclarationNameInfo &NameInfo,
431 const TemplateArgumentListInfo *TemplateArgs) {
432 // Even in dependent contexts, try to diagnose base expressions with
433 // obviously wrong types, e.g.:
434 //
435 // T* t;
436 // t.f;
437 //
438 // In Obj-C++, however, the above expression is valid, since it could be
439 // accessing the 'f' property if T is an Obj-C interface. The extra check
440 // allows this, while still reporting an error if T is a struct pointer.
441 if (!IsArrow) {
442 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000443 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000444 PT->getPointeeType()->isRecordType())) {
445 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000446 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000447 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000448 return ExprError();
449 }
450 }
451
452 assert(BaseType->isDependentType() ||
453 NameInfo.getName().isDependentName() ||
454 isDependentScopeSpecifier(SS));
455
456 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
457 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000458 return CXXDependentScopeMemberExpr::Create(
459 Context, BaseExpr, BaseType, IsArrow, OpLoc,
460 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
461 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000462}
463
464/// We know that the given qualified member reference points only to
465/// declarations which do not belong to the static type of the base
466/// expression. Diagnose the problem.
467static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
468 Expr *BaseExpr,
469 QualType BaseType,
470 const CXXScopeSpec &SS,
471 NamedDecl *rep,
472 const DeclarationNameInfo &nameInfo) {
473 // If this is an implicit member access, use a different set of
474 // diagnostics.
475 if (!BaseExpr)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000476 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000477
478 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
479 << SS.getRange() << rep << BaseType;
480}
481
482// Check whether the declarations we found through a nested-name
483// specifier in a member expression are actually members of the base
484// type. The restriction here is:
485//
486// C++ [expr.ref]p2:
487// ... In these cases, the id-expression shall name a
488// member of the class or of one of its base classes.
489//
490// So it's perfectly legitimate for the nested-name specifier to name
491// an unrelated class, and for us to find an overload set including
492// decls from classes which are not superclasses, as long as the decl
493// we actually pick through overload resolution is from a superclass.
494bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
495 QualType BaseType,
496 const CXXScopeSpec &SS,
497 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000498 CXXRecordDecl *BaseRecord =
499 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
500 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000501 // We can't check this yet because the base type is still
502 // dependent.
503 assert(BaseType->isDependentType());
504 return false;
505 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000506
507 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
508 // If this is an implicit member reference and we find a
509 // non-instance member, it's not an error.
510 if (!BaseExpr && !(*I)->isCXXInstanceMember())
511 return false;
512
513 // Note that we use the DC of the decl, not the underlying decl.
514 DeclContext *DC = (*I)->getDeclContext();
515 while (DC->isTransparentContext())
516 DC = DC->getParent();
517
518 if (!DC->isRecord())
519 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000520
Richard Smithd80b2d52012-11-22 00:24:47 +0000521 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
522 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
523 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000524 return false;
525 }
526
527 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
528 R.getRepresentativeDecl(),
529 R.getLookupNameInfo());
530 return true;
531}
532
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000533namespace {
534
535// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000536// FunctionTemplateDecl and are declared in the current record or, for a C++
537// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000538class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
539 public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000540 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
541 : Record(RTy->getDecl()) {}
542
Craig Toppere14c0f82014-03-12 04:55:44 +0000543 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000544 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000545 // Don't accept candidates that cannot be member functions, constants,
546 // variables, or templates.
547 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
548 return false;
549
550 // Accept candidates that occur in the current record.
551 if (Record->containsDecl(ND))
552 return true;
553
554 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
555 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000556 for (const auto &BS : RD->bases()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000557 if (const RecordType *BSTy = dyn_cast_or_null<RecordType>(
Aaron Ballman574705e2014-03-13 15:41:46 +0000558 BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000559 if (BSTy->getDecl()->containsDecl(ND))
560 return true;
561 }
562 }
563 }
564
565 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000566 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000567
568 private:
569 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000570};
571
572}
573
Douglas Gregor5476205b2011-06-23 00:49:38 +0000574static bool
Douglas Gregor3024f072012-04-16 07:05:22 +0000575LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000576 SourceRange BaseRange, const RecordType *RTy,
577 SourceLocation OpLoc, CXXScopeSpec &SS,
578 bool HasTemplateArgs) {
579 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000580 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
581 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000582 diag::err_typecheck_incomplete_tag,
583 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000584 return true;
585
586 if (HasTemplateArgs) {
587 // LookupTemplateName doesn't expect these both to exist simultaneously.
588 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
589
590 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000591 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000592 return false;
593 }
594
595 DeclContext *DC = RDecl;
596 if (SS.isSet()) {
597 // If the member name was a qualified-id, look into the
598 // nested-name-specifier.
599 DC = SemaRef.computeDeclContext(SS, false);
600
601 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
602 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
603 << SS.getRange() << DC;
604 return true;
605 }
606
607 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
608
609 if (!isa<TypeDecl>(DC)) {
610 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
611 << DC << SS.getRange();
612 return true;
613 }
614 }
615
616 // The record definition is complete, now look up the member.
617 SemaRef.LookupQualifiedName(R, DC);
618
619 if (!R.empty())
620 return false;
621
622 // We didn't find anything with the given name, so try to correct
623 // for typos.
624 DeclarationName Name = R.getLookupName();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000625 RecordMemberExprValidatorCCC Validator(RTy);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000626 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000627 R.getLookupKind(), nullptr,
John Thompson2255f2c2014-04-23 12:57:01 +0000628 &SS, Validator,
629 Sema::CTK_ErrorRecovery, DC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000630 R.clear();
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000631 if (Corrected.isResolved() && !Corrected.isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000632 R.setLookupName(Corrected.getCorrection());
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000633 for (TypoCorrection::decl_iterator DI = Corrected.begin(),
634 DIEnd = Corrected.end();
635 DI != DIEnd; ++DI) {
636 R.addDecl(*DI);
637 }
638 R.resolveKind();
639
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000640 // If we're typo-correcting to an overloaded name, we don't yet have enough
641 // information to do overload resolution, so we don't know which previous
642 // declaration to point to.
Richard Smithf9b15102013-08-17 00:46:16 +0000643 if (Corrected.isOverloaded())
Craig Topperc3ec1492014-05-26 06:22:03 +0000644 Corrected.setCorrectionDecl(nullptr);
Richard Smithf9b15102013-08-17 00:46:16 +0000645 bool DroppedSpecifier =
646 Corrected.WillReplaceSpecifier() &&
647 Name.getAsString() == Corrected.getAsString(SemaRef.getLangOpts());
648 SemaRef.diagnoseTypo(Corrected,
649 SemaRef.PDiag(diag::err_no_member_suggest)
650 << Name << DC << DroppedSpecifier << SS.getRange());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000651 }
652
653 return false;
654}
655
656ExprResult
657Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
658 SourceLocation OpLoc, bool IsArrow,
659 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000660 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000661 NamedDecl *FirstQualifierInScope,
662 const DeclarationNameInfo &NameInfo,
663 const TemplateArgumentListInfo *TemplateArgs) {
664 if (BaseType->isDependentType() ||
665 (SS.isSet() && isDependentScopeSpecifier(SS)))
666 return ActOnDependentMemberExpr(Base, BaseType,
667 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000668 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000669 NameInfo, TemplateArgs);
670
671 LookupResult R(*this, NameInfo, LookupMemberName);
672
673 // Implicit member accesses.
674 if (!Base) {
675 QualType RecordTy = BaseType;
676 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
677 if (LookupMemberExprInRecord(*this, R, SourceRange(),
678 RecordTy->getAs<RecordType>(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000679 OpLoc, SS, TemplateArgs != nullptr))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000680 return ExprError();
681
682 // Explicit member accesses.
683 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000684 ExprResult BaseResult = Base;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000685 ExprResult Result =
686 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +0000687 SS, /*ObjCImpDecl*/ nullptr, TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000688
689 if (BaseResult.isInvalid())
690 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000691 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000692
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000693 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000694 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000695
696 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000697 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000698
699 // LookupMemberExpr can modify Base, and thus change BaseType
700 BaseType = Base->getType();
701 }
702
703 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000704 OpLoc, IsArrow, SS, TemplateKWLoc,
705 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000706}
707
708static ExprResult
709BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
710 const CXXScopeSpec &SS, FieldDecl *Field,
711 DeclAccessPair FoundDecl,
712 const DeclarationNameInfo &MemberNameInfo);
713
714ExprResult
715Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
716 SourceLocation loc,
717 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000718 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000719 Expr *baseObjectExpr,
720 SourceLocation opLoc) {
721 // First, build the expression that refers to the base object.
722
723 bool baseObjectIsPointer = false;
724 Qualifiers baseQuals;
725
726 // Case 1: the base of the indirect field is not a field.
727 VarDecl *baseVariable = indirectField->getVarDecl();
728 CXXScopeSpec EmptySS;
729 if (baseVariable) {
730 assert(baseVariable->getType()->isRecordType());
731
732 // In principle we could have a member access expression that
733 // accesses an anonymous struct/union that's a static member of
734 // the base object's class. However, under the current standard,
735 // static data members cannot be anonymous structs or unions.
736 // Supporting this is as easy as building a MemberExpr here.
737 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
738
739 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
740
741 ExprResult result
742 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
743 if (result.isInvalid()) return ExprError();
744
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000745 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000746 baseObjectIsPointer = false;
747 baseQuals = baseObjectExpr->getType().getQualifiers();
748
749 // Case 2: the base of the indirect field is a field and the user
750 // wrote a member expression.
751 } else if (baseObjectExpr) {
752 // The caller provided the base object expression. Determine
753 // whether its a pointer and whether it adds any qualifiers to the
754 // anonymous struct/union fields we're looking into.
755 QualType objectType = baseObjectExpr->getType();
756
757 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
758 baseObjectIsPointer = true;
759 objectType = ptr->getPointeeType();
760 } else {
761 baseObjectIsPointer = false;
762 }
763 baseQuals = objectType.getQualifiers();
764
765 // Case 3: the base of the indirect field is a field and we should
766 // build an implicit member access.
767 } else {
768 // We've found a member of an anonymous struct/union that is
769 // inside a non-anonymous struct/union, so in a well-formed
770 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000771 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000772 if (ThisTy.isNull()) {
773 Diag(loc, diag::err_invalid_member_use_in_static_method)
774 << indirectField->getDeclName();
775 return ExprError();
776 }
777
778 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000779 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000780 baseObjectExpr
781 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
782 baseObjectIsPointer = true;
783 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
784 }
785
786 // Build the implicit member references to the field of the
787 // anonymous struct/union.
788 Expr *result = baseObjectExpr;
789 IndirectFieldDecl::chain_iterator
790 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
791
792 // Build the first member access in the chain with full information.
793 if (!baseVariable) {
794 FieldDecl *field = cast<FieldDecl>(*FI);
795
Douglas Gregor5476205b2011-06-23 00:49:38 +0000796 // Make a nameInfo that properly uses the anonymous name.
797 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
798
799 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
800 EmptySS, field, foundDecl,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000801 memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000802 if (!result)
803 return ExprError();
804
Douglas Gregor5476205b2011-06-23 00:49:38 +0000805 // FIXME: check qualified member access
806 }
807
808 // In all cases, we should now skip the first declaration in the chain.
809 ++FI;
810
811 while (FI != FEnd) {
812 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000813
Douglas Gregor5476205b2011-06-23 00:49:38 +0000814 // FIXME: these are somewhat meaningless
815 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000816 DeclAccessPair fakeFoundDecl =
817 DeclAccessPair::make(field, field->getAccess());
818
Douglas Gregor5476205b2011-06-23 00:49:38 +0000819 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Eli Friedmancccd0642013-07-16 00:01:31 +0000820 (FI == FEnd? SS : EmptySS), field,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000821 fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000822 }
823
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000824 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000825}
826
John McCall5e77d762013-04-16 07:28:30 +0000827static ExprResult
828BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
829 const CXXScopeSpec &SS,
830 MSPropertyDecl *PD,
831 const DeclarationNameInfo &NameInfo) {
832 // Property names are always simple identifiers and therefore never
833 // require any interesting additional storage.
834 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
835 S.Context.PseudoObjectTy, VK_LValue,
836 SS.getWithLocInContext(S.Context),
837 NameInfo.getLoc());
838}
839
Douglas Gregor5476205b2011-06-23 00:49:38 +0000840/// \brief Build a MemberExpr AST node.
Craig Topperc3ec1492014-05-26 06:22:03 +0000841static MemberExpr *
842BuildMemberExpr(Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
843 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
844 ValueDecl *Member, DeclAccessPair FoundDecl,
845 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
846 ExprValueKind VK, ExprObjectKind OK,
847 const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000848 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedmanfa0df832012-02-02 03:46:19 +0000849 MemberExpr *E =
850 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
851 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
852 TemplateArgs, Ty, VK, OK);
853 SemaRef.MarkMemberReferenced(E);
854 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000855}
856
857ExprResult
858Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
859 SourceLocation OpLoc, bool IsArrow,
860 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000861 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000862 NamedDecl *FirstQualifierInScope,
863 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000864 const TemplateArgumentListInfo *TemplateArgs,
865 bool SuppressQualifierCheck,
866 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000867 QualType BaseType = BaseExprType;
868 if (IsArrow) {
869 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000870 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000871 }
872 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000873
874 LambdaScopeInfo *const CurLSI = getCurLambda();
875 // If this is an implicit member reference and the overloaded
876 // name refers to both static and non-static member functions
877 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
878 // check if we should/can capture 'this'...
879 // Keep this example in mind:
880 // struct X {
881 // void f(int) { }
882 // static void f(double) { }
883 //
884 // int g() {
885 // auto L = [=](auto a) {
886 // return [](int i) {
887 // return [=](auto b) {
888 // f(b);
889 // //f(decltype(a){});
890 // };
891 // };
892 // };
893 // auto M = L(0.0);
894 // auto N = M(3);
895 // N(5.32); // OK, must not error.
896 // return 0;
897 // }
898 // };
899 //
900 if (!BaseExpr && CurLSI) {
901 SourceLocation Loc = R.getNameLoc();
902 if (SS.getRange().isValid())
903 Loc = SS.getRange().getBegin();
904 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
905 // If the enclosing function is not dependent, then this lambda is
906 // capture ready, so if we can capture this, do so.
907 if (!EnclosingFunctionCtx->isDependentContext()) {
908 // If the current lambda and all enclosing lambdas can capture 'this' -
909 // then go ahead and capture 'this' (since our unresolved overload set
910 // contains both static and non-static member functions).
911 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
912 CheckCXXThisCapture(Loc);
913 } else if (CurContext->isDependentContext()) {
914 // ... since this is an implicit member reference, that might potentially
915 // involve a 'this' capture, mark 'this' for potential capture in
916 // enclosing lambdas.
917 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
918 CurLSI->addPotentialThisCapture(Loc);
919 }
920 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000921 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
922 DeclarationName MemberName = MemberNameInfo.getName();
923 SourceLocation MemberLoc = MemberNameInfo.getLoc();
924
925 if (R.isAmbiguous())
926 return ExprError();
927
928 if (R.empty()) {
929 // Rederive where we looked up.
930 DeclContext *DC = (SS.isSet()
931 ? computeDeclContext(SS, false)
932 : BaseType->getAs<RecordType>()->getDecl());
933
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000934 if (ExtraArgs) {
935 ExprResult RetryExpr;
936 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000937 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000938 ParsedType ObjectType;
939 bool MayBePseudoDestructor = false;
940 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
941 OpLoc, tok::arrow, ObjectType,
942 MayBePseudoDestructor);
943 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
944 CXXScopeSpec TempSS(SS);
945 RetryExpr = ActOnMemberAccessExpr(
946 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
947 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
948 ExtraArgs->HasTrailingLParen);
949 }
950 if (Trap.hasErrorOccurred())
951 RetryExpr = ExprError();
952 }
953 if (RetryExpr.isUsable()) {
954 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
955 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
956 return RetryExpr;
957 }
958 }
959
Douglas Gregor5476205b2011-06-23 00:49:38 +0000960 Diag(R.getNameLoc(), diag::err_no_member)
961 << MemberName << DC
962 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
963 return ExprError();
964 }
965
966 // Diagnose lookups that find only declarations from a non-base
967 // type. This is possible for either qualified lookups (which may
968 // have been qualified with an unrelated type) or implicit member
969 // expressions (which were found with unqualified lookup and thus
970 // may have come from an enclosing scope). Note that it's okay for
971 // lookup to find declarations from a non-base type as long as those
972 // aren't the ones picked by overload resolution.
973 if ((SS.isSet() || !BaseExpr ||
974 (isa<CXXThisExpr>(BaseExpr) &&
975 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
976 !SuppressQualifierCheck &&
977 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
978 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +0000979
Douglas Gregor5476205b2011-06-23 00:49:38 +0000980 // Construct an unresolved result if we in fact got an unresolved
981 // result.
982 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
983 // Suppress any lookup-related diagnostics; we'll do these when we
984 // pick a member.
985 R.suppressDiagnostics();
986
987 UnresolvedMemberExpr *MemExpr
988 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
989 BaseExpr, BaseExprType,
990 IsArrow, OpLoc,
991 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000992 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000993 TemplateArgs, R.begin(), R.end());
994
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000995 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000996 }
997
998 assert(R.isSingleResult());
999 DeclAccessPair FoundDecl = R.begin().getPair();
1000 NamedDecl *MemberDecl = R.getFoundDecl();
1001
1002 // FIXME: diagnose the presence of template arguments now.
1003
1004 // If the decl being referenced had an error, return an error for this
1005 // sub-expr without emitting another error, in order to avoid cascading
1006 // error cases.
1007 if (MemberDecl->isInvalidDecl())
1008 return ExprError();
1009
1010 // Handle the implicit-member-access case.
1011 if (!BaseExpr) {
1012 // If this is not an instance member, convert to a non-member access.
1013 if (!MemberDecl->isCXXInstanceMember())
1014 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1015
1016 SourceLocation Loc = R.getNameLoc();
1017 if (SS.getRange().isValid())
1018 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001019 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001020 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1021 }
1022
1023 bool ShouldCheckUse = true;
1024 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1025 // Don't diagnose the use of a virtual member function unless it's
1026 // explicitly qualified.
1027 if (MD->isVirtual() && !SS.isSet())
1028 ShouldCheckUse = false;
1029 }
1030
1031 // Check the use of this member.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001032 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001033 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001034
Douglas Gregor5476205b2011-06-23 00:49:38 +00001035 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1036 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
1037 SS, FD, FoundDecl, MemberNameInfo);
1038
John McCall5e77d762013-04-16 07:28:30 +00001039 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1040 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1041 MemberNameInfo);
1042
Douglas Gregor5476205b2011-06-23 00:49:38 +00001043 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1044 // We may have found a field within an anonymous union or struct
1045 // (C++ [class.union]).
1046 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001047 FoundDecl, BaseExpr,
1048 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001049
1050 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001051 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1052 Var, FoundDecl, MemberNameInfo,
1053 Var->getType().getNonReferenceType(), VK_LValue,
1054 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001055 }
1056
1057 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1058 ExprValueKind valueKind;
1059 QualType type;
1060 if (MemberFn->isInstance()) {
1061 valueKind = VK_RValue;
1062 type = Context.BoundMemberTy;
1063 } else {
1064 valueKind = VK_LValue;
1065 type = MemberFn->getType();
1066 }
1067
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001068 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1069 MemberFn, FoundDecl, MemberNameInfo, type, valueKind,
1070 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001071 }
1072 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1073
1074 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001075 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1076 Enum, FoundDecl, MemberNameInfo, Enum->getType(),
1077 VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001078 }
1079
Douglas Gregor5476205b2011-06-23 00:49:38 +00001080 // We found something that we didn't expect. Complain.
1081 if (isa<TypeDecl>(MemberDecl))
1082 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1083 << MemberName << BaseType << int(IsArrow);
1084 else
1085 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1086 << MemberName << BaseType << int(IsArrow);
1087
1088 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1089 << MemberName;
1090 R.suppressDiagnostics();
1091 return ExprError();
1092}
1093
1094/// Given that normal member access failed on the given expression,
1095/// and given that the expression's type involves builtin-id or
1096/// builtin-Class, decide whether substituting in the redefinition
1097/// types would be profitable. The redefinition type is whatever
1098/// this translation unit tried to typedef to id/Class; we store
1099/// it to the side and then re-use it in places like this.
1100static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1101 const ObjCObjectPointerType *opty
1102 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1103 if (!opty) return false;
1104
1105 const ObjCObjectType *ty = opty->getObjectType();
1106
1107 QualType redef;
1108 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001109 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001110 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001111 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001112 } else {
1113 return false;
1114 }
1115
1116 // Do the substitution as long as the redefinition type isn't just a
1117 // possibly-qualified pointer to builtin-id or builtin-Class again.
1118 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001119 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001120 return false;
1121
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001122 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001123 return true;
1124}
1125
John McCall50a2c2c2011-10-11 23:14:30 +00001126static bool isRecordType(QualType T) {
1127 return T->isRecordType();
1128}
1129static bool isPointerToRecordType(QualType T) {
1130 if (const PointerType *PT = T->getAs<PointerType>())
1131 return PT->getPointeeType()->isRecordType();
1132 return false;
1133}
1134
Richard Smithcab9a7d2011-10-26 19:06:56 +00001135/// Perform conversions on the LHS of a member access expression.
1136ExprResult
1137Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001138 if (IsArrow && !Base->getType()->isFunctionType())
1139 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001140
Eli Friedman9a766c42012-01-13 02:20:01 +00001141 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001142}
1143
Douglas Gregor5476205b2011-06-23 00:49:38 +00001144/// Look up the given member of the given non-type-dependent
1145/// expression. This can return in one of two ways:
1146/// * If it returns a sentinel null-but-valid result, the caller will
1147/// assume that lookup was performed and the results written into
1148/// the provided structure. It will take over from there.
1149/// * Otherwise, the returned expression will be produced in place of
1150/// an ordinary member expression.
1151///
1152/// The ObjCImpDecl bit is a gross hack that will need to be properly
1153/// fixed for ObjC++.
1154ExprResult
1155Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1156 bool &IsArrow, SourceLocation OpLoc,
1157 CXXScopeSpec &SS,
1158 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1159 assert(BaseExpr.get() && "no base expression");
1160
1161 // Perform default conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001162 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001163 if (BaseExpr.isInvalid())
1164 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001165
Douglas Gregor5476205b2011-06-23 00:49:38 +00001166 QualType BaseType = BaseExpr.get()->getType();
1167 assert(!BaseType->isDependentType());
1168
1169 DeclarationName MemberName = R.getLookupName();
1170 SourceLocation MemberLoc = R.getNameLoc();
1171
1172 // For later type-checking purposes, turn arrow accesses into dot
1173 // accesses. The only access type we support that doesn't follow
1174 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1175 // and those never use arrows, so this is unaffected.
1176 if (IsArrow) {
1177 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1178 BaseType = Ptr->getPointeeType();
1179 else if (const ObjCObjectPointerType *Ptr
1180 = BaseType->getAs<ObjCObjectPointerType>())
1181 BaseType = Ptr->getPointeeType();
1182 else if (BaseType->isRecordType()) {
1183 // Recover from arrow accesses to records, e.g.:
1184 // struct MyRecord foo;
1185 // foo->bar
1186 // This is actually well-formed in C++ if MyRecord has an
1187 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001188 // by now--or a diagnostic message already issued if a problem
1189 // was encountered while looking for the overloaded operator->.
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001190 if (!getLangOpts().CPlusPlus) {
1191 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1192 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1193 << FixItHint::CreateReplacement(OpLoc, ".");
1194 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001195 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001196 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001197 goto fail;
1198 } else {
1199 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1200 << BaseType << BaseExpr.get()->getSourceRange();
1201 return ExprError();
1202 }
1203 }
1204
1205 // Handle field access to simple records.
1206 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1207 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1208 RTy, OpLoc, SS, HasTemplateArgs))
1209 return ExprError();
1210
1211 // Returning valid-but-null is how we indicate to the caller that
1212 // the lookup result was filled in.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001213 return ExprResult((Expr *)nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001214 }
1215
1216 // Handle ivar access to Objective-C objects.
1217 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001218 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregor12340e52011-10-09 23:22:49 +00001219 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1220 << 1 << SS.getScopeRep()
1221 << FixItHint::CreateRemoval(SS.getRange());
1222 SS.clear();
1223 }
1224
Douglas Gregor5476205b2011-06-23 00:49:38 +00001225 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1226
1227 // There are three cases for the base type:
1228 // - builtin id (qualified or unqualified)
1229 // - builtin Class (qualified or unqualified)
1230 // - an interface
1231 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1232 if (!IDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001233 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001234 (OTy->isObjCId() || OTy->isObjCClass()))
1235 goto fail;
1236 // There's an implicit 'isa' ivar on all objects.
1237 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001238 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001239 if (OTy->isObjCId() && Member->isStr("isa"))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001240 return new (Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1241 OpLoc, Context.getObjCClassType());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001242 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1243 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1244 ObjCImpDecl, HasTemplateArgs);
1245 goto fail;
1246 }
Fariborz Jahanian25cb4ac2012-06-21 21:35:15 +00001247
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001248 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1249 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001250 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001251
1252 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001253 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1254
1255 if (!IV) {
1256 // Attempt to correct for typos in ivar names.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001257 DeclFilterCCC<ObjCIvarDecl> Validator;
1258 Validator.IsObjCIvarLookup = IsArrow;
1259 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001260 LookupMemberName, nullptr,
1261 nullptr, Validator,
1262 CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001263 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smithf9b15102013-08-17 00:46:16 +00001264 diagnoseTypo(Corrected,
1265 PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1266 << IDecl->getDeclName() << MemberName);
1267
Ted Kremenek679b4782012-03-17 00:53:39 +00001268 // Figure out the class that declares the ivar.
1269 assert(!ClassDeclared);
1270 Decl *D = cast<Decl>(IV->getDeclContext());
1271 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1272 D = CAT->getClassInterface();
1273 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001274 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001275 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1276 Diag(MemberLoc,
1277 diag::err_property_found_suggest)
1278 << Member << BaseExpr.get()->getType()
1279 << FixItHint::CreateReplacement(OpLoc, ".");
1280 return ExprError();
1281 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001282
1283 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1284 << IDecl->getDeclName() << MemberName
1285 << BaseExpr.get()->getSourceRange();
1286 return ExprError();
1287 }
1288 }
Ted Kremenek679b4782012-03-17 00:53:39 +00001289
1290 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001291
1292 // If the decl being referenced had an error, return an error for this
1293 // sub-expr without emitting another error, in order to avoid cascading
1294 // error cases.
1295 if (IV->isInvalidDecl())
1296 return ExprError();
1297
1298 // Check whether we can reference this field.
1299 if (DiagnoseUseOfDecl(IV, MemberLoc))
1300 return ExprError();
1301 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1302 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001303 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001304 if (ObjCMethodDecl *MD = getCurMethodDecl())
1305 ClassOfMethodDecl = MD->getClassInterface();
1306 else if (ObjCImpDecl && getCurFunctionDecl()) {
1307 // Case of a c-function declared inside an objc implementation.
1308 // FIXME: For a c-style function nested inside an objc implementation
1309 // class, there is no implementation context available, so we pass
1310 // down the context as argument to this routine. Ideally, this context
1311 // need be passed down in the AST node and somehow calculated from the
1312 // AST for a function decl.
1313 if (ObjCImplementationDecl *IMPD =
1314 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1315 ClassOfMethodDecl = IMPD->getClassInterface();
1316 else if (ObjCCategoryImplDecl* CatImplClass =
1317 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1318 ClassOfMethodDecl = CatImplClass->getClassInterface();
1319 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001320 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001321 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1322 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1323 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1324 Diag(MemberLoc, diag::error_private_ivar_access)
1325 << IV->getDeclName();
1326 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1327 // @protected
1328 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001329 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001330 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001331 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001332 bool warn = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001333 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001334 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1335 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1336 if (UO->getOpcode() == UO_Deref)
1337 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1338
1339 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001340 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001341 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001342 warn = false;
1343 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001344 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001345 if (warn) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001346 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1347 ObjCMethodFamily MF = MD->getMethodFamily();
1348 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001349 MF != OMF_finalize &&
1350 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001351 }
1352 if (warn)
1353 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1354 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001355
1356 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001357 MemberLoc, OpLoc,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001358 BaseExpr.get(),
Jordan Rose657b5f42012-09-28 22:21:35 +00001359 IsArrow);
1360
1361 if (getLangOpts().ObjCAutoRefCount) {
1362 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1363 DiagnosticsEngine::Level Level =
1364 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1365 MemberLoc);
1366 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00001367 recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001368 }
1369 }
1370
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001371 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001372 }
1373
1374 // Objective-C property access.
1375 const ObjCObjectPointerType *OPT;
1376 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001377 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregor12340e52011-10-09 23:22:49 +00001378 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1379 << 0 << SS.getScopeRep()
1380 << FixItHint::CreateRemoval(SS.getRange());
1381 SS.clear();
1382 }
1383
Douglas Gregor5476205b2011-06-23 00:49:38 +00001384 // This actually uses the base as an r-value.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001385 BaseExpr = DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001386 if (BaseExpr.isInvalid())
1387 return ExprError();
1388
1389 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1390
1391 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1392
1393 const ObjCObjectType *OT = OPT->getObjectType();
1394
1395 // id, with and without qualifiers.
1396 if (OT->isObjCId()) {
1397 // Check protocols on qualified interfaces.
1398 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1399 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1400 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1401 // Check the use of this declaration
1402 if (DiagnoseUseOfDecl(PD, MemberLoc))
1403 return ExprError();
1404
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001405 return new (Context)
1406 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1407 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001408 }
1409
1410 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1411 // Check the use of this method.
1412 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1413 return ExprError();
1414 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001415 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1416 PP.getSelectorTable(),
1417 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001418 ObjCMethodDecl *SMD = nullptr;
1419 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1420 /*Property id*/nullptr,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001421 SetterSel, Context))
1422 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001423
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001424 return new (Context)
1425 ObjCPropertyRefExpr(OMD, SMD, Context.PseudoObjectTy, VK_LValue,
1426 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001427 }
1428 }
1429 // Use of id.member can only be for a property reference. Do not
1430 // use the 'id' redefinition in this case.
1431 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1432 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1433 ObjCImpDecl, HasTemplateArgs);
1434
1435 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1436 << MemberName << BaseType);
1437 }
1438
1439 // 'Class', unqualified only.
1440 if (OT->isObjCClass()) {
1441 // Only works in a method declaration (??!).
1442 ObjCMethodDecl *MD = getCurMethodDecl();
1443 if (!MD) {
1444 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1445 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1446 ObjCImpDecl, HasTemplateArgs);
1447
1448 goto fail;
1449 }
1450
1451 // Also must look for a getter name which uses property syntax.
1452 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1453 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1454 ObjCMethodDecl *Getter;
1455 if ((Getter = IFace->lookupClassMethod(Sel))) {
1456 // Check the use of this method.
1457 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1458 return ExprError();
1459 } else
1460 Getter = IFace->lookupPrivateMethod(Sel, false);
1461 // If we found a getter then this may be a valid dot-reference, we
1462 // will look for the matching setter, in case it is needed.
1463 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001464 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1465 PP.getSelectorTable(),
1466 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001467 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1468 if (!Setter) {
1469 // If this reference is in an @implementation, also check for 'private'
1470 // methods.
1471 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1472 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001473
1474 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1475 return ExprError();
1476
1477 if (Getter || Setter) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001478 return new (Context) ObjCPropertyRefExpr(
1479 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1480 MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001481 }
1482
1483 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1484 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1485 ObjCImpDecl, HasTemplateArgs);
1486
1487 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1488 << MemberName << BaseType);
1489 }
1490
1491 // Normal property access.
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001492 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1493 MemberName, MemberLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001494 SourceLocation(), QualType(), false);
1495 }
1496
1497 // Handle 'field access' to vectors, such as 'V.xx'.
1498 if (BaseType->isExtVectorType()) {
1499 // FIXME: this expr should store IsArrow.
1500 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1501 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1502 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1503 Member, MemberLoc);
1504 if (ret.isNull())
1505 return ExprError();
1506
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001507 return new (Context)
1508 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001509 }
1510
1511 // Adjust builtin-sel to the appropriate redefinition type if that's
1512 // not just a pointer to builtin-sel again.
1513 if (IsArrow &&
1514 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor97673472011-08-11 20:58:55 +00001515 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001516 BaseExpr = ImpCastExprToType(BaseExpr.get(),
Douglas Gregor97673472011-08-11 20:58:55 +00001517 Context.getObjCSelRedefinitionType(),
Douglas Gregor5476205b2011-06-23 00:49:38 +00001518 CK_BitCast);
1519 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1520 ObjCImpDecl, HasTemplateArgs);
1521 }
1522
1523 // Failure cases.
1524 fail:
1525
1526 // Recover from dot accesses to pointers, e.g.:
1527 // type *foo;
1528 // foo.bar
1529 // This is actually well-formed in two cases:
1530 // - 'type' is an Objective C type
1531 // - 'bar' is a pseudo-destructor name which happens to refer to
1532 // the appropriate pointer type
1533 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1534 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1535 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1536 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1537 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1538 << FixItHint::CreateReplacement(OpLoc, "->");
1539
1540 // Recurse as an -> access.
1541 IsArrow = true;
1542 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1543 ObjCImpDecl, HasTemplateArgs);
1544 }
1545 }
1546
1547 // If the user is trying to apply -> or . to a function name, it's probably
1548 // because they forgot parentheses to call that function.
John McCall50a2c2c2011-10-11 23:14:30 +00001549 if (tryToRecoverWithCall(BaseExpr,
1550 PDiag(diag::err_member_reference_needs_call),
1551 /*complain*/ false,
Eli Friedman9a766c42012-01-13 02:20:01 +00001552 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001553 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001554 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001555 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.get());
John McCall50a2c2c2011-10-11 23:14:30 +00001556 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1557 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001558 }
1559
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +00001560 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001561 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001562
1563 return ExprError();
1564}
1565
1566/// The main callback when the parser finds something like
1567/// expression . [nested-name-specifier] identifier
1568/// expression -> [nested-name-specifier] identifier
1569/// where 'identifier' encompasses a fairly broad spectrum of
1570/// possibilities, including destructor and operator references.
1571///
1572/// \param OpKind either tok::arrow or tok::period
1573/// \param HasTrailingLParen whether the next token is '(', which
1574/// is used to diagnose mis-uses of special members that can
1575/// only be called
James Dennett2a4d13c2012-06-15 07:13:21 +00001576/// \param ObjCImpDecl the current Objective-C \@implementation
1577/// decl; this is an ugly hack around the fact that Objective-C
1578/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001579ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1580 SourceLocation OpLoc,
1581 tok::TokenKind OpKind,
1582 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001583 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001584 UnqualifiedId &Id,
1585 Decl *ObjCImpDecl,
1586 bool HasTrailingLParen) {
1587 if (SS.isSet() && SS.isInvalid())
1588 return ExprError();
1589
1590 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001591 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001592 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1593 Diag(Id.getSourceRange().getBegin(),
1594 diag::ext_ms_explicit_constructor_call);
1595
1596 TemplateArgumentListInfo TemplateArgsBuffer;
1597
1598 // Decompose the name into its component parts.
1599 DeclarationNameInfo NameInfo;
1600 const TemplateArgumentListInfo *TemplateArgs;
1601 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1602 NameInfo, TemplateArgs);
1603
1604 DeclarationName Name = NameInfo.getName();
1605 bool IsArrow = (OpKind == tok::arrow);
1606
1607 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001608 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001609
1610 // This is a postfix expression, so get rid of ParenListExprs.
1611 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1612 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001613 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001614
1615 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1616 isDependentScopeSpecifier(SS)) {
1617 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1618 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001619 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001620 NameInfo, TemplateArgs);
1621 } else {
1622 LookupResult R(*this, NameInfo, LookupMemberName);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001623 ExprResult BaseResult = Base;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001624 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001625 SS, ObjCImpDecl, TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001626 if (BaseResult.isInvalid())
1627 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001628 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001629
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001630 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001631 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001632
1633 if (Result.get()) {
1634 // The only way a reference to a destructor can be used is to
1635 // immediately call it, which falls into this case. If the
1636 // next token is not a '(', produce a diagnostic and build the
1637 // call now.
1638 if (!HasTrailingLParen &&
1639 Id.getKind() == UnqualifiedId::IK_DestructorName)
1640 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1641
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001642 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001643 }
1644
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001645 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor5476205b2011-06-23 00:49:38 +00001646 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001647 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001648 FirstQualifierInScope, R, TemplateArgs,
1649 false, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001650 }
1651
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001652 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001653}
1654
1655static ExprResult
1656BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1657 const CXXScopeSpec &SS, FieldDecl *Field,
1658 DeclAccessPair FoundDecl,
1659 const DeclarationNameInfo &MemberNameInfo) {
1660 // x.a is an l-value if 'a' has a reference type. Otherwise:
1661 // x.a is an l-value/x-value/pr-value if the base is (and note
1662 // that *x is always an l-value), except that if the base isn't
1663 // an ordinary object then we must have an rvalue.
1664 ExprValueKind VK = VK_LValue;
1665 ExprObjectKind OK = OK_Ordinary;
1666 if (!IsArrow) {
1667 if (BaseExpr->getObjectKind() == OK_Ordinary)
1668 VK = BaseExpr->getValueKind();
1669 else
1670 VK = VK_RValue;
1671 }
1672 if (VK != VK_RValue && Field->isBitField())
1673 OK = OK_BitField;
1674
1675 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1676 QualType MemberType = Field->getType();
1677 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1678 MemberType = Ref->getPointeeType();
1679 VK = VK_LValue;
1680 } else {
1681 QualType BaseType = BaseExpr->getType();
1682 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001683
Douglas Gregor5476205b2011-06-23 00:49:38 +00001684 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001685
Douglas Gregor5476205b2011-06-23 00:49:38 +00001686 // GC attributes are never picked up by members.
1687 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001688
Douglas Gregor5476205b2011-06-23 00:49:38 +00001689 // CVR attributes from the base are picked up by members,
1690 // except that 'mutable' members don't pick up 'const'.
1691 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001692
Douglas Gregor5476205b2011-06-23 00:49:38 +00001693 Qualifiers MemberQuals
1694 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001695
Douglas Gregor5476205b2011-06-23 00:49:38 +00001696 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001697
1698
Douglas Gregor5476205b2011-06-23 00:49:38 +00001699 Qualifiers Combined = BaseQuals + MemberQuals;
1700 if (Combined != MemberQuals)
1701 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1702 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001703
Daniel Jasper0baec5492012-06-06 08:32:04 +00001704 S.UnusedPrivateFields.remove(Field);
1705
Douglas Gregor5476205b2011-06-23 00:49:38 +00001706 ExprResult Base =
1707 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1708 FoundDecl, Field);
1709 if (Base.isInvalid())
1710 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001711 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, SS,
1712 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1713 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001714}
1715
1716/// Builds an implicit member access expression. The current context
1717/// is known to be an instance method, and the given unqualified lookup
1718/// set is known to contain only instance members, at least one of which
1719/// is from an appropriate type.
1720ExprResult
1721Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001722 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001723 LookupResult &R,
1724 const TemplateArgumentListInfo *TemplateArgs,
1725 bool IsKnownInstance) {
1726 assert(!R.empty() && !R.isAmbiguous());
1727
1728 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001729
Douglas Gregor5476205b2011-06-23 00:49:38 +00001730 // If this is known to be an instance access, go ahead and build an
1731 // implicit 'this' expression now.
1732 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001733 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001734 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001735
1736 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001737 if (IsKnownInstance) {
1738 SourceLocation Loc = R.getNameLoc();
1739 if (SS.getRange().isValid())
1740 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001741 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001742 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1743 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001744
Douglas Gregor5476205b2011-06-23 00:49:38 +00001745 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1746 /*OpLoc*/ SourceLocation(),
1747 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001748 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001749 /*FirstQualifierInScope*/ nullptr,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001750 R, TemplateArgs);
1751}