blob: 1c34ace856280271a911a4e2f0e26e839eed5899 [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) {
Faisal Valid143a0c2017-04-01 21:30:49 +0000136 case Sema::ExpressionEvaluationContext::Unevaluated:
137 case Sema::ExpressionEvaluationContext::UnevaluatedList:
John McCallf413f5e2013-05-03 00:10:13 +0000138 if (isField && SemaRef.getLangOpts().CPlusPlus11)
139 AbstractInstanceResult = IMA_Field_Uneval_Context;
140 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000141
Faisal Valid143a0c2017-04-01 21:30:49 +0000142 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
John McCallf413f5e2013-05-03 00:10:13 +0000143 AbstractInstanceResult = IMA_Abstract;
144 break;
145
Faisal Valid143a0c2017-04-01 21:30:49 +0000146 case Sema::ExpressionEvaluationContext::DiscardedStatement:
147 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
148 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
149 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
John McCallf413f5e2013-05-03 00:10:13 +0000150 break;
Richard Smitheae99682012-02-25 10:04:07 +0000151 }
152
Douglas Gregor5476205b2011-06-23 00:49:38 +0000153 // If the current context is not an instance method, it can't be
154 // an implicit member reference.
155 if (isStaticContext) {
156 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000157 return IMA_Mixed_StaticContext;
158
John McCallf413f5e2013-05-03 00:10:13 +0000159 return AbstractInstanceResult ? AbstractInstanceResult
160 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000161 }
162
163 CXXRecordDecl *contextClass;
164 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
165 contextClass = MD->getParent()->getCanonicalDecl();
166 else
167 contextClass = cast<CXXRecordDecl>(DC);
168
169 // [class.mfct.non-static]p3:
170 // ...is used in the body of a non-static member function of class X,
171 // if name lookup (3.4.1) resolves the name in the id-expression to a
172 // non-static non-type member of some class C [...]
173 // ...if C is not X or a base class of X, the class member access expression
174 // is ill-formed.
175 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000176 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000177 R.getNamingClass()->getCanonicalDecl()) {
178 // If the naming class is not the current context, this was a qualified
179 // member name lookup, and it's sufficient to check that we have the naming
180 // class as a base class.
181 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000182 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000183 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000184
185 // If we can prove that the current context is unrelated to all the
186 // declaring classes, it can't be an implicit member reference (in
187 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000188 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000189 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000190 AbstractInstanceResult ? AbstractInstanceResult :
191 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000192
193 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
194}
195
196/// Diagnose a reference to a field with no object available.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000197static void diagnoseInstanceReference(Sema &SemaRef,
198 const CXXScopeSpec &SS,
199 NamedDecl *Rep,
200 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000201 SourceLocation Loc = nameInfo.getLoc();
202 SourceRange Range(Loc);
203 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000204
Reid Klecknerae628962014-12-18 00:42:51 +0000205 // Look through using shadow decls and aliases.
206 Rep = Rep->getUnderlyingDecl();
207
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000208 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
Richard Smithfa0a1f52012-04-05 01:13:04 +0000209 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000210 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000211 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
212
213 bool InStaticMethod = Method && Method->isStatic();
214 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
215
216 if (IsField && InStaticMethod)
217 // "invalid use of member 'x' in static member function"
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000218 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000219 << Range << nameInfo.getName();
220 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
221 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
222 // Unqualified lookup in a non-static member function found a member of an
223 // enclosing class.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000224 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
225 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000226 else if (IsField)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000227 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
228 << nameInfo.getName() << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000229 else
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000230 SemaRef.Diag(Loc, diag::err_member_call_without_object)
231 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000232}
233
234/// Builds an expression which might be an implicit member expression.
235ExprResult
236Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000237 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000238 LookupResult &R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000239 const TemplateArgumentListInfo *TemplateArgs,
240 const Scope *S) {
Reid Klecknerae628962014-12-18 00:42:51 +0000241 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000242 case IMA_Instance:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000243 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000244
245 case IMA_Mixed:
246 case IMA_Mixed_Unrelated:
247 case IMA_Unresolved:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000248 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
249 S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000250
Richard Smith2a986112012-02-25 10:20:59 +0000251 case IMA_Field_Uneval_Context:
252 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
253 << R.getLookupNameInfo().getName();
254 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000255 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000256 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000257 case IMA_Mixed_StaticContext:
258 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000259 if (TemplateArgs || TemplateKWLoc.isValid())
260 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000261 return BuildDeclarationNameExpr(SS, R, false);
262
263 case IMA_Error_StaticContext:
264 case IMA_Error_Unrelated:
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000265 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000266 R.getLookupNameInfo());
267 return ExprError();
268 }
269
270 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000271}
272
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000273/// Determine whether input char is from rgba component set.
274static bool
275IsRGBA(char c) {
276 switch (c) {
277 case 'r':
278 case 'g':
279 case 'b':
280 case 'a':
281 return true;
282 default:
283 return false;
284 }
285}
286
Egor Churaev392a5072017-03-21 13:20:57 +0000287// OpenCL v1.1, s6.1.7
288// The component swizzle length must be in accordance with the acceptable
289// vector sizes.
290static bool IsValidOpenCLComponentSwizzleLength(unsigned len)
291{
292 return (len >= 1 && len <= 4) || len == 8 || len == 16;
293}
294
Douglas Gregor5476205b2011-06-23 00:49:38 +0000295/// Check an ext-vector component access expression.
296///
297/// VK should be set in advance to the value kind of the base
298/// expression.
299static QualType
300CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
301 SourceLocation OpLoc, const IdentifierInfo *CompName,
302 SourceLocation CompLoc) {
303 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
304 // see FIXME there.
305 //
306 // FIXME: This logic can be greatly simplified by splitting it along
307 // halving/not halving and reworking the component checking.
308 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
309
310 // The vector accessor can't exceed the number of elements.
311 const char *compStr = CompName->getNameStart();
312
313 // This flag determines whether or not the component is one of the four
314 // special names that indicate a subset of exactly half the elements are
315 // to be selected.
316 bool HalvingSwizzle = false;
317
318 // This flag determines whether or not CompName has an 's' char prefix,
319 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000320 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000321
322 bool HasRepeated = false;
323 bool HasIndex[16] = {};
324
325 int Idx;
326
327 // Check that we've found one of the special components, or that the component
328 // names must come from the same set.
329 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
330 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
331 HalvingSwizzle = true;
332 } else if (!HexSwizzle &&
333 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000334 bool HasRGBA = IsRGBA(*compStr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000335 do {
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000336 // Ensure that xyzw and rgba components don't intermingle.
337 if (HasRGBA != IsRGBA(*compStr))
338 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000339 if (HasIndex[Idx]) HasRepeated = true;
340 HasIndex[Idx] = true;
341 compStr++;
342 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000343
344 // Emit a warning if an rgba selector is used earlier than OpenCL 2.2
345 if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
346 if (S.getLangOpts().OpenCL && S.getLangOpts().OpenCLVersion < 220) {
347 const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
348 S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
349 << StringRef(DiagBegin, 1)
350 << S.getLangOpts().OpenCLVersion << SourceRange(CompLoc);
351 }
352 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000353 } else {
354 if (HexSwizzle) compStr++;
355 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
356 if (HasIndex[Idx]) HasRepeated = true;
357 HasIndex[Idx] = true;
358 compStr++;
359 }
360 }
361
362 if (!HalvingSwizzle && *compStr) {
363 // We didn't get to the end of the string. This means the component names
364 // didn't come from the same set *or* we encountered an illegal name.
365 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000366 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000367 return QualType();
368 }
369
370 // Ensure no component accessor exceeds the width of the vector type it
371 // operates on.
372 if (!HalvingSwizzle) {
373 compStr = CompName->getNameStart();
374
375 if (HexSwizzle)
376 compStr++;
377
378 while (*compStr) {
Pirama Arumuga Nainar98eaa622016-07-22 18:49:43 +0000379 if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000380 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
381 << baseType << SourceRange(CompLoc);
382 return QualType();
383 }
384 }
385 }
386
Egor Churaev392a5072017-03-21 13:20:57 +0000387 if (!HalvingSwizzle) {
388 unsigned SwizzleLength = CompName->getLength();
389
390 if (HexSwizzle)
391 SwizzleLength--;
392
393 if (IsValidOpenCLComponentSwizzleLength(SwizzleLength) == false) {
394 S.Diag(OpLoc, diag::err_opencl_ext_vector_component_invalid_length)
395 << SwizzleLength << SourceRange(CompLoc);
396 return QualType();
397 }
398 }
399
Douglas Gregor5476205b2011-06-23 00:49:38 +0000400 // The component accessor looks fine - now we need to compute the actual type.
401 // The vector type is implied by the component accessor. For example,
402 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
403 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
404 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
405 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
406 : CompName->getLength();
407 if (HexSwizzle)
408 CompSize--;
409
410 if (CompSize == 1)
411 return vecType->getElementType();
412
413 if (HasRepeated) VK = VK_RValue;
414
415 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
416 // Now look up the TypeDefDecl from the vector type. Without this,
417 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000418 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000419 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000420 E = S.ExtVectorDecls.end();
421 I != E; ++I) {
422 if ((*I)->getUnderlyingType() == VT)
423 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000424 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000425
Douglas Gregor5476205b2011-06-23 00:49:38 +0000426 return VT; // should never get here (a typedef type should always be found).
427}
428
429static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
430 IdentifierInfo *Member,
431 const Selector &Sel,
432 ASTContext &Context) {
433 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000434 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
435 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000436 return PD;
437 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
438 return OMD;
439
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000440 for (const auto *I : PDecl->protocols()) {
441 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000442 Context))
443 return D;
444 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000445 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000446}
447
448static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
449 IdentifierInfo *Member,
450 const Selector &Sel,
451 ASTContext &Context) {
452 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000453 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000454 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000455 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000456 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
457 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000458 GDecl = PD;
459 break;
460 }
461 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000462 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000463 GDecl = OMD;
464 break;
465 }
466 }
467 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000468 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000469 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000470 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000471 if (GDecl)
472 return GDecl;
473 }
474 }
475 return GDecl;
476}
477
478ExprResult
479Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
480 bool IsArrow, SourceLocation OpLoc,
481 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000482 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000483 NamedDecl *FirstQualifierInScope,
484 const DeclarationNameInfo &NameInfo,
485 const TemplateArgumentListInfo *TemplateArgs) {
486 // Even in dependent contexts, try to diagnose base expressions with
487 // obviously wrong types, e.g.:
488 //
489 // T* t;
490 // t.f;
491 //
492 // In Obj-C++, however, the above expression is valid, since it could be
493 // accessing the 'f' property if T is an Obj-C interface. The extra check
494 // allows this, while still reporting an error if T is a struct pointer.
495 if (!IsArrow) {
496 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000497 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000498 PT->getPointeeType()->isRecordType())) {
499 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000500 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000501 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000502 return ExprError();
503 }
504 }
505
506 assert(BaseType->isDependentType() ||
507 NameInfo.getName().isDependentName() ||
508 isDependentScopeSpecifier(SS));
509
510 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
511 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000512 return CXXDependentScopeMemberExpr::Create(
513 Context, BaseExpr, BaseType, IsArrow, OpLoc,
514 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
515 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000516}
517
518/// We know that the given qualified member reference points only to
519/// declarations which do not belong to the static type of the base
520/// expression. Diagnose the problem.
521static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
522 Expr *BaseExpr,
523 QualType BaseType,
524 const CXXScopeSpec &SS,
525 NamedDecl *rep,
526 const DeclarationNameInfo &nameInfo) {
527 // If this is an implicit member access, use a different set of
528 // diagnostics.
529 if (!BaseExpr)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000530 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000531
532 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
533 << SS.getRange() << rep << BaseType;
534}
535
536// Check whether the declarations we found through a nested-name
537// specifier in a member expression are actually members of the base
538// type. The restriction here is:
539//
540// C++ [expr.ref]p2:
541// ... In these cases, the id-expression shall name a
542// member of the class or of one of its base classes.
543//
544// So it's perfectly legitimate for the nested-name specifier to name
545// an unrelated class, and for us to find an overload set including
546// decls from classes which are not superclasses, as long as the decl
547// we actually pick through overload resolution is from a superclass.
548bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
549 QualType BaseType,
550 const CXXScopeSpec &SS,
551 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000552 CXXRecordDecl *BaseRecord =
553 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
554 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000555 // We can't check this yet because the base type is still
556 // dependent.
557 assert(BaseType->isDependentType());
558 return false;
559 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000560
561 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
562 // If this is an implicit member reference and we find a
563 // non-instance member, it's not an error.
564 if (!BaseExpr && !(*I)->isCXXInstanceMember())
565 return false;
566
567 // Note that we use the DC of the decl, not the underlying decl.
568 DeclContext *DC = (*I)->getDeclContext();
569 while (DC->isTransparentContext())
570 DC = DC->getParent();
571
572 if (!DC->isRecord())
573 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000574
Richard Smithd80b2d52012-11-22 00:24:47 +0000575 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
576 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
577 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000578 return false;
579 }
580
581 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
582 R.getRepresentativeDecl(),
583 R.getLookupNameInfo());
584 return true;
585}
586
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000587namespace {
588
589// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000590// FunctionTemplateDecl and are declared in the current record or, for a C++
591// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000592class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000593public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000594 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000595 : Record(RTy->getDecl()) {
596 // Don't add bare keywords to the consumer since they will always fail
597 // validation by virtue of not being associated with any decls.
598 WantTypeSpecifiers = false;
599 WantExpressionKeywords = false;
600 WantCXXNamedCasts = false;
601 WantFunctionLikeCasts = false;
602 WantRemainingKeywords = false;
603 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000604
Craig Toppere14c0f82014-03-12 04:55:44 +0000605 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000606 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000607 // Don't accept candidates that cannot be member functions, constants,
608 // variables, or templates.
609 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
610 return false;
611
612 // Accept candidates that occur in the current record.
613 if (Record->containsDecl(ND))
614 return true;
615
616 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
617 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000618 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000619 if (const RecordType *BSTy =
620 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000621 if (BSTy->getDecl()->containsDecl(ND))
622 return true;
623 }
624 }
625 }
626
627 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000628 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000629
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000630private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000631 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000632};
633
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000634}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000635
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000636static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000637 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000638 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000639 SourceLocation OpLoc, bool IsArrow,
640 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000641 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000642 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000643 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000644 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
645 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000646 diag::err_typecheck_incomplete_tag,
647 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000648 return true;
649
650 if (HasTemplateArgs) {
651 // LookupTemplateName doesn't expect these both to exist simultaneously.
652 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
653
654 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000655 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000656 return false;
657 }
658
659 DeclContext *DC = RDecl;
660 if (SS.isSet()) {
661 // If the member name was a qualified-id, look into the
662 // nested-name-specifier.
663 DC = SemaRef.computeDeclContext(SS, false);
664
665 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
666 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000667 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000668 return true;
669 }
670
671 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
672
673 if (!isa<TypeDecl>(DC)) {
674 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000675 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000676 return true;
677 }
678 }
679
680 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000681 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000682
683 if (!R.empty())
684 return false;
685
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000686 DeclarationName Typo = R.getLookupName();
687 SourceLocation TypoLoc = R.getNameLoc();
David Blaikiea8173ba2015-09-28 23:48:55 +0000688
689 struct QueryState {
690 Sema &SemaRef;
691 DeclarationNameInfo NameInfo;
692 Sema::LookupNameKind LookupKind;
693 Sema::RedeclarationKind Redecl;
694 };
695 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
696 R.isForRedeclaration() ? Sema::ForRedeclaration
697 : Sema::NotForRedeclaration};
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000698 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000699 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
700 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000701 [=, &SemaRef](const TypoCorrection &TC) {
702 if (TC) {
703 assert(!TC.isKeyword() &&
704 "Got a keyword as a correction for a member!");
705 bool DroppedSpecifier =
706 TC.WillReplaceSpecifier() &&
707 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
708 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
709 << Typo << DC << DroppedSpecifier
710 << SS.getRange());
711 } else {
712 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
713 }
714 },
715 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
David Blaikiea8173ba2015-09-28 23:48:55 +0000716 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000717 R.clear(); // Ensure there's no decls lingering in the shared state.
718 R.suppressDiagnostics();
719 R.setLookupName(TC.getCorrection());
720 for (NamedDecl *ND : TC)
721 R.addDecl(ND);
722 R.resolveKind();
723 return SemaRef.BuildMemberReferenceExpr(
724 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000725 nullptr, R, nullptr, nullptr);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000726 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000727 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000728
729 return false;
730}
731
Richard Smitha0edd302014-05-31 00:18:32 +0000732static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
733 ExprResult &BaseExpr, bool &IsArrow,
734 SourceLocation OpLoc, CXXScopeSpec &SS,
735 Decl *ObjCImpDecl, bool HasTemplateArgs);
736
Douglas Gregor5476205b2011-06-23 00:49:38 +0000737ExprResult
738Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
739 SourceLocation OpLoc, bool IsArrow,
740 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000741 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000742 NamedDecl *FirstQualifierInScope,
743 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000744 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000745 const Scope *S,
Richard Smitha0edd302014-05-31 00:18:32 +0000746 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000747 if (BaseType->isDependentType() ||
748 (SS.isSet() && isDependentScopeSpecifier(SS)))
749 return ActOnDependentMemberExpr(Base, BaseType,
750 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000751 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000752 NameInfo, TemplateArgs);
753
754 LookupResult R(*this, NameInfo, LookupMemberName);
755
756 // Implicit member accesses.
757 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000758 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000759 QualType RecordTy = BaseType;
760 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000761 if (LookupMemberExprInRecord(*this, R, nullptr,
762 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000763 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000764 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000765 if (TE)
766 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000767
768 // Explicit member accesses.
769 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000770 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000771 ExprResult Result = LookupMemberExpr(
772 *this, R, BaseResult, IsArrow, OpLoc, SS,
773 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
774 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000775
776 if (BaseResult.isInvalid())
777 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000778 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000779
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000780 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000781 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000782
783 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000784 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000785
786 // LookupMemberExpr can modify Base, and thus change BaseType
787 BaseType = Base->getType();
788 }
789
790 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000791 OpLoc, IsArrow, SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000792 FirstQualifierInScope, R, TemplateArgs, S,
Richard Smitha0edd302014-05-31 00:18:32 +0000793 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000794}
795
Douglas Gregor5476205b2011-06-23 00:49:38 +0000796ExprResult
797Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
798 SourceLocation loc,
799 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000800 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000801 Expr *baseObjectExpr,
802 SourceLocation opLoc) {
803 // First, build the expression that refers to the base object.
804
805 bool baseObjectIsPointer = false;
806 Qualifiers baseQuals;
807
808 // Case 1: the base of the indirect field is not a field.
809 VarDecl *baseVariable = indirectField->getVarDecl();
810 CXXScopeSpec EmptySS;
811 if (baseVariable) {
812 assert(baseVariable->getType()->isRecordType());
813
814 // In principle we could have a member access expression that
815 // accesses an anonymous struct/union that's a static member of
816 // the base object's class. However, under the current standard,
817 // static data members cannot be anonymous structs or unions.
818 // Supporting this is as easy as building a MemberExpr here.
819 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
820
821 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
822
823 ExprResult result
824 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
825 if (result.isInvalid()) return ExprError();
826
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000827 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000828 baseObjectIsPointer = false;
829 baseQuals = baseObjectExpr->getType().getQualifiers();
830
831 // Case 2: the base of the indirect field is a field and the user
832 // wrote a member expression.
833 } else if (baseObjectExpr) {
834 // The caller provided the base object expression. Determine
835 // whether its a pointer and whether it adds any qualifiers to the
836 // anonymous struct/union fields we're looking into.
837 QualType objectType = baseObjectExpr->getType();
838
839 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
840 baseObjectIsPointer = true;
841 objectType = ptr->getPointeeType();
842 } else {
843 baseObjectIsPointer = false;
844 }
845 baseQuals = objectType.getQualifiers();
846
847 // Case 3: the base of the indirect field is a field and we should
848 // build an implicit member access.
849 } else {
850 // We've found a member of an anonymous struct/union that is
851 // inside a non-anonymous struct/union, so in a well-formed
852 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000853 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000854 if (ThisTy.isNull()) {
855 Diag(loc, diag::err_invalid_member_use_in_static_method)
856 << indirectField->getDeclName();
857 return ExprError();
858 }
859
860 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000861 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000862 baseObjectExpr
863 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
864 baseObjectIsPointer = true;
865 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
866 }
867
868 // Build the implicit member references to the field of the
869 // anonymous struct/union.
870 Expr *result = baseObjectExpr;
871 IndirectFieldDecl::chain_iterator
872 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
873
874 // Build the first member access in the chain with full information.
875 if (!baseVariable) {
876 FieldDecl *field = cast<FieldDecl>(*FI);
877
Douglas Gregor5476205b2011-06-23 00:49:38 +0000878 // Make a nameInfo that properly uses the anonymous name.
879 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000880
Richard Smith7873de02016-08-11 22:25:46 +0000881 result = BuildFieldReferenceExpr(result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000882 SourceLocation(), EmptySS, field,
883 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000884 if (!result)
885 return ExprError();
886
Douglas Gregor5476205b2011-06-23 00:49:38 +0000887 // FIXME: check qualified member access
888 }
889
890 // In all cases, we should now skip the first declaration in the chain.
891 ++FI;
892
893 while (FI != FEnd) {
894 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000895
Douglas Gregor5476205b2011-06-23 00:49:38 +0000896 // FIXME: these are somewhat meaningless
897 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000898 DeclAccessPair fakeFoundDecl =
899 DeclAccessPair::make(field, field->getAccess());
900
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000901 result =
Richard Smith7873de02016-08-11 22:25:46 +0000902 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
903 (FI == FEnd ? SS : EmptySS), field,
904 fakeFoundDecl, memberNameInfo)
905 .get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000906 }
907
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000908 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000909}
910
John McCall5e77d762013-04-16 07:28:30 +0000911static ExprResult
912BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
913 const CXXScopeSpec &SS,
914 MSPropertyDecl *PD,
915 const DeclarationNameInfo &NameInfo) {
916 // Property names are always simple identifiers and therefore never
917 // require any interesting additional storage.
918 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
919 S.Context.PseudoObjectTy, VK_LValue,
920 SS.getWithLocInContext(S.Context),
921 NameInfo.getLoc());
922}
923
Douglas Gregor5476205b2011-06-23 00:49:38 +0000924/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000925static MemberExpr *BuildMemberExpr(
926 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
927 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
928 ValueDecl *Member, DeclAccessPair FoundDecl,
929 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
930 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000931 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000932 MemberExpr *E = MemberExpr::Create(
933 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
934 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000935 SemaRef.MarkMemberReferenced(E);
936 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000937}
938
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000939/// \brief Determine if the given scope is within a function-try-block handler.
940static bool IsInFnTryBlockHandler(const Scope *S) {
941 // Walk the scope stack until finding a FnTryCatchScope, or leave the
942 // function scope. If a FnTryCatchScope is found, check whether the TryScope
943 // flag is set. If it is not, it's a function-try-block handler.
944 for (; S != S->getFnParent(); S = S->getParent()) {
945 if (S->getFlags() & Scope::FnTryCatchScope)
946 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
947 }
948 return false;
949}
950
Faisal Valie7f8fb92016-02-22 02:24:29 +0000951static VarDecl *
952getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
953 const TemplateArgumentListInfo *TemplateArgs,
954 const DeclarationNameInfo &MemberNameInfo,
955 SourceLocation TemplateKWLoc) {
956
957 if (!TemplateArgs) {
958 S.Diag(MemberNameInfo.getBeginLoc(), diag::err_template_decl_ref)
959 << /*Variable template*/ 1 << MemberNameInfo.getName()
960 << MemberNameInfo.getSourceRange();
961
962 S.Diag(VarTempl->getLocation(), diag::note_template_decl_here);
963
964 return nullptr;
965 }
966 DeclResult VDecl = S.CheckVarTemplateId(
967 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
968 if (VDecl.isInvalid())
969 return nullptr;
970 VarDecl *Var = cast<VarDecl>(VDecl.get());
971 if (!Var->getTemplateSpecializationKind())
972 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
973 MemberNameInfo.getLoc());
974 return Var;
975}
976
Douglas Gregor5476205b2011-06-23 00:49:38 +0000977ExprResult
978Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
979 SourceLocation OpLoc, bool IsArrow,
980 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000981 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000982 NamedDecl *FirstQualifierInScope,
983 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000984 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000985 const Scope *S,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000986 bool SuppressQualifierCheck,
987 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000988 QualType BaseType = BaseExprType;
989 if (IsArrow) {
990 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000991 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000992 }
993 R.setBaseObjectType(BaseType);
Richard Smith4baaa5a2016-12-03 01:14:32 +0000994
995 // C++1z [expr.ref]p2:
996 // For the first option (dot) the first expression shall be a glvalue [...]
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000997 if (!IsArrow && BaseExpr && BaseExpr->isRValue()) {
Richard Smith4baaa5a2016-12-03 01:14:32 +0000998 ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
999 if (Converted.isInvalid())
1000 return ExprError();
1001 BaseExpr = Converted.get();
1002 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001003
1004 LambdaScopeInfo *const CurLSI = getCurLambda();
1005 // If this is an implicit member reference and the overloaded
1006 // name refers to both static and non-static member functions
1007 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
1008 // check if we should/can capture 'this'...
1009 // Keep this example in mind:
1010 // struct X {
1011 // void f(int) { }
1012 // static void f(double) { }
1013 //
1014 // int g() {
1015 // auto L = [=](auto a) {
1016 // return [](int i) {
1017 // return [=](auto b) {
1018 // f(b);
1019 // //f(decltype(a){});
1020 // };
1021 // };
1022 // };
1023 // auto M = L(0.0);
1024 // auto N = M(3);
1025 // N(5.32); // OK, must not error.
1026 // return 0;
1027 // }
1028 // };
1029 //
1030 if (!BaseExpr && CurLSI) {
1031 SourceLocation Loc = R.getNameLoc();
1032 if (SS.getRange().isValid())
1033 Loc = SS.getRange().getBegin();
1034 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
1035 // If the enclosing function is not dependent, then this lambda is
1036 // capture ready, so if we can capture this, do so.
1037 if (!EnclosingFunctionCtx->isDependentContext()) {
1038 // If the current lambda and all enclosing lambdas can capture 'this' -
1039 // then go ahead and capture 'this' (since our unresolved overload set
1040 // contains both static and non-static member functions).
1041 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
1042 CheckCXXThisCapture(Loc);
1043 } else if (CurContext->isDependentContext()) {
1044 // ... since this is an implicit member reference, that might potentially
1045 // involve a 'this' capture, mark 'this' for potential capture in
1046 // enclosing lambdas.
1047 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
1048 CurLSI->addPotentialThisCapture(Loc);
1049 }
1050 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001051 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
1052 DeclarationName MemberName = MemberNameInfo.getName();
1053 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1054
1055 if (R.isAmbiguous())
1056 return ExprError();
1057
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001058 // [except.handle]p10: Referring to any non-static member or base class of an
1059 // object in the handler for a function-try-block of a constructor or
1060 // destructor for that object results in undefined behavior.
1061 const auto *FD = getCurFunctionDecl();
1062 if (S && BaseExpr && FD &&
1063 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1064 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1065 IsInFnTryBlockHandler(S))
1066 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1067 << isa<CXXDestructorDecl>(FD);
1068
Douglas Gregor5476205b2011-06-23 00:49:38 +00001069 if (R.empty()) {
1070 // Rederive where we looked up.
1071 DeclContext *DC = (SS.isSet()
1072 ? computeDeclContext(SS, false)
1073 : BaseType->getAs<RecordType>()->getDecl());
1074
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001075 if (ExtraArgs) {
1076 ExprResult RetryExpr;
1077 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +00001078 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001079 ParsedType ObjectType;
1080 bool MayBePseudoDestructor = false;
1081 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1082 OpLoc, tok::arrow, ObjectType,
1083 MayBePseudoDestructor);
1084 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1085 CXXScopeSpec TempSS(SS);
1086 RetryExpr = ActOnMemberAccessExpr(
1087 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +00001088 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001089 }
1090 if (Trap.hasErrorOccurred())
1091 RetryExpr = ExprError();
1092 }
1093 if (RetryExpr.isUsable()) {
1094 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1095 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1096 return RetryExpr;
1097 }
1098 }
1099
Douglas Gregor5476205b2011-06-23 00:49:38 +00001100 Diag(R.getNameLoc(), diag::err_no_member)
1101 << MemberName << DC
1102 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1103 return ExprError();
1104 }
1105
1106 // Diagnose lookups that find only declarations from a non-base
1107 // type. This is possible for either qualified lookups (which may
1108 // have been qualified with an unrelated type) or implicit member
1109 // expressions (which were found with unqualified lookup and thus
1110 // may have come from an enclosing scope). Note that it's okay for
1111 // lookup to find declarations from a non-base type as long as those
1112 // aren't the ones picked by overload resolution.
1113 if ((SS.isSet() || !BaseExpr ||
1114 (isa<CXXThisExpr>(BaseExpr) &&
1115 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1116 !SuppressQualifierCheck &&
1117 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1118 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001119
Douglas Gregor5476205b2011-06-23 00:49:38 +00001120 // Construct an unresolved result if we in fact got an unresolved
1121 // result.
1122 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1123 // Suppress any lookup-related diagnostics; we'll do these when we
1124 // pick a member.
1125 R.suppressDiagnostics();
1126
1127 UnresolvedMemberExpr *MemExpr
1128 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1129 BaseExpr, BaseExprType,
1130 IsArrow, OpLoc,
1131 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001132 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001133 TemplateArgs, R.begin(), R.end());
1134
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001135 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001136 }
1137
1138 assert(R.isSingleResult());
1139 DeclAccessPair FoundDecl = R.begin().getPair();
1140 NamedDecl *MemberDecl = R.getFoundDecl();
1141
1142 // FIXME: diagnose the presence of template arguments now.
1143
1144 // If the decl being referenced had an error, return an error for this
1145 // sub-expr without emitting another error, in order to avoid cascading
1146 // error cases.
1147 if (MemberDecl->isInvalidDecl())
1148 return ExprError();
1149
1150 // Handle the implicit-member-access case.
1151 if (!BaseExpr) {
1152 // If this is not an instance member, convert to a non-member access.
Faisal Valie7f8fb92016-02-22 02:24:29 +00001153 if (!MemberDecl->isCXXInstanceMember()) {
1154 // If this is a variable template, get the instantiated variable
1155 // declaration corresponding to the supplied template arguments
1156 // (while emitting diagnostics as necessary) that will be referenced
1157 // by this expression.
Faisal Vali640dc752016-02-25 05:09:30 +00001158 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1159 "How did we get template arguments here sans a variable template");
Faisal Valie7f8fb92016-02-22 02:24:29 +00001160 if (isa<VarTemplateDecl>(MemberDecl)) {
1161 MemberDecl = getVarTemplateSpecialization(
1162 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1163 R.getLookupNameInfo(), TemplateKWLoc);
1164 if (!MemberDecl)
1165 return ExprError();
1166 }
Faisal Vali640dc752016-02-25 05:09:30 +00001167 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1168 FoundDecl, TemplateArgs);
Faisal Valie7f8fb92016-02-22 02:24:29 +00001169 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001170 SourceLocation Loc = R.getNameLoc();
1171 if (SS.getRange().isValid())
1172 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001173 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001174 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1175 }
1176
Douglas Gregor5476205b2011-06-23 00:49:38 +00001177 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001178 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001179 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001180
Douglas Gregor5476205b2011-06-23 00:49:38 +00001181 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Richard Smith7873de02016-08-11 22:25:46 +00001182 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1183 MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001184
John McCall5e77d762013-04-16 07:28:30 +00001185 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1186 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1187 MemberNameInfo);
1188
Douglas Gregor5476205b2011-06-23 00:49:38 +00001189 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1190 // We may have found a field within an anonymous union or struct
1191 // (C++ [class.union]).
1192 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001193 FoundDecl, BaseExpr,
1194 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001195
1196 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001197 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1198 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001199 Var->getType().getNonReferenceType(), VK_LValue,
1200 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001201 }
1202
1203 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1204 ExprValueKind valueKind;
1205 QualType type;
1206 if (MemberFn->isInstance()) {
1207 valueKind = VK_RValue;
1208 type = Context.BoundMemberTy;
1209 } else {
1210 valueKind = VK_LValue;
1211 type = MemberFn->getType();
1212 }
1213
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001214 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1215 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1216 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001217 }
1218 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1219
1220 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001221 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1222 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1223 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001224 }
Faisal Valie7f8fb92016-02-22 02:24:29 +00001225 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1226 if (VarDecl *Var = getVarTemplateSpecialization(
1227 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1228 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1229 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1230 Var->getType().getNonReferenceType(), VK_LValue,
1231 OK_Ordinary);
1232 return ExprError();
1233 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001234
Douglas Gregor5476205b2011-06-23 00:49:38 +00001235 // We found something that we didn't expect. Complain.
1236 if (isa<TypeDecl>(MemberDecl))
1237 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1238 << MemberName << BaseType << int(IsArrow);
1239 else
1240 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1241 << MemberName << BaseType << int(IsArrow);
1242
1243 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1244 << MemberName;
1245 R.suppressDiagnostics();
1246 return ExprError();
1247}
1248
1249/// Given that normal member access failed on the given expression,
1250/// and given that the expression's type involves builtin-id or
1251/// builtin-Class, decide whether substituting in the redefinition
1252/// types would be profitable. The redefinition type is whatever
1253/// this translation unit tried to typedef to id/Class; we store
1254/// it to the side and then re-use it in places like this.
1255static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1256 const ObjCObjectPointerType *opty
1257 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1258 if (!opty) return false;
1259
1260 const ObjCObjectType *ty = opty->getObjectType();
1261
1262 QualType redef;
1263 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001264 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001265 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001266 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001267 } else {
1268 return false;
1269 }
1270
1271 // Do the substitution as long as the redefinition type isn't just a
1272 // possibly-qualified pointer to builtin-id or builtin-Class again.
1273 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001274 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001275 return false;
1276
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001277 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001278 return true;
1279}
1280
John McCall50a2c2c2011-10-11 23:14:30 +00001281static bool isRecordType(QualType T) {
1282 return T->isRecordType();
1283}
1284static bool isPointerToRecordType(QualType T) {
1285 if (const PointerType *PT = T->getAs<PointerType>())
1286 return PT->getPointeeType()->isRecordType();
1287 return false;
1288}
1289
Richard Smithcab9a7d2011-10-26 19:06:56 +00001290/// Perform conversions on the LHS of a member access expression.
1291ExprResult
1292Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001293 if (IsArrow && !Base->getType()->isFunctionType())
1294 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001295
Eli Friedman9a766c42012-01-13 02:20:01 +00001296 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001297}
1298
Douglas Gregor5476205b2011-06-23 00:49:38 +00001299/// Look up the given member of the given non-type-dependent
1300/// expression. This can return in one of two ways:
1301/// * If it returns a sentinel null-but-valid result, the caller will
1302/// assume that lookup was performed and the results written into
1303/// the provided structure. It will take over from there.
1304/// * Otherwise, the returned expression will be produced in place of
1305/// an ordinary member expression.
1306///
1307/// The ObjCImpDecl bit is a gross hack that will need to be properly
1308/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001309static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1310 ExprResult &BaseExpr, bool &IsArrow,
1311 SourceLocation OpLoc, CXXScopeSpec &SS,
1312 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001313 assert(BaseExpr.get() && "no base expression");
1314
1315 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001316 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001317 if (BaseExpr.isInvalid())
1318 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001319
Douglas Gregor5476205b2011-06-23 00:49:38 +00001320 QualType BaseType = BaseExpr.get()->getType();
1321 assert(!BaseType->isDependentType());
1322
1323 DeclarationName MemberName = R.getLookupName();
1324 SourceLocation MemberLoc = R.getNameLoc();
1325
1326 // For later type-checking purposes, turn arrow accesses into dot
1327 // accesses. The only access type we support that doesn't follow
1328 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1329 // and those never use arrows, so this is unaffected.
1330 if (IsArrow) {
1331 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1332 BaseType = Ptr->getPointeeType();
1333 else if (const ObjCObjectPointerType *Ptr
1334 = BaseType->getAs<ObjCObjectPointerType>())
1335 BaseType = Ptr->getPointeeType();
1336 else if (BaseType->isRecordType()) {
1337 // Recover from arrow accesses to records, e.g.:
1338 // struct MyRecord foo;
1339 // foo->bar
1340 // This is actually well-formed in C++ if MyRecord has an
1341 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001342 // by now--or a diagnostic message already issued if a problem
1343 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001344 if (!S.getLangOpts().CPlusPlus) {
1345 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001346 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1347 << FixItHint::CreateReplacement(OpLoc, ".");
1348 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001349 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001350 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001351 goto fail;
1352 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001353 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001354 << BaseType << BaseExpr.get()->getSourceRange();
1355 return ExprError();
1356 }
1357 }
1358
1359 // Handle field access to simple records.
1360 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001361 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001362 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001363 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001364 return ExprError();
1365
1366 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001367 // the lookup result was filled in. If typo correction was attempted and
1368 // failed, the lookup result will have been cleared--that combined with the
1369 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1370 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001371 }
1372
1373 // Handle ivar access to Objective-C objects.
1374 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001375 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001376 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001377 << 1 << SS.getScopeRep()
1378 << FixItHint::CreateRemoval(SS.getRange());
1379 SS.clear();
1380 }
Richard Smitha0edd302014-05-31 00:18:32 +00001381
Douglas Gregor5476205b2011-06-23 00:49:38 +00001382 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1383
1384 // There are three cases for the base type:
1385 // - builtin id (qualified or unqualified)
1386 // - builtin Class (qualified or unqualified)
1387 // - an interface
1388 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1389 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001390 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001391 (OTy->isObjCId() || OTy->isObjCClass()))
1392 goto fail;
1393 // There's an implicit 'isa' ivar on all objects.
1394 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001395 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001396 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001397 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1398 OpLoc, S.Context.getObjCClassType());
1399 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1400 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001401 ObjCImpDecl, HasTemplateArgs);
1402 goto fail;
1403 }
Richard Smitha0edd302014-05-31 00:18:32 +00001404
1405 if (S.RequireCompleteType(OpLoc, BaseType,
1406 diag::err_typecheck_incomplete_tag,
1407 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001408 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001409
1410 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001411 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1412
1413 if (!IV) {
1414 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001415 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1416 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001417 if (TypoCorrection Corrected = S.CorrectTypo(
1418 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001419 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001420 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001421 S.diagnoseTypo(
1422 Corrected,
1423 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1424 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001425
Ted Kremenek679b4782012-03-17 00:53:39 +00001426 // Figure out the class that declares the ivar.
1427 assert(!ClassDeclared);
Saleem Abdulrasool765a2192016-11-17 17:10:54 +00001428
Ted Kremenek679b4782012-03-17 00:53:39 +00001429 Decl *D = cast<Decl>(IV->getDeclContext());
Saleem Abdulrasool765a2192016-11-17 17:10:54 +00001430 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1431 D = Category->getClassInterface();
1432
1433 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1434 ClassDeclared = Implementation->getClassInterface();
1435 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1436 ClassDeclared = Interface;
1437
1438 assert(ClassDeclared && "cannot query interface");
Douglas Gregor5476205b2011-06-23 00:49:38 +00001439 } else {
Manman Ren5b786402016-01-28 18:49:28 +00001440 if (IsArrow &&
1441 IDecl->FindPropertyDeclaration(
1442 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001443 S.Diag(MemberLoc, diag::err_property_found_suggest)
1444 << Member << BaseExpr.get()->getType()
1445 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001446 return ExprError();
1447 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001448
Richard Smitha0edd302014-05-31 00:18:32 +00001449 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1450 << IDecl->getDeclName() << MemberName
1451 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001452 return ExprError();
1453 }
1454 }
Richard Smitha0edd302014-05-31 00:18:32 +00001455
Ted Kremenek679b4782012-03-17 00:53:39 +00001456 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001457
1458 // If the decl being referenced had an error, return an error for this
1459 // sub-expr without emitting another error, in order to avoid cascading
1460 // error cases.
1461 if (IV->isInvalidDecl())
1462 return ExprError();
1463
1464 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001465 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001466 return ExprError();
1467 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1468 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001469 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001470 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001471 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001472 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001473 // Case of a c-function declared inside an objc implementation.
1474 // FIXME: For a c-style function nested inside an objc implementation
1475 // class, there is no implementation context available, so we pass
1476 // down the context as argument to this routine. Ideally, this context
1477 // need be passed down in the AST node and somehow calculated from the
1478 // AST for a function decl.
1479 if (ObjCImplementationDecl *IMPD =
1480 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1481 ClassOfMethodDecl = IMPD->getClassInterface();
1482 else if (ObjCCategoryImplDecl* CatImplClass =
1483 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1484 ClassOfMethodDecl = CatImplClass->getClassInterface();
1485 }
Richard Smitha0edd302014-05-31 00:18:32 +00001486 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001487 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1488 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1489 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smithf8812672016-12-02 22:38:31 +00001490 S.Diag(MemberLoc, diag::err_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001491 << IV->getDeclName();
1492 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1493 // @protected
Richard Smithf8812672016-12-02 22:38:31 +00001494 S.Diag(MemberLoc, diag::err_protected_ivar_access)
Richard Smitha0edd302014-05-31 00:18:32 +00001495 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001496 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001497 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001498 bool warn = true;
Brian Kelleycafd9122017-03-29 17:55:11 +00001499 if (S.getLangOpts().ObjCWeak) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001500 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1501 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1502 if (UO->getOpcode() == UO_Deref)
1503 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1504
1505 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001506 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smithf8812672016-12-02 22:38:31 +00001507 S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001508 warn = false;
1509 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001510 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001511 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001512 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001513 ObjCMethodFamily MF = MD->getMethodFamily();
1514 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001515 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001516 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001517 }
1518 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001519 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001520 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001521
Richard Smitha0edd302014-05-31 00:18:32 +00001522 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001523 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1524 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001525
Brian Kelleycafd9122017-03-29 17:55:11 +00001526 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1527 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1528 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001529 }
1530
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001531 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001532 }
1533
1534 // Objective-C property access.
1535 const ObjCObjectPointerType *OPT;
1536 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001537 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001538 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1539 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001540 SS.clear();
1541 }
1542
Douglas Gregor5476205b2011-06-23 00:49:38 +00001543 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001544 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001545 if (BaseExpr.isInvalid())
1546 return ExprError();
1547
Richard Smitha0edd302014-05-31 00:18:32 +00001548 assert(S.Context.hasSameUnqualifiedType(BaseType,
1549 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001550
1551 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1552
1553 const ObjCObjectType *OT = OPT->getObjectType();
1554
1555 // id, with and without qualifiers.
1556 if (OT->isObjCId()) {
1557 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001558 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1559 if (Decl *PMDecl =
1560 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001561 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1562 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001563 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001564 return ExprError();
1565
Richard Smitha0edd302014-05-31 00:18:32 +00001566 return new (S.Context)
1567 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001568 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001569 }
1570
1571 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1572 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001573 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001574 return ExprError();
1575 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001576 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1577 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001578 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001579 ObjCMethodDecl *SMD = nullptr;
1580 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001581 /*Property id*/ nullptr,
1582 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001583 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001584
1585 return new (S.Context)
1586 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001587 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001588 }
1589 }
1590 // Use of id.member can only be for a property reference. Do not
1591 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001592 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1593 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001594 ObjCImpDecl, HasTemplateArgs);
1595
Richard Smitha0edd302014-05-31 00:18:32 +00001596 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001597 << MemberName << BaseType);
1598 }
1599
1600 // 'Class', unqualified only.
1601 if (OT->isObjCClass()) {
1602 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001603 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001604 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001605 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1606 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001607 ObjCImpDecl, HasTemplateArgs);
1608
1609 goto fail;
1610 }
1611
1612 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001613 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001614 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1615 ObjCMethodDecl *Getter;
1616 if ((Getter = IFace->lookupClassMethod(Sel))) {
1617 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001618 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001619 return ExprError();
1620 } else
1621 Getter = IFace->lookupPrivateMethod(Sel, false);
1622 // If we found a getter then this may be a valid dot-reference, we
1623 // will look for the matching setter, in case it is needed.
1624 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001625 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1626 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001627 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001628 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1629 if (!Setter) {
1630 // If this reference is in an @implementation, also check for 'private'
1631 // methods.
1632 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1633 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001634
Richard Smitha0edd302014-05-31 00:18:32 +00001635 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001636 return ExprError();
1637
1638 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001639 return new (S.Context) ObjCPropertyRefExpr(
1640 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1641 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001642 }
1643
Richard Smitha0edd302014-05-31 00:18:32 +00001644 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1645 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001646 ObjCImpDecl, HasTemplateArgs);
1647
Richard Smitha0edd302014-05-31 00:18:32 +00001648 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001649 << MemberName << BaseType);
1650 }
1651
1652 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001653 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1654 MemberLoc, SourceLocation(), QualType(),
1655 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001656 }
1657
1658 // Handle 'field access' to vectors, such as 'V.xx'.
1659 if (BaseType->isExtVectorType()) {
1660 // FIXME: this expr should store IsArrow.
1661 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001662 ExprValueKind VK;
1663 if (IsArrow)
1664 VK = VK_LValue;
1665 else {
1666 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1667 VK = POE->getSyntacticForm()->getValueKind();
1668 else
1669 VK = BaseExpr.get()->getValueKind();
1670 }
Richard Smitha0edd302014-05-31 00:18:32 +00001671 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001672 Member, MemberLoc);
1673 if (ret.isNull())
1674 return ExprError();
1675
Richard Smitha0edd302014-05-31 00:18:32 +00001676 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001677 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001678 }
1679
1680 // Adjust builtin-sel to the appropriate redefinition type if that's
1681 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001682 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1683 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1684 BaseExpr = S.ImpCastExprToType(
1685 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1686 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001687 ObjCImpDecl, HasTemplateArgs);
1688 }
1689
1690 // Failure cases.
1691 fail:
1692
1693 // Recover from dot accesses to pointers, e.g.:
1694 // type *foo;
1695 // foo.bar
1696 // This is actually well-formed in two cases:
1697 // - 'type' is an Objective C type
1698 // - 'bar' is a pseudo-destructor name which happens to refer to
1699 // the appropriate pointer type
1700 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1701 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1702 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001703 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1704 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001705 << FixItHint::CreateReplacement(OpLoc, "->");
1706
1707 // Recurse as an -> access.
1708 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001709 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001710 ObjCImpDecl, HasTemplateArgs);
1711 }
1712 }
1713
1714 // If the user is trying to apply -> or . to a function name, it's probably
1715 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001716 if (S.tryToRecoverWithCall(
1717 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1718 /*complain*/ false,
1719 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001720 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001721 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001722 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1723 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001724 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001725 }
1726
Richard Smitha0edd302014-05-31 00:18:32 +00001727 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001728 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001729
1730 return ExprError();
1731}
1732
1733/// The main callback when the parser finds something like
1734/// expression . [nested-name-specifier] identifier
1735/// expression -> [nested-name-specifier] identifier
1736/// where 'identifier' encompasses a fairly broad spectrum of
1737/// possibilities, including destructor and operator references.
1738///
1739/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001740/// \param ObjCImpDecl the current Objective-C \@implementation
1741/// decl; this is an ugly hack around the fact that Objective-C
1742/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001743ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1744 SourceLocation OpLoc,
1745 tok::TokenKind OpKind,
1746 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001747 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001748 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001749 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001750 if (SS.isSet() && SS.isInvalid())
1751 return ExprError();
1752
1753 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001754 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001755 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1756 Diag(Id.getSourceRange().getBegin(),
1757 diag::ext_ms_explicit_constructor_call);
1758
1759 TemplateArgumentListInfo TemplateArgsBuffer;
1760
1761 // Decompose the name into its component parts.
1762 DeclarationNameInfo NameInfo;
1763 const TemplateArgumentListInfo *TemplateArgs;
1764 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1765 NameInfo, TemplateArgs);
1766
1767 DeclarationName Name = NameInfo.getName();
1768 bool IsArrow = (OpKind == tok::arrow);
1769
1770 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001771 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001772
1773 // This is a postfix expression, so get rid of ParenListExprs.
1774 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1775 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001776 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001777
1778 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1779 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001780 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1781 TemplateKWLoc, FirstQualifierInScope,
1782 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001783 }
1784
David Majnemerced8bdf2015-02-25 17:36:15 +00001785 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001786 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1787 TemplateKWLoc, FirstQualifierInScope,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001788 NameInfo, TemplateArgs, S, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001789}
1790
Richard Smith7873de02016-08-11 22:25:46 +00001791ExprResult
1792Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1793 SourceLocation OpLoc, const CXXScopeSpec &SS,
1794 FieldDecl *Field, DeclAccessPair FoundDecl,
1795 const DeclarationNameInfo &MemberNameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001796 // x.a is an l-value if 'a' has a reference type. Otherwise:
1797 // x.a is an l-value/x-value/pr-value if the base is (and note
1798 // that *x is always an l-value), except that if the base isn't
1799 // an ordinary object then we must have an rvalue.
1800 ExprValueKind VK = VK_LValue;
1801 ExprObjectKind OK = OK_Ordinary;
1802 if (!IsArrow) {
1803 if (BaseExpr->getObjectKind() == OK_Ordinary)
1804 VK = BaseExpr->getValueKind();
1805 else
1806 VK = VK_RValue;
1807 }
1808 if (VK != VK_RValue && Field->isBitField())
1809 OK = OK_BitField;
1810
1811 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1812 QualType MemberType = Field->getType();
1813 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1814 MemberType = Ref->getPointeeType();
1815 VK = VK_LValue;
1816 } else {
1817 QualType BaseType = BaseExpr->getType();
1818 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001819
Douglas Gregor5476205b2011-06-23 00:49:38 +00001820 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001821
Douglas Gregor5476205b2011-06-23 00:49:38 +00001822 // GC attributes are never picked up by members.
1823 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001824
Douglas Gregor5476205b2011-06-23 00:49:38 +00001825 // CVR attributes from the base are picked up by members,
1826 // except that 'mutable' members don't pick up 'const'.
1827 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001828
Richard Smith7873de02016-08-11 22:25:46 +00001829 Qualifiers MemberQuals =
1830 Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001831
Douglas Gregor5476205b2011-06-23 00:49:38 +00001832 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001833
Douglas Gregor5476205b2011-06-23 00:49:38 +00001834 Qualifiers Combined = BaseQuals + MemberQuals;
1835 if (Combined != MemberQuals)
Richard Smith7873de02016-08-11 22:25:46 +00001836 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001837 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001838
Richard Smith7873de02016-08-11 22:25:46 +00001839 UnusedPrivateFields.remove(Field);
Daniel Jasper0baec5492012-06-06 08:32:04 +00001840
Richard Smith7873de02016-08-11 22:25:46 +00001841 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1842 FoundDecl, Field);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001843 if (Base.isInvalid())
1844 return ExprError();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001845
1846 // Build a reference to a private copy for non-static data members in
1847 // non-static member functions, privatized by OpenMP constructs.
Richard Smith7873de02016-08-11 22:25:46 +00001848 if (getLangOpts().OpenMP && IsArrow &&
1849 !CurContext->isDependentContext() &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001850 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001851 if (auto *PrivateCopy = IsOpenMPCapturedDecl(Field)) {
1852 return getOpenMPCapturedExpr(PrivateCopy, VK, OK,
1853 MemberNameInfo.getLoc());
1854 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001855 }
Alexey Bataevd0c03ca2017-07-11 19:43:28 +00001856
1857 return BuildMemberExpr(*this, Context, Base.get(), IsArrow, OpLoc, SS,
1858 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1859 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001860}
1861
1862/// Builds an implicit member access expression. The current context
1863/// is known to be an instance method, and the given unqualified lookup
1864/// set is known to contain only instance members, at least one of which
1865/// is from an appropriate type.
1866ExprResult
1867Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001868 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001869 LookupResult &R,
1870 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001871 bool IsKnownInstance, const Scope *S) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001872 assert(!R.empty() && !R.isAmbiguous());
1873
1874 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001875
Douglas Gregor5476205b2011-06-23 00:49:38 +00001876 // If this is known to be an instance access, go ahead and build an
1877 // implicit 'this' expression now.
1878 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001879 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001880 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001881
1882 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001883 if (IsKnownInstance) {
1884 SourceLocation Loc = R.getNameLoc();
1885 if (SS.getRange().isValid())
1886 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001887 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001888 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1889 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001890
Douglas Gregor5476205b2011-06-23 00:49:38 +00001891 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1892 /*OpLoc*/ SourceLocation(),
1893 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001894 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001895 /*FirstQualifierInScope*/ nullptr,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001896 R, TemplateArgs, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001897}