blob: dfe63a86d28d2bc16d80264919f7f4e20b5c1ec2 [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//===----------------------------------------------------------------------===//
Kaelyn Takatafe408a72014-10-27 18:07:46 +000013#include "clang/Sema/Overload.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"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "clang/Sema/SemaInternal.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000025
26using namespace clang;
27using namespace sema;
28
Richard Smithd80b2d52012-11-22 00:24:47 +000029typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
Richard Smithd80b2d52012-11-22 00:24:47 +000030
Douglas Gregor5476205b2011-06-23 00:49:38 +000031/// Determines if the given class is provably not derived from all of
32/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000033static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
34 const BaseSet &Bases) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +000035 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
36 return !Bases.count(Base->getCanonicalDecl());
37 };
38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
Douglas Gregor5476205b2011-06-23 00:49:38 +000039}
40
41enum IMAKind {
42 /// The reference is definitely not an instance member access.
43 IMA_Static,
44
45 /// The reference may be an implicit instance member access.
46 IMA_Mixed,
47
Eli Friedman7bda7f72012-01-18 03:53:45 +000048 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000049 /// so, because the context is not an instance method.
50 IMA_Mixed_StaticContext,
51
52 /// The reference may be to an instance member, but it is invalid if
53 /// so, because the context is from an unrelated class.
54 IMA_Mixed_Unrelated,
55
56 /// The reference is definitely an implicit instance member access.
57 IMA_Instance,
58
59 /// The reference may be to an unresolved using declaration.
60 IMA_Unresolved,
61
John McCallf413f5e2013-05-03 00:10:13 +000062 /// The reference is a contextually-permitted abstract member reference.
63 IMA_Abstract,
64
Douglas Gregor5476205b2011-06-23 00:49:38 +000065 /// The reference may be to an unresolved using declaration and the
66 /// context is not an instance method.
67 IMA_Unresolved_StaticContext,
68
Eli Friedman456f0182012-01-20 01:26:23 +000069 // The reference refers to a field which is not a member of the containing
70 // class, which is allowed because we're in C++11 mode and the context is
71 // unevaluated.
72 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000073
Douglas Gregor5476205b2011-06-23 00:49:38 +000074 /// All possible referrents are instance members and the current
75 /// context is not an instance method.
76 IMA_Error_StaticContext,
77
78 /// All possible referrents are instance members of an unrelated
79 /// class.
80 IMA_Error_Unrelated
81};
82
83/// The given lookup names class member(s) and is not being used for
84/// an address-of-member expression. Classify the type of access
85/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000086/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000087/// conservatively answer "yes", in which case some errors will simply
88/// not be caught until template-instantiation.
89static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +000090 const LookupResult &R) {
91 assert(!R.empty() && (*R.begin())->isCXXClassMember());
92
93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
94
Douglas Gregor3024f072012-04-16 07:05:22 +000095 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +000097
98 if (R.isUnresolvableResult())
99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
100
101 // Collect all the declaring classes of instance members we find.
102 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000103 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000104 BaseSet Classes;
Reid Kleckner077fe122015-10-20 18:12:08 +0000105 for (NamedDecl *D : R) {
106 // Look through any using decls.
107 D = D->getUnderlyingDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000108
109 if (D->isCXXInstanceMember()) {
Benjamin Kramera008d3a2015-04-10 11:37:55 +0000110 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
111 isa<IndirectFieldDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000112
113 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
114 Classes.insert(R->getCanonicalDecl());
Reid Kleckner077fe122015-10-20 18:12:08 +0000115 } else
Douglas Gregor5476205b2011-06-23 00:49:38 +0000116 hasNonInstance = true;
117 }
118
119 // If we didn't find any instance members, it can't be an implicit
120 // member reference.
121 if (Classes.empty())
122 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000123
124 // C++11 [expr.prim.general]p12:
125 // An id-expression that denotes a non-static data member or non-static
126 // member function of a class can only be used:
127 // (...)
128 // - if that id-expression denotes a non-static data member and it
129 // appears in an unevaluated operand.
130 //
131 // This rule is specific to C++11. However, we also permit this form
132 // in unevaluated inline assembly operands, like the operand to a SIZE.
133 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
134 assert(!AbstractInstanceResult);
135 switch (SemaRef.ExprEvalContexts.back().Context) {
136 case Sema::Unevaluated:
137 if (isField && SemaRef.getLangOpts().CPlusPlus11)
138 AbstractInstanceResult = IMA_Field_Uneval_Context;
139 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000140
John McCallf413f5e2013-05-03 00:10:13 +0000141 case Sema::UnevaluatedAbstract:
142 AbstractInstanceResult = IMA_Abstract;
143 break;
144
145 case Sema::ConstantEvaluated:
146 case Sema::PotentiallyEvaluated:
147 case Sema::PotentiallyEvaluatedIfUsed:
148 break;
Richard Smitheae99682012-02-25 10:04:07 +0000149 }
150
Douglas Gregor5476205b2011-06-23 00:49:38 +0000151 // If the current context is not an instance method, it can't be
152 // an implicit member reference.
153 if (isStaticContext) {
154 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000155 return IMA_Mixed_StaticContext;
156
John McCallf413f5e2013-05-03 00:10:13 +0000157 return AbstractInstanceResult ? AbstractInstanceResult
158 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000159 }
160
161 CXXRecordDecl *contextClass;
162 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
163 contextClass = MD->getParent()->getCanonicalDecl();
164 else
165 contextClass = cast<CXXRecordDecl>(DC);
166
167 // [class.mfct.non-static]p3:
168 // ...is used in the body of a non-static member function of class X,
169 // if name lookup (3.4.1) resolves the name in the id-expression to a
170 // non-static non-type member of some class C [...]
171 // ...if C is not X or a base class of X, the class member access expression
172 // is ill-formed.
173 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000174 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000175 R.getNamingClass()->getCanonicalDecl()) {
176 // If the naming class is not the current context, this was a qualified
177 // member name lookup, and it's sufficient to check that we have the naming
178 // class as a base class.
179 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000180 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000181 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000182
183 // If we can prove that the current context is unrelated to all the
184 // declaring classes, it can't be an implicit member reference (in
185 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000186 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000187 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000188 AbstractInstanceResult ? AbstractInstanceResult :
189 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000190
191 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
192}
193
194/// Diagnose a reference to a field with no object available.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000195static void diagnoseInstanceReference(Sema &SemaRef,
196 const CXXScopeSpec &SS,
197 NamedDecl *Rep,
198 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000199 SourceLocation Loc = nameInfo.getLoc();
200 SourceRange Range(Loc);
201 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000202
Reid Klecknerae628962014-12-18 00:42:51 +0000203 // Look through using shadow decls and aliases.
204 Rep = Rep->getUnderlyingDecl();
205
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000206 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
Richard Smithfa0a1f52012-04-05 01:13:04 +0000207 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000208 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000209 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
210
211 bool InStaticMethod = Method && Method->isStatic();
212 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
213
214 if (IsField && InStaticMethod)
215 // "invalid use of member 'x' in static member function"
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000216 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000217 << Range << nameInfo.getName();
218 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
219 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
220 // Unqualified lookup in a non-static member function found a member of an
221 // enclosing class.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000222 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
223 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000224 else if (IsField)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
226 << nameInfo.getName() << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000227 else
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000228 SemaRef.Diag(Loc, diag::err_member_call_without_object)
229 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000230}
231
232/// Builds an expression which might be an implicit member expression.
233ExprResult
234Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000235 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000236 LookupResult &R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000237 const TemplateArgumentListInfo *TemplateArgs,
238 const Scope *S) {
Reid Klecknerae628962014-12-18 00:42:51 +0000239 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000240 case IMA_Instance:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000241 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000242
243 case IMA_Mixed:
244 case IMA_Mixed_Unrelated:
245 case IMA_Unresolved:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000246 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
247 S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000248
Richard Smith2a986112012-02-25 10:20:59 +0000249 case IMA_Field_Uneval_Context:
250 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
251 << R.getLookupNameInfo().getName();
252 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000253 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000254 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000255 case IMA_Mixed_StaticContext:
256 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000257 if (TemplateArgs || TemplateKWLoc.isValid())
258 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000259 return BuildDeclarationNameExpr(SS, R, false);
260
261 case IMA_Error_StaticContext:
262 case IMA_Error_Unrelated:
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000263 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000264 R.getLookupNameInfo());
265 return ExprError();
266 }
267
268 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000269}
270
271/// Check an ext-vector component access expression.
272///
273/// VK should be set in advance to the value kind of the base
274/// expression.
275static QualType
276CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
277 SourceLocation OpLoc, const IdentifierInfo *CompName,
278 SourceLocation CompLoc) {
279 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
280 // see FIXME there.
281 //
282 // FIXME: This logic can be greatly simplified by splitting it along
283 // halving/not halving and reworking the component checking.
284 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
285
286 // The vector accessor can't exceed the number of elements.
287 const char *compStr = CompName->getNameStart();
288
289 // This flag determines whether or not the component is one of the four
290 // special names that indicate a subset of exactly half the elements are
291 // to be selected.
292 bool HalvingSwizzle = false;
293
294 // This flag determines whether or not CompName has an 's' char prefix,
295 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000296 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000297
298 bool HasRepeated = false;
299 bool HasIndex[16] = {};
300
301 int Idx;
302
303 // Check that we've found one of the special components, or that the component
304 // names must come from the same set.
305 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
306 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
307 HalvingSwizzle = true;
308 } else if (!HexSwizzle &&
309 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
310 do {
311 if (HasIndex[Idx]) HasRepeated = true;
312 HasIndex[Idx] = true;
313 compStr++;
314 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
315 } else {
316 if (HexSwizzle) compStr++;
317 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
318 if (HasIndex[Idx]) HasRepeated = true;
319 HasIndex[Idx] = true;
320 compStr++;
321 }
322 }
323
324 if (!HalvingSwizzle && *compStr) {
325 // We didn't get to the end of the string. This means the component names
326 // didn't come from the same set *or* we encountered an illegal name.
327 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000328 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000329 return QualType();
330 }
331
332 // Ensure no component accessor exceeds the width of the vector type it
333 // operates on.
334 if (!HalvingSwizzle) {
335 compStr = CompName->getNameStart();
336
337 if (HexSwizzle)
338 compStr++;
339
340 while (*compStr) {
341 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
342 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
343 << baseType << SourceRange(CompLoc);
344 return QualType();
345 }
346 }
347 }
348
349 // The component accessor looks fine - now we need to compute the actual type.
350 // The vector type is implied by the component accessor. For example,
351 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
352 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
353 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
354 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
355 : CompName->getLength();
356 if (HexSwizzle)
357 CompSize--;
358
359 if (CompSize == 1)
360 return vecType->getElementType();
361
362 if (HasRepeated) VK = VK_RValue;
363
364 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
365 // Now look up the TypeDefDecl from the vector type. Without this,
366 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000367 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000368 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000369 E = S.ExtVectorDecls.end();
370 I != E; ++I) {
371 if ((*I)->getUnderlyingType() == VT)
372 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000373 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000374
Douglas Gregor5476205b2011-06-23 00:49:38 +0000375 return VT; // should never get here (a typedef type should always be found).
376}
377
378static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
379 IdentifierInfo *Member,
380 const Selector &Sel,
381 ASTContext &Context) {
382 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000383 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
384 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000385 return PD;
386 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
387 return OMD;
388
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000389 for (const auto *I : PDecl->protocols()) {
390 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000391 Context))
392 return D;
393 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000394 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000395}
396
397static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
398 IdentifierInfo *Member,
399 const Selector &Sel,
400 ASTContext &Context) {
401 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000402 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000403 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000404 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000405 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
406 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000407 GDecl = PD;
408 break;
409 }
410 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000411 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000412 GDecl = OMD;
413 break;
414 }
415 }
416 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000417 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000418 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000419 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000420 if (GDecl)
421 return GDecl;
422 }
423 }
424 return GDecl;
425}
426
427ExprResult
428Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
429 bool IsArrow, SourceLocation OpLoc,
430 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000431 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000432 NamedDecl *FirstQualifierInScope,
433 const DeclarationNameInfo &NameInfo,
434 const TemplateArgumentListInfo *TemplateArgs) {
435 // Even in dependent contexts, try to diagnose base expressions with
436 // obviously wrong types, e.g.:
437 //
438 // T* t;
439 // t.f;
440 //
441 // In Obj-C++, however, the above expression is valid, since it could be
442 // accessing the 'f' property if T is an Obj-C interface. The extra check
443 // allows this, while still reporting an error if T is a struct pointer.
444 if (!IsArrow) {
445 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000446 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000447 PT->getPointeeType()->isRecordType())) {
448 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000449 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000450 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000451 return ExprError();
452 }
453 }
454
455 assert(BaseType->isDependentType() ||
456 NameInfo.getName().isDependentName() ||
457 isDependentScopeSpecifier(SS));
458
459 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
460 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000461 return CXXDependentScopeMemberExpr::Create(
462 Context, BaseExpr, BaseType, IsArrow, OpLoc,
463 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
464 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000465}
466
467/// We know that the given qualified member reference points only to
468/// declarations which do not belong to the static type of the base
469/// expression. Diagnose the problem.
470static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
471 Expr *BaseExpr,
472 QualType BaseType,
473 const CXXScopeSpec &SS,
474 NamedDecl *rep,
475 const DeclarationNameInfo &nameInfo) {
476 // If this is an implicit member access, use a different set of
477 // diagnostics.
478 if (!BaseExpr)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000479 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000480
481 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
482 << SS.getRange() << rep << BaseType;
483}
484
485// Check whether the declarations we found through a nested-name
486// specifier in a member expression are actually members of the base
487// type. The restriction here is:
488//
489// C++ [expr.ref]p2:
490// ... In these cases, the id-expression shall name a
491// member of the class or of one of its base classes.
492//
493// So it's perfectly legitimate for the nested-name specifier to name
494// an unrelated class, and for us to find an overload set including
495// decls from classes which are not superclasses, as long as the decl
496// we actually pick through overload resolution is from a superclass.
497bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
498 QualType BaseType,
499 const CXXScopeSpec &SS,
500 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000501 CXXRecordDecl *BaseRecord =
502 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
503 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000504 // We can't check this yet because the base type is still
505 // dependent.
506 assert(BaseType->isDependentType());
507 return false;
508 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000509
510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
511 // If this is an implicit member reference and we find a
512 // non-instance member, it's not an error.
513 if (!BaseExpr && !(*I)->isCXXInstanceMember())
514 return false;
515
516 // Note that we use the DC of the decl, not the underlying decl.
517 DeclContext *DC = (*I)->getDeclContext();
518 while (DC->isTransparentContext())
519 DC = DC->getParent();
520
521 if (!DC->isRecord())
522 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000523
Richard Smithd80b2d52012-11-22 00:24:47 +0000524 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
525 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
526 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000527 return false;
528 }
529
530 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
531 R.getRepresentativeDecl(),
532 R.getLookupNameInfo());
533 return true;
534}
535
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000536namespace {
537
538// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000539// FunctionTemplateDecl and are declared in the current record or, for a C++
540// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000541class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000542public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000543 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000544 : Record(RTy->getDecl()) {
545 // Don't add bare keywords to the consumer since they will always fail
546 // validation by virtue of not being associated with any decls.
547 WantTypeSpecifiers = false;
548 WantExpressionKeywords = false;
549 WantCXXNamedCasts = false;
550 WantFunctionLikeCasts = false;
551 WantRemainingKeywords = false;
552 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000553
Craig Toppere14c0f82014-03-12 04:55:44 +0000554 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000555 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000556 // Don't accept candidates that cannot be member functions, constants,
557 // variables, or templates.
558 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
559 return false;
560
561 // Accept candidates that occur in the current record.
562 if (Record->containsDecl(ND))
563 return true;
564
565 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
566 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000567 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000568 if (const RecordType *BSTy =
569 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000570 if (BSTy->getDecl()->containsDecl(ND))
571 return true;
572 }
573 }
574 }
575
576 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000577 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000578
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000579private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000580 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000581};
582
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000583}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000584
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000585static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000586 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000587 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000588 SourceLocation OpLoc, bool IsArrow,
589 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000590 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000591 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000592 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000593 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
594 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000595 diag::err_typecheck_incomplete_tag,
596 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000597 return true;
598
599 if (HasTemplateArgs) {
600 // LookupTemplateName doesn't expect these both to exist simultaneously.
601 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
602
603 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000604 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000605 return false;
606 }
607
608 DeclContext *DC = RDecl;
609 if (SS.isSet()) {
610 // If the member name was a qualified-id, look into the
611 // nested-name-specifier.
612 DC = SemaRef.computeDeclContext(SS, false);
613
614 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
615 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000616 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000617 return true;
618 }
619
620 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
621
622 if (!isa<TypeDecl>(DC)) {
623 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000624 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000625 return true;
626 }
627 }
628
629 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000630 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000631
632 if (!R.empty())
633 return false;
634
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000635 DeclarationName Typo = R.getLookupName();
636 SourceLocation TypoLoc = R.getNameLoc();
David Blaikiea8173ba2015-09-28 23:48:55 +0000637
638 struct QueryState {
639 Sema &SemaRef;
640 DeclarationNameInfo NameInfo;
641 Sema::LookupNameKind LookupKind;
642 Sema::RedeclarationKind Redecl;
643 };
644 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
645 R.isForRedeclaration() ? Sema::ForRedeclaration
646 : Sema::NotForRedeclaration};
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000647 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000648 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
649 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000650 [=, &SemaRef](const TypoCorrection &TC) {
651 if (TC) {
652 assert(!TC.isKeyword() &&
653 "Got a keyword as a correction for a member!");
654 bool DroppedSpecifier =
655 TC.WillReplaceSpecifier() &&
656 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
657 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
658 << Typo << DC << DroppedSpecifier
659 << SS.getRange());
660 } else {
661 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
662 }
663 },
664 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
David Blaikiea8173ba2015-09-28 23:48:55 +0000665 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000666 R.clear(); // Ensure there's no decls lingering in the shared state.
667 R.suppressDiagnostics();
668 R.setLookupName(TC.getCorrection());
669 for (NamedDecl *ND : TC)
670 R.addDecl(ND);
671 R.resolveKind();
672 return SemaRef.BuildMemberReferenceExpr(
673 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000674 nullptr, R, nullptr, nullptr);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000675 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000676 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000677
678 return false;
679}
680
Richard Smitha0edd302014-05-31 00:18:32 +0000681static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
682 ExprResult &BaseExpr, bool &IsArrow,
683 SourceLocation OpLoc, CXXScopeSpec &SS,
684 Decl *ObjCImpDecl, bool HasTemplateArgs);
685
Douglas Gregor5476205b2011-06-23 00:49:38 +0000686ExprResult
687Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
688 SourceLocation OpLoc, bool IsArrow,
689 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000690 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000691 NamedDecl *FirstQualifierInScope,
692 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000693 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000694 const Scope *S,
Richard Smitha0edd302014-05-31 00:18:32 +0000695 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000696 if (BaseType->isDependentType() ||
697 (SS.isSet() && isDependentScopeSpecifier(SS)))
698 return ActOnDependentMemberExpr(Base, BaseType,
699 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000700 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000701 NameInfo, TemplateArgs);
702
703 LookupResult R(*this, NameInfo, LookupMemberName);
704
705 // Implicit member accesses.
706 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000707 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000708 QualType RecordTy = BaseType;
709 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000710 if (LookupMemberExprInRecord(*this, R, nullptr,
711 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000712 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000713 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000714 if (TE)
715 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000716
717 // Explicit member accesses.
718 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000719 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000720 ExprResult Result = LookupMemberExpr(
721 *this, R, BaseResult, IsArrow, OpLoc, SS,
722 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
723 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000724
725 if (BaseResult.isInvalid())
726 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000727 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000728
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000729 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000730 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000731
732 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000733 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000734
735 // LookupMemberExpr can modify Base, and thus change BaseType
736 BaseType = Base->getType();
737 }
738
739 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000740 OpLoc, IsArrow, SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000741 FirstQualifierInScope, R, TemplateArgs, S,
Richard Smitha0edd302014-05-31 00:18:32 +0000742 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000743}
744
745static ExprResult
746BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000747 SourceLocation OpLoc, const CXXScopeSpec &SS,
748 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000749 const DeclarationNameInfo &MemberNameInfo);
750
751ExprResult
752Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
753 SourceLocation loc,
754 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000755 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000756 Expr *baseObjectExpr,
757 SourceLocation opLoc) {
758 // First, build the expression that refers to the base object.
759
760 bool baseObjectIsPointer = false;
761 Qualifiers baseQuals;
762
763 // Case 1: the base of the indirect field is not a field.
764 VarDecl *baseVariable = indirectField->getVarDecl();
765 CXXScopeSpec EmptySS;
766 if (baseVariable) {
767 assert(baseVariable->getType()->isRecordType());
768
769 // In principle we could have a member access expression that
770 // accesses an anonymous struct/union that's a static member of
771 // the base object's class. However, under the current standard,
772 // static data members cannot be anonymous structs or unions.
773 // Supporting this is as easy as building a MemberExpr here.
774 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
775
776 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
777
778 ExprResult result
779 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
780 if (result.isInvalid()) return ExprError();
781
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000782 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000783 baseObjectIsPointer = false;
784 baseQuals = baseObjectExpr->getType().getQualifiers();
785
786 // Case 2: the base of the indirect field is a field and the user
787 // wrote a member expression.
788 } else if (baseObjectExpr) {
789 // The caller provided the base object expression. Determine
790 // whether its a pointer and whether it adds any qualifiers to the
791 // anonymous struct/union fields we're looking into.
792 QualType objectType = baseObjectExpr->getType();
793
794 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
795 baseObjectIsPointer = true;
796 objectType = ptr->getPointeeType();
797 } else {
798 baseObjectIsPointer = false;
799 }
800 baseQuals = objectType.getQualifiers();
801
802 // Case 3: the base of the indirect field is a field and we should
803 // build an implicit member access.
804 } else {
805 // We've found a member of an anonymous struct/union that is
806 // inside a non-anonymous struct/union, so in a well-formed
807 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000808 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000809 if (ThisTy.isNull()) {
810 Diag(loc, diag::err_invalid_member_use_in_static_method)
811 << indirectField->getDeclName();
812 return ExprError();
813 }
814
815 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000816 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000817 baseObjectExpr
818 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
819 baseObjectIsPointer = true;
820 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
821 }
822
823 // Build the implicit member references to the field of the
824 // anonymous struct/union.
825 Expr *result = baseObjectExpr;
826 IndirectFieldDecl::chain_iterator
827 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
828
829 // Build the first member access in the chain with full information.
830 if (!baseVariable) {
831 FieldDecl *field = cast<FieldDecl>(*FI);
832
Douglas Gregor5476205b2011-06-23 00:49:38 +0000833 // Make a nameInfo that properly uses the anonymous name.
834 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000835
Douglas Gregor5476205b2011-06-23 00:49:38 +0000836 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000837 SourceLocation(), EmptySS, field,
838 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000839 if (!result)
840 return ExprError();
841
Douglas Gregor5476205b2011-06-23 00:49:38 +0000842 // FIXME: check qualified member access
843 }
844
845 // In all cases, we should now skip the first declaration in the chain.
846 ++FI;
847
848 while (FI != FEnd) {
849 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000850
Douglas Gregor5476205b2011-06-23 00:49:38 +0000851 // FIXME: these are somewhat meaningless
852 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000853 DeclAccessPair fakeFoundDecl =
854 DeclAccessPair::make(field, field->getAccess());
855
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000856 result =
857 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
858 SourceLocation(), (FI == FEnd ? SS : EmptySS),
859 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000860 }
861
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000862 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000863}
864
John McCall5e77d762013-04-16 07:28:30 +0000865static ExprResult
866BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
867 const CXXScopeSpec &SS,
868 MSPropertyDecl *PD,
869 const DeclarationNameInfo &NameInfo) {
870 // Property names are always simple identifiers and therefore never
871 // require any interesting additional storage.
872 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
873 S.Context.PseudoObjectTy, VK_LValue,
874 SS.getWithLocInContext(S.Context),
875 NameInfo.getLoc());
876}
877
Douglas Gregor5476205b2011-06-23 00:49:38 +0000878/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000879static MemberExpr *BuildMemberExpr(
880 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
881 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
882 ValueDecl *Member, DeclAccessPair FoundDecl,
883 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
884 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000885 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000886 MemberExpr *E = MemberExpr::Create(
887 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
888 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000889 SemaRef.MarkMemberReferenced(E);
890 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000891}
892
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000893/// \brief Determine if the given scope is within a function-try-block handler.
894static bool IsInFnTryBlockHandler(const Scope *S) {
895 // Walk the scope stack until finding a FnTryCatchScope, or leave the
896 // function scope. If a FnTryCatchScope is found, check whether the TryScope
897 // flag is set. If it is not, it's a function-try-block handler.
898 for (; S != S->getFnParent(); S = S->getParent()) {
899 if (S->getFlags() & Scope::FnTryCatchScope)
900 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
901 }
902 return false;
903}
904
Faisal Valie7f8fb92016-02-22 02:24:29 +0000905static VarDecl *
906getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
907 const TemplateArgumentListInfo *TemplateArgs,
908 const DeclarationNameInfo &MemberNameInfo,
909 SourceLocation TemplateKWLoc) {
910
911 if (!TemplateArgs) {
912 S.Diag(MemberNameInfo.getBeginLoc(), diag::err_template_decl_ref)
913 << /*Variable template*/ 1 << MemberNameInfo.getName()
914 << MemberNameInfo.getSourceRange();
915
916 S.Diag(VarTempl->getLocation(), diag::note_template_decl_here);
917
918 return nullptr;
919 }
920 DeclResult VDecl = S.CheckVarTemplateId(
921 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
922 if (VDecl.isInvalid())
923 return nullptr;
924 VarDecl *Var = cast<VarDecl>(VDecl.get());
925 if (!Var->getTemplateSpecializationKind())
926 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
927 MemberNameInfo.getLoc());
928 return Var;
929}
930
Douglas Gregor5476205b2011-06-23 00:49:38 +0000931ExprResult
932Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
933 SourceLocation OpLoc, bool IsArrow,
934 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000935 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000936 NamedDecl *FirstQualifierInScope,
937 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000938 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000939 const Scope *S,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000940 bool SuppressQualifierCheck,
941 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000942 QualType BaseType = BaseExprType;
943 if (IsArrow) {
944 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000945 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000946 }
947 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000948
949 LambdaScopeInfo *const CurLSI = getCurLambda();
950 // If this is an implicit member reference and the overloaded
951 // name refers to both static and non-static member functions
952 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
953 // check if we should/can capture 'this'...
954 // Keep this example in mind:
955 // struct X {
956 // void f(int) { }
957 // static void f(double) { }
958 //
959 // int g() {
960 // auto L = [=](auto a) {
961 // return [](int i) {
962 // return [=](auto b) {
963 // f(b);
964 // //f(decltype(a){});
965 // };
966 // };
967 // };
968 // auto M = L(0.0);
969 // auto N = M(3);
970 // N(5.32); // OK, must not error.
971 // return 0;
972 // }
973 // };
974 //
975 if (!BaseExpr && CurLSI) {
976 SourceLocation Loc = R.getNameLoc();
977 if (SS.getRange().isValid())
978 Loc = SS.getRange().getBegin();
979 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
980 // If the enclosing function is not dependent, then this lambda is
981 // capture ready, so if we can capture this, do so.
982 if (!EnclosingFunctionCtx->isDependentContext()) {
983 // If the current lambda and all enclosing lambdas can capture 'this' -
984 // then go ahead and capture 'this' (since our unresolved overload set
985 // contains both static and non-static member functions).
986 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
987 CheckCXXThisCapture(Loc);
988 } else if (CurContext->isDependentContext()) {
989 // ... since this is an implicit member reference, that might potentially
990 // involve a 'this' capture, mark 'this' for potential capture in
991 // enclosing lambdas.
992 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
993 CurLSI->addPotentialThisCapture(Loc);
994 }
995 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000996 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
997 DeclarationName MemberName = MemberNameInfo.getName();
998 SourceLocation MemberLoc = MemberNameInfo.getLoc();
999
1000 if (R.isAmbiguous())
1001 return ExprError();
1002
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001003 // [except.handle]p10: Referring to any non-static member or base class of an
1004 // object in the handler for a function-try-block of a constructor or
1005 // destructor for that object results in undefined behavior.
1006 const auto *FD = getCurFunctionDecl();
1007 if (S && BaseExpr && FD &&
1008 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1009 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1010 IsInFnTryBlockHandler(S))
1011 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1012 << isa<CXXDestructorDecl>(FD);
1013
Douglas Gregor5476205b2011-06-23 00:49:38 +00001014 if (R.empty()) {
1015 // Rederive where we looked up.
1016 DeclContext *DC = (SS.isSet()
1017 ? computeDeclContext(SS, false)
1018 : BaseType->getAs<RecordType>()->getDecl());
1019
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001020 if (ExtraArgs) {
1021 ExprResult RetryExpr;
1022 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +00001023 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001024 ParsedType ObjectType;
1025 bool MayBePseudoDestructor = false;
1026 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1027 OpLoc, tok::arrow, ObjectType,
1028 MayBePseudoDestructor);
1029 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1030 CXXScopeSpec TempSS(SS);
1031 RetryExpr = ActOnMemberAccessExpr(
1032 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +00001033 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001034 }
1035 if (Trap.hasErrorOccurred())
1036 RetryExpr = ExprError();
1037 }
1038 if (RetryExpr.isUsable()) {
1039 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1040 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1041 return RetryExpr;
1042 }
1043 }
1044
Douglas Gregor5476205b2011-06-23 00:49:38 +00001045 Diag(R.getNameLoc(), diag::err_no_member)
1046 << MemberName << DC
1047 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1048 return ExprError();
1049 }
1050
1051 // Diagnose lookups that find only declarations from a non-base
1052 // type. This is possible for either qualified lookups (which may
1053 // have been qualified with an unrelated type) or implicit member
1054 // expressions (which were found with unqualified lookup and thus
1055 // may have come from an enclosing scope). Note that it's okay for
1056 // lookup to find declarations from a non-base type as long as those
1057 // aren't the ones picked by overload resolution.
1058 if ((SS.isSet() || !BaseExpr ||
1059 (isa<CXXThisExpr>(BaseExpr) &&
1060 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1061 !SuppressQualifierCheck &&
1062 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1063 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001064
Douglas Gregor5476205b2011-06-23 00:49:38 +00001065 // Construct an unresolved result if we in fact got an unresolved
1066 // result.
1067 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1068 // Suppress any lookup-related diagnostics; we'll do these when we
1069 // pick a member.
1070 R.suppressDiagnostics();
1071
1072 UnresolvedMemberExpr *MemExpr
1073 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1074 BaseExpr, BaseExprType,
1075 IsArrow, OpLoc,
1076 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001077 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001078 TemplateArgs, R.begin(), R.end());
1079
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001080 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001081 }
1082
1083 assert(R.isSingleResult());
1084 DeclAccessPair FoundDecl = R.begin().getPair();
1085 NamedDecl *MemberDecl = R.getFoundDecl();
1086
1087 // FIXME: diagnose the presence of template arguments now.
1088
1089 // If the decl being referenced had an error, return an error for this
1090 // sub-expr without emitting another error, in order to avoid cascading
1091 // error cases.
1092 if (MemberDecl->isInvalidDecl())
1093 return ExprError();
1094
1095 // Handle the implicit-member-access case.
1096 if (!BaseExpr) {
1097 // If this is not an instance member, convert to a non-member access.
Faisal Valie7f8fb92016-02-22 02:24:29 +00001098 if (!MemberDecl->isCXXInstanceMember()) {
1099 // If this is a variable template, get the instantiated variable
1100 // declaration corresponding to the supplied template arguments
1101 // (while emitting diagnostics as necessary) that will be referenced
1102 // by this expression.
Faisal Vali640dc752016-02-25 05:09:30 +00001103 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1104 "How did we get template arguments here sans a variable template");
Faisal Valie7f8fb92016-02-22 02:24:29 +00001105 if (isa<VarTemplateDecl>(MemberDecl)) {
1106 MemberDecl = getVarTemplateSpecialization(
1107 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1108 R.getLookupNameInfo(), TemplateKWLoc);
1109 if (!MemberDecl)
1110 return ExprError();
1111 }
Faisal Vali640dc752016-02-25 05:09:30 +00001112 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1113 FoundDecl, TemplateArgs);
Faisal Valie7f8fb92016-02-22 02:24:29 +00001114 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001115 SourceLocation Loc = R.getNameLoc();
1116 if (SS.getRange().isValid())
1117 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001118 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001119 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1120 }
1121
Douglas Gregor5476205b2011-06-23 00:49:38 +00001122 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001123 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001124 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001125
Douglas Gregor5476205b2011-06-23 00:49:38 +00001126 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001127 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1128 FoundDecl, MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001129
John McCall5e77d762013-04-16 07:28:30 +00001130 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1131 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1132 MemberNameInfo);
1133
Douglas Gregor5476205b2011-06-23 00:49:38 +00001134 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1135 // We may have found a field within an anonymous union or struct
1136 // (C++ [class.union]).
1137 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001138 FoundDecl, BaseExpr,
1139 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001140
1141 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001142 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1143 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001144 Var->getType().getNonReferenceType(), VK_LValue,
1145 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001146 }
1147
1148 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1149 ExprValueKind valueKind;
1150 QualType type;
1151 if (MemberFn->isInstance()) {
1152 valueKind = VK_RValue;
1153 type = Context.BoundMemberTy;
1154 } else {
1155 valueKind = VK_LValue;
1156 type = MemberFn->getType();
1157 }
1158
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001159 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1160 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1161 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001162 }
1163 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1164
1165 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001166 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1167 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1168 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001169 }
Faisal Valie7f8fb92016-02-22 02:24:29 +00001170 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1171 if (VarDecl *Var = getVarTemplateSpecialization(
1172 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1173 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1174 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1175 Var->getType().getNonReferenceType(), VK_LValue,
1176 OK_Ordinary);
1177 return ExprError();
1178 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001179
Douglas Gregor5476205b2011-06-23 00:49:38 +00001180 // We found something that we didn't expect. Complain.
1181 if (isa<TypeDecl>(MemberDecl))
1182 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1183 << MemberName << BaseType << int(IsArrow);
1184 else
1185 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1186 << MemberName << BaseType << int(IsArrow);
1187
1188 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1189 << MemberName;
1190 R.suppressDiagnostics();
1191 return ExprError();
1192}
1193
1194/// Given that normal member access failed on the given expression,
1195/// and given that the expression's type involves builtin-id or
1196/// builtin-Class, decide whether substituting in the redefinition
1197/// types would be profitable. The redefinition type is whatever
1198/// this translation unit tried to typedef to id/Class; we store
1199/// it to the side and then re-use it in places like this.
1200static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1201 const ObjCObjectPointerType *opty
1202 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1203 if (!opty) return false;
1204
1205 const ObjCObjectType *ty = opty->getObjectType();
1206
1207 QualType redef;
1208 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001209 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001210 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001211 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001212 } else {
1213 return false;
1214 }
1215
1216 // Do the substitution as long as the redefinition type isn't just a
1217 // possibly-qualified pointer to builtin-id or builtin-Class again.
1218 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001219 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001220 return false;
1221
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001222 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001223 return true;
1224}
1225
John McCall50a2c2c2011-10-11 23:14:30 +00001226static bool isRecordType(QualType T) {
1227 return T->isRecordType();
1228}
1229static bool isPointerToRecordType(QualType T) {
1230 if (const PointerType *PT = T->getAs<PointerType>())
1231 return PT->getPointeeType()->isRecordType();
1232 return false;
1233}
1234
Richard Smithcab9a7d2011-10-26 19:06:56 +00001235/// Perform conversions on the LHS of a member access expression.
1236ExprResult
1237Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001238 if (IsArrow && !Base->getType()->isFunctionType())
1239 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001240
Eli Friedman9a766c42012-01-13 02:20:01 +00001241 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001242}
1243
Douglas Gregor5476205b2011-06-23 00:49:38 +00001244/// Look up the given member of the given non-type-dependent
1245/// expression. This can return in one of two ways:
1246/// * If it returns a sentinel null-but-valid result, the caller will
1247/// assume that lookup was performed and the results written into
1248/// the provided structure. It will take over from there.
1249/// * Otherwise, the returned expression will be produced in place of
1250/// an ordinary member expression.
1251///
1252/// The ObjCImpDecl bit is a gross hack that will need to be properly
1253/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001254static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1255 ExprResult &BaseExpr, bool &IsArrow,
1256 SourceLocation OpLoc, CXXScopeSpec &SS,
1257 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001258 assert(BaseExpr.get() && "no base expression");
1259
1260 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001261 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001262 if (BaseExpr.isInvalid())
1263 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001264
Douglas Gregor5476205b2011-06-23 00:49:38 +00001265 QualType BaseType = BaseExpr.get()->getType();
1266 assert(!BaseType->isDependentType());
1267
1268 DeclarationName MemberName = R.getLookupName();
1269 SourceLocation MemberLoc = R.getNameLoc();
1270
1271 // For later type-checking purposes, turn arrow accesses into dot
1272 // accesses. The only access type we support that doesn't follow
1273 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1274 // and those never use arrows, so this is unaffected.
1275 if (IsArrow) {
1276 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1277 BaseType = Ptr->getPointeeType();
1278 else if (const ObjCObjectPointerType *Ptr
1279 = BaseType->getAs<ObjCObjectPointerType>())
1280 BaseType = Ptr->getPointeeType();
1281 else if (BaseType->isRecordType()) {
1282 // Recover from arrow accesses to records, e.g.:
1283 // struct MyRecord foo;
1284 // foo->bar
1285 // This is actually well-formed in C++ if MyRecord has an
1286 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001287 // by now--or a diagnostic message already issued if a problem
1288 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001289 if (!S.getLangOpts().CPlusPlus) {
1290 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001291 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1292 << FixItHint::CreateReplacement(OpLoc, ".");
1293 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001294 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001295 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001296 goto fail;
1297 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001298 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001299 << BaseType << BaseExpr.get()->getSourceRange();
1300 return ExprError();
1301 }
1302 }
1303
1304 // Handle field access to simple records.
1305 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001306 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001307 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001308 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001309 return ExprError();
1310
1311 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001312 // the lookup result was filled in. If typo correction was attempted and
1313 // failed, the lookup result will have been cleared--that combined with the
1314 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1315 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001316 }
1317
1318 // Handle ivar access to Objective-C objects.
1319 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001320 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001321 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001322 << 1 << SS.getScopeRep()
1323 << FixItHint::CreateRemoval(SS.getRange());
1324 SS.clear();
1325 }
Richard Smitha0edd302014-05-31 00:18:32 +00001326
Douglas Gregor5476205b2011-06-23 00:49:38 +00001327 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1328
1329 // There are three cases for the base type:
1330 // - builtin id (qualified or unqualified)
1331 // - builtin Class (qualified or unqualified)
1332 // - an interface
1333 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1334 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001335 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001336 (OTy->isObjCId() || OTy->isObjCClass()))
1337 goto fail;
1338 // There's an implicit 'isa' ivar on all objects.
1339 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001340 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001341 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001342 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1343 OpLoc, S.Context.getObjCClassType());
1344 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1345 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001346 ObjCImpDecl, HasTemplateArgs);
1347 goto fail;
1348 }
Richard Smitha0edd302014-05-31 00:18:32 +00001349
1350 if (S.RequireCompleteType(OpLoc, BaseType,
1351 diag::err_typecheck_incomplete_tag,
1352 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001353 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001354
1355 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001356 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1357
1358 if (!IV) {
1359 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001360 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1361 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001362 if (TypoCorrection Corrected = S.CorrectTypo(
1363 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001364 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001365 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001366 S.diagnoseTypo(
1367 Corrected,
1368 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1369 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001370
Ted Kremenek679b4782012-03-17 00:53:39 +00001371 // Figure out the class that declares the ivar.
1372 assert(!ClassDeclared);
1373 Decl *D = cast<Decl>(IV->getDeclContext());
1374 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1375 D = CAT->getClassInterface();
1376 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001377 } else {
Manman Ren5b786402016-01-28 18:49:28 +00001378 if (IsArrow &&
1379 IDecl->FindPropertyDeclaration(
1380 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001381 S.Diag(MemberLoc, diag::err_property_found_suggest)
1382 << Member << BaseExpr.get()->getType()
1383 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001384 return ExprError();
1385 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001386
Richard Smitha0edd302014-05-31 00:18:32 +00001387 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1388 << IDecl->getDeclName() << MemberName
1389 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001390 return ExprError();
1391 }
1392 }
Richard Smitha0edd302014-05-31 00:18:32 +00001393
Ted Kremenek679b4782012-03-17 00:53:39 +00001394 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001395
1396 // If the decl being referenced had an error, return an error for this
1397 // sub-expr without emitting another error, in order to avoid cascading
1398 // error cases.
1399 if (IV->isInvalidDecl())
1400 return ExprError();
1401
1402 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001403 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001404 return ExprError();
1405 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1406 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001407 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001408 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001409 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001410 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001411 // Case of a c-function declared inside an objc implementation.
1412 // FIXME: For a c-style function nested inside an objc implementation
1413 // class, there is no implementation context available, so we pass
1414 // down the context as argument to this routine. Ideally, this context
1415 // need be passed down in the AST node and somehow calculated from the
1416 // AST for a function decl.
1417 if (ObjCImplementationDecl *IMPD =
1418 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1419 ClassOfMethodDecl = IMPD->getClassInterface();
1420 else if (ObjCCategoryImplDecl* CatImplClass =
1421 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1422 ClassOfMethodDecl = CatImplClass->getClassInterface();
1423 }
Richard Smitha0edd302014-05-31 00:18:32 +00001424 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001425 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1426 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1427 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001428 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001429 << IV->getDeclName();
1430 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1431 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001432 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1433 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001434 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001435 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001436 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001437 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001438 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1439 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1440 if (UO->getOpcode() == UO_Deref)
1441 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1442
1443 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001444 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001445 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001446 warn = false;
1447 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001448 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001449 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001450 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001451 ObjCMethodFamily MF = MD->getMethodFamily();
1452 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001453 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001454 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001455 }
1456 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001457 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001458 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001459
Richard Smitha0edd302014-05-31 00:18:32 +00001460 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001461 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1462 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001463
Richard Smitha0edd302014-05-31 00:18:32 +00001464 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001465 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001466 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001467 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001468 }
1469 }
1470
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001471 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001472 }
1473
1474 // Objective-C property access.
1475 const ObjCObjectPointerType *OPT;
1476 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001477 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001478 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1479 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001480 SS.clear();
1481 }
1482
Douglas Gregor5476205b2011-06-23 00:49:38 +00001483 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001484 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001485 if (BaseExpr.isInvalid())
1486 return ExprError();
1487
Richard Smitha0edd302014-05-31 00:18:32 +00001488 assert(S.Context.hasSameUnqualifiedType(BaseType,
1489 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001490
1491 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1492
1493 const ObjCObjectType *OT = OPT->getObjectType();
1494
1495 // id, with and without qualifiers.
1496 if (OT->isObjCId()) {
1497 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001498 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1499 if (Decl *PMDecl =
1500 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001501 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1502 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001503 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001504 return ExprError();
1505
Richard Smitha0edd302014-05-31 00:18:32 +00001506 return new (S.Context)
1507 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001508 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001509 }
1510
1511 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1512 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001513 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001514 return ExprError();
1515 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001516 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1517 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001518 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001519 ObjCMethodDecl *SMD = nullptr;
1520 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001521 /*Property id*/ nullptr,
1522 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001523 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001524
1525 return new (S.Context)
1526 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001527 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001528 }
1529 }
1530 // Use of id.member can only be for a property reference. Do not
1531 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001532 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1533 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001534 ObjCImpDecl, HasTemplateArgs);
1535
Richard Smitha0edd302014-05-31 00:18:32 +00001536 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001537 << MemberName << BaseType);
1538 }
1539
1540 // 'Class', unqualified only.
1541 if (OT->isObjCClass()) {
1542 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001543 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001544 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001545 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1546 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001547 ObjCImpDecl, HasTemplateArgs);
1548
1549 goto fail;
1550 }
1551
1552 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001553 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001554 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1555 ObjCMethodDecl *Getter;
1556 if ((Getter = IFace->lookupClassMethod(Sel))) {
1557 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001558 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001559 return ExprError();
1560 } else
1561 Getter = IFace->lookupPrivateMethod(Sel, false);
1562 // If we found a getter then this may be a valid dot-reference, we
1563 // will look for the matching setter, in case it is needed.
1564 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001565 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1566 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001567 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001568 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1569 if (!Setter) {
1570 // If this reference is in an @implementation, also check for 'private'
1571 // methods.
1572 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1573 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001574
Richard Smitha0edd302014-05-31 00:18:32 +00001575 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001576 return ExprError();
1577
1578 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001579 return new (S.Context) ObjCPropertyRefExpr(
1580 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1581 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001582 }
1583
Richard Smitha0edd302014-05-31 00:18:32 +00001584 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1585 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001586 ObjCImpDecl, HasTemplateArgs);
1587
Richard Smitha0edd302014-05-31 00:18:32 +00001588 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001589 << MemberName << BaseType);
1590 }
1591
1592 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001593 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1594 MemberLoc, SourceLocation(), QualType(),
1595 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001596 }
1597
1598 // Handle 'field access' to vectors, such as 'V.xx'.
1599 if (BaseType->isExtVectorType()) {
1600 // FIXME: this expr should store IsArrow.
1601 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001602 ExprValueKind VK;
1603 if (IsArrow)
1604 VK = VK_LValue;
1605 else {
1606 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1607 VK = POE->getSyntacticForm()->getValueKind();
1608 else
1609 VK = BaseExpr.get()->getValueKind();
1610 }
Richard Smitha0edd302014-05-31 00:18:32 +00001611 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001612 Member, MemberLoc);
1613 if (ret.isNull())
1614 return ExprError();
1615
Richard Smitha0edd302014-05-31 00:18:32 +00001616 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001617 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001618 }
1619
1620 // Adjust builtin-sel to the appropriate redefinition type if that's
1621 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001622 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1623 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1624 BaseExpr = S.ImpCastExprToType(
1625 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1626 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001627 ObjCImpDecl, HasTemplateArgs);
1628 }
1629
1630 // Failure cases.
1631 fail:
1632
1633 // Recover from dot accesses to pointers, e.g.:
1634 // type *foo;
1635 // foo.bar
1636 // This is actually well-formed in two cases:
1637 // - 'type' is an Objective C type
1638 // - 'bar' is a pseudo-destructor name which happens to refer to
1639 // the appropriate pointer type
1640 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1641 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1642 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001643 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1644 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001645 << FixItHint::CreateReplacement(OpLoc, "->");
1646
1647 // Recurse as an -> access.
1648 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001649 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001650 ObjCImpDecl, HasTemplateArgs);
1651 }
1652 }
1653
1654 // If the user is trying to apply -> or . to a function name, it's probably
1655 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001656 if (S.tryToRecoverWithCall(
1657 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1658 /*complain*/ false,
1659 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001660 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001661 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001662 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1663 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001664 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001665 }
1666
Richard Smitha0edd302014-05-31 00:18:32 +00001667 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001668 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001669
1670 return ExprError();
1671}
1672
1673/// The main callback when the parser finds something like
1674/// expression . [nested-name-specifier] identifier
1675/// expression -> [nested-name-specifier] identifier
1676/// where 'identifier' encompasses a fairly broad spectrum of
1677/// possibilities, including destructor and operator references.
1678///
1679/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001680/// \param ObjCImpDecl the current Objective-C \@implementation
1681/// decl; this is an ugly hack around the fact that Objective-C
1682/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001683ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1684 SourceLocation OpLoc,
1685 tok::TokenKind OpKind,
1686 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001687 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001688 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001689 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001690 if (SS.isSet() && SS.isInvalid())
1691 return ExprError();
1692
1693 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001694 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001695 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1696 Diag(Id.getSourceRange().getBegin(),
1697 diag::ext_ms_explicit_constructor_call);
1698
1699 TemplateArgumentListInfo TemplateArgsBuffer;
1700
1701 // Decompose the name into its component parts.
1702 DeclarationNameInfo NameInfo;
1703 const TemplateArgumentListInfo *TemplateArgs;
1704 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1705 NameInfo, TemplateArgs);
1706
1707 DeclarationName Name = NameInfo.getName();
1708 bool IsArrow = (OpKind == tok::arrow);
1709
1710 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001711 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001712
1713 // This is a postfix expression, so get rid of ParenListExprs.
1714 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1715 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001716 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001717
1718 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1719 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001720 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1721 TemplateKWLoc, FirstQualifierInScope,
1722 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001723 }
1724
David Majnemerced8bdf2015-02-25 17:36:15 +00001725 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001726 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1727 TemplateKWLoc, FirstQualifierInScope,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001728 NameInfo, TemplateArgs, S, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001729}
1730
1731static ExprResult
1732BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001733 SourceLocation OpLoc, const CXXScopeSpec &SS,
1734 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001735 const DeclarationNameInfo &MemberNameInfo) {
1736 // x.a is an l-value if 'a' has a reference type. Otherwise:
1737 // x.a is an l-value/x-value/pr-value if the base is (and note
1738 // that *x is always an l-value), except that if the base isn't
1739 // an ordinary object then we must have an rvalue.
1740 ExprValueKind VK = VK_LValue;
1741 ExprObjectKind OK = OK_Ordinary;
1742 if (!IsArrow) {
1743 if (BaseExpr->getObjectKind() == OK_Ordinary)
1744 VK = BaseExpr->getValueKind();
1745 else
1746 VK = VK_RValue;
1747 }
1748 if (VK != VK_RValue && Field->isBitField())
1749 OK = OK_BitField;
1750
1751 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1752 QualType MemberType = Field->getType();
1753 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1754 MemberType = Ref->getPointeeType();
1755 VK = VK_LValue;
1756 } else {
1757 QualType BaseType = BaseExpr->getType();
1758 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001759
Douglas Gregor5476205b2011-06-23 00:49:38 +00001760 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001761
Douglas Gregor5476205b2011-06-23 00:49:38 +00001762 // GC attributes are never picked up by members.
1763 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001764
Douglas Gregor5476205b2011-06-23 00:49:38 +00001765 // CVR attributes from the base are picked up by members,
1766 // except that 'mutable' members don't pick up 'const'.
1767 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001768
Douglas Gregor5476205b2011-06-23 00:49:38 +00001769 Qualifiers MemberQuals
1770 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001771
Douglas Gregor5476205b2011-06-23 00:49:38 +00001772 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001773
1774
Douglas Gregor5476205b2011-06-23 00:49:38 +00001775 Qualifiers Combined = BaseQuals + MemberQuals;
1776 if (Combined != MemberQuals)
1777 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1778 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001779
Daniel Jasper0baec5492012-06-06 08:32:04 +00001780 S.UnusedPrivateFields.remove(Field);
1781
Douglas Gregor5476205b2011-06-23 00:49:38 +00001782 ExprResult Base =
1783 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1784 FoundDecl, Field);
1785 if (Base.isInvalid())
1786 return ExprError();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001787 MemberExpr *ME =
1788 BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
1789 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1790 MemberNameInfo, MemberType, VK, OK);
1791
1792 // Build a reference to a private copy for non-static data members in
1793 // non-static member functions, privatized by OpenMP constructs.
1794 if (S.getLangOpts().OpenMP && IsArrow &&
1795 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
1796 if (auto *PrivateCopy = S.IsOpenMPCapturedDecl(Field))
1797 return S.getOpenMPCapturedExpr(PrivateCopy, VK, OK);
1798 }
1799 return ME;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001800}
1801
1802/// Builds an implicit member access expression. The current context
1803/// is known to be an instance method, and the given unqualified lookup
1804/// set is known to contain only instance members, at least one of which
1805/// is from an appropriate type.
1806ExprResult
1807Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001808 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001809 LookupResult &R,
1810 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001811 bool IsKnownInstance, const Scope *S) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001812 assert(!R.empty() && !R.isAmbiguous());
1813
1814 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001815
Douglas Gregor5476205b2011-06-23 00:49:38 +00001816 // If this is known to be an instance access, go ahead and build an
1817 // implicit 'this' expression now.
1818 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001819 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001820 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001821
1822 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001823 if (IsKnownInstance) {
1824 SourceLocation Loc = R.getNameLoc();
1825 if (SS.getRange().isValid())
1826 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001827 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001828 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1829 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001830
Douglas Gregor5476205b2011-06-23 00:49:38 +00001831 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1832 /*OpLoc*/ SourceLocation(),
1833 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001834 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001835 /*FirstQualifierInScope*/ nullptr,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001836 R, TemplateArgs, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001837}