blob: 2e099ad6c67df0842a6d44fa58758e864dca57f3 [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;
Faisal Vali55bc3892017-08-27 19:00:08 +0000105 for (NamedDecl *D : R) {
106 // Look through any using decls.
107 D = D->getUnderlyingDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000108
Faisal Vali55bc3892017-08-27 19:00:08 +0000109 if (D->isCXXInstanceMember()) {
110 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
111 isa<IndirectFieldDecl>(D);
112
113 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000114 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:
Faisal Valic3ef5322017-08-29 03:04:13 +0000246 case IMA_Mixed_Unrelated:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000247 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();
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +0000254 LLVM_FALLTHROUGH;
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
Bruno Cardoso Lopes9e575182017-10-17 17:54:57 +0000387 // OpenCL mode requires swizzle length to be in accordance with accepted
388 // sizes. Clang however supports arbitrary lengths for other languages.
389 if (S.getLangOpts().OpenCL && !HalvingSwizzle) {
Egor Churaev392a5072017-03-21 13:20:57 +0000390 unsigned SwizzleLength = CompName->getLength();
391
392 if (HexSwizzle)
393 SwizzleLength--;
394
395 if (IsValidOpenCLComponentSwizzleLength(SwizzleLength) == false) {
396 S.Diag(OpLoc, diag::err_opencl_ext_vector_component_invalid_length)
397 << SwizzleLength << SourceRange(CompLoc);
398 return QualType();
399 }
400 }
401
Douglas Gregor5476205b2011-06-23 00:49:38 +0000402 // The component accessor looks fine - now we need to compute the actual type.
403 // The vector type is implied by the component accessor. For example,
404 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
405 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
406 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
407 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
408 : CompName->getLength();
409 if (HexSwizzle)
410 CompSize--;
411
412 if (CompSize == 1)
413 return vecType->getElementType();
414
415 if (HasRepeated) VK = VK_RValue;
416
417 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
418 // Now look up the TypeDefDecl from the vector type. Without this,
419 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000420 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000421 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000422 E = S.ExtVectorDecls.end();
423 I != E; ++I) {
424 if ((*I)->getUnderlyingType() == VT)
425 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000426 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000427
Douglas Gregor5476205b2011-06-23 00:49:38 +0000428 return VT; // should never get here (a typedef type should always be found).
429}
430
431static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
432 IdentifierInfo *Member,
433 const Selector &Sel,
434 ASTContext &Context) {
435 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000436 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
437 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000438 return PD;
439 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
440 return OMD;
441
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000442 for (const auto *I : PDecl->protocols()) {
443 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000444 Context))
445 return D;
446 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000447 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000448}
449
450static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
451 IdentifierInfo *Member,
452 const Selector &Sel,
453 ASTContext &Context) {
454 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000455 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000456 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000457 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000458 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
459 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000460 GDecl = PD;
461 break;
462 }
463 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000464 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000465 GDecl = OMD;
466 break;
467 }
468 }
469 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000470 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000471 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000472 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000473 if (GDecl)
474 return GDecl;
475 }
476 }
477 return GDecl;
478}
479
480ExprResult
481Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
482 bool IsArrow, SourceLocation OpLoc,
483 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000484 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000485 NamedDecl *FirstQualifierInScope,
486 const DeclarationNameInfo &NameInfo,
487 const TemplateArgumentListInfo *TemplateArgs) {
488 // Even in dependent contexts, try to diagnose base expressions with
489 // obviously wrong types, e.g.:
490 //
491 // T* t;
492 // t.f;
493 //
494 // In Obj-C++, however, the above expression is valid, since it could be
495 // accessing the 'f' property if T is an Obj-C interface. The extra check
496 // allows this, while still reporting an error if T is a struct pointer.
497 if (!IsArrow) {
498 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000499 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000500 PT->getPointeeType()->isRecordType())) {
501 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000502 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000503 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000504 return ExprError();
505 }
506 }
507
508 assert(BaseType->isDependentType() ||
509 NameInfo.getName().isDependentName() ||
510 isDependentScopeSpecifier(SS));
511
512 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
513 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000514 return CXXDependentScopeMemberExpr::Create(
515 Context, BaseExpr, BaseType, IsArrow, OpLoc,
516 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
517 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000518}
519
520/// We know that the given qualified member reference points only to
521/// declarations which do not belong to the static type of the base
522/// expression. Diagnose the problem.
523static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
524 Expr *BaseExpr,
525 QualType BaseType,
526 const CXXScopeSpec &SS,
527 NamedDecl *rep,
528 const DeclarationNameInfo &nameInfo) {
529 // If this is an implicit member access, use a different set of
530 // diagnostics.
531 if (!BaseExpr)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000532 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000533
534 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
535 << SS.getRange() << rep << BaseType;
536}
537
538// Check whether the declarations we found through a nested-name
539// specifier in a member expression are actually members of the base
540// type. The restriction here is:
541//
542// C++ [expr.ref]p2:
543// ... In these cases, the id-expression shall name a
544// member of the class or of one of its base classes.
545//
546// So it's perfectly legitimate for the nested-name specifier to name
547// an unrelated class, and for us to find an overload set including
548// decls from classes which are not superclasses, as long as the decl
549// we actually pick through overload resolution is from a superclass.
550bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
551 QualType BaseType,
552 const CXXScopeSpec &SS,
553 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000554 CXXRecordDecl *BaseRecord =
555 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
556 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000557 // We can't check this yet because the base type is still
558 // dependent.
559 assert(BaseType->isDependentType());
560 return false;
561 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000562
563 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
564 // If this is an implicit member reference and we find a
565 // non-instance member, it's not an error.
566 if (!BaseExpr && !(*I)->isCXXInstanceMember())
567 return false;
568
569 // Note that we use the DC of the decl, not the underlying decl.
570 DeclContext *DC = (*I)->getDeclContext();
571 while (DC->isTransparentContext())
572 DC = DC->getParent();
573
574 if (!DC->isRecord())
575 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000576
Richard Smithd80b2d52012-11-22 00:24:47 +0000577 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
578 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
579 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000580 return false;
581 }
582
583 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
584 R.getRepresentativeDecl(),
585 R.getLookupNameInfo());
586 return true;
587}
588
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000589namespace {
590
591// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000592// FunctionTemplateDecl and are declared in the current record or, for a C++
593// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000594class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000595public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000596 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000597 : Record(RTy->getDecl()) {
598 // Don't add bare keywords to the consumer since they will always fail
599 // validation by virtue of not being associated with any decls.
600 WantTypeSpecifiers = false;
601 WantExpressionKeywords = false;
602 WantCXXNamedCasts = false;
603 WantFunctionLikeCasts = false;
604 WantRemainingKeywords = false;
605 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000606
Craig Toppere14c0f82014-03-12 04:55:44 +0000607 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000608 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000609 // Don't accept candidates that cannot be member functions, constants,
610 // variables, or templates.
611 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
612 return false;
613
614 // Accept candidates that occur in the current record.
615 if (Record->containsDecl(ND))
616 return true;
617
618 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
619 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000620 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000621 if (const RecordType *BSTy =
622 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000623 if (BSTy->getDecl()->containsDecl(ND))
624 return true;
625 }
626 }
627 }
628
629 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000630 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000631
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000632private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000633 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000634};
635
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000636}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000637
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000638static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000639 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000640 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000641 SourceLocation OpLoc, bool IsArrow,
642 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000643 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000644 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000645 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000646 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
647 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000648 diag::err_typecheck_incomplete_tag,
649 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000650 return true;
651
652 if (HasTemplateArgs) {
653 // LookupTemplateName doesn't expect these both to exist simultaneously.
654 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
655
656 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000657 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000658 return false;
659 }
660
661 DeclContext *DC = RDecl;
662 if (SS.isSet()) {
663 // If the member name was a qualified-id, look into the
664 // nested-name-specifier.
665 DC = SemaRef.computeDeclContext(SS, false);
666
667 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
668 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000669 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000670 return true;
671 }
672
673 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
674
675 if (!isa<TypeDecl>(DC)) {
676 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000677 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000678 return true;
679 }
680 }
681
682 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000683 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000684
685 if (!R.empty())
686 return false;
687
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000688 DeclarationName Typo = R.getLookupName();
689 SourceLocation TypoLoc = R.getNameLoc();
David Blaikiea8173ba2015-09-28 23:48:55 +0000690
691 struct QueryState {
692 Sema &SemaRef;
693 DeclarationNameInfo NameInfo;
694 Sema::LookupNameKind LookupKind;
695 Sema::RedeclarationKind Redecl;
696 };
697 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
Richard Smithbecb92d2017-10-10 22:33:17 +0000698 R.redeclarationKind()};
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000699 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000700 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
701 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000702 [=, &SemaRef](const TypoCorrection &TC) {
703 if (TC) {
704 assert(!TC.isKeyword() &&
705 "Got a keyword as a correction for a member!");
706 bool DroppedSpecifier =
707 TC.WillReplaceSpecifier() &&
708 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
709 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
710 << Typo << DC << DroppedSpecifier
711 << SS.getRange());
712 } else {
713 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
714 }
715 },
716 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
David Blaikiea8173ba2015-09-28 23:48:55 +0000717 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000718 R.clear(); // Ensure there's no decls lingering in the shared state.
719 R.suppressDiagnostics();
720 R.setLookupName(TC.getCorrection());
721 for (NamedDecl *ND : TC)
722 R.addDecl(ND);
723 R.resolveKind();
724 return SemaRef.BuildMemberReferenceExpr(
725 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000726 nullptr, R, nullptr, nullptr);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000727 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000728 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000729
730 return false;
731}
732
Richard Smitha0edd302014-05-31 00:18:32 +0000733static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
734 ExprResult &BaseExpr, bool &IsArrow,
735 SourceLocation OpLoc, CXXScopeSpec &SS,
736 Decl *ObjCImpDecl, bool HasTemplateArgs);
737
Douglas Gregor5476205b2011-06-23 00:49:38 +0000738ExprResult
739Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
740 SourceLocation OpLoc, bool IsArrow,
741 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000742 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000743 NamedDecl *FirstQualifierInScope,
744 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000745 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000746 const Scope *S,
Richard Smitha0edd302014-05-31 00:18:32 +0000747 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000748 if (BaseType->isDependentType() ||
749 (SS.isSet() && isDependentScopeSpecifier(SS)))
750 return ActOnDependentMemberExpr(Base, BaseType,
751 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000752 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000753 NameInfo, TemplateArgs);
754
755 LookupResult R(*this, NameInfo, LookupMemberName);
756
757 // Implicit member accesses.
758 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000759 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000760 QualType RecordTy = BaseType;
761 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Richard Smithc08b6932018-04-27 02:00:13 +0000762 if (LookupMemberExprInRecord(
763 *this, R, nullptr, RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
764 SS, TemplateKWLoc.isValid() || TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000765 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000766 if (TE)
767 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000768
769 // Explicit member accesses.
770 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000771 ExprResult BaseResult = Base;
Richard Smithc08b6932018-04-27 02:00:13 +0000772 ExprResult Result =
773 LookupMemberExpr(*this, R, BaseResult, IsArrow, OpLoc, SS,
774 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
775 TemplateKWLoc.isValid() || TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000776
777 if (BaseResult.isInvalid())
778 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000779 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000780
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000781 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000782 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000783
784 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000785 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000786
787 // LookupMemberExpr can modify Base, and thus change BaseType
788 BaseType = Base->getType();
789 }
790
791 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000792 OpLoc, IsArrow, SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000793 FirstQualifierInScope, R, TemplateArgs, S,
Richard Smitha0edd302014-05-31 00:18:32 +0000794 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000795}
796
Douglas Gregor5476205b2011-06-23 00:49:38 +0000797ExprResult
798Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
799 SourceLocation loc,
800 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000801 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000802 Expr *baseObjectExpr,
803 SourceLocation opLoc) {
804 // First, build the expression that refers to the base object.
Eric Fiseliere099fc12018-04-08 05:12:55 +0000805
Douglas Gregor5476205b2011-06-23 00:49:38 +0000806 // Case 1: the base of the indirect field is not a field.
807 VarDecl *baseVariable = indirectField->getVarDecl();
808 CXXScopeSpec EmptySS;
809 if (baseVariable) {
810 assert(baseVariable->getType()->isRecordType());
Eric Fiseliere099fc12018-04-08 05:12:55 +0000811
Douglas Gregor5476205b2011-06-23 00:49:38 +0000812 // In principle we could have a member access expression that
813 // accesses an anonymous struct/union that's a static member of
814 // the base object's class. However, under the current standard,
815 // static data members cannot be anonymous structs or unions.
816 // Supporting this is as easy as building a MemberExpr here.
817 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
818
819 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
820
821 ExprResult result
822 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
823 if (result.isInvalid()) return ExprError();
Eric Fiseliere099fc12018-04-08 05:12:55 +0000824
825 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000826 }
Eric Fiseliere099fc12018-04-08 05:12:55 +0000827
828 assert((baseVariable || baseObjectExpr) &&
829 "referencing anonymous struct/union without a base variable or "
830 "expression");
831
Douglas Gregor5476205b2011-06-23 00:49:38 +0000832 // Build the implicit member references to the field of the
833 // anonymous struct/union.
834 Expr *result = baseObjectExpr;
835 IndirectFieldDecl::chain_iterator
836 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
Eric Fiseliere099fc12018-04-08 05:12:55 +0000837
838 // Case 2: the base of the indirect field is a field and the user
839 // wrote a member expression.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000840 if (!baseVariable) {
841 FieldDecl *field = cast<FieldDecl>(*FI);
Eric Fiseliere099fc12018-04-08 05:12:55 +0000842
843 bool baseObjectIsPointer = baseObjectExpr->getType()->isPointerType();
844
Douglas Gregor5476205b2011-06-23 00:49:38 +0000845 // Make a nameInfo that properly uses the anonymous name.
846 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000847
Eric Fiseliere099fc12018-04-08 05:12:55 +0000848 // Build the first member access in the chain with full information.
849 result =
850 BuildFieldReferenceExpr(result, baseObjectIsPointer, SourceLocation(),
Eric Fiselier4b8c9912018-04-08 06:21:33 +0000851 SS, field, foundDecl, memberNameInfo)
Eric Fiseliere099fc12018-04-08 05:12:55 +0000852 .get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000853 if (!result)
854 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000855 }
856
857 // In all cases, we should now skip the first declaration in the chain.
858 ++FI;
859
860 while (FI != FEnd) {
861 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000862
Douglas Gregor5476205b2011-06-23 00:49:38 +0000863 // FIXME: these are somewhat meaningless
864 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000865 DeclAccessPair fakeFoundDecl =
866 DeclAccessPair::make(field, field->getAccess());
867
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000868 result =
Richard Smith7873de02016-08-11 22:25:46 +0000869 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
870 (FI == FEnd ? SS : EmptySS), field,
871 fakeFoundDecl, memberNameInfo)
872 .get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000873 }
874
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000875 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000876}
877
John McCall5e77d762013-04-16 07:28:30 +0000878static ExprResult
879BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
880 const CXXScopeSpec &SS,
881 MSPropertyDecl *PD,
882 const DeclarationNameInfo &NameInfo) {
883 // Property names are always simple identifiers and therefore never
884 // require any interesting additional storage.
885 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
886 S.Context.PseudoObjectTy, VK_LValue,
887 SS.getWithLocInContext(S.Context),
888 NameInfo.getLoc());
889}
890
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000891/// Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000892static MemberExpr *BuildMemberExpr(
893 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
894 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
895 ValueDecl *Member, DeclAccessPair FoundDecl,
896 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
897 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000898 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000899 MemberExpr *E = MemberExpr::Create(
900 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
901 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000902 SemaRef.MarkMemberReferenced(E);
903 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000904}
905
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000906/// Determine if the given scope is within a function-try-block handler.
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000907static bool IsInFnTryBlockHandler(const Scope *S) {
908 // Walk the scope stack until finding a FnTryCatchScope, or leave the
909 // function scope. If a FnTryCatchScope is found, check whether the TryScope
910 // flag is set. If it is not, it's a function-try-block handler.
911 for (; S != S->getFnParent(); S = S->getParent()) {
912 if (S->getFlags() & Scope::FnTryCatchScope)
913 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
914 }
915 return false;
916}
917
Faisal Valie7f8fb92016-02-22 02:24:29 +0000918static VarDecl *
919getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
920 const TemplateArgumentListInfo *TemplateArgs,
921 const DeclarationNameInfo &MemberNameInfo,
922 SourceLocation TemplateKWLoc) {
Faisal Valie7f8fb92016-02-22 02:24:29 +0000923 if (!TemplateArgs) {
Richard Smithecad88d2018-04-26 01:08:00 +0000924 S.diagnoseMissingTemplateArguments(TemplateName(VarTempl),
925 MemberNameInfo.getBeginLoc());
Faisal Valie7f8fb92016-02-22 02:24:29 +0000926 return nullptr;
927 }
Richard Smithecad88d2018-04-26 01:08:00 +0000928
Faisal Valie7f8fb92016-02-22 02:24:29 +0000929 DeclResult VDecl = S.CheckVarTemplateId(
930 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
931 if (VDecl.isInvalid())
932 return nullptr;
933 VarDecl *Var = cast<VarDecl>(VDecl.get());
934 if (!Var->getTemplateSpecializationKind())
935 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
936 MemberNameInfo.getLoc());
937 return Var;
938}
939
Douglas Gregor5476205b2011-06-23 00:49:38 +0000940ExprResult
941Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
942 SourceLocation OpLoc, bool IsArrow,
943 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000944 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000945 NamedDecl *FirstQualifierInScope,
946 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000947 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000948 const Scope *S,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000949 bool SuppressQualifierCheck,
950 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000951 QualType BaseType = BaseExprType;
952 if (IsArrow) {
953 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000954 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000955 }
956 R.setBaseObjectType(BaseType);
Richard Smith4baaa5a2016-12-03 01:14:32 +0000957
958 // C++1z [expr.ref]p2:
959 // For the first option (dot) the first expression shall be a glvalue [...]
Gor Nishanov6dcb0eb2017-03-09 03:09:43 +0000960 if (!IsArrow && BaseExpr && BaseExpr->isRValue()) {
Richard Smith4baaa5a2016-12-03 01:14:32 +0000961 ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
962 if (Converted.isInvalid())
963 return ExprError();
964 BaseExpr = Converted.get();
965 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000966
Faisal Valif60ebcd2017-09-17 15:37:51 +0000967
Douglas Gregor5476205b2011-06-23 00:49:38 +0000968 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
969 DeclarationName MemberName = MemberNameInfo.getName();
970 SourceLocation MemberLoc = MemberNameInfo.getLoc();
971
972 if (R.isAmbiguous())
973 return ExprError();
974
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000975 // [except.handle]p10: Referring to any non-static member or base class of an
976 // object in the handler for a function-try-block of a constructor or
977 // destructor for that object results in undefined behavior.
978 const auto *FD = getCurFunctionDecl();
979 if (S && BaseExpr && FD &&
980 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
981 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
982 IsInFnTryBlockHandler(S))
983 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
984 << isa<CXXDestructorDecl>(FD);
985
Douglas Gregor5476205b2011-06-23 00:49:38 +0000986 if (R.empty()) {
987 // Rederive where we looked up.
988 DeclContext *DC = (SS.isSet()
989 ? computeDeclContext(SS, false)
990 : BaseType->getAs<RecordType>()->getDecl());
991
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000992 if (ExtraArgs) {
993 ExprResult RetryExpr;
994 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000995 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000996 ParsedType ObjectType;
997 bool MayBePseudoDestructor = false;
998 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
999 OpLoc, tok::arrow, ObjectType,
1000 MayBePseudoDestructor);
1001 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1002 CXXScopeSpec TempSS(SS);
1003 RetryExpr = ActOnMemberAccessExpr(
1004 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +00001005 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001006 }
1007 if (Trap.hasErrorOccurred())
1008 RetryExpr = ExprError();
1009 }
1010 if (RetryExpr.isUsable()) {
1011 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1012 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1013 return RetryExpr;
1014 }
1015 }
1016
Douglas Gregor5476205b2011-06-23 00:49:38 +00001017 Diag(R.getNameLoc(), diag::err_no_member)
1018 << MemberName << DC
1019 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1020 return ExprError();
1021 }
1022
1023 // Diagnose lookups that find only declarations from a non-base
1024 // type. This is possible for either qualified lookups (which may
1025 // have been qualified with an unrelated type) or implicit member
1026 // expressions (which were found with unqualified lookup and thus
1027 // may have come from an enclosing scope). Note that it's okay for
1028 // lookup to find declarations from a non-base type as long as those
1029 // aren't the ones picked by overload resolution.
1030 if ((SS.isSet() || !BaseExpr ||
1031 (isa<CXXThisExpr>(BaseExpr) &&
1032 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1033 !SuppressQualifierCheck &&
1034 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1035 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001036
Douglas Gregor5476205b2011-06-23 00:49:38 +00001037 // Construct an unresolved result if we in fact got an unresolved
1038 // result.
1039 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1040 // Suppress any lookup-related diagnostics; we'll do these when we
1041 // pick a member.
1042 R.suppressDiagnostics();
1043
1044 UnresolvedMemberExpr *MemExpr
1045 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1046 BaseExpr, BaseExprType,
1047 IsArrow, OpLoc,
1048 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001049 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001050 TemplateArgs, R.begin(), R.end());
1051
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001052 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001053 }
1054
1055 assert(R.isSingleResult());
1056 DeclAccessPair FoundDecl = R.begin().getPair();
1057 NamedDecl *MemberDecl = R.getFoundDecl();
1058
1059 // FIXME: diagnose the presence of template arguments now.
1060
1061 // If the decl being referenced had an error, return an error for this
1062 // sub-expr without emitting another error, in order to avoid cascading
1063 // error cases.
1064 if (MemberDecl->isInvalidDecl())
1065 return ExprError();
1066
1067 // Handle the implicit-member-access case.
1068 if (!BaseExpr) {
1069 // If this is not an instance member, convert to a non-member access.
Faisal Valie7f8fb92016-02-22 02:24:29 +00001070 if (!MemberDecl->isCXXInstanceMember()) {
1071 // If this is a variable template, get the instantiated variable
1072 // declaration corresponding to the supplied template arguments
1073 // (while emitting diagnostics as necessary) that will be referenced
1074 // by this expression.
Faisal Vali640dc752016-02-25 05:09:30 +00001075 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1076 "How did we get template arguments here sans a variable template");
Faisal Valie7f8fb92016-02-22 02:24:29 +00001077 if (isa<VarTemplateDecl>(MemberDecl)) {
1078 MemberDecl = getVarTemplateSpecialization(
1079 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1080 R.getLookupNameInfo(), TemplateKWLoc);
1081 if (!MemberDecl)
1082 return ExprError();
1083 }
Faisal Vali640dc752016-02-25 05:09:30 +00001084 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1085 FoundDecl, TemplateArgs);
Faisal Valie7f8fb92016-02-22 02:24:29 +00001086 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001087 SourceLocation Loc = R.getNameLoc();
1088 if (SS.getRange().isValid())
1089 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001090 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001091 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1092 }
1093
Douglas Gregor5476205b2011-06-23 00:49:38 +00001094 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001095 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001096 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001097
Douglas Gregor5476205b2011-06-23 00:49:38 +00001098 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Richard Smith7873de02016-08-11 22:25:46 +00001099 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1100 MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001101
John McCall5e77d762013-04-16 07:28:30 +00001102 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1103 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1104 MemberNameInfo);
1105
Douglas Gregor5476205b2011-06-23 00:49:38 +00001106 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1107 // We may have found a field within an anonymous union or struct
1108 // (C++ [class.union]).
1109 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001110 FoundDecl, BaseExpr,
1111 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001112
1113 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001114 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1115 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001116 Var->getType().getNonReferenceType(), VK_LValue,
1117 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001118 }
1119
1120 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1121 ExprValueKind valueKind;
1122 QualType type;
1123 if (MemberFn->isInstance()) {
1124 valueKind = VK_RValue;
1125 type = Context.BoundMemberTy;
1126 } else {
1127 valueKind = VK_LValue;
1128 type = MemberFn->getType();
1129 }
1130
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001131 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1132 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1133 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001134 }
1135 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1136
1137 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001138 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1139 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1140 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001141 }
Faisal Valie7f8fb92016-02-22 02:24:29 +00001142 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1143 if (VarDecl *Var = getVarTemplateSpecialization(
1144 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1145 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1146 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1147 Var->getType().getNonReferenceType(), VK_LValue,
1148 OK_Ordinary);
1149 return ExprError();
1150 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001151
Douglas Gregor5476205b2011-06-23 00:49:38 +00001152 // We found something that we didn't expect. Complain.
1153 if (isa<TypeDecl>(MemberDecl))
1154 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1155 << MemberName << BaseType << int(IsArrow);
1156 else
1157 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1158 << MemberName << BaseType << int(IsArrow);
1159
1160 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1161 << MemberName;
1162 R.suppressDiagnostics();
1163 return ExprError();
1164}
1165
1166/// Given that normal member access failed on the given expression,
1167/// and given that the expression's type involves builtin-id or
1168/// builtin-Class, decide whether substituting in the redefinition
1169/// types would be profitable. The redefinition type is whatever
1170/// this translation unit tried to typedef to id/Class; we store
1171/// it to the side and then re-use it in places like this.
1172static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1173 const ObjCObjectPointerType *opty
1174 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1175 if (!opty) return false;
1176
1177 const ObjCObjectType *ty = opty->getObjectType();
1178
1179 QualType redef;
1180 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001181 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001182 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001183 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001184 } else {
1185 return false;
1186 }
1187
1188 // Do the substitution as long as the redefinition type isn't just a
1189 // possibly-qualified pointer to builtin-id or builtin-Class again.
1190 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001191 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001192 return false;
1193
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001194 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001195 return true;
1196}
1197
John McCall50a2c2c2011-10-11 23:14:30 +00001198static bool isRecordType(QualType T) {
1199 return T->isRecordType();
1200}
1201static bool isPointerToRecordType(QualType T) {
1202 if (const PointerType *PT = T->getAs<PointerType>())
1203 return PT->getPointeeType()->isRecordType();
1204 return false;
1205}
1206
Richard Smithcab9a7d2011-10-26 19:06:56 +00001207/// Perform conversions on the LHS of a member access expression.
1208ExprResult
1209Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001210 if (IsArrow && !Base->getType()->isFunctionType())
1211 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001212
Eli Friedman9a766c42012-01-13 02:20:01 +00001213 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001214}
1215
Douglas Gregor5476205b2011-06-23 00:49:38 +00001216/// Look up the given member of the given non-type-dependent
1217/// expression. This can return in one of two ways:
1218/// * If it returns a sentinel null-but-valid result, the caller will
1219/// assume that lookup was performed and the results written into
1220/// the provided structure. It will take over from there.
1221/// * Otherwise, the returned expression will be produced in place of
1222/// an ordinary member expression.
1223///
1224/// The ObjCImpDecl bit is a gross hack that will need to be properly
1225/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001226static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1227 ExprResult &BaseExpr, bool &IsArrow,
1228 SourceLocation OpLoc, CXXScopeSpec &SS,
1229 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001230 assert(BaseExpr.get() && "no base expression");
1231
1232 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001233 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001234 if (BaseExpr.isInvalid())
1235 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001236
Douglas Gregor5476205b2011-06-23 00:49:38 +00001237 QualType BaseType = BaseExpr.get()->getType();
1238 assert(!BaseType->isDependentType());
1239
1240 DeclarationName MemberName = R.getLookupName();
1241 SourceLocation MemberLoc = R.getNameLoc();
1242
1243 // For later type-checking purposes, turn arrow accesses into dot
1244 // accesses. The only access type we support that doesn't follow
1245 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1246 // and those never use arrows, so this is unaffected.
1247 if (IsArrow) {
1248 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1249 BaseType = Ptr->getPointeeType();
1250 else if (const ObjCObjectPointerType *Ptr
1251 = BaseType->getAs<ObjCObjectPointerType>())
1252 BaseType = Ptr->getPointeeType();
1253 else if (BaseType->isRecordType()) {
1254 // Recover from arrow accesses to records, e.g.:
1255 // struct MyRecord foo;
1256 // foo->bar
1257 // This is actually well-formed in C++ if MyRecord has an
1258 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001259 // by now--or a diagnostic message already issued if a problem
1260 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001261 if (!S.getLangOpts().CPlusPlus) {
1262 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001263 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1264 << FixItHint::CreateReplacement(OpLoc, ".");
1265 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001266 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001267 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001268 goto fail;
1269 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001270 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001271 << BaseType << BaseExpr.get()->getSourceRange();
1272 return ExprError();
1273 }
1274 }
1275
1276 // Handle field access to simple records.
1277 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001278 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001279 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001280 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001281 return ExprError();
1282
1283 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001284 // the lookup result was filled in. If typo correction was attempted and
1285 // failed, the lookup result will have been cleared--that combined with the
1286 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1287 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001288 }
1289
1290 // Handle ivar access to Objective-C objects.
1291 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001292 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001293 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001294 << 1 << SS.getScopeRep()
1295 << FixItHint::CreateRemoval(SS.getRange());
1296 SS.clear();
1297 }
Richard Smitha0edd302014-05-31 00:18:32 +00001298
Douglas Gregor5476205b2011-06-23 00:49:38 +00001299 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1300
1301 // There are three cases for the base type:
1302 // - builtin id (qualified or unqualified)
1303 // - builtin Class (qualified or unqualified)
1304 // - an interface
1305 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1306 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001307 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001308 (OTy->isObjCId() || OTy->isObjCClass()))
1309 goto fail;
1310 // There's an implicit 'isa' ivar on all objects.
1311 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001312 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001313 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001314 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1315 OpLoc, S.Context.getObjCClassType());
1316 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1317 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001318 ObjCImpDecl, HasTemplateArgs);
1319 goto fail;
1320 }
Richard Smitha0edd302014-05-31 00:18:32 +00001321
1322 if (S.RequireCompleteType(OpLoc, BaseType,
1323 diag::err_typecheck_incomplete_tag,
1324 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001325 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001326
1327 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001328 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1329
1330 if (!IV) {
1331 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001332 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1333 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001334 if (TypoCorrection Corrected = S.CorrectTypo(
1335 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001336 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001337 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001338 S.diagnoseTypo(
1339 Corrected,
1340 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1341 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001342
Ted Kremenek679b4782012-03-17 00:53:39 +00001343 // Figure out the class that declares the ivar.
1344 assert(!ClassDeclared);
Saleem Abdulrasool765a2192016-11-17 17:10:54 +00001345
Ted Kremenek679b4782012-03-17 00:53:39 +00001346 Decl *D = cast<Decl>(IV->getDeclContext());
Saleem Abdulrasool765a2192016-11-17 17:10:54 +00001347 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1348 D = Category->getClassInterface();
1349
1350 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1351 ClassDeclared = Implementation->getClassInterface();
1352 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1353 ClassDeclared = Interface;
1354
1355 assert(ClassDeclared && "cannot query interface");
Douglas Gregor5476205b2011-06-23 00:49:38 +00001356 } else {
Manman Ren5b786402016-01-28 18:49:28 +00001357 if (IsArrow &&
1358 IDecl->FindPropertyDeclaration(
1359 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001360 S.Diag(MemberLoc, diag::err_property_found_suggest)
1361 << Member << BaseExpr.get()->getType()
1362 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001363 return ExprError();
1364 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001365
Richard Smitha0edd302014-05-31 00:18:32 +00001366 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1367 << IDecl->getDeclName() << MemberName
1368 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001369 return ExprError();
1370 }
1371 }
Richard Smitha0edd302014-05-31 00:18:32 +00001372
Ted Kremenek679b4782012-03-17 00:53:39 +00001373 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001374
1375 // If the decl being referenced had an error, return an error for this
1376 // sub-expr without emitting another error, in order to avoid cascading
1377 // error cases.
1378 if (IV->isInvalidDecl())
1379 return ExprError();
1380
1381 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001382 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001383 return ExprError();
1384 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1385 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001386 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001387 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001388 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001389 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001390 // Case of a c-function declared inside an objc implementation.
1391 // FIXME: For a c-style function nested inside an objc implementation
1392 // class, there is no implementation context available, so we pass
1393 // down the context as argument to this routine. Ideally, this context
1394 // need be passed down in the AST node and somehow calculated from the
1395 // AST for a function decl.
1396 if (ObjCImplementationDecl *IMPD =
1397 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1398 ClassOfMethodDecl = IMPD->getClassInterface();
1399 else if (ObjCCategoryImplDecl* CatImplClass =
1400 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1401 ClassOfMethodDecl = CatImplClass->getClassInterface();
1402 }
Richard Smitha0edd302014-05-31 00:18:32 +00001403 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001404 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1405 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1406 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smithf8812672016-12-02 22:38:31 +00001407 S.Diag(MemberLoc, diag::err_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001408 << IV->getDeclName();
1409 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1410 // @protected
Richard Smithf8812672016-12-02 22:38:31 +00001411 S.Diag(MemberLoc, diag::err_protected_ivar_access)
Richard Smitha0edd302014-05-31 00:18:32 +00001412 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001413 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001414 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001415 bool warn = true;
Brian Kelleycafd9122017-03-29 17:55:11 +00001416 if (S.getLangOpts().ObjCWeak) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001417 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1418 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1419 if (UO->getOpcode() == UO_Deref)
1420 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1421
1422 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001423 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smithf8812672016-12-02 22:38:31 +00001424 S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001425 warn = false;
1426 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001427 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001428 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001429 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001430 ObjCMethodFamily MF = MD->getMethodFamily();
1431 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001432 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001433 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001434 }
1435 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001436 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001437 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001438
Richard Smitha0edd302014-05-31 00:18:32 +00001439 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001440 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1441 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001442
Brian Kelleycafd9122017-03-29 17:55:11 +00001443 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Reid Kleckner04f9bca2018-03-07 22:48:35 +00001444 if (!S.isUnevaluatedContext() &&
1445 !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1446 S.getCurFunction()->recordUseOfWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001447 }
1448
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001449 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001450 }
1451
1452 // Objective-C property access.
1453 const ObjCObjectPointerType *OPT;
1454 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001455 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001456 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1457 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001458 SS.clear();
1459 }
1460
Douglas Gregor5476205b2011-06-23 00:49:38 +00001461 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001462 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001463 if (BaseExpr.isInvalid())
1464 return ExprError();
1465
Richard Smitha0edd302014-05-31 00:18:32 +00001466 assert(S.Context.hasSameUnqualifiedType(BaseType,
1467 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001468
1469 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1470
1471 const ObjCObjectType *OT = OPT->getObjectType();
1472
1473 // id, with and without qualifiers.
1474 if (OT->isObjCId()) {
1475 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001476 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1477 if (Decl *PMDecl =
1478 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001479 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1480 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001481 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001482 return ExprError();
1483
Richard Smitha0edd302014-05-31 00:18:32 +00001484 return new (S.Context)
1485 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001486 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001487 }
1488
1489 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1490 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001491 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001492 return ExprError();
1493 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001494 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1495 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001496 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001497 ObjCMethodDecl *SMD = nullptr;
1498 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001499 /*Property id*/ nullptr,
1500 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001501 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001502
1503 return new (S.Context)
1504 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001505 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001506 }
1507 }
1508 // Use of id.member can only be for a property reference. Do not
1509 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001510 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1511 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001512 ObjCImpDecl, HasTemplateArgs);
1513
Richard Smitha0edd302014-05-31 00:18:32 +00001514 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001515 << MemberName << BaseType);
1516 }
1517
1518 // 'Class', unqualified only.
1519 if (OT->isObjCClass()) {
1520 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001521 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001522 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001523 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1524 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001525 ObjCImpDecl, HasTemplateArgs);
1526
1527 goto fail;
1528 }
1529
1530 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001531 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001532 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Shoaib Meenaiadf5a322018-03-27 18:58:28 +00001533 if (!IFace)
1534 goto fail;
1535
Douglas Gregor5476205b2011-06-23 00:49:38 +00001536 ObjCMethodDecl *Getter;
1537 if ((Getter = IFace->lookupClassMethod(Sel))) {
1538 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001539 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001540 return ExprError();
1541 } else
1542 Getter = IFace->lookupPrivateMethod(Sel, false);
1543 // If we found a getter then this may be a valid dot-reference, we
1544 // will look for the matching setter, in case it is needed.
1545 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001546 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1547 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001548 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001549 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1550 if (!Setter) {
1551 // If this reference is in an @implementation, also check for 'private'
1552 // methods.
1553 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1554 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001555
Richard Smitha0edd302014-05-31 00:18:32 +00001556 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001557 return ExprError();
1558
1559 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001560 return new (S.Context) ObjCPropertyRefExpr(
1561 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1562 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001563 }
1564
Richard Smitha0edd302014-05-31 00:18:32 +00001565 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1566 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001567 ObjCImpDecl, HasTemplateArgs);
1568
Richard Smitha0edd302014-05-31 00:18:32 +00001569 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001570 << MemberName << BaseType);
1571 }
1572
1573 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001574 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1575 MemberLoc, SourceLocation(), QualType(),
1576 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001577 }
1578
1579 // Handle 'field access' to vectors, such as 'V.xx'.
1580 if (BaseType->isExtVectorType()) {
1581 // FIXME: this expr should store IsArrow.
1582 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001583 ExprValueKind VK;
1584 if (IsArrow)
1585 VK = VK_LValue;
1586 else {
1587 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1588 VK = POE->getSyntacticForm()->getValueKind();
1589 else
1590 VK = BaseExpr.get()->getValueKind();
1591 }
Andrew V. Tischenko425f7b42018-02-09 09:30:42 +00001592
Richard Smitha0edd302014-05-31 00:18:32 +00001593 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001594 Member, MemberLoc);
1595 if (ret.isNull())
1596 return ExprError();
Andrew V. Tischenko425f7b42018-02-09 09:30:42 +00001597 Qualifiers BaseQ =
1598 S.Context.getCanonicalType(BaseExpr.get()->getType()).getQualifiers();
1599 ret = S.Context.getQualifiedType(ret, BaseQ);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001600
Richard Smitha0edd302014-05-31 00:18:32 +00001601 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001602 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001603 }
1604
1605 // Adjust builtin-sel to the appropriate redefinition type if that's
1606 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001607 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1608 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1609 BaseExpr = S.ImpCastExprToType(
1610 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1611 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001612 ObjCImpDecl, HasTemplateArgs);
1613 }
1614
1615 // Failure cases.
1616 fail:
1617
1618 // Recover from dot accesses to pointers, e.g.:
1619 // type *foo;
1620 // foo.bar
1621 // This is actually well-formed in two cases:
1622 // - 'type' is an Objective C type
1623 // - 'bar' is a pseudo-destructor name which happens to refer to
1624 // the appropriate pointer type
1625 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1626 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1627 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001628 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1629 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001630 << FixItHint::CreateReplacement(OpLoc, "->");
1631
1632 // Recurse as an -> access.
1633 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001634 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001635 ObjCImpDecl, HasTemplateArgs);
1636 }
1637 }
1638
1639 // If the user is trying to apply -> or . to a function name, it's probably
1640 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001641 if (S.tryToRecoverWithCall(
1642 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1643 /*complain*/ false,
1644 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001645 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001646 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001647 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1648 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001649 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001650 }
1651
Richard Smitha0edd302014-05-31 00:18:32 +00001652 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001653 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001654
1655 return ExprError();
1656}
1657
1658/// The main callback when the parser finds something like
1659/// expression . [nested-name-specifier] identifier
1660/// expression -> [nested-name-specifier] identifier
1661/// where 'identifier' encompasses a fairly broad spectrum of
1662/// possibilities, including destructor and operator references.
1663///
1664/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001665/// \param ObjCImpDecl the current Objective-C \@implementation
1666/// decl; this is an ugly hack around the fact that Objective-C
1667/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001668ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1669 SourceLocation OpLoc,
1670 tok::TokenKind OpKind,
1671 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001672 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001673 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001674 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001675 if (SS.isSet() && SS.isInvalid())
1676 return ExprError();
1677
1678 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001679 if (getLangOpts().MicrosoftExt &&
Faisal Vali2ab8c152017-12-30 04:15:27 +00001680 Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001681 Diag(Id.getSourceRange().getBegin(),
1682 diag::ext_ms_explicit_constructor_call);
1683
1684 TemplateArgumentListInfo TemplateArgsBuffer;
1685
1686 // Decompose the name into its component parts.
1687 DeclarationNameInfo NameInfo;
1688 const TemplateArgumentListInfo *TemplateArgs;
1689 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1690 NameInfo, TemplateArgs);
1691
1692 DeclarationName Name = NameInfo.getName();
1693 bool IsArrow = (OpKind == tok::arrow);
1694
1695 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001696 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001697
1698 // This is a postfix expression, so get rid of ParenListExprs.
1699 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1700 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001701 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001702
1703 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1704 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001705 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1706 TemplateKWLoc, FirstQualifierInScope,
1707 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001708 }
1709
David Majnemerced8bdf2015-02-25 17:36:15 +00001710 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001711 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1712 TemplateKWLoc, FirstQualifierInScope,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001713 NameInfo, TemplateArgs, S, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001714}
1715
Richard Smith7873de02016-08-11 22:25:46 +00001716ExprResult
1717Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1718 SourceLocation OpLoc, const CXXScopeSpec &SS,
1719 FieldDecl *Field, DeclAccessPair FoundDecl,
1720 const DeclarationNameInfo &MemberNameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001721 // x.a is an l-value if 'a' has a reference type. Otherwise:
1722 // x.a is an l-value/x-value/pr-value if the base is (and note
1723 // that *x is always an l-value), except that if the base isn't
1724 // an ordinary object then we must have an rvalue.
1725 ExprValueKind VK = VK_LValue;
1726 ExprObjectKind OK = OK_Ordinary;
1727 if (!IsArrow) {
1728 if (BaseExpr->getObjectKind() == OK_Ordinary)
1729 VK = BaseExpr->getValueKind();
1730 else
1731 VK = VK_RValue;
1732 }
1733 if (VK != VK_RValue && Field->isBitField())
1734 OK = OK_BitField;
1735
1736 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1737 QualType MemberType = Field->getType();
1738 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1739 MemberType = Ref->getPointeeType();
1740 VK = VK_LValue;
1741 } else {
1742 QualType BaseType = BaseExpr->getType();
1743 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001744
Douglas Gregor5476205b2011-06-23 00:49:38 +00001745 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001746
Douglas Gregor5476205b2011-06-23 00:49:38 +00001747 // GC attributes are never picked up by members.
1748 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001749
Douglas Gregor5476205b2011-06-23 00:49:38 +00001750 // CVR attributes from the base are picked up by members,
1751 // except that 'mutable' members don't pick up 'const'.
1752 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001753
Richard Smith7873de02016-08-11 22:25:46 +00001754 Qualifiers MemberQuals =
1755 Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001756
Douglas Gregor5476205b2011-06-23 00:49:38 +00001757 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001758
Douglas Gregor5476205b2011-06-23 00:49:38 +00001759 Qualifiers Combined = BaseQuals + MemberQuals;
1760 if (Combined != MemberQuals)
Richard Smith7873de02016-08-11 22:25:46 +00001761 MemberType = Context.getQualifiedType(MemberType, Combined);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001762 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001763
Richard Smitha31174e2017-11-01 04:52:12 +00001764 auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1765 if (!(CurMethod && CurMethod->isDefaulted()))
1766 UnusedPrivateFields.remove(Field);
Daniel Jasper0baec5492012-06-06 08:32:04 +00001767
Richard Smith7873de02016-08-11 22:25:46 +00001768 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1769 FoundDecl, Field);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001770 if (Base.isInvalid())
1771 return ExprError();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001772
1773 // Build a reference to a private copy for non-static data members in
1774 // non-static member functions, privatized by OpenMP constructs.
Richard Smith7873de02016-08-11 22:25:46 +00001775 if (getLangOpts().OpenMP && IsArrow &&
1776 !CurContext->isDependentContext() &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001777 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001778 if (auto *PrivateCopy = isOpenMPCapturedDecl(Field)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001779 return getOpenMPCapturedExpr(PrivateCopy, VK, OK,
1780 MemberNameInfo.getLoc());
1781 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001782 }
Alexey Bataevd0c03ca2017-07-11 19:43:28 +00001783
1784 return BuildMemberExpr(*this, Context, Base.get(), IsArrow, OpLoc, SS,
1785 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1786 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001787}
1788
1789/// Builds an implicit member access expression. The current context
1790/// is known to be an instance method, and the given unqualified lookup
1791/// set is known to contain only instance members, at least one of which
1792/// is from an appropriate type.
1793ExprResult
1794Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001795 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001796 LookupResult &R,
1797 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001798 bool IsKnownInstance, const Scope *S) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001799 assert(!R.empty() && !R.isAmbiguous());
1800
1801 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001802
Douglas Gregor5476205b2011-06-23 00:49:38 +00001803 // If this is known to be an instance access, go ahead and build an
1804 // implicit 'this' expression now.
1805 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001806 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001807 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001808
1809 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001810 if (IsKnownInstance) {
1811 SourceLocation Loc = R.getNameLoc();
1812 if (SS.getRange().isValid())
1813 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001814 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001815 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1816 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001817
Douglas Gregor5476205b2011-06-23 00:49:38 +00001818 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1819 /*OpLoc*/ SourceLocation(),
1820 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001821 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001822 /*FirstQualifierInScope*/ nullptr,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001823 R, TemplateArgs, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001824}