blob: 806a3d813ee8787bca5554ec5d5cb3072ac77889 [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
Richard Smithb130fe72016-06-23 19:16:49 +0000145 case Sema::DiscardedStatement:
John McCallf413f5e2013-05-03 00:10:13 +0000146 case Sema::ConstantEvaluated:
147 case Sema::PotentiallyEvaluated:
148 case Sema::PotentiallyEvaluatedIfUsed:
149 break;
Richard Smitheae99682012-02-25 10:04:07 +0000150 }
151
Douglas Gregor5476205b2011-06-23 00:49:38 +0000152 // If the current context is not an instance method, it can't be
153 // an implicit member reference.
154 if (isStaticContext) {
155 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000156 return IMA_Mixed_StaticContext;
157
John McCallf413f5e2013-05-03 00:10:13 +0000158 return AbstractInstanceResult ? AbstractInstanceResult
159 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000160 }
161
162 CXXRecordDecl *contextClass;
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
164 contextClass = MD->getParent()->getCanonicalDecl();
165 else
166 contextClass = cast<CXXRecordDecl>(DC);
167
168 // [class.mfct.non-static]p3:
169 // ...is used in the body of a non-static member function of class X,
170 // if name lookup (3.4.1) resolves the name in the id-expression to a
171 // non-static non-type member of some class C [...]
172 // ...if C is not X or a base class of X, the class member access expression
173 // is ill-formed.
174 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000175 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000176 R.getNamingClass()->getCanonicalDecl()) {
177 // If the naming class is not the current context, this was a qualified
178 // member name lookup, and it's sufficient to check that we have the naming
179 // class as a base class.
180 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000181 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000182 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000183
184 // If we can prove that the current context is unrelated to all the
185 // declaring classes, it can't be an implicit member reference (in
186 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000187 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000188 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000189 AbstractInstanceResult ? AbstractInstanceResult :
190 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000191
192 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
193}
194
195/// Diagnose a reference to a field with no object available.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000196static void diagnoseInstanceReference(Sema &SemaRef,
197 const CXXScopeSpec &SS,
198 NamedDecl *Rep,
199 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000200 SourceLocation Loc = nameInfo.getLoc();
201 SourceRange Range(Loc);
202 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000203
Reid Klecknerae628962014-12-18 00:42:51 +0000204 // Look through using shadow decls and aliases.
205 Rep = Rep->getUnderlyingDecl();
206
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000207 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
Richard Smithfa0a1f52012-04-05 01:13:04 +0000208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000209 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000210 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
211
212 bool InStaticMethod = Method && Method->isStatic();
213 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
214
215 if (IsField && InStaticMethod)
216 // "invalid use of member 'x' in static member function"
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000217 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000218 << Range << nameInfo.getName();
219 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
220 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
221 // Unqualified lookup in a non-static member function found a member of an
222 // enclosing class.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000223 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
224 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000225 else if (IsField)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000226 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
227 << nameInfo.getName() << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000228 else
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000229 SemaRef.Diag(Loc, diag::err_member_call_without_object)
230 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000231}
232
233/// Builds an expression which might be an implicit member expression.
234ExprResult
235Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000236 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000237 LookupResult &R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000238 const TemplateArgumentListInfo *TemplateArgs,
239 const Scope *S) {
Reid Klecknerae628962014-12-18 00:42:51 +0000240 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000241 case IMA_Instance:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000242 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000243
244 case IMA_Mixed:
245 case IMA_Mixed_Unrelated:
246 case IMA_Unresolved:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000247 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
248 S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000249
Richard Smith2a986112012-02-25 10:20:59 +0000250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
253 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000254 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000255 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000256 case IMA_Mixed_StaticContext:
257 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000258 if (TemplateArgs || TemplateKWLoc.isValid())
259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000260 return BuildDeclarationNameExpr(SS, R, false);
261
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000265 R.getLookupNameInfo());
266 return ExprError();
267 }
268
269 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000270}
271
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000272/// Determine whether input char is from rgba component set.
273static bool
274IsRGBA(char c) {
275 switch (c) {
276 case 'r':
277 case 'g':
278 case 'b':
279 case 'a':
280 return true;
281 default:
282 return false;
283 }
284}
285
Douglas Gregor5476205b2011-06-23 00:49:38 +0000286/// Check an ext-vector component access expression.
287///
288/// VK should be set in advance to the value kind of the base
289/// expression.
290static QualType
291CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
292 SourceLocation OpLoc, const IdentifierInfo *CompName,
293 SourceLocation CompLoc) {
294 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
295 // see FIXME there.
296 //
297 // FIXME: This logic can be greatly simplified by splitting it along
298 // halving/not halving and reworking the component checking.
299 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
300
301 // The vector accessor can't exceed the number of elements.
302 const char *compStr = CompName->getNameStart();
303
304 // This flag determines whether or not the component is one of the four
305 // special names that indicate a subset of exactly half the elements are
306 // to be selected.
307 bool HalvingSwizzle = false;
308
309 // This flag determines whether or not CompName has an 's' char prefix,
310 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000311 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000312
313 bool HasRepeated = false;
314 bool HasIndex[16] = {};
315
316 int Idx;
317
318 // Check that we've found one of the special components, or that the component
319 // names must come from the same set.
320 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
321 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
322 HalvingSwizzle = true;
323 } else if (!HexSwizzle &&
324 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000325 bool HasRGBA = IsRGBA(*compStr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000326 do {
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000327 // Ensure that xyzw and rgba components don't intermingle.
328 if (HasRGBA != IsRGBA(*compStr))
329 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000330 if (HasIndex[Idx]) HasRepeated = true;
331 HasIndex[Idx] = true;
332 compStr++;
333 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000334
335 // Emit a warning if an rgba selector is used earlier than OpenCL 2.2
336 if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
337 if (S.getLangOpts().OpenCL && S.getLangOpts().OpenCLVersion < 220) {
338 const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
339 S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
340 << StringRef(DiagBegin, 1)
341 << S.getLangOpts().OpenCLVersion << SourceRange(CompLoc);
342 }
343 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000344 } else {
345 if (HexSwizzle) compStr++;
346 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
347 if (HasIndex[Idx]) HasRepeated = true;
348 HasIndex[Idx] = true;
349 compStr++;
350 }
351 }
352
353 if (!HalvingSwizzle && *compStr) {
354 // We didn't get to the end of the string. This means the component names
355 // didn't come from the same set *or* we encountered an illegal name.
356 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000357 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000358 return QualType();
359 }
360
361 // Ensure no component accessor exceeds the width of the vector type it
362 // operates on.
363 if (!HalvingSwizzle) {
364 compStr = CompName->getNameStart();
365
366 if (HexSwizzle)
367 compStr++;
368
369 while (*compStr) {
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000370 if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000371 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
372 << baseType << SourceRange(CompLoc);
373 return QualType();
374 }
375 }
376 }
377
378 // The component accessor looks fine - now we need to compute the actual type.
379 // The vector type is implied by the component accessor. For example,
380 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
381 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
382 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
383 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
384 : CompName->getLength();
385 if (HexSwizzle)
386 CompSize--;
387
388 if (CompSize == 1)
389 return vecType->getElementType();
390
391 if (HasRepeated) VK = VK_RValue;
392
393 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
394 // Now look up the TypeDefDecl from the vector type. Without this,
395 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000396 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000397 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000398 E = S.ExtVectorDecls.end();
399 I != E; ++I) {
400 if ((*I)->getUnderlyingType() == VT)
401 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000402 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000403
Douglas Gregor5476205b2011-06-23 00:49:38 +0000404 return VT; // should never get here (a typedef type should always be found).
405}
406
407static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
408 IdentifierInfo *Member,
409 const Selector &Sel,
410 ASTContext &Context) {
411 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000412 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
413 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000414 return PD;
415 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
416 return OMD;
417
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000418 for (const auto *I : PDecl->protocols()) {
419 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000420 Context))
421 return D;
422 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000423 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000424}
425
426static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
427 IdentifierInfo *Member,
428 const Selector &Sel,
429 ASTContext &Context) {
430 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000431 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000432 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000433 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000434 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
435 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000436 GDecl = PD;
437 break;
438 }
439 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000440 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000441 GDecl = OMD;
442 break;
443 }
444 }
445 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000446 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000447 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000448 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000449 if (GDecl)
450 return GDecl;
451 }
452 }
453 return GDecl;
454}
455
456ExprResult
457Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
458 bool IsArrow, SourceLocation OpLoc,
459 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000460 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000461 NamedDecl *FirstQualifierInScope,
462 const DeclarationNameInfo &NameInfo,
463 const TemplateArgumentListInfo *TemplateArgs) {
464 // Even in dependent contexts, try to diagnose base expressions with
465 // obviously wrong types, e.g.:
466 //
467 // T* t;
468 // t.f;
469 //
470 // In Obj-C++, however, the above expression is valid, since it could be
471 // accessing the 'f' property if T is an Obj-C interface. The extra check
472 // allows this, while still reporting an error if T is a struct pointer.
473 if (!IsArrow) {
474 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000475 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000476 PT->getPointeeType()->isRecordType())) {
477 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000478 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000479 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000480 return ExprError();
481 }
482 }
483
484 assert(BaseType->isDependentType() ||
485 NameInfo.getName().isDependentName() ||
486 isDependentScopeSpecifier(SS));
487
488 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
489 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000490 return CXXDependentScopeMemberExpr::Create(
491 Context, BaseExpr, BaseType, IsArrow, OpLoc,
492 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
493 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000494}
495
496/// We know that the given qualified member reference points only to
497/// declarations which do not belong to the static type of the base
498/// expression. Diagnose the problem.
499static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
500 Expr *BaseExpr,
501 QualType BaseType,
502 const CXXScopeSpec &SS,
503 NamedDecl *rep,
504 const DeclarationNameInfo &nameInfo) {
505 // If this is an implicit member access, use a different set of
506 // diagnostics.
507 if (!BaseExpr)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000508 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000509
510 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
511 << SS.getRange() << rep << BaseType;
512}
513
514// Check whether the declarations we found through a nested-name
515// specifier in a member expression are actually members of the base
516// type. The restriction here is:
517//
518// C++ [expr.ref]p2:
519// ... In these cases, the id-expression shall name a
520// member of the class or of one of its base classes.
521//
522// So it's perfectly legitimate for the nested-name specifier to name
523// an unrelated class, and for us to find an overload set including
524// decls from classes which are not superclasses, as long as the decl
525// we actually pick through overload resolution is from a superclass.
526bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
527 QualType BaseType,
528 const CXXScopeSpec &SS,
529 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000530 CXXRecordDecl *BaseRecord =
531 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
532 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000533 // We can't check this yet because the base type is still
534 // dependent.
535 assert(BaseType->isDependentType());
536 return false;
537 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000538
539 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
540 // If this is an implicit member reference and we find a
541 // non-instance member, it's not an error.
542 if (!BaseExpr && !(*I)->isCXXInstanceMember())
543 return false;
544
545 // Note that we use the DC of the decl, not the underlying decl.
546 DeclContext *DC = (*I)->getDeclContext();
547 while (DC->isTransparentContext())
548 DC = DC->getParent();
549
550 if (!DC->isRecord())
551 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000552
Richard Smithd80b2d52012-11-22 00:24:47 +0000553 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
554 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
555 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000556 return false;
557 }
558
559 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
560 R.getRepresentativeDecl(),
561 R.getLookupNameInfo());
562 return true;
563}
564
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000565namespace {
566
567// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000568// FunctionTemplateDecl and are declared in the current record or, for a C++
569// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000570class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000571public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000572 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000573 : Record(RTy->getDecl()) {
574 // Don't add bare keywords to the consumer since they will always fail
575 // validation by virtue of not being associated with any decls.
576 WantTypeSpecifiers = false;
577 WantExpressionKeywords = false;
578 WantCXXNamedCasts = false;
579 WantFunctionLikeCasts = false;
580 WantRemainingKeywords = false;
581 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000582
Craig Toppere14c0f82014-03-12 04:55:44 +0000583 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000584 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000585 // Don't accept candidates that cannot be member functions, constants,
586 // variables, or templates.
587 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
588 return false;
589
590 // Accept candidates that occur in the current record.
591 if (Record->containsDecl(ND))
592 return true;
593
594 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
595 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000596 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000597 if (const RecordType *BSTy =
598 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000599 if (BSTy->getDecl()->containsDecl(ND))
600 return true;
601 }
602 }
603 }
604
605 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000606 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000607
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000608private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000609 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000610};
611
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000612}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000613
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000614static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000615 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000616 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000617 SourceLocation OpLoc, bool IsArrow,
618 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000619 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000620 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000621 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000622 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
623 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000624 diag::err_typecheck_incomplete_tag,
625 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000626 return true;
627
628 if (HasTemplateArgs) {
629 // LookupTemplateName doesn't expect these both to exist simultaneously.
630 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
631
632 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000633 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000634 return false;
635 }
636
637 DeclContext *DC = RDecl;
638 if (SS.isSet()) {
639 // If the member name was a qualified-id, look into the
640 // nested-name-specifier.
641 DC = SemaRef.computeDeclContext(SS, false);
642
643 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
644 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000645 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000646 return true;
647 }
648
649 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
650
651 if (!isa<TypeDecl>(DC)) {
652 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000653 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000654 return true;
655 }
656 }
657
658 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000659 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000660
661 if (!R.empty())
662 return false;
663
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000664 DeclarationName Typo = R.getLookupName();
665 SourceLocation TypoLoc = R.getNameLoc();
David Blaikiea8173ba2015-09-28 23:48:55 +0000666
667 struct QueryState {
668 Sema &SemaRef;
669 DeclarationNameInfo NameInfo;
670 Sema::LookupNameKind LookupKind;
671 Sema::RedeclarationKind Redecl;
672 };
673 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
674 R.isForRedeclaration() ? Sema::ForRedeclaration
675 : Sema::NotForRedeclaration};
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000676 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000677 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
678 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000679 [=, &SemaRef](const TypoCorrection &TC) {
680 if (TC) {
681 assert(!TC.isKeyword() &&
682 "Got a keyword as a correction for a member!");
683 bool DroppedSpecifier =
684 TC.WillReplaceSpecifier() &&
685 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
686 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
687 << Typo << DC << DroppedSpecifier
688 << SS.getRange());
689 } else {
690 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
691 }
692 },
693 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
David Blaikiea8173ba2015-09-28 23:48:55 +0000694 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000695 R.clear(); // Ensure there's no decls lingering in the shared state.
696 R.suppressDiagnostics();
697 R.setLookupName(TC.getCorrection());
698 for (NamedDecl *ND : TC)
699 R.addDecl(ND);
700 R.resolveKind();
701 return SemaRef.BuildMemberReferenceExpr(
702 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000703 nullptr, R, nullptr, nullptr);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000704 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000705 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000706
707 return false;
708}
709
Richard Smitha0edd302014-05-31 00:18:32 +0000710static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
711 ExprResult &BaseExpr, bool &IsArrow,
712 SourceLocation OpLoc, CXXScopeSpec &SS,
713 Decl *ObjCImpDecl, bool HasTemplateArgs);
714
Douglas Gregor5476205b2011-06-23 00:49:38 +0000715ExprResult
716Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
717 SourceLocation OpLoc, bool IsArrow,
718 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000719 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000720 NamedDecl *FirstQualifierInScope,
721 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000722 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000723 const Scope *S,
Richard Smitha0edd302014-05-31 00:18:32 +0000724 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000725 if (BaseType->isDependentType() ||
726 (SS.isSet() && isDependentScopeSpecifier(SS)))
727 return ActOnDependentMemberExpr(Base, BaseType,
728 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000729 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000730 NameInfo, TemplateArgs);
731
732 LookupResult R(*this, NameInfo, LookupMemberName);
733
734 // Implicit member accesses.
735 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000736 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000737 QualType RecordTy = BaseType;
738 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000739 if (LookupMemberExprInRecord(*this, R, nullptr,
740 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000741 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000742 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000743 if (TE)
744 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000745
746 // Explicit member accesses.
747 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000748 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000749 ExprResult Result = LookupMemberExpr(
750 *this, R, BaseResult, IsArrow, OpLoc, SS,
751 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
752 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000753
754 if (BaseResult.isInvalid())
755 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000756 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000757
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000758 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000759 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000760
761 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000762 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000763
764 // LookupMemberExpr can modify Base, and thus change BaseType
765 BaseType = Base->getType();
766 }
767
768 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000769 OpLoc, IsArrow, SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000770 FirstQualifierInScope, R, TemplateArgs, S,
Richard Smitha0edd302014-05-31 00:18:32 +0000771 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000772}
773
Douglas Gregor5476205b2011-06-23 00:49:38 +0000774ExprResult
775Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
776 SourceLocation loc,
777 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000778 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000779 Expr *baseObjectExpr,
780 SourceLocation opLoc) {
781 // First, build the expression that refers to the base object.
782
783 bool baseObjectIsPointer = false;
784 Qualifiers baseQuals;
785
786 // Case 1: the base of the indirect field is not a field.
787 VarDecl *baseVariable = indirectField->getVarDecl();
788 CXXScopeSpec EmptySS;
789 if (baseVariable) {
790 assert(baseVariable->getType()->isRecordType());
791
792 // In principle we could have a member access expression that
793 // accesses an anonymous struct/union that's a static member of
794 // the base object's class. However, under the current standard,
795 // static data members cannot be anonymous structs or unions.
796 // Supporting this is as easy as building a MemberExpr here.
797 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
798
799 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
800
801 ExprResult result
802 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
803 if (result.isInvalid()) return ExprError();
804
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000805 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000806 baseObjectIsPointer = false;
807 baseQuals = baseObjectExpr->getType().getQualifiers();
808
809 // Case 2: the base of the indirect field is a field and the user
810 // wrote a member expression.
811 } else if (baseObjectExpr) {
812 // The caller provided the base object expression. Determine
813 // whether its a pointer and whether it adds any qualifiers to the
814 // anonymous struct/union fields we're looking into.
815 QualType objectType = baseObjectExpr->getType();
816
817 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
818 baseObjectIsPointer = true;
819 objectType = ptr->getPointeeType();
820 } else {
821 baseObjectIsPointer = false;
822 }
823 baseQuals = objectType.getQualifiers();
824
825 // Case 3: the base of the indirect field is a field and we should
826 // build an implicit member access.
827 } else {
828 // We've found a member of an anonymous struct/union that is
829 // inside a non-anonymous struct/union, so in a well-formed
830 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000831 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000832 if (ThisTy.isNull()) {
833 Diag(loc, diag::err_invalid_member_use_in_static_method)
834 << indirectField->getDeclName();
835 return ExprError();
836 }
837
838 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000839 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000840 baseObjectExpr
841 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
842 baseObjectIsPointer = true;
843 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
844 }
845
846 // Build the implicit member references to the field of the
847 // anonymous struct/union.
848 Expr *result = baseObjectExpr;
849 IndirectFieldDecl::chain_iterator
850 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
851
852 // Build the first member access in the chain with full information.
853 if (!baseVariable) {
854 FieldDecl *field = cast<FieldDecl>(*FI);
855
Douglas Gregor5476205b2011-06-23 00:49:38 +0000856 // Make a nameInfo that properly uses the anonymous name.
857 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000858
Richard Smith7873de02016-08-11 22:25:46 +0000859 result = BuildFieldReferenceExpr(result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000860 SourceLocation(), EmptySS, field,
861 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000862 if (!result)
863 return ExprError();
864
Douglas Gregor5476205b2011-06-23 00:49:38 +0000865 // FIXME: check qualified member access
866 }
867
868 // In all cases, we should now skip the first declaration in the chain.
869 ++FI;
870
871 while (FI != FEnd) {
872 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000873
Douglas Gregor5476205b2011-06-23 00:49:38 +0000874 // FIXME: these are somewhat meaningless
875 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000876 DeclAccessPair fakeFoundDecl =
877 DeclAccessPair::make(field, field->getAccess());
878
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000879 result =
Richard Smith7873de02016-08-11 22:25:46 +0000880 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
881 (FI == FEnd ? SS : EmptySS), field,
882 fakeFoundDecl, memberNameInfo)
883 .get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000884 }
885
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000886 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000887}
888
John McCall5e77d762013-04-16 07:28:30 +0000889static ExprResult
890BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
891 const CXXScopeSpec &SS,
892 MSPropertyDecl *PD,
893 const DeclarationNameInfo &NameInfo) {
894 // Property names are always simple identifiers and therefore never
895 // require any interesting additional storage.
896 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
897 S.Context.PseudoObjectTy, VK_LValue,
898 SS.getWithLocInContext(S.Context),
899 NameInfo.getLoc());
900}
901
Douglas Gregor5476205b2011-06-23 00:49:38 +0000902/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000903static MemberExpr *BuildMemberExpr(
904 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
905 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
906 ValueDecl *Member, DeclAccessPair FoundDecl,
907 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
908 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000909 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000910 MemberExpr *E = MemberExpr::Create(
911 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
912 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000913 SemaRef.MarkMemberReferenced(E);
914 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000915}
916
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000917/// \brief Determine if the given scope is within a function-try-block handler.
918static bool IsInFnTryBlockHandler(const Scope *S) {
919 // Walk the scope stack until finding a FnTryCatchScope, or leave the
920 // function scope. If a FnTryCatchScope is found, check whether the TryScope
921 // flag is set. If it is not, it's a function-try-block handler.
922 for (; S != S->getFnParent(); S = S->getParent()) {
923 if (S->getFlags() & Scope::FnTryCatchScope)
924 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
925 }
926 return false;
927}
928
Faisal Valie7f8fb92016-02-22 02:24:29 +0000929static VarDecl *
930getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
931 const TemplateArgumentListInfo *TemplateArgs,
932 const DeclarationNameInfo &MemberNameInfo,
933 SourceLocation TemplateKWLoc) {
934
935 if (!TemplateArgs) {
936 S.Diag(MemberNameInfo.getBeginLoc(), diag::err_template_decl_ref)
937 << /*Variable template*/ 1 << MemberNameInfo.getName()
938 << MemberNameInfo.getSourceRange();
939
940 S.Diag(VarTempl->getLocation(), diag::note_template_decl_here);
941
942 return nullptr;
943 }
944 DeclResult VDecl = S.CheckVarTemplateId(
945 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
946 if (VDecl.isInvalid())
947 return nullptr;
948 VarDecl *Var = cast<VarDecl>(VDecl.get());
949 if (!Var->getTemplateSpecializationKind())
950 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
951 MemberNameInfo.getLoc());
952 return Var;
953}
954
Douglas Gregor5476205b2011-06-23 00:49:38 +0000955ExprResult
956Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
957 SourceLocation OpLoc, bool IsArrow,
958 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000959 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000960 NamedDecl *FirstQualifierInScope,
961 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000962 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000963 const Scope *S,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000964 bool SuppressQualifierCheck,
965 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000966 QualType BaseType = BaseExprType;
967 if (IsArrow) {
968 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000969 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000970 }
971 R.setBaseObjectType(BaseType);
Richard Smith4baaa5a2016-12-03 01:14:32 +0000972
973 // C++1z [expr.ref]p2:
974 // For the first option (dot) the first expression shall be a glvalue [...]
975 if (!IsArrow && BaseExpr->isRValue()) {
976 ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
977 if (Converted.isInvalid())
978 return ExprError();
979 BaseExpr = Converted.get();
980 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000981
982 LambdaScopeInfo *const CurLSI = getCurLambda();
983 // If this is an implicit member reference and the overloaded
984 // name refers to both static and non-static member functions
985 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
986 // check if we should/can capture 'this'...
987 // Keep this example in mind:
988 // struct X {
989 // void f(int) { }
990 // static void f(double) { }
991 //
992 // int g() {
993 // auto L = [=](auto a) {
994 // return [](int i) {
995 // return [=](auto b) {
996 // f(b);
997 // //f(decltype(a){});
998 // };
999 // };
1000 // };
1001 // auto M = L(0.0);
1002 // auto N = M(3);
1003 // N(5.32); // OK, must not error.
1004 // return 0;
1005 // }
1006 // };
1007 //
1008 if (!BaseExpr && CurLSI) {
1009 SourceLocation Loc = R.getNameLoc();
1010 if (SS.getRange().isValid())
1011 Loc = SS.getRange().getBegin();
1012 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
1013 // If the enclosing function is not dependent, then this lambda is
1014 // capture ready, so if we can capture this, do so.
1015 if (!EnclosingFunctionCtx->isDependentContext()) {
1016 // If the current lambda and all enclosing lambdas can capture 'this' -
1017 // then go ahead and capture 'this' (since our unresolved overload set
1018 // contains both static and non-static member functions).
1019 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
1020 CheckCXXThisCapture(Loc);
1021 } else if (CurContext->isDependentContext()) {
1022 // ... since this is an implicit member reference, that might potentially
1023 // involve a 'this' capture, mark 'this' for potential capture in
1024 // enclosing lambdas.
1025 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
1026 CurLSI->addPotentialThisCapture(Loc);
1027 }
1028 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001029 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
1030 DeclarationName MemberName = MemberNameInfo.getName();
1031 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1032
1033 if (R.isAmbiguous())
1034 return ExprError();
1035
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001036 // [except.handle]p10: Referring to any non-static member or base class of an
1037 // object in the handler for a function-try-block of a constructor or
1038 // destructor for that object results in undefined behavior.
1039 const auto *FD = getCurFunctionDecl();
1040 if (S && BaseExpr && FD &&
1041 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1042 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1043 IsInFnTryBlockHandler(S))
1044 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1045 << isa<CXXDestructorDecl>(FD);
1046
Douglas Gregor5476205b2011-06-23 00:49:38 +00001047 if (R.empty()) {
1048 // Rederive where we looked up.
1049 DeclContext *DC = (SS.isSet()
1050 ? computeDeclContext(SS, false)
1051 : BaseType->getAs<RecordType>()->getDecl());
1052
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001053 if (ExtraArgs) {
1054 ExprResult RetryExpr;
1055 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +00001056 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001057 ParsedType ObjectType;
1058 bool MayBePseudoDestructor = false;
1059 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1060 OpLoc, tok::arrow, ObjectType,
1061 MayBePseudoDestructor);
1062 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1063 CXXScopeSpec TempSS(SS);
1064 RetryExpr = ActOnMemberAccessExpr(
1065 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +00001066 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001067 }
1068 if (Trap.hasErrorOccurred())
1069 RetryExpr = ExprError();
1070 }
1071 if (RetryExpr.isUsable()) {
1072 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1073 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1074 return RetryExpr;
1075 }
1076 }
1077
Douglas Gregor5476205b2011-06-23 00:49:38 +00001078 Diag(R.getNameLoc(), diag::err_no_member)
1079 << MemberName << DC
1080 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1081 return ExprError();
1082 }
1083
1084 // Diagnose lookups that find only declarations from a non-base
1085 // type. This is possible for either qualified lookups (which may
1086 // have been qualified with an unrelated type) or implicit member
1087 // expressions (which were found with unqualified lookup and thus
1088 // may have come from an enclosing scope). Note that it's okay for
1089 // lookup to find declarations from a non-base type as long as those
1090 // aren't the ones picked by overload resolution.
1091 if ((SS.isSet() || !BaseExpr ||
1092 (isa<CXXThisExpr>(BaseExpr) &&
1093 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1094 !SuppressQualifierCheck &&
1095 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1096 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001097
Douglas Gregor5476205b2011-06-23 00:49:38 +00001098 // Construct an unresolved result if we in fact got an unresolved
1099 // result.
1100 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1101 // Suppress any lookup-related diagnostics; we'll do these when we
1102 // pick a member.
1103 R.suppressDiagnostics();
1104
1105 UnresolvedMemberExpr *MemExpr
1106 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1107 BaseExpr, BaseExprType,
1108 IsArrow, OpLoc,
1109 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001110 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001111 TemplateArgs, R.begin(), R.end());
1112
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001113 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001114 }
1115
1116 assert(R.isSingleResult());
1117 DeclAccessPair FoundDecl = R.begin().getPair();
1118 NamedDecl *MemberDecl = R.getFoundDecl();
1119
1120 // FIXME: diagnose the presence of template arguments now.
1121
1122 // If the decl being referenced had an error, return an error for this
1123 // sub-expr without emitting another error, in order to avoid cascading
1124 // error cases.
1125 if (MemberDecl->isInvalidDecl())
1126 return ExprError();
1127
1128 // Handle the implicit-member-access case.
1129 if (!BaseExpr) {
1130 // If this is not an instance member, convert to a non-member access.
Faisal Valie7f8fb92016-02-22 02:24:29 +00001131 if (!MemberDecl->isCXXInstanceMember()) {
1132 // If this is a variable template, get the instantiated variable
1133 // declaration corresponding to the supplied template arguments
1134 // (while emitting diagnostics as necessary) that will be referenced
1135 // by this expression.
Faisal Vali640dc752016-02-25 05:09:30 +00001136 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1137 "How did we get template arguments here sans a variable template");
Faisal Valie7f8fb92016-02-22 02:24:29 +00001138 if (isa<VarTemplateDecl>(MemberDecl)) {
1139 MemberDecl = getVarTemplateSpecialization(
1140 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1141 R.getLookupNameInfo(), TemplateKWLoc);
1142 if (!MemberDecl)
1143 return ExprError();
1144 }
Faisal Vali640dc752016-02-25 05:09:30 +00001145 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1146 FoundDecl, TemplateArgs);
Faisal Valie7f8fb92016-02-22 02:24:29 +00001147 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001148 SourceLocation Loc = R.getNameLoc();
1149 if (SS.getRange().isValid())
1150 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001151 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001152 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1153 }
1154
Douglas Gregor5476205b2011-06-23 00:49:38 +00001155 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001156 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001157 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001158
Douglas Gregor5476205b2011-06-23 00:49:38 +00001159 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Richard Smith7873de02016-08-11 22:25:46 +00001160 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1161 MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001162
John McCall5e77d762013-04-16 07:28:30 +00001163 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1164 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1165 MemberNameInfo);
1166
Douglas Gregor5476205b2011-06-23 00:49:38 +00001167 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1168 // We may have found a field within an anonymous union or struct
1169 // (C++ [class.union]).
1170 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001171 FoundDecl, BaseExpr,
1172 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001173
1174 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001175 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1176 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001177 Var->getType().getNonReferenceType(), VK_LValue,
1178 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001179 }
1180
1181 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1182 ExprValueKind valueKind;
1183 QualType type;
1184 if (MemberFn->isInstance()) {
1185 valueKind = VK_RValue;
1186 type = Context.BoundMemberTy;
1187 } else {
1188 valueKind = VK_LValue;
1189 type = MemberFn->getType();
1190 }
1191
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001192 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1193 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1194 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001195 }
1196 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1197
1198 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001199 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1200 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1201 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001202 }
Faisal Valie7f8fb92016-02-22 02:24:29 +00001203 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1204 if (VarDecl *Var = getVarTemplateSpecialization(
1205 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1206 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1207 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1208 Var->getType().getNonReferenceType(), VK_LValue,
1209 OK_Ordinary);
1210 return ExprError();
1211 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001212
Douglas Gregor5476205b2011-06-23 00:49:38 +00001213 // We found something that we didn't expect. Complain.
1214 if (isa<TypeDecl>(MemberDecl))
1215 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1216 << MemberName << BaseType << int(IsArrow);
1217 else
1218 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1219 << MemberName << BaseType << int(IsArrow);
1220
1221 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1222 << MemberName;
1223 R.suppressDiagnostics();
1224 return ExprError();
1225}
1226
1227/// Given that normal member access failed on the given expression,
1228/// and given that the expression's type involves builtin-id or
1229/// builtin-Class, decide whether substituting in the redefinition
1230/// types would be profitable. The redefinition type is whatever
1231/// this translation unit tried to typedef to id/Class; we store
1232/// it to the side and then re-use it in places like this.
1233static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1234 const ObjCObjectPointerType *opty
1235 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1236 if (!opty) return false;
1237
1238 const ObjCObjectType *ty = opty->getObjectType();
1239
1240 QualType redef;
1241 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001242 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001243 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001244 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001245 } else {
1246 return false;
1247 }
1248
1249 // Do the substitution as long as the redefinition type isn't just a
1250 // possibly-qualified pointer to builtin-id or builtin-Class again.
1251 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001252 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001253 return false;
1254
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001255 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001256 return true;
1257}
1258
John McCall50a2c2c2011-10-11 23:14:30 +00001259static bool isRecordType(QualType T) {
1260 return T->isRecordType();
1261}
1262static bool isPointerToRecordType(QualType T) {
1263 if (const PointerType *PT = T->getAs<PointerType>())
1264 return PT->getPointeeType()->isRecordType();
1265 return false;
1266}
1267
Richard Smithcab9a7d2011-10-26 19:06:56 +00001268/// Perform conversions on the LHS of a member access expression.
1269ExprResult
1270Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001271 if (IsArrow && !Base->getType()->isFunctionType())
1272 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001273
Eli Friedman9a766c42012-01-13 02:20:01 +00001274 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001275}
1276
Douglas Gregor5476205b2011-06-23 00:49:38 +00001277/// Look up the given member of the given non-type-dependent
1278/// expression. This can return in one of two ways:
1279/// * If it returns a sentinel null-but-valid result, the caller will
1280/// assume that lookup was performed and the results written into
1281/// the provided structure. It will take over from there.
1282/// * Otherwise, the returned expression will be produced in place of
1283/// an ordinary member expression.
1284///
1285/// The ObjCImpDecl bit is a gross hack that will need to be properly
1286/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001287static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1288 ExprResult &BaseExpr, bool &IsArrow,
1289 SourceLocation OpLoc, CXXScopeSpec &SS,
1290 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001291 assert(BaseExpr.get() && "no base expression");
1292
1293 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001294 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001295 if (BaseExpr.isInvalid())
1296 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001297
Douglas Gregor5476205b2011-06-23 00:49:38 +00001298 QualType BaseType = BaseExpr.get()->getType();
1299 assert(!BaseType->isDependentType());
1300
1301 DeclarationName MemberName = R.getLookupName();
1302 SourceLocation MemberLoc = R.getNameLoc();
1303
1304 // For later type-checking purposes, turn arrow accesses into dot
1305 // accesses. The only access type we support that doesn't follow
1306 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1307 // and those never use arrows, so this is unaffected.
1308 if (IsArrow) {
1309 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1310 BaseType = Ptr->getPointeeType();
1311 else if (const ObjCObjectPointerType *Ptr
1312 = BaseType->getAs<ObjCObjectPointerType>())
1313 BaseType = Ptr->getPointeeType();
1314 else if (BaseType->isRecordType()) {
1315 // Recover from arrow accesses to records, e.g.:
1316 // struct MyRecord foo;
1317 // foo->bar
1318 // This is actually well-formed in C++ if MyRecord has an
1319 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001320 // by now--or a diagnostic message already issued if a problem
1321 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001322 if (!S.getLangOpts().CPlusPlus) {
1323 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001324 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1325 << FixItHint::CreateReplacement(OpLoc, ".");
1326 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001327 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001328 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001329 goto fail;
1330 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001331 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001332 << BaseType << BaseExpr.get()->getSourceRange();
1333 return ExprError();
1334 }
1335 }
1336
1337 // Handle field access to simple records.
1338 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001339 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001340 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001341 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001342 return ExprError();
1343
1344 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001345 // the lookup result was filled in. If typo correction was attempted and
1346 // failed, the lookup result will have been cleared--that combined with the
1347 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1348 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001349 }
1350
1351 // Handle ivar access to Objective-C objects.
1352 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001353 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001354 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001355 << 1 << SS.getScopeRep()
1356 << FixItHint::CreateRemoval(SS.getRange());
1357 SS.clear();
1358 }
Richard Smitha0edd302014-05-31 00:18:32 +00001359
Douglas Gregor5476205b2011-06-23 00:49:38 +00001360 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1361
1362 // There are three cases for the base type:
1363 // - builtin id (qualified or unqualified)
1364 // - builtin Class (qualified or unqualified)
1365 // - an interface
1366 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1367 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001368 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001369 (OTy->isObjCId() || OTy->isObjCClass()))
1370 goto fail;
1371 // There's an implicit 'isa' ivar on all objects.
1372 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001373 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001374 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001375 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1376 OpLoc, S.Context.getObjCClassType());
1377 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1378 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001379 ObjCImpDecl, HasTemplateArgs);
1380 goto fail;
1381 }
Richard Smitha0edd302014-05-31 00:18:32 +00001382
1383 if (S.RequireCompleteType(OpLoc, BaseType,
1384 diag::err_typecheck_incomplete_tag,
1385 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001386 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001387
1388 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001389 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1390
1391 if (!IV) {
1392 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001393 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1394 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001395 if (TypoCorrection Corrected = S.CorrectTypo(
1396 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001397 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001398 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001399 S.diagnoseTypo(
1400 Corrected,
1401 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1402 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001403
Ted Kremenek679b4782012-03-17 00:53:39 +00001404 // Figure out the class that declares the ivar.
1405 assert(!ClassDeclared);
Saleem Abdulrasool765a2192016-11-17 17:10:54 +00001406
Ted Kremenek679b4782012-03-17 00:53:39 +00001407 Decl *D = cast<Decl>(IV->getDeclContext());
Saleem Abdulrasool765a2192016-11-17 17:10:54 +00001408 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1409 D = Category->getClassInterface();
1410
1411 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1412 ClassDeclared = Implementation->getClassInterface();
1413 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1414 ClassDeclared = Interface;
1415
1416 assert(ClassDeclared && "cannot query interface");
Douglas Gregor5476205b2011-06-23 00:49:38 +00001417 } else {
Manman Ren5b786402016-01-28 18:49:28 +00001418 if (IsArrow &&
1419 IDecl->FindPropertyDeclaration(
1420 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001421 S.Diag(MemberLoc, diag::err_property_found_suggest)
1422 << Member << BaseExpr.get()->getType()
1423 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001424 return ExprError();
1425 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001426
Richard Smitha0edd302014-05-31 00:18:32 +00001427 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1428 << IDecl->getDeclName() << MemberName
1429 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001430 return ExprError();
1431 }
1432 }
Richard Smitha0edd302014-05-31 00:18:32 +00001433
Ted Kremenek679b4782012-03-17 00:53:39 +00001434 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001435
1436 // If the decl being referenced had an error, return an error for this
1437 // sub-expr without emitting another error, in order to avoid cascading
1438 // error cases.
1439 if (IV->isInvalidDecl())
1440 return ExprError();
1441
1442 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001443 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001444 return ExprError();
1445 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1446 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001447 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001448 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001449 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001450 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001451 // Case of a c-function declared inside an objc implementation.
1452 // FIXME: For a c-style function nested inside an objc implementation
1453 // class, there is no implementation context available, so we pass
1454 // down the context as argument to this routine. Ideally, this context
1455 // need be passed down in the AST node and somehow calculated from the
1456 // AST for a function decl.
1457 if (ObjCImplementationDecl *IMPD =
1458 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1459 ClassOfMethodDecl = IMPD->getClassInterface();
1460 else if (ObjCCategoryImplDecl* CatImplClass =
1461 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1462 ClassOfMethodDecl = CatImplClass->getClassInterface();
1463 }
Richard Smitha0edd302014-05-31 00:18:32 +00001464 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001465 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1466 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1467 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smithf8812672016-12-02 22:38:31 +00001468 S.Diag(MemberLoc, diag::err_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001469 << IV->getDeclName();
1470 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1471 // @protected
Richard Smithf8812672016-12-02 22:38:31 +00001472 S.Diag(MemberLoc, diag::err_protected_ivar_access)
Richard Smitha0edd302014-05-31 00:18:32 +00001473 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001474 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001475 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001476 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001477 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001478 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1479 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1480 if (UO->getOpcode() == UO_Deref)
1481 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1482
1483 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001484 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smithf8812672016-12-02 22:38:31 +00001485 S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001486 warn = false;
1487 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001488 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001489 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001490 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001491 ObjCMethodFamily MF = MD->getMethodFamily();
1492 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001493 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001494 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001495 }
1496 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001497 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001498 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001499
Richard Smitha0edd302014-05-31 00:18:32 +00001500 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001501 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1502 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001503
Richard Smitha0edd302014-05-31 00:18:32 +00001504 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001505 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001506 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001507 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001508 }
1509 }
1510
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001511 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001512 }
1513
1514 // Objective-C property access.
1515 const ObjCObjectPointerType *OPT;
1516 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001517 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001518 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1519 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001520 SS.clear();
1521 }
1522
Douglas Gregor5476205b2011-06-23 00:49:38 +00001523 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001524 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001525 if (BaseExpr.isInvalid())
1526 return ExprError();
1527
Richard Smitha0edd302014-05-31 00:18:32 +00001528 assert(S.Context.hasSameUnqualifiedType(BaseType,
1529 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001530
1531 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1532
1533 const ObjCObjectType *OT = OPT->getObjectType();
1534
1535 // id, with and without qualifiers.
1536 if (OT->isObjCId()) {
1537 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001538 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1539 if (Decl *PMDecl =
1540 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001541 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1542 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001543 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001544 return ExprError();
1545
Richard Smitha0edd302014-05-31 00:18:32 +00001546 return new (S.Context)
1547 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001548 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001549 }
1550
1551 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1552 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001553 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001554 return ExprError();
1555 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001556 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1557 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001558 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001559 ObjCMethodDecl *SMD = nullptr;
1560 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001561 /*Property id*/ nullptr,
1562 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001563 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001564
1565 return new (S.Context)
1566 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001567 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001568 }
1569 }
1570 // Use of id.member can only be for a property reference. Do not
1571 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001572 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1573 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001574 ObjCImpDecl, HasTemplateArgs);
1575
Richard Smitha0edd302014-05-31 00:18:32 +00001576 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001577 << MemberName << BaseType);
1578 }
1579
1580 // 'Class', unqualified only.
1581 if (OT->isObjCClass()) {
1582 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001583 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001584 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001585 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1586 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001587 ObjCImpDecl, HasTemplateArgs);
1588
1589 goto fail;
1590 }
1591
1592 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001593 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001594 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1595 ObjCMethodDecl *Getter;
1596 if ((Getter = IFace->lookupClassMethod(Sel))) {
1597 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001598 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001599 return ExprError();
1600 } else
1601 Getter = IFace->lookupPrivateMethod(Sel, false);
1602 // If we found a getter then this may be a valid dot-reference, we
1603 // will look for the matching setter, in case it is needed.
1604 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001605 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1606 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001607 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001608 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1609 if (!Setter) {
1610 // If this reference is in an @implementation, also check for 'private'
1611 // methods.
1612 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1613 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001614
Richard Smitha0edd302014-05-31 00:18:32 +00001615 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001616 return ExprError();
1617
1618 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001619 return new (S.Context) ObjCPropertyRefExpr(
1620 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1621 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001622 }
1623
Richard Smitha0edd302014-05-31 00:18:32 +00001624 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1625 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001626 ObjCImpDecl, HasTemplateArgs);
1627
Richard Smitha0edd302014-05-31 00:18:32 +00001628 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001629 << MemberName << BaseType);
1630 }
1631
1632 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001633 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1634 MemberLoc, SourceLocation(), QualType(),
1635 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001636 }
1637
1638 // Handle 'field access' to vectors, such as 'V.xx'.
1639 if (BaseType->isExtVectorType()) {
1640 // FIXME: this expr should store IsArrow.
1641 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001642 ExprValueKind VK;
1643 if (IsArrow)
1644 VK = VK_LValue;
1645 else {
1646 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1647 VK = POE->getSyntacticForm()->getValueKind();
1648 else
1649 VK = BaseExpr.get()->getValueKind();
1650 }
Richard Smitha0edd302014-05-31 00:18:32 +00001651 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001652 Member, MemberLoc);
1653 if (ret.isNull())
1654 return ExprError();
1655
Richard Smitha0edd302014-05-31 00:18:32 +00001656 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001657 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001658 }
1659
1660 // Adjust builtin-sel to the appropriate redefinition type if that's
1661 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001662 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1663 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1664 BaseExpr = S.ImpCastExprToType(
1665 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1666 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001667 ObjCImpDecl, HasTemplateArgs);
1668 }
1669
1670 // Failure cases.
1671 fail:
1672
1673 // Recover from dot accesses to pointers, e.g.:
1674 // type *foo;
1675 // foo.bar
1676 // This is actually well-formed in two cases:
1677 // - 'type' is an Objective C type
1678 // - 'bar' is a pseudo-destructor name which happens to refer to
1679 // the appropriate pointer type
1680 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1681 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1682 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001683 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1684 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001685 << FixItHint::CreateReplacement(OpLoc, "->");
1686
1687 // Recurse as an -> access.
1688 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001689 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001690 ObjCImpDecl, HasTemplateArgs);
1691 }
1692 }
1693
1694 // If the user is trying to apply -> or . to a function name, it's probably
1695 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001696 if (S.tryToRecoverWithCall(
1697 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1698 /*complain*/ false,
1699 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001700 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001701 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001702 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1703 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001704 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001705 }
1706
Richard Smitha0edd302014-05-31 00:18:32 +00001707 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001708 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001709
1710 return ExprError();
1711}
1712
1713/// The main callback when the parser finds something like
1714/// expression . [nested-name-specifier] identifier
1715/// expression -> [nested-name-specifier] identifier
1716/// where 'identifier' encompasses a fairly broad spectrum of
1717/// possibilities, including destructor and operator references.
1718///
1719/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001720/// \param ObjCImpDecl the current Objective-C \@implementation
1721/// decl; this is an ugly hack around the fact that Objective-C
1722/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001723ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1724 SourceLocation OpLoc,
1725 tok::TokenKind OpKind,
1726 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001727 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001728 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001729 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001730 if (SS.isSet() && SS.isInvalid())
1731 return ExprError();
1732
1733 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001734 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001735 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1736 Diag(Id.getSourceRange().getBegin(),
1737 diag::ext_ms_explicit_constructor_call);
1738
1739 TemplateArgumentListInfo TemplateArgsBuffer;
1740
1741 // Decompose the name into its component parts.
1742 DeclarationNameInfo NameInfo;
1743 const TemplateArgumentListInfo *TemplateArgs;
1744 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1745 NameInfo, TemplateArgs);
1746
1747 DeclarationName Name = NameInfo.getName();
1748 bool IsArrow = (OpKind == tok::arrow);
1749
1750 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001751 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001752
1753 // This is a postfix expression, so get rid of ParenListExprs.
1754 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1755 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001756 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001757
1758 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1759 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001760 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1761 TemplateKWLoc, FirstQualifierInScope,
1762 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001763 }
1764
David Majnemerced8bdf2015-02-25 17:36:15 +00001765 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001766 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1767 TemplateKWLoc, FirstQualifierInScope,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001768 NameInfo, TemplateArgs, S, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001769}
1770
Richard Smith7873de02016-08-11 22:25:46 +00001771ExprResult
1772Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1773 SourceLocation OpLoc, const CXXScopeSpec &SS,
1774 FieldDecl *Field, DeclAccessPair FoundDecl,
1775 const DeclarationNameInfo &MemberNameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001776 // x.a is an l-value if 'a' has a reference type. Otherwise:
1777 // x.a is an l-value/x-value/pr-value if the base is (and note
1778 // that *x is always an l-value), except that if the base isn't
1779 // an ordinary object then we must have an rvalue.
1780 ExprValueKind VK = VK_LValue;
1781 ExprObjectKind OK = OK_Ordinary;
1782 if (!IsArrow) {
1783 if (BaseExpr->getObjectKind() == OK_Ordinary)
1784 VK = BaseExpr->getValueKind();
1785 else
1786 VK = VK_RValue;
1787 }
1788 if (VK != VK_RValue && Field->isBitField())
1789 OK = OK_BitField;
1790
1791 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1792 QualType MemberType = Field->getType();
1793 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1794 MemberType = Ref->getPointeeType();
1795 VK = VK_LValue;
1796 } else {
1797 QualType BaseType = BaseExpr->getType();
1798 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001799
Douglas Gregor5476205b2011-06-23 00:49:38 +00001800 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001801
Douglas Gregor5476205b2011-06-23 00:49:38 +00001802 // GC attributes are never picked up by members.
1803 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001804
Douglas Gregor5476205b2011-06-23 00:49:38 +00001805 // CVR attributes from the base are picked up by members,
1806 // except that 'mutable' members don't pick up 'const'.
1807 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001808
Richard Smith7873de02016-08-11 22:25:46 +00001809 Qualifiers MemberQuals =
1810 Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001811
Douglas Gregor5476205b2011-06-23 00:49:38 +00001812 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001813
Douglas Gregor5476205b2011-06-23 00:49:38 +00001814 Qualifiers Combined = BaseQuals + MemberQuals;
1815 if (Combined != MemberQuals)
Richard Smith7873de02016-08-11 22:25:46 +00001816 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001817 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001818
Richard Smith7873de02016-08-11 22:25:46 +00001819 UnusedPrivateFields.remove(Field);
Daniel Jasper0baec5492012-06-06 08:32:04 +00001820
Richard Smith7873de02016-08-11 22:25:46 +00001821 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1822 FoundDecl, Field);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001823 if (Base.isInvalid())
1824 return ExprError();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001825 MemberExpr *ME =
Richard Smith7873de02016-08-11 22:25:46 +00001826 BuildMemberExpr(*this, Context, Base.get(), IsArrow, OpLoc, SS,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001827 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1828 MemberNameInfo, MemberType, VK, OK);
1829
1830 // Build a reference to a private copy for non-static data members in
1831 // non-static member functions, privatized by OpenMP constructs.
Richard Smith7873de02016-08-11 22:25:46 +00001832 if (getLangOpts().OpenMP && IsArrow &&
1833 !CurContext->isDependentContext() &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001834 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
Richard Smith7873de02016-08-11 22:25:46 +00001835 if (auto *PrivateCopy = IsOpenMPCapturedDecl(Field))
1836 return getOpenMPCapturedExpr(PrivateCopy, VK, OK, OpLoc);
Alexey Bataev90c228f2016-02-08 09:29:13 +00001837 }
1838 return ME;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001839}
1840
1841/// Builds an implicit member access expression. The current context
1842/// is known to be an instance method, and the given unqualified lookup
1843/// set is known to contain only instance members, at least one of which
1844/// is from an appropriate type.
1845ExprResult
1846Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001847 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001848 LookupResult &R,
1849 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001850 bool IsKnownInstance, const Scope *S) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001851 assert(!R.empty() && !R.isAmbiguous());
1852
1853 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001854
Douglas Gregor5476205b2011-06-23 00:49:38 +00001855 // If this is known to be an instance access, go ahead and build an
1856 // implicit 'this' expression now.
1857 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001858 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001859 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001860
1861 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001862 if (IsKnownInstance) {
1863 SourceLocation Loc = R.getNameLoc();
1864 if (SS.getRange().isValid())
1865 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001866 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001867 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1868 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001869
Douglas Gregor5476205b2011-06-23 00:49:38 +00001870 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1871 /*OpLoc*/ SourceLocation(),
1872 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001873 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001874 /*FirstQualifierInScope*/ nullptr,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001875 R, TemplateArgs, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001876}