blob: 283621889f8026a0923100afce0692ffcba0813b [file] [log] [blame]
Douglas Gregor5476205b2011-06-23 00:49:38 +00001//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis member access expressions.
11//
12//===----------------------------------------------------------------------===//
Kaelyn Takatafe408a72014-10-27 18:07:46 +000013#include "clang/Sema/Overload.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000014#include "clang/AST/ASTLambda.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000015#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "clang/Sema/SemaInternal.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000025
26using namespace clang;
27using namespace sema;
28
Richard Smithd80b2d52012-11-22 00:24:47 +000029typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
Richard Smithd80b2d52012-11-22 00:24:47 +000030
Douglas Gregor5476205b2011-06-23 00:49:38 +000031/// Determines if the given class is provably not derived from all of
32/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000033static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
34 const BaseSet &Bases) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +000035 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
36 return !Bases.count(Base->getCanonicalDecl());
37 };
38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
Douglas Gregor5476205b2011-06-23 00:49:38 +000039}
40
41enum IMAKind {
42 /// The reference is definitely not an instance member access.
43 IMA_Static,
44
45 /// The reference may be an implicit instance member access.
46 IMA_Mixed,
47
Eli Friedman7bda7f72012-01-18 03:53:45 +000048 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000049 /// so, because the context is not an instance method.
50 IMA_Mixed_StaticContext,
51
52 /// The reference may be to an instance member, but it is invalid if
53 /// so, because the context is from an unrelated class.
54 IMA_Mixed_Unrelated,
55
56 /// The reference is definitely an implicit instance member access.
57 IMA_Instance,
58
59 /// The reference may be to an unresolved using declaration.
60 IMA_Unresolved,
61
John McCallf413f5e2013-05-03 00:10:13 +000062 /// The reference is a contextually-permitted abstract member reference.
63 IMA_Abstract,
64
Douglas Gregor5476205b2011-06-23 00:49:38 +000065 /// The reference may be to an unresolved using declaration and the
66 /// context is not an instance method.
67 IMA_Unresolved_StaticContext,
68
Eli Friedman456f0182012-01-20 01:26:23 +000069 // The reference refers to a field which is not a member of the containing
70 // class, which is allowed because we're in C++11 mode and the context is
71 // unevaluated.
72 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000073
Douglas Gregor5476205b2011-06-23 00:49:38 +000074 /// All possible referrents are instance members and the current
75 /// context is not an instance method.
76 IMA_Error_StaticContext,
77
78 /// All possible referrents are instance members of an unrelated
79 /// class.
80 IMA_Error_Unrelated
81};
82
83/// The given lookup names class member(s) and is not being used for
84/// an address-of-member expression. Classify the type of access
85/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000086/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000087/// conservatively answer "yes", in which case some errors will simply
88/// not be caught until template-instantiation.
89static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +000090 const LookupResult &R) {
91 assert(!R.empty() && (*R.begin())->isCXXClassMember());
92
93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
94
Douglas Gregor3024f072012-04-16 07:05:22 +000095 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +000097
98 if (R.isUnresolvableResult())
99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
100
101 // Collect all the declaring classes of instance members we find.
102 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000103 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000104 BaseSet Classes;
Reid Kleckner077fe122015-10-20 18:12:08 +0000105 for (NamedDecl *D : R) {
106 // Look through any using decls.
107 D = D->getUnderlyingDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000108
109 if (D->isCXXInstanceMember()) {
Benjamin Kramera008d3a2015-04-10 11:37:55 +0000110 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
111 isa<IndirectFieldDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000112
113 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
114 Classes.insert(R->getCanonicalDecl());
Reid Kleckner077fe122015-10-20 18:12:08 +0000115 } else
Douglas Gregor5476205b2011-06-23 00:49:38 +0000116 hasNonInstance = true;
117 }
118
119 // If we didn't find any instance members, it can't be an implicit
120 // member reference.
121 if (Classes.empty())
122 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000123
124 // C++11 [expr.prim.general]p12:
125 // An id-expression that denotes a non-static data member or non-static
126 // member function of a class can only be used:
127 // (...)
128 // - if that id-expression denotes a non-static data member and it
129 // appears in an unevaluated operand.
130 //
131 // This rule is specific to C++11. However, we also permit this form
132 // in unevaluated inline assembly operands, like the operand to a SIZE.
133 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
134 assert(!AbstractInstanceResult);
135 switch (SemaRef.ExprEvalContexts.back().Context) {
136 case Sema::Unevaluated:
137 if (isField && SemaRef.getLangOpts().CPlusPlus11)
138 AbstractInstanceResult = IMA_Field_Uneval_Context;
139 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000140
John McCallf413f5e2013-05-03 00:10:13 +0000141 case Sema::UnevaluatedAbstract:
142 AbstractInstanceResult = IMA_Abstract;
143 break;
144
Richard Smithb130fe72016-06-23 19:16:49 +0000145 case Sema::DiscardedStatement:
John McCallf413f5e2013-05-03 00:10:13 +0000146 case Sema::ConstantEvaluated:
147 case Sema::PotentiallyEvaluated:
148 case Sema::PotentiallyEvaluatedIfUsed:
149 break;
Richard Smitheae99682012-02-25 10:04:07 +0000150 }
151
Douglas Gregor5476205b2011-06-23 00:49:38 +0000152 // If the current context is not an instance method, it can't be
153 // an implicit member reference.
154 if (isStaticContext) {
155 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000156 return IMA_Mixed_StaticContext;
157
John McCallf413f5e2013-05-03 00:10:13 +0000158 return AbstractInstanceResult ? AbstractInstanceResult
159 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000160 }
161
162 CXXRecordDecl *contextClass;
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
164 contextClass = MD->getParent()->getCanonicalDecl();
165 else
166 contextClass = cast<CXXRecordDecl>(DC);
167
168 // [class.mfct.non-static]p3:
169 // ...is used in the body of a non-static member function of class X,
170 // if name lookup (3.4.1) resolves the name in the id-expression to a
171 // non-static non-type member of some class C [...]
172 // ...if C is not X or a base class of X, the class member access expression
173 // is ill-formed.
174 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000175 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000176 R.getNamingClass()->getCanonicalDecl()) {
177 // If the naming class is not the current context, this was a qualified
178 // member name lookup, and it's sufficient to check that we have the naming
179 // class as a base class.
180 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000181 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000182 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000183
184 // If we can prove that the current context is unrelated to all the
185 // declaring classes, it can't be an implicit member reference (in
186 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000187 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000188 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000189 AbstractInstanceResult ? AbstractInstanceResult :
190 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000191
192 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
193}
194
195/// Diagnose a reference to a field with no object available.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000196static void diagnoseInstanceReference(Sema &SemaRef,
197 const CXXScopeSpec &SS,
198 NamedDecl *Rep,
199 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000200 SourceLocation Loc = nameInfo.getLoc();
201 SourceRange Range(Loc);
202 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000203
Reid Klecknerae628962014-12-18 00:42:51 +0000204 // Look through using shadow decls and aliases.
205 Rep = Rep->getUnderlyingDecl();
206
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000207 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
Richard Smithfa0a1f52012-04-05 01:13:04 +0000208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000209 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000210 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
211
212 bool InStaticMethod = Method && Method->isStatic();
213 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
214
215 if (IsField && InStaticMethod)
216 // "invalid use of member 'x' in static member function"
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000217 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000218 << Range << nameInfo.getName();
219 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
220 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
221 // Unqualified lookup in a non-static member function found a member of an
222 // enclosing class.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000223 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
224 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000225 else if (IsField)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000226 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
227 << nameInfo.getName() << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000228 else
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000229 SemaRef.Diag(Loc, diag::err_member_call_without_object)
230 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000231}
232
233/// Builds an expression which might be an implicit member expression.
234ExprResult
235Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000236 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000237 LookupResult &R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000238 const TemplateArgumentListInfo *TemplateArgs,
239 const Scope *S) {
Reid Klecknerae628962014-12-18 00:42:51 +0000240 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000241 case IMA_Instance:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000242 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000243
244 case IMA_Mixed:
245 case IMA_Mixed_Unrelated:
246 case IMA_Unresolved:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000247 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
248 S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000249
Richard Smith2a986112012-02-25 10:20:59 +0000250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
253 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000254 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000255 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000256 case IMA_Mixed_StaticContext:
257 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000258 if (TemplateArgs || TemplateKWLoc.isValid())
259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000260 return BuildDeclarationNameExpr(SS, R, false);
261
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000265 R.getLookupNameInfo());
266 return ExprError();
267 }
268
269 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000270}
271
272/// Check an ext-vector component access expression.
273///
274/// VK should be set in advance to the value kind of the base
275/// expression.
276static QualType
277CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
278 SourceLocation OpLoc, const IdentifierInfo *CompName,
279 SourceLocation CompLoc) {
280 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
281 // see FIXME there.
282 //
283 // FIXME: This logic can be greatly simplified by splitting it along
284 // halving/not halving and reworking the component checking.
285 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
286
287 // The vector accessor can't exceed the number of elements.
288 const char *compStr = CompName->getNameStart();
289
290 // This flag determines whether or not the component is one of the four
291 // special names that indicate a subset of exactly half the elements are
292 // to be selected.
293 bool HalvingSwizzle = false;
294
295 // This flag determines whether or not CompName has an 's' char prefix,
296 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000297 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000298
299 bool HasRepeated = false;
300 bool HasIndex[16] = {};
301
302 int Idx;
303
304 // Check that we've found one of the special components, or that the component
305 // names must come from the same set.
306 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
307 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
308 HalvingSwizzle = true;
309 } else if (!HexSwizzle &&
310 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
311 do {
312 if (HasIndex[Idx]) HasRepeated = true;
313 HasIndex[Idx] = true;
314 compStr++;
315 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
316 } else {
317 if (HexSwizzle) compStr++;
318 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
319 if (HasIndex[Idx]) HasRepeated = true;
320 HasIndex[Idx] = true;
321 compStr++;
322 }
323 }
324
325 if (!HalvingSwizzle && *compStr) {
326 // We didn't get to the end of the string. This means the component names
327 // didn't come from the same set *or* we encountered an illegal name.
328 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000329 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000330 return QualType();
331 }
332
333 // Ensure no component accessor exceeds the width of the vector type it
334 // operates on.
335 if (!HalvingSwizzle) {
336 compStr = CompName->getNameStart();
337
338 if (HexSwizzle)
339 compStr++;
340
341 while (*compStr) {
342 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
343 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
344 << baseType << SourceRange(CompLoc);
345 return QualType();
346 }
347 }
348 }
349
350 // The component accessor looks fine - now we need to compute the actual type.
351 // The vector type is implied by the component accessor. For example,
352 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
353 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
354 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
355 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
356 : CompName->getLength();
357 if (HexSwizzle)
358 CompSize--;
359
360 if (CompSize == 1)
361 return vecType->getElementType();
362
363 if (HasRepeated) VK = VK_RValue;
364
365 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
366 // Now look up the TypeDefDecl from the vector type. Without this,
367 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000368 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000369 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000370 E = S.ExtVectorDecls.end();
371 I != E; ++I) {
372 if ((*I)->getUnderlyingType() == VT)
373 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000374 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000375
Douglas Gregor5476205b2011-06-23 00:49:38 +0000376 return VT; // should never get here (a typedef type should always be found).
377}
378
379static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
380 IdentifierInfo *Member,
381 const Selector &Sel,
382 ASTContext &Context) {
383 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000384 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
385 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000386 return PD;
387 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
388 return OMD;
389
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000390 for (const auto *I : PDecl->protocols()) {
391 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000392 Context))
393 return D;
394 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000395 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000396}
397
398static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
399 IdentifierInfo *Member,
400 const Selector &Sel,
401 ASTContext &Context) {
402 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000403 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000404 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000405 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000406 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
407 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000408 GDecl = PD;
409 break;
410 }
411 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000412 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000413 GDecl = OMD;
414 break;
415 }
416 }
417 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000418 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000419 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000420 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000421 if (GDecl)
422 return GDecl;
423 }
424 }
425 return GDecl;
426}
427
428ExprResult
429Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
430 bool IsArrow, SourceLocation OpLoc,
431 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000432 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000433 NamedDecl *FirstQualifierInScope,
434 const DeclarationNameInfo &NameInfo,
435 const TemplateArgumentListInfo *TemplateArgs) {
436 // Even in dependent contexts, try to diagnose base expressions with
437 // obviously wrong types, e.g.:
438 //
439 // T* t;
440 // t.f;
441 //
442 // In Obj-C++, however, the above expression is valid, since it could be
443 // accessing the 'f' property if T is an Obj-C interface. The extra check
444 // allows this, while still reporting an error if T is a struct pointer.
445 if (!IsArrow) {
446 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000447 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000448 PT->getPointeeType()->isRecordType())) {
449 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000450 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000451 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000452 return ExprError();
453 }
454 }
455
456 assert(BaseType->isDependentType() ||
457 NameInfo.getName().isDependentName() ||
458 isDependentScopeSpecifier(SS));
459
460 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
461 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000462 return CXXDependentScopeMemberExpr::Create(
463 Context, BaseExpr, BaseType, IsArrow, OpLoc,
464 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
465 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000466}
467
468/// We know that the given qualified member reference points only to
469/// declarations which do not belong to the static type of the base
470/// expression. Diagnose the problem.
471static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
472 Expr *BaseExpr,
473 QualType BaseType,
474 const CXXScopeSpec &SS,
475 NamedDecl *rep,
476 const DeclarationNameInfo &nameInfo) {
477 // If this is an implicit member access, use a different set of
478 // diagnostics.
479 if (!BaseExpr)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000480 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000481
482 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
483 << SS.getRange() << rep << BaseType;
484}
485
486// Check whether the declarations we found through a nested-name
487// specifier in a member expression are actually members of the base
488// type. The restriction here is:
489//
490// C++ [expr.ref]p2:
491// ... In these cases, the id-expression shall name a
492// member of the class or of one of its base classes.
493//
494// So it's perfectly legitimate for the nested-name specifier to name
495// an unrelated class, and for us to find an overload set including
496// decls from classes which are not superclasses, as long as the decl
497// we actually pick through overload resolution is from a superclass.
498bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
499 QualType BaseType,
500 const CXXScopeSpec &SS,
501 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000502 CXXRecordDecl *BaseRecord =
503 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
504 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000505 // We can't check this yet because the base type is still
506 // dependent.
507 assert(BaseType->isDependentType());
508 return false;
509 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000510
511 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
512 // If this is an implicit member reference and we find a
513 // non-instance member, it's not an error.
514 if (!BaseExpr && !(*I)->isCXXInstanceMember())
515 return false;
516
517 // Note that we use the DC of the decl, not the underlying decl.
518 DeclContext *DC = (*I)->getDeclContext();
519 while (DC->isTransparentContext())
520 DC = DC->getParent();
521
522 if (!DC->isRecord())
523 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000524
Richard Smithd80b2d52012-11-22 00:24:47 +0000525 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
526 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
527 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000528 return false;
529 }
530
531 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
532 R.getRepresentativeDecl(),
533 R.getLookupNameInfo());
534 return true;
535}
536
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000537namespace {
538
539// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000540// FunctionTemplateDecl and are declared in the current record or, for a C++
541// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000542class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000543public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000544 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000545 : Record(RTy->getDecl()) {
546 // Don't add bare keywords to the consumer since they will always fail
547 // validation by virtue of not being associated with any decls.
548 WantTypeSpecifiers = false;
549 WantExpressionKeywords = false;
550 WantCXXNamedCasts = false;
551 WantFunctionLikeCasts = false;
552 WantRemainingKeywords = false;
553 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000554
Craig Toppere14c0f82014-03-12 04:55:44 +0000555 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000556 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000557 // Don't accept candidates that cannot be member functions, constants,
558 // variables, or templates.
559 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
560 return false;
561
562 // Accept candidates that occur in the current record.
563 if (Record->containsDecl(ND))
564 return true;
565
566 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
567 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000568 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000569 if (const RecordType *BSTy =
570 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000571 if (BSTy->getDecl()->containsDecl(ND))
572 return true;
573 }
574 }
575 }
576
577 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000578 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000579
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000580private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000581 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000582};
583
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000584}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000585
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000586static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000587 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000588 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000589 SourceLocation OpLoc, bool IsArrow,
590 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000591 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000592 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000593 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000594 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
595 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000596 diag::err_typecheck_incomplete_tag,
597 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000598 return true;
599
600 if (HasTemplateArgs) {
601 // LookupTemplateName doesn't expect these both to exist simultaneously.
602 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
603
604 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000605 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000606 return false;
607 }
608
609 DeclContext *DC = RDecl;
610 if (SS.isSet()) {
611 // If the member name was a qualified-id, look into the
612 // nested-name-specifier.
613 DC = SemaRef.computeDeclContext(SS, false);
614
615 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
616 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000617 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000618 return true;
619 }
620
621 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
622
623 if (!isa<TypeDecl>(DC)) {
624 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000625 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000626 return true;
627 }
628 }
629
630 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000631 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000632
633 if (!R.empty())
634 return false;
635
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000636 DeclarationName Typo = R.getLookupName();
637 SourceLocation TypoLoc = R.getNameLoc();
David Blaikiea8173ba2015-09-28 23:48:55 +0000638
639 struct QueryState {
640 Sema &SemaRef;
641 DeclarationNameInfo NameInfo;
642 Sema::LookupNameKind LookupKind;
643 Sema::RedeclarationKind Redecl;
644 };
645 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
646 R.isForRedeclaration() ? Sema::ForRedeclaration
647 : Sema::NotForRedeclaration};
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000648 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000649 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
650 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000651 [=, &SemaRef](const TypoCorrection &TC) {
652 if (TC) {
653 assert(!TC.isKeyword() &&
654 "Got a keyword as a correction for a member!");
655 bool DroppedSpecifier =
656 TC.WillReplaceSpecifier() &&
657 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
658 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
659 << Typo << DC << DroppedSpecifier
660 << SS.getRange());
661 } else {
662 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
663 }
664 },
665 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
David Blaikiea8173ba2015-09-28 23:48:55 +0000666 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000667 R.clear(); // Ensure there's no decls lingering in the shared state.
668 R.suppressDiagnostics();
669 R.setLookupName(TC.getCorrection());
670 for (NamedDecl *ND : TC)
671 R.addDecl(ND);
672 R.resolveKind();
673 return SemaRef.BuildMemberReferenceExpr(
674 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000675 nullptr, R, nullptr, nullptr);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000676 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000677 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000678
679 return false;
680}
681
Richard Smitha0edd302014-05-31 00:18:32 +0000682static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
683 ExprResult &BaseExpr, bool &IsArrow,
684 SourceLocation OpLoc, CXXScopeSpec &SS,
685 Decl *ObjCImpDecl, bool HasTemplateArgs);
686
Douglas Gregor5476205b2011-06-23 00:49:38 +0000687ExprResult
688Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
689 SourceLocation OpLoc, bool IsArrow,
690 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000691 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000692 NamedDecl *FirstQualifierInScope,
693 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000694 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000695 const Scope *S,
Richard Smitha0edd302014-05-31 00:18:32 +0000696 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000697 if (BaseType->isDependentType() ||
698 (SS.isSet() && isDependentScopeSpecifier(SS)))
699 return ActOnDependentMemberExpr(Base, BaseType,
700 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000701 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000702 NameInfo, TemplateArgs);
703
704 LookupResult R(*this, NameInfo, LookupMemberName);
705
706 // Implicit member accesses.
707 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000708 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000709 QualType RecordTy = BaseType;
710 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000711 if (LookupMemberExprInRecord(*this, R, nullptr,
712 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000713 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000714 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000715 if (TE)
716 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000717
718 // Explicit member accesses.
719 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000720 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000721 ExprResult Result = LookupMemberExpr(
722 *this, R, BaseResult, IsArrow, OpLoc, SS,
723 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
724 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000725
726 if (BaseResult.isInvalid())
727 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000728 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000729
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000730 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000731 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000732
733 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000734 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000735
736 // LookupMemberExpr can modify Base, and thus change BaseType
737 BaseType = Base->getType();
738 }
739
740 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000741 OpLoc, IsArrow, SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000742 FirstQualifierInScope, R, TemplateArgs, S,
Richard Smitha0edd302014-05-31 00:18:32 +0000743 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000744}
745
746static ExprResult
747BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000748 SourceLocation OpLoc, const CXXScopeSpec &SS,
749 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000750 const DeclarationNameInfo &MemberNameInfo);
751
752ExprResult
753Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
754 SourceLocation loc,
755 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000756 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000757 Expr *baseObjectExpr,
758 SourceLocation opLoc) {
759 // First, build the expression that refers to the base object.
760
761 bool baseObjectIsPointer = false;
762 Qualifiers baseQuals;
763
764 // Case 1: the base of the indirect field is not a field.
765 VarDecl *baseVariable = indirectField->getVarDecl();
766 CXXScopeSpec EmptySS;
767 if (baseVariable) {
768 assert(baseVariable->getType()->isRecordType());
769
770 // In principle we could have a member access expression that
771 // accesses an anonymous struct/union that's a static member of
772 // the base object's class. However, under the current standard,
773 // static data members cannot be anonymous structs or unions.
774 // Supporting this is as easy as building a MemberExpr here.
775 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
776
777 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
778
779 ExprResult result
780 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
781 if (result.isInvalid()) return ExprError();
782
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000783 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000784 baseObjectIsPointer = false;
785 baseQuals = baseObjectExpr->getType().getQualifiers();
786
787 // Case 2: the base of the indirect field is a field and the user
788 // wrote a member expression.
789 } else if (baseObjectExpr) {
790 // The caller provided the base object expression. Determine
791 // whether its a pointer and whether it adds any qualifiers to the
792 // anonymous struct/union fields we're looking into.
793 QualType objectType = baseObjectExpr->getType();
794
795 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
796 baseObjectIsPointer = true;
797 objectType = ptr->getPointeeType();
798 } else {
799 baseObjectIsPointer = false;
800 }
801 baseQuals = objectType.getQualifiers();
802
803 // Case 3: the base of the indirect field is a field and we should
804 // build an implicit member access.
805 } else {
806 // We've found a member of an anonymous struct/union that is
807 // inside a non-anonymous struct/union, so in a well-formed
808 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000809 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000810 if (ThisTy.isNull()) {
811 Diag(loc, diag::err_invalid_member_use_in_static_method)
812 << indirectField->getDeclName();
813 return ExprError();
814 }
815
816 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000817 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000818 baseObjectExpr
819 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
820 baseObjectIsPointer = true;
821 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
822 }
823
824 // Build the implicit member references to the field of the
825 // anonymous struct/union.
826 Expr *result = baseObjectExpr;
827 IndirectFieldDecl::chain_iterator
828 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
829
830 // Build the first member access in the chain with full information.
831 if (!baseVariable) {
832 FieldDecl *field = cast<FieldDecl>(*FI);
833
Douglas Gregor5476205b2011-06-23 00:49:38 +0000834 // Make a nameInfo that properly uses the anonymous name.
835 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000836
Douglas Gregor5476205b2011-06-23 00:49:38 +0000837 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000838 SourceLocation(), EmptySS, field,
839 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000840 if (!result)
841 return ExprError();
842
Douglas Gregor5476205b2011-06-23 00:49:38 +0000843 // FIXME: check qualified member access
844 }
845
846 // In all cases, we should now skip the first declaration in the chain.
847 ++FI;
848
849 while (FI != FEnd) {
850 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000851
Douglas Gregor5476205b2011-06-23 00:49:38 +0000852 // FIXME: these are somewhat meaningless
853 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000854 DeclAccessPair fakeFoundDecl =
855 DeclAccessPair::make(field, field->getAccess());
856
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000857 result =
858 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
859 SourceLocation(), (FI == FEnd ? SS : EmptySS),
860 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000861 }
862
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000863 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000864}
865
John McCall5e77d762013-04-16 07:28:30 +0000866static ExprResult
867BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
868 const CXXScopeSpec &SS,
869 MSPropertyDecl *PD,
870 const DeclarationNameInfo &NameInfo) {
871 // Property names are always simple identifiers and therefore never
872 // require any interesting additional storage.
873 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
874 S.Context.PseudoObjectTy, VK_LValue,
875 SS.getWithLocInContext(S.Context),
876 NameInfo.getLoc());
877}
878
Douglas Gregor5476205b2011-06-23 00:49:38 +0000879/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000880static MemberExpr *BuildMemberExpr(
881 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
882 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
883 ValueDecl *Member, DeclAccessPair FoundDecl,
884 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
885 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000886 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000887 MemberExpr *E = MemberExpr::Create(
888 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
889 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000890 SemaRef.MarkMemberReferenced(E);
891 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000892}
893
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000894/// \brief Determine if the given scope is within a function-try-block handler.
895static bool IsInFnTryBlockHandler(const Scope *S) {
896 // Walk the scope stack until finding a FnTryCatchScope, or leave the
897 // function scope. If a FnTryCatchScope is found, check whether the TryScope
898 // flag is set. If it is not, it's a function-try-block handler.
899 for (; S != S->getFnParent(); S = S->getParent()) {
900 if (S->getFlags() & Scope::FnTryCatchScope)
901 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
902 }
903 return false;
904}
905
Faisal Valie7f8fb92016-02-22 02:24:29 +0000906static VarDecl *
907getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
908 const TemplateArgumentListInfo *TemplateArgs,
909 const DeclarationNameInfo &MemberNameInfo,
910 SourceLocation TemplateKWLoc) {
911
912 if (!TemplateArgs) {
913 S.Diag(MemberNameInfo.getBeginLoc(), diag::err_template_decl_ref)
914 << /*Variable template*/ 1 << MemberNameInfo.getName()
915 << MemberNameInfo.getSourceRange();
916
917 S.Diag(VarTempl->getLocation(), diag::note_template_decl_here);
918
919 return nullptr;
920 }
921 DeclResult VDecl = S.CheckVarTemplateId(
922 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
923 if (VDecl.isInvalid())
924 return nullptr;
925 VarDecl *Var = cast<VarDecl>(VDecl.get());
926 if (!Var->getTemplateSpecializationKind())
927 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
928 MemberNameInfo.getLoc());
929 return Var;
930}
931
Douglas Gregor5476205b2011-06-23 00:49:38 +0000932ExprResult
933Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
934 SourceLocation OpLoc, bool IsArrow,
935 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000936 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000937 NamedDecl *FirstQualifierInScope,
938 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000939 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000940 const Scope *S,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000941 bool SuppressQualifierCheck,
942 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000943 QualType BaseType = BaseExprType;
944 if (IsArrow) {
945 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000946 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000947 }
948 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000949
950 LambdaScopeInfo *const CurLSI = getCurLambda();
951 // If this is an implicit member reference and the overloaded
952 // name refers to both static and non-static member functions
953 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
954 // check if we should/can capture 'this'...
955 // Keep this example in mind:
956 // struct X {
957 // void f(int) { }
958 // static void f(double) { }
959 //
960 // int g() {
961 // auto L = [=](auto a) {
962 // return [](int i) {
963 // return [=](auto b) {
964 // f(b);
965 // //f(decltype(a){});
966 // };
967 // };
968 // };
969 // auto M = L(0.0);
970 // auto N = M(3);
971 // N(5.32); // OK, must not error.
972 // return 0;
973 // }
974 // };
975 //
976 if (!BaseExpr && CurLSI) {
977 SourceLocation Loc = R.getNameLoc();
978 if (SS.getRange().isValid())
979 Loc = SS.getRange().getBegin();
980 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
981 // If the enclosing function is not dependent, then this lambda is
982 // capture ready, so if we can capture this, do so.
983 if (!EnclosingFunctionCtx->isDependentContext()) {
984 // If the current lambda and all enclosing lambdas can capture 'this' -
985 // then go ahead and capture 'this' (since our unresolved overload set
986 // contains both static and non-static member functions).
987 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
988 CheckCXXThisCapture(Loc);
989 } else if (CurContext->isDependentContext()) {
990 // ... since this is an implicit member reference, that might potentially
991 // involve a 'this' capture, mark 'this' for potential capture in
992 // enclosing lambdas.
993 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
994 CurLSI->addPotentialThisCapture(Loc);
995 }
996 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000997 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
998 DeclarationName MemberName = MemberNameInfo.getName();
999 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1000
1001 if (R.isAmbiguous())
1002 return ExprError();
1003
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001004 // [except.handle]p10: Referring to any non-static member or base class of an
1005 // object in the handler for a function-try-block of a constructor or
1006 // destructor for that object results in undefined behavior.
1007 const auto *FD = getCurFunctionDecl();
1008 if (S && BaseExpr && FD &&
1009 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1010 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1011 IsInFnTryBlockHandler(S))
1012 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1013 << isa<CXXDestructorDecl>(FD);
1014
Douglas Gregor5476205b2011-06-23 00:49:38 +00001015 if (R.empty()) {
1016 // Rederive where we looked up.
1017 DeclContext *DC = (SS.isSet()
1018 ? computeDeclContext(SS, false)
1019 : BaseType->getAs<RecordType>()->getDecl());
1020
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001021 if (ExtraArgs) {
1022 ExprResult RetryExpr;
1023 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +00001024 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001025 ParsedType ObjectType;
1026 bool MayBePseudoDestructor = false;
1027 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1028 OpLoc, tok::arrow, ObjectType,
1029 MayBePseudoDestructor);
1030 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1031 CXXScopeSpec TempSS(SS);
1032 RetryExpr = ActOnMemberAccessExpr(
1033 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +00001034 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001035 }
1036 if (Trap.hasErrorOccurred())
1037 RetryExpr = ExprError();
1038 }
1039 if (RetryExpr.isUsable()) {
1040 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1041 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1042 return RetryExpr;
1043 }
1044 }
1045
Douglas Gregor5476205b2011-06-23 00:49:38 +00001046 Diag(R.getNameLoc(), diag::err_no_member)
1047 << MemberName << DC
1048 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1049 return ExprError();
1050 }
1051
1052 // Diagnose lookups that find only declarations from a non-base
1053 // type. This is possible for either qualified lookups (which may
1054 // have been qualified with an unrelated type) or implicit member
1055 // expressions (which were found with unqualified lookup and thus
1056 // may have come from an enclosing scope). Note that it's okay for
1057 // lookup to find declarations from a non-base type as long as those
1058 // aren't the ones picked by overload resolution.
1059 if ((SS.isSet() || !BaseExpr ||
1060 (isa<CXXThisExpr>(BaseExpr) &&
1061 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1062 !SuppressQualifierCheck &&
1063 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1064 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001065
Douglas Gregor5476205b2011-06-23 00:49:38 +00001066 // Construct an unresolved result if we in fact got an unresolved
1067 // result.
1068 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1069 // Suppress any lookup-related diagnostics; we'll do these when we
1070 // pick a member.
1071 R.suppressDiagnostics();
1072
1073 UnresolvedMemberExpr *MemExpr
1074 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1075 BaseExpr, BaseExprType,
1076 IsArrow, OpLoc,
1077 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001078 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001079 TemplateArgs, R.begin(), R.end());
1080
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001081 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001082 }
1083
1084 assert(R.isSingleResult());
1085 DeclAccessPair FoundDecl = R.begin().getPair();
1086 NamedDecl *MemberDecl = R.getFoundDecl();
1087
1088 // FIXME: diagnose the presence of template arguments now.
1089
1090 // If the decl being referenced had an error, return an error for this
1091 // sub-expr without emitting another error, in order to avoid cascading
1092 // error cases.
1093 if (MemberDecl->isInvalidDecl())
1094 return ExprError();
1095
1096 // Handle the implicit-member-access case.
1097 if (!BaseExpr) {
1098 // If this is not an instance member, convert to a non-member access.
Faisal Valie7f8fb92016-02-22 02:24:29 +00001099 if (!MemberDecl->isCXXInstanceMember()) {
1100 // If this is a variable template, get the instantiated variable
1101 // declaration corresponding to the supplied template arguments
1102 // (while emitting diagnostics as necessary) that will be referenced
1103 // by this expression.
Faisal Vali640dc752016-02-25 05:09:30 +00001104 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1105 "How did we get template arguments here sans a variable template");
Faisal Valie7f8fb92016-02-22 02:24:29 +00001106 if (isa<VarTemplateDecl>(MemberDecl)) {
1107 MemberDecl = getVarTemplateSpecialization(
1108 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1109 R.getLookupNameInfo(), TemplateKWLoc);
1110 if (!MemberDecl)
1111 return ExprError();
1112 }
Faisal Vali640dc752016-02-25 05:09:30 +00001113 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1114 FoundDecl, TemplateArgs);
Faisal Valie7f8fb92016-02-22 02:24:29 +00001115 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001116 SourceLocation Loc = R.getNameLoc();
1117 if (SS.getRange().isValid())
1118 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001119 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001120 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1121 }
1122
Douglas Gregor5476205b2011-06-23 00:49:38 +00001123 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001124 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001125 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001126
Douglas Gregor5476205b2011-06-23 00:49:38 +00001127 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001128 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1129 FoundDecl, MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001130
John McCall5e77d762013-04-16 07:28:30 +00001131 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1132 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1133 MemberNameInfo);
1134
Douglas Gregor5476205b2011-06-23 00:49:38 +00001135 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1136 // We may have found a field within an anonymous union or struct
1137 // (C++ [class.union]).
1138 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001139 FoundDecl, BaseExpr,
1140 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001141
1142 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001143 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1144 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001145 Var->getType().getNonReferenceType(), VK_LValue,
1146 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001147 }
1148
1149 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1150 ExprValueKind valueKind;
1151 QualType type;
1152 if (MemberFn->isInstance()) {
1153 valueKind = VK_RValue;
1154 type = Context.BoundMemberTy;
1155 } else {
1156 valueKind = VK_LValue;
1157 type = MemberFn->getType();
1158 }
1159
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001160 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1161 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1162 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001163 }
1164 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1165
1166 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001167 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1168 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1169 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001170 }
Faisal Valie7f8fb92016-02-22 02:24:29 +00001171 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1172 if (VarDecl *Var = getVarTemplateSpecialization(
1173 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1174 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1175 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1176 Var->getType().getNonReferenceType(), VK_LValue,
1177 OK_Ordinary);
1178 return ExprError();
1179 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001180
Douglas Gregor5476205b2011-06-23 00:49:38 +00001181 // We found something that we didn't expect. Complain.
1182 if (isa<TypeDecl>(MemberDecl))
1183 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1184 << MemberName << BaseType << int(IsArrow);
1185 else
1186 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1187 << MemberName << BaseType << int(IsArrow);
1188
1189 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1190 << MemberName;
1191 R.suppressDiagnostics();
1192 return ExprError();
1193}
1194
1195/// Given that normal member access failed on the given expression,
1196/// and given that the expression's type involves builtin-id or
1197/// builtin-Class, decide whether substituting in the redefinition
1198/// types would be profitable. The redefinition type is whatever
1199/// this translation unit tried to typedef to id/Class; we store
1200/// it to the side and then re-use it in places like this.
1201static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1202 const ObjCObjectPointerType *opty
1203 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1204 if (!opty) return false;
1205
1206 const ObjCObjectType *ty = opty->getObjectType();
1207
1208 QualType redef;
1209 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001210 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001211 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001212 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001213 } else {
1214 return false;
1215 }
1216
1217 // Do the substitution as long as the redefinition type isn't just a
1218 // possibly-qualified pointer to builtin-id or builtin-Class again.
1219 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001220 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001221 return false;
1222
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001223 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001224 return true;
1225}
1226
John McCall50a2c2c2011-10-11 23:14:30 +00001227static bool isRecordType(QualType T) {
1228 return T->isRecordType();
1229}
1230static bool isPointerToRecordType(QualType T) {
1231 if (const PointerType *PT = T->getAs<PointerType>())
1232 return PT->getPointeeType()->isRecordType();
1233 return false;
1234}
1235
Richard Smithcab9a7d2011-10-26 19:06:56 +00001236/// Perform conversions on the LHS of a member access expression.
1237ExprResult
1238Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001239 if (IsArrow && !Base->getType()->isFunctionType())
1240 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001241
Eli Friedman9a766c42012-01-13 02:20:01 +00001242 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001243}
1244
Douglas Gregor5476205b2011-06-23 00:49:38 +00001245/// Look up the given member of the given non-type-dependent
1246/// expression. This can return in one of two ways:
1247/// * If it returns a sentinel null-but-valid result, the caller will
1248/// assume that lookup was performed and the results written into
1249/// the provided structure. It will take over from there.
1250/// * Otherwise, the returned expression will be produced in place of
1251/// an ordinary member expression.
1252///
1253/// The ObjCImpDecl bit is a gross hack that will need to be properly
1254/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001255static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1256 ExprResult &BaseExpr, bool &IsArrow,
1257 SourceLocation OpLoc, CXXScopeSpec &SS,
1258 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001259 assert(BaseExpr.get() && "no base expression");
1260
1261 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001262 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001263 if (BaseExpr.isInvalid())
1264 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001265
Douglas Gregor5476205b2011-06-23 00:49:38 +00001266 QualType BaseType = BaseExpr.get()->getType();
1267 assert(!BaseType->isDependentType());
1268
1269 DeclarationName MemberName = R.getLookupName();
1270 SourceLocation MemberLoc = R.getNameLoc();
1271
1272 // For later type-checking purposes, turn arrow accesses into dot
1273 // accesses. The only access type we support that doesn't follow
1274 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1275 // and those never use arrows, so this is unaffected.
1276 if (IsArrow) {
1277 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1278 BaseType = Ptr->getPointeeType();
1279 else if (const ObjCObjectPointerType *Ptr
1280 = BaseType->getAs<ObjCObjectPointerType>())
1281 BaseType = Ptr->getPointeeType();
1282 else if (BaseType->isRecordType()) {
1283 // Recover from arrow accesses to records, e.g.:
1284 // struct MyRecord foo;
1285 // foo->bar
1286 // This is actually well-formed in C++ if MyRecord has an
1287 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001288 // by now--or a diagnostic message already issued if a problem
1289 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001290 if (!S.getLangOpts().CPlusPlus) {
1291 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001292 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1293 << FixItHint::CreateReplacement(OpLoc, ".");
1294 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001295 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001296 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001297 goto fail;
1298 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001299 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001300 << BaseType << BaseExpr.get()->getSourceRange();
1301 return ExprError();
1302 }
1303 }
1304
1305 // Handle field access to simple records.
1306 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001307 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001308 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001309 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001310 return ExprError();
1311
1312 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001313 // the lookup result was filled in. If typo correction was attempted and
1314 // failed, the lookup result will have been cleared--that combined with the
1315 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1316 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001317 }
1318
1319 // Handle ivar access to Objective-C objects.
1320 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001321 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001322 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001323 << 1 << SS.getScopeRep()
1324 << FixItHint::CreateRemoval(SS.getRange());
1325 SS.clear();
1326 }
Richard Smitha0edd302014-05-31 00:18:32 +00001327
Douglas Gregor5476205b2011-06-23 00:49:38 +00001328 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1329
1330 // There are three cases for the base type:
1331 // - builtin id (qualified or unqualified)
1332 // - builtin Class (qualified or unqualified)
1333 // - an interface
1334 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1335 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001336 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001337 (OTy->isObjCId() || OTy->isObjCClass()))
1338 goto fail;
1339 // There's an implicit 'isa' ivar on all objects.
1340 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001341 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001342 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001343 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1344 OpLoc, S.Context.getObjCClassType());
1345 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1346 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001347 ObjCImpDecl, HasTemplateArgs);
1348 goto fail;
1349 }
Richard Smitha0edd302014-05-31 00:18:32 +00001350
1351 if (S.RequireCompleteType(OpLoc, BaseType,
1352 diag::err_typecheck_incomplete_tag,
1353 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001354 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001355
1356 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001357 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1358
1359 if (!IV) {
1360 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001361 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1362 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001363 if (TypoCorrection Corrected = S.CorrectTypo(
1364 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001365 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001366 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001367 S.diagnoseTypo(
1368 Corrected,
1369 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1370 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001371
Ted Kremenek679b4782012-03-17 00:53:39 +00001372 // Figure out the class that declares the ivar.
1373 assert(!ClassDeclared);
1374 Decl *D = cast<Decl>(IV->getDeclContext());
1375 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1376 D = CAT->getClassInterface();
1377 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001378 } else {
Manman Ren5b786402016-01-28 18:49:28 +00001379 if (IsArrow &&
1380 IDecl->FindPropertyDeclaration(
1381 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001382 S.Diag(MemberLoc, diag::err_property_found_suggest)
1383 << Member << BaseExpr.get()->getType()
1384 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001385 return ExprError();
1386 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001387
Richard Smitha0edd302014-05-31 00:18:32 +00001388 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1389 << IDecl->getDeclName() << MemberName
1390 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001391 return ExprError();
1392 }
1393 }
Richard Smitha0edd302014-05-31 00:18:32 +00001394
Ted Kremenek679b4782012-03-17 00:53:39 +00001395 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001396
1397 // If the decl being referenced had an error, return an error for this
1398 // sub-expr without emitting another error, in order to avoid cascading
1399 // error cases.
1400 if (IV->isInvalidDecl())
1401 return ExprError();
1402
1403 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001404 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001405 return ExprError();
1406 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1407 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001408 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001409 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001410 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001411 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001412 // Case of a c-function declared inside an objc implementation.
1413 // FIXME: For a c-style function nested inside an objc implementation
1414 // class, there is no implementation context available, so we pass
1415 // down the context as argument to this routine. Ideally, this context
1416 // need be passed down in the AST node and somehow calculated from the
1417 // AST for a function decl.
1418 if (ObjCImplementationDecl *IMPD =
1419 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1420 ClassOfMethodDecl = IMPD->getClassInterface();
1421 else if (ObjCCategoryImplDecl* CatImplClass =
1422 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1423 ClassOfMethodDecl = CatImplClass->getClassInterface();
1424 }
Richard Smitha0edd302014-05-31 00:18:32 +00001425 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001426 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1427 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1428 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001429 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001430 << IV->getDeclName();
1431 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1432 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001433 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1434 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001435 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001436 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001437 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001438 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001439 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1440 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1441 if (UO->getOpcode() == UO_Deref)
1442 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1443
1444 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001445 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001446 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001447 warn = false;
1448 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001449 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001450 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001451 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001452 ObjCMethodFamily MF = MD->getMethodFamily();
1453 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001454 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001455 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001456 }
1457 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001458 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001459 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001460
Richard Smitha0edd302014-05-31 00:18:32 +00001461 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001462 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1463 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001464
Richard Smitha0edd302014-05-31 00:18:32 +00001465 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001466 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001467 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001468 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001469 }
1470 }
1471
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001472 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001473 }
1474
1475 // Objective-C property access.
1476 const ObjCObjectPointerType *OPT;
1477 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001478 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001479 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1480 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001481 SS.clear();
1482 }
1483
Douglas Gregor5476205b2011-06-23 00:49:38 +00001484 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001485 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001486 if (BaseExpr.isInvalid())
1487 return ExprError();
1488
Richard Smitha0edd302014-05-31 00:18:32 +00001489 assert(S.Context.hasSameUnqualifiedType(BaseType,
1490 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001491
1492 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1493
1494 const ObjCObjectType *OT = OPT->getObjectType();
1495
1496 // id, with and without qualifiers.
1497 if (OT->isObjCId()) {
1498 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001499 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1500 if (Decl *PMDecl =
1501 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001502 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1503 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001504 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001505 return ExprError();
1506
Richard Smitha0edd302014-05-31 00:18:32 +00001507 return new (S.Context)
1508 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001509 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001510 }
1511
1512 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1513 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001514 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001515 return ExprError();
1516 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001517 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1518 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001519 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001520 ObjCMethodDecl *SMD = nullptr;
1521 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001522 /*Property id*/ nullptr,
1523 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001524 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001525
1526 return new (S.Context)
1527 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001528 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001529 }
1530 }
1531 // Use of id.member can only be for a property reference. Do not
1532 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001533 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1534 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001535 ObjCImpDecl, HasTemplateArgs);
1536
Richard Smitha0edd302014-05-31 00:18:32 +00001537 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001538 << MemberName << BaseType);
1539 }
1540
1541 // 'Class', unqualified only.
1542 if (OT->isObjCClass()) {
1543 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001544 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001545 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001546 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1547 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001548 ObjCImpDecl, HasTemplateArgs);
1549
1550 goto fail;
1551 }
1552
1553 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001554 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001555 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1556 ObjCMethodDecl *Getter;
1557 if ((Getter = IFace->lookupClassMethod(Sel))) {
1558 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001559 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001560 return ExprError();
1561 } else
1562 Getter = IFace->lookupPrivateMethod(Sel, false);
1563 // If we found a getter then this may be a valid dot-reference, we
1564 // will look for the matching setter, in case it is needed.
1565 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001566 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1567 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001568 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001569 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1570 if (!Setter) {
1571 // If this reference is in an @implementation, also check for 'private'
1572 // methods.
1573 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1574 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001575
Richard Smitha0edd302014-05-31 00:18:32 +00001576 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001577 return ExprError();
1578
1579 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001580 return new (S.Context) ObjCPropertyRefExpr(
1581 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1582 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001583 }
1584
Richard Smitha0edd302014-05-31 00:18:32 +00001585 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1586 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001587 ObjCImpDecl, HasTemplateArgs);
1588
Richard Smitha0edd302014-05-31 00:18:32 +00001589 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001590 << MemberName << BaseType);
1591 }
1592
1593 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001594 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1595 MemberLoc, SourceLocation(), QualType(),
1596 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001597 }
1598
1599 // Handle 'field access' to vectors, such as 'V.xx'.
1600 if (BaseType->isExtVectorType()) {
1601 // FIXME: this expr should store IsArrow.
1602 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001603 ExprValueKind VK;
1604 if (IsArrow)
1605 VK = VK_LValue;
1606 else {
1607 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1608 VK = POE->getSyntacticForm()->getValueKind();
1609 else
1610 VK = BaseExpr.get()->getValueKind();
1611 }
Richard Smitha0edd302014-05-31 00:18:32 +00001612 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001613 Member, MemberLoc);
1614 if (ret.isNull())
1615 return ExprError();
1616
Richard Smitha0edd302014-05-31 00:18:32 +00001617 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001618 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001619 }
1620
1621 // Adjust builtin-sel to the appropriate redefinition type if that's
1622 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001623 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1624 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1625 BaseExpr = S.ImpCastExprToType(
1626 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1627 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001628 ObjCImpDecl, HasTemplateArgs);
1629 }
1630
1631 // Failure cases.
1632 fail:
1633
1634 // Recover from dot accesses to pointers, e.g.:
1635 // type *foo;
1636 // foo.bar
1637 // This is actually well-formed in two cases:
1638 // - 'type' is an Objective C type
1639 // - 'bar' is a pseudo-destructor name which happens to refer to
1640 // the appropriate pointer type
1641 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1642 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1643 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001644 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1645 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001646 << FixItHint::CreateReplacement(OpLoc, "->");
1647
1648 // Recurse as an -> access.
1649 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001650 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001651 ObjCImpDecl, HasTemplateArgs);
1652 }
1653 }
1654
1655 // If the user is trying to apply -> or . to a function name, it's probably
1656 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001657 if (S.tryToRecoverWithCall(
1658 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1659 /*complain*/ false,
1660 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001661 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001662 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001663 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1664 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001665 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001666 }
1667
Richard Smitha0edd302014-05-31 00:18:32 +00001668 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001669 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001670
1671 return ExprError();
1672}
1673
1674/// The main callback when the parser finds something like
1675/// expression . [nested-name-specifier] identifier
1676/// expression -> [nested-name-specifier] identifier
1677/// where 'identifier' encompasses a fairly broad spectrum of
1678/// possibilities, including destructor and operator references.
1679///
1680/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001681/// \param ObjCImpDecl the current Objective-C \@implementation
1682/// decl; this is an ugly hack around the fact that Objective-C
1683/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001684ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1685 SourceLocation OpLoc,
1686 tok::TokenKind OpKind,
1687 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001688 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001689 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001690 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001691 if (SS.isSet() && SS.isInvalid())
1692 return ExprError();
1693
1694 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001695 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001696 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1697 Diag(Id.getSourceRange().getBegin(),
1698 diag::ext_ms_explicit_constructor_call);
1699
1700 TemplateArgumentListInfo TemplateArgsBuffer;
1701
1702 // Decompose the name into its component parts.
1703 DeclarationNameInfo NameInfo;
1704 const TemplateArgumentListInfo *TemplateArgs;
1705 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1706 NameInfo, TemplateArgs);
1707
1708 DeclarationName Name = NameInfo.getName();
1709 bool IsArrow = (OpKind == tok::arrow);
1710
1711 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001712 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001713
1714 // This is a postfix expression, so get rid of ParenListExprs.
1715 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1716 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001717 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001718
1719 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1720 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001721 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1722 TemplateKWLoc, FirstQualifierInScope,
1723 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001724 }
1725
David Majnemerced8bdf2015-02-25 17:36:15 +00001726 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001727 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1728 TemplateKWLoc, FirstQualifierInScope,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001729 NameInfo, TemplateArgs, S, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001730}
1731
1732static ExprResult
1733BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001734 SourceLocation OpLoc, const CXXScopeSpec &SS,
1735 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001736 const DeclarationNameInfo &MemberNameInfo) {
1737 // x.a is an l-value if 'a' has a reference type. Otherwise:
1738 // x.a is an l-value/x-value/pr-value if the base is (and note
1739 // that *x is always an l-value), except that if the base isn't
1740 // an ordinary object then we must have an rvalue.
1741 ExprValueKind VK = VK_LValue;
1742 ExprObjectKind OK = OK_Ordinary;
1743 if (!IsArrow) {
1744 if (BaseExpr->getObjectKind() == OK_Ordinary)
1745 VK = BaseExpr->getValueKind();
1746 else
1747 VK = VK_RValue;
1748 }
1749 if (VK != VK_RValue && Field->isBitField())
1750 OK = OK_BitField;
1751
1752 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1753 QualType MemberType = Field->getType();
1754 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1755 MemberType = Ref->getPointeeType();
1756 VK = VK_LValue;
1757 } else {
1758 QualType BaseType = BaseExpr->getType();
1759 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001760
Douglas Gregor5476205b2011-06-23 00:49:38 +00001761 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001762
Douglas Gregor5476205b2011-06-23 00:49:38 +00001763 // GC attributes are never picked up by members.
1764 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001765
Douglas Gregor5476205b2011-06-23 00:49:38 +00001766 // CVR attributes from the base are picked up by members,
1767 // except that 'mutable' members don't pick up 'const'.
1768 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001769
Douglas Gregor5476205b2011-06-23 00:49:38 +00001770 Qualifiers MemberQuals
1771 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001772
Douglas Gregor5476205b2011-06-23 00:49:38 +00001773 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001774
1775
Douglas Gregor5476205b2011-06-23 00:49:38 +00001776 Qualifiers Combined = BaseQuals + MemberQuals;
1777 if (Combined != MemberQuals)
1778 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1779 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001780
Daniel Jasper0baec5492012-06-06 08:32:04 +00001781 S.UnusedPrivateFields.remove(Field);
1782
Douglas Gregor5476205b2011-06-23 00:49:38 +00001783 ExprResult Base =
1784 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1785 FoundDecl, Field);
1786 if (Base.isInvalid())
1787 return ExprError();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001788 MemberExpr *ME =
1789 BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
1790 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1791 MemberNameInfo, MemberType, VK, OK);
1792
1793 // Build a reference to a private copy for non-static data members in
1794 // non-static member functions, privatized by OpenMP constructs.
1795 if (S.getLangOpts().OpenMP && IsArrow &&
Alexey Bataev8b427062016-05-25 12:36:08 +00001796 !S.CurContext->isDependentContext() &&
Alexey Bataev90c228f2016-02-08 09:29:13 +00001797 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
1798 if (auto *PrivateCopy = S.IsOpenMPCapturedDecl(Field))
Alexey Bataev61205072016-03-02 04:57:40 +00001799 return S.getOpenMPCapturedExpr(PrivateCopy, VK, OK, OpLoc);
Alexey Bataev90c228f2016-02-08 09:29:13 +00001800 }
1801 return ME;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001802}
1803
1804/// Builds an implicit member access expression. The current context
1805/// is known to be an instance method, and the given unqualified lookup
1806/// set is known to contain only instance members, at least one of which
1807/// is from an appropriate type.
1808ExprResult
1809Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001810 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001811 LookupResult &R,
1812 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001813 bool IsKnownInstance, const Scope *S) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001814 assert(!R.empty() && !R.isAmbiguous());
1815
1816 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001817
Douglas Gregor5476205b2011-06-23 00:49:38 +00001818 // If this is known to be an instance access, go ahead and build an
1819 // implicit 'this' expression now.
1820 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001821 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001822 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001823
1824 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001825 if (IsKnownInstance) {
1826 SourceLocation Loc = R.getNameLoc();
1827 if (SS.getRange().isValid())
1828 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001829 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001830 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1831 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001832
Douglas Gregor5476205b2011-06-23 00:49:38 +00001833 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1834 /*OpLoc*/ SourceLocation(),
1835 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001836 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001837 /*FirstQualifierInScope*/ nullptr,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001838 R, TemplateArgs, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001839}