1//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis member access expressions.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/AST/DeclCXX.h"
13#include "clang/AST/DeclObjC.h"
14#include "clang/AST/DeclTemplate.h"
15#include "clang/AST/Expr.h"
16#include "clang/AST/ExprCXX.h"
17#include "clang/AST/ExprObjC.h"
18#include "clang/AST/TypeBase.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Overload.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
24#include "clang/Sema/SemaHLSL.h"
25#include "clang/Sema/SemaObjC.h"
26#include "clang/Sema/SemaOpenMP.h"
27
28using namespace clang;
29using namespace sema;
30
31typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
32
33/// Determines if the given class is provably not derived from all of
34/// the prospective base classes.
35static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
36 const BaseSet &Bases) {
37 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
38 return !Bases.count(Ptr: Base->getCanonicalDecl());
39 };
40 return BaseIsNotInSet(Record) && Record->forallBases(BaseMatches: BaseIsNotInSet);
41}
42
43enum IMAKind {
44 /// The reference is definitely not an instance member access.
45 IMA_Static,
46
47 /// The reference may be an implicit instance member access.
48 IMA_Mixed,
49
50 /// The reference may be to an instance member, but it might be invalid if
51 /// so, because the context is not an instance method.
52 IMA_Mixed_StaticOrExplicitContext,
53
54 /// The reference may be to an instance member, but it is invalid if
55 /// so, because the context is from an unrelated class.
56 IMA_Mixed_Unrelated,
57
58 /// The reference is definitely an implicit instance member access.
59 IMA_Instance,
60
61 /// The reference may be to an unresolved using declaration.
62 IMA_Unresolved,
63
64 /// The reference is a contextually-permitted abstract member reference.
65 IMA_Abstract,
66
67 /// Whether the context is static is dependent on the enclosing template (i.e.
68 /// in a dependent class scope explicit specialization).
69 IMA_Dependent,
70
71 /// The reference may be to an unresolved using declaration and the
72 /// context is not an instance method.
73 IMA_Unresolved_StaticOrExplicitContext,
74
75 // The reference refers to a field which is not a member of the containing
76 // class, which is allowed because we're in C++11 mode and the context is
77 // unevaluated.
78 IMA_Field_Uneval_Context,
79
80 /// All possible referrents are instance members and the current
81 /// context is not an instance method.
82 IMA_Error_StaticOrExplicitContext,
83
84 /// All possible referrents are instance members of an unrelated
85 /// class.
86 IMA_Error_Unrelated
87};
88
89/// The given lookup names class member(s) and is not being used for
90/// an address-of-member expression. Classify the type of access
91/// according to whether it's possible that this reference names an
92/// instance member. This is best-effort in dependent contexts; it is okay to
93/// conservatively answer "yes", in which case some errors will simply
94/// not be caught until template-instantiation.
95static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
96 const LookupResult &R) {
97 assert(!R.empty() && (*R.begin())->isCXXClassMember());
98
99 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
100
101 bool couldInstantiateToStatic = false;
102 bool isStaticOrExplicitContext = SemaRef.CXXThisTypeOverride.isNull();
103
104 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: DC)) {
105 if (MD->isImplicitObjectMemberFunction()) {
106 isStaticOrExplicitContext = false;
107 // A dependent class scope function template explicit specialization
108 // that is neither declared 'static' nor with an explicit object
109 // parameter could instantiate to a static or non-static member function.
110 couldInstantiateToStatic = MD->getDependentSpecializationInfo();
111 }
112 }
113
114 if (R.isUnresolvableResult()) {
115 if (couldInstantiateToStatic)
116 return IMA_Dependent;
117 return isStaticOrExplicitContext ? IMA_Unresolved_StaticOrExplicitContext
118 : IMA_Unresolved;
119 }
120
121 // Collect all the declaring classes of instance members we find.
122 bool hasNonInstance = false;
123 bool isField = false;
124 BaseSet Classes;
125 for (NamedDecl *D : R) {
126 // Look through any using decls.
127 D = D->getUnderlyingDecl();
128
129 if (D->isCXXInstanceMember()) {
130 isField |= isa<FieldDecl>(Val: D) || isa<MSPropertyDecl>(Val: D) ||
131 isa<IndirectFieldDecl>(Val: D);
132
133 CXXRecordDecl *R = cast<CXXRecordDecl>(Val: D->getDeclContext());
134 Classes.insert(Ptr: R->getCanonicalDecl());
135 } else
136 hasNonInstance = true;
137 }
138
139 // If we didn't find any instance members, it can't be an implicit
140 // member reference.
141 if (Classes.empty())
142 return IMA_Static;
143
144 if (couldInstantiateToStatic)
145 return IMA_Dependent;
146
147 // C++11 [expr.prim.general]p12:
148 // An id-expression that denotes a non-static data member or non-static
149 // member function of a class can only be used:
150 // (...)
151 // - if that id-expression denotes a non-static data member and it
152 // appears in an unevaluated operand.
153 //
154 // This rule is specific to C++11. However, we also permit this form
155 // in unevaluated inline assembly operands, like the operand to a SIZE.
156 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
157 assert(!AbstractInstanceResult);
158 switch (SemaRef.ExprEvalContexts.back().Context) {
159 case Sema::ExpressionEvaluationContext::Unevaluated:
160 case Sema::ExpressionEvaluationContext::UnevaluatedList:
161 if (isField && SemaRef.getLangOpts().CPlusPlus11)
162 AbstractInstanceResult = IMA_Field_Uneval_Context;
163 break;
164
165 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
166 AbstractInstanceResult = IMA_Abstract;
167 break;
168
169 case Sema::ExpressionEvaluationContext::DiscardedStatement:
170 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
171 case Sema::ExpressionEvaluationContext::ImmediateFunctionContext:
172 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
173 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
174 break;
175 }
176
177 // If the current context is not an instance method, it can't be
178 // an implicit member reference.
179 if (isStaticOrExplicitContext) {
180 if (hasNonInstance)
181 return IMA_Mixed_StaticOrExplicitContext;
182
183 return AbstractInstanceResult ? AbstractInstanceResult
184 : IMA_Error_StaticOrExplicitContext;
185 }
186
187 CXXRecordDecl *contextClass;
188 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: DC))
189 contextClass = MD->getParent()->getCanonicalDecl();
190 else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: DC))
191 contextClass = RD;
192 else
193 return AbstractInstanceResult ? AbstractInstanceResult
194 : IMA_Error_StaticOrExplicitContext;
195
196 // [class.mfct.non-static]p3:
197 // ...is used in the body of a non-static member function of class X,
198 // if name lookup (3.4.1) resolves the name in the id-expression to a
199 // non-static non-type member of some class C [...]
200 // ...if C is not X or a base class of X, the class member access expression
201 // is ill-formed.
202 if (R.getNamingClass() &&
203 contextClass->getCanonicalDecl() !=
204 R.getNamingClass()->getCanonicalDecl()) {
205 // If the naming class is not the current context, this was a qualified
206 // member name lookup, and it's sufficient to check that we have the naming
207 // class as a base class.
208 Classes.clear();
209 Classes.insert(Ptr: R.getNamingClass()->getCanonicalDecl());
210 }
211
212 // If we can prove that the current context is unrelated to all the
213 // declaring classes, it can't be an implicit member reference (in
214 // which case it's an error if any of those members are selected).
215 if (isProvablyNotDerivedFrom(SemaRef, Record: contextClass, Bases: Classes))
216 return hasNonInstance ? IMA_Mixed_Unrelated :
217 AbstractInstanceResult ? AbstractInstanceResult :
218 IMA_Error_Unrelated;
219
220 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
221}
222
223/// Diagnose a reference to a field with no object available.
224static void diagnoseInstanceReference(Sema &SemaRef,
225 const CXXScopeSpec &SS,
226 NamedDecl *Rep,
227 const DeclarationNameInfo &nameInfo) {
228 SourceLocation Loc = nameInfo.getLoc();
229 SourceRange Range(Loc);
230 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
231
232 // Look through using shadow decls and aliases.
233 Rep = Rep->getUnderlyingDecl();
234
235 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
236 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: FunctionLevelDC);
237 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
238 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Val: Rep->getDeclContext());
239
240 bool InStaticMethod = Method && Method->isStatic();
241 bool InExplicitObjectMethod =
242 Method && Method->isExplicitObjectMemberFunction();
243 bool IsField = isa<FieldDecl>(Val: Rep) || isa<IndirectFieldDecl>(Val: Rep);
244
245 std::string Replacement;
246 if (InExplicitObjectMethod) {
247 DeclarationName N = Method->getParamDecl(i: 0)->getDeclName();
248 if (!N.isEmpty()) {
249 Replacement.append(str: N.getAsString());
250 Replacement.append(s: ".");
251 }
252 }
253 if (IsField && InStaticMethod)
254 // "invalid use of member 'x' in static member function"
255 SemaRef.Diag(Loc, DiagID: diag::err_invalid_member_use_in_method)
256 << Range << nameInfo.getName() << /*static*/ 0;
257 else if (IsField && InExplicitObjectMethod) {
258 auto Diag = SemaRef.Diag(Loc, DiagID: diag::err_invalid_member_use_in_method)
259 << Range << nameInfo.getName() << /*explicit*/ 1;
260 if (!Replacement.empty())
261 Diag << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: Replacement);
262 } else if (ContextClass && RepClass && SS.isEmpty() &&
263 !InExplicitObjectMethod && !InStaticMethod &&
264 !RepClass->Equals(DC: ContextClass) &&
265 RepClass->Encloses(DC: ContextClass))
266 // Unqualified lookup in a non-static member function found a member of an
267 // enclosing class.
268 SemaRef.Diag(Loc, DiagID: diag::err_nested_non_static_member_use)
269 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
270 else if (IsField)
271 SemaRef.Diag(Loc, DiagID: diag::err_invalid_non_static_member_use)
272 << nameInfo.getName() << Range;
273 else if (!InExplicitObjectMethod)
274 SemaRef.Diag(Loc, DiagID: diag::err_member_call_without_object)
275 << Range << /*static*/ 0;
276 else {
277 if (const auto *Tpl = dyn_cast<FunctionTemplateDecl>(Val: Rep))
278 Rep = Tpl->getTemplatedDecl();
279 const auto *Callee = cast<CXXMethodDecl>(Val: Rep);
280 auto Diag = SemaRef.Diag(Loc, DiagID: diag::err_member_call_without_object)
281 << Range << Callee->isExplicitObjectMemberFunction();
282 if (!Replacement.empty())
283 Diag << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: Replacement);
284 }
285}
286
287bool Sema::isPotentialImplicitMemberAccess(const CXXScopeSpec &SS,
288 LookupResult &R,
289 bool IsAddressOfOperand) {
290 if (!getLangOpts().CPlusPlus)
291 return false;
292 else if (R.empty() || !R.begin()->isCXXClassMember())
293 return false;
294 else if (!IsAddressOfOperand)
295 return true;
296 else if (!SS.isEmpty())
297 return false;
298 else if (R.isOverloadedResult())
299 return false;
300 else if (R.isUnresolvableResult())
301 return true;
302 else
303 return isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(Val: R.getFoundDecl());
304}
305
306ExprResult Sema::BuildPossibleImplicitMemberExpr(
307 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
308 const TemplateArgumentListInfo *TemplateArgs, const Scope *S) {
309 switch (IMAKind Classification = ClassifyImplicitMemberAccess(SemaRef&: *this, R)) {
310 case IMA_Instance:
311 case IMA_Mixed:
312 case IMA_Mixed_Unrelated:
313 case IMA_Unresolved:
314 return BuildImplicitMemberExpr(
315 SS, TemplateKWLoc, R, TemplateArgs,
316 /*IsKnownInstance=*/IsDefiniteInstance: Classification == IMA_Instance, S);
317 case IMA_Field_Uneval_Context:
318 Diag(Loc: R.getNameLoc(), DiagID: diag::warn_cxx98_compat_non_static_member_use)
319 << R.getLookupNameInfo().getName();
320 [[fallthrough]];
321 case IMA_Static:
322 case IMA_Abstract:
323 case IMA_Mixed_StaticOrExplicitContext:
324 case IMA_Unresolved_StaticOrExplicitContext:
325 if (TemplateArgs || TemplateKWLoc.isValid())
326 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*RequiresADL=*/false,
327 TemplateArgs);
328 return BuildDeclarationNameExpr(SS, R, /*NeedsADL=*/false,
329 /*AcceptInvalidDecl=*/false);
330 case IMA_Dependent:
331 R.suppressDiagnostics();
332 return UnresolvedLookupExpr::Create(
333 Context, NamingClass: R.getNamingClass(), QualifierLoc: SS.getWithLocInContext(Context),
334 TemplateKWLoc, NameInfo: R.getLookupNameInfo(), /*RequiresADL=*/false,
335 Args: TemplateArgs, Begin: R.begin(), End: R.end(), /*KnownDependent=*/true,
336 /*KnownInstantiationDependent=*/true);
337
338 case IMA_Error_StaticOrExplicitContext:
339 case IMA_Error_Unrelated:
340 diagnoseInstanceReference(SemaRef&: *this, SS, Rep: R.getRepresentativeDecl(),
341 nameInfo: R.getLookupNameInfo());
342 return ExprError();
343 }
344
345 llvm_unreachable("unexpected instance member access kind");
346}
347
348/// Determine whether input char is from rgba component set.
349static bool
350IsRGBA(char c) {
351 switch (c) {
352 case 'r':
353 case 'g':
354 case 'b':
355 case 'a':
356 return true;
357 default:
358 return false;
359 }
360}
361
362// OpenCL v1.1, s6.1.7
363// The component swizzle length must be in accordance with the acceptable
364// vector sizes.
365static bool IsValidOpenCLComponentSwizzleLength(unsigned len)
366{
367 return (len >= 1 && len <= 4) || len == 8 || len == 16;
368}
369
370/// Check an ext-vector component access expression.
371///
372/// VK should be set in advance to the value kind of the base
373/// expression.
374static QualType
375CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
376 SourceLocation OpLoc, const IdentifierInfo *CompName,
377 SourceLocation CompLoc) {
378 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
379 // see FIXME there.
380 //
381 // FIXME: This logic can be greatly simplified by splitting it along
382 // halving/not halving and reworking the component checking.
383 const ExtVectorType *vecType = baseType->castAs<ExtVectorType>();
384
385 // The vector accessor can't exceed the number of elements.
386 const char *compStr = CompName->getNameStart();
387
388 // This flag determines whether or not the component is one of the four
389 // special names that indicate a subset of exactly half the elements are
390 // to be selected.
391 bool HalvingSwizzle = false;
392
393 // This flag determines whether or not CompName has an 's' char prefix,
394 // indicating that it is a string of hex values to be used as vector indices.
395 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
396
397 bool PointAccessor = false;
398 bool HasRepeated = false;
399 bool HasIndex[16] = {};
400
401 int Idx;
402
403 // Check that we've found one of the special components, or that the component
404 // names must come from the same set.
405 if (!strcmp(s1: compStr, s2: "hi") || !strcmp(s1: compStr, s2: "lo") ||
406 !strcmp(s1: compStr, s2: "even") || !strcmp(s1: compStr, s2: "odd")) {
407 HalvingSwizzle = true;
408 } else if (!HexSwizzle &&
409 (Idx = vecType->getPointAccessorIdx(c: *compStr)) != -1) {
410 PointAccessor = true;
411 bool HasRGBA = IsRGBA(c: *compStr);
412 do {
413 // Ensure that xyzw and rgba components don't intermingle.
414 if (HasRGBA != IsRGBA(c: *compStr))
415 break;
416 if (HasIndex[Idx]) HasRepeated = true;
417 HasIndex[Idx] = true;
418 compStr++;
419 } while (*compStr && (Idx = vecType->getPointAccessorIdx(c: *compStr)) != -1);
420
421 // Emit a warning if an rgba selector is used earlier than OpenCL C 3.0.
422 if (HasRGBA || (*compStr && IsRGBA(c: *compStr))) {
423 if (S.getLangOpts().OpenCL &&
424 S.getLangOpts().getOpenCLCompatibleVersion() < 300) {
425 const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
426 S.Diag(Loc: OpLoc, DiagID: diag::ext_opencl_ext_vector_type_rgba_selector)
427 << StringRef(DiagBegin, 1) << SourceRange(CompLoc);
428 }
429 }
430 } else {
431 if (HexSwizzle) compStr++;
432 while ((Idx = vecType->getNumericAccessorIdx(c: *compStr)) != -1) {
433 if (HasIndex[Idx]) HasRepeated = true;
434 HasIndex[Idx] = true;
435 compStr++;
436 }
437 }
438
439 if (!HalvingSwizzle && *compStr) {
440 // We didn't get to the end of the string. This means the component names
441 // didn't come from the same set *or* we encountered an illegal name.
442 size_t Offset = compStr - CompName->getNameStart() + 1;
443 char Fmt[3] = {'\'', *compStr, '\''};
444 S.Diag(Loc: OpLoc.getLocWithOffset(Offset),
445 DiagID: diag::err_ext_vector_component_name_illegal)
446 << StringRef(Fmt, 3) << SourceRange(CompLoc);
447 return QualType();
448 }
449
450 if (S.getLangOpts().HLSL && !PointAccessor) {
451 S.Diag(Loc: OpLoc, DiagID: diag::err_ext_vector_component_name_illegal)
452 << CompName << SourceRange(CompLoc);
453 return QualType();
454 }
455
456 if (S.getLangOpts().HLSL && PointAccessor && vecType->getNumElements() > 4) {
457 S.Diag(Loc: OpLoc, DiagID: diag::err_hlsl_long_vector_swizzle)
458 << CompName << SourceRange(CompLoc);
459 return QualType();
460 }
461
462 // Ensure no component accessor exceeds the width of the vector type it
463 // operates on.
464 if (!HalvingSwizzle) {
465 compStr = CompName->getNameStart();
466
467 if (HexSwizzle)
468 compStr++;
469
470 while (*compStr) {
471 if (!vecType->isAccessorWithinNumElements(c: *compStr++, isNumericAccessor: HexSwizzle)) {
472 S.Diag(Loc: OpLoc, DiagID: diag::err_ext_vector_component_exceeds_length)
473 << baseType << SourceRange(CompLoc);
474 return QualType();
475 }
476 }
477 }
478
479 // OpenCL mode requires swizzle length to be in accordance with accepted
480 // sizes. Clang however supports arbitrary lengths for other languages.
481 if (S.getLangOpts().OpenCL && !HalvingSwizzle) {
482 unsigned SwizzleLength = CompName->getLength();
483
484 if (HexSwizzle)
485 SwizzleLength--;
486
487 if (IsValidOpenCLComponentSwizzleLength(len: SwizzleLength) == false) {
488 S.Diag(Loc: OpLoc, DiagID: diag::err_opencl_ext_vector_component_invalid_length)
489 << SwizzleLength << SourceRange(CompLoc);
490 return QualType();
491 }
492 }
493
494 // The component accessor looks fine - now we need to compute the actual type.
495 // The vector type is implied by the component accessor. For example,
496 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
497 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
498 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
499 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
500 : CompName->getLength();
501 if (HexSwizzle)
502 CompSize--;
503
504 if (CompSize == 1)
505 return vecType->getElementType();
506
507 if (HasRepeated)
508 VK = VK_PRValue;
509
510 QualType VT = S.Context.getExtVectorType(VectorType: vecType->getElementType(), NumElts: CompSize);
511 // Now look up the TypeDefDecl from the vector type. Without this,
512 // diagnostics look bad. We want extended vector types to appear built-in.
513 for (Sema::ExtVectorDeclsType::iterator
514 I = S.ExtVectorDecls.begin(source: S.getExternalSource()),
515 E = S.ExtVectorDecls.end();
516 I != E; ++I) {
517 if ((*I)->getUnderlyingType() == VT)
518 return S.Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
519 /*Qualifier=*/std::nullopt, Decl: *I);
520 }
521
522 return VT; // should never get here (a typedef type should always be found).
523}
524
525static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
526 IdentifierInfo *Member,
527 const Selector &Sel,
528 ASTContext &Context) {
529 if (Member)
530 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
531 PropertyId: Member, QueryKind: ObjCPropertyQueryKind::OBJC_PR_query_instance))
532 return PD;
533 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
534 return OMD;
535
536 for (const auto *I : PDecl->protocols()) {
537 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(PDecl: I, Member, Sel,
538 Context))
539 return D;
540 }
541 return nullptr;
542}
543
544static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
545 IdentifierInfo *Member,
546 const Selector &Sel,
547 ASTContext &Context) {
548 // Check protocols on qualified interfaces.
549 Decl *GDecl = nullptr;
550 for (const auto *I : QIdTy->quals()) {
551 if (Member)
552 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
553 PropertyId: Member, QueryKind: ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
554 GDecl = PD;
555 break;
556 }
557 // Also must look for a getter or setter name which uses property syntax.
558 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
559 GDecl = OMD;
560 break;
561 }
562 }
563 if (!GDecl) {
564 for (const auto *I : QIdTy->quals()) {
565 // Search in the protocol-qualifier list of current protocol.
566 GDecl = FindGetterSetterNameDeclFromProtocolList(PDecl: I, Member, Sel, Context);
567 if (GDecl)
568 return GDecl;
569 }
570 }
571 return GDecl;
572}
573
574ExprResult
575Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
576 bool IsArrow, SourceLocation OpLoc,
577 const CXXScopeSpec &SS,
578 SourceLocation TemplateKWLoc,
579 NamedDecl *FirstQualifierInScope,
580 const DeclarationNameInfo &NameInfo,
581 const TemplateArgumentListInfo *TemplateArgs) {
582 // Even in dependent contexts, try to diagnose base expressions with
583 // obviously wrong types, e.g.:
584 //
585 // T* t;
586 // t.f;
587 //
588 // In Obj-C++, however, the above expression is valid, since it could be
589 // accessing the 'f' property if T is an Obj-C interface. The extra check
590 // allows this, while still reporting an error if T is a struct pointer.
591 if (!IsArrow) {
592 const PointerType *PT = BaseType->getAs<PointerType>();
593 if (PT && (!getLangOpts().ObjC ||
594 PT->getPointeeType()->isRecordType())) {
595 assert(BaseExpr && "cannot happen with implicit member accesses");
596 Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_struct_union)
597 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
598 return ExprError();
599 }
600 }
601
602 assert(BaseType->isDependentType() || NameInfo.getName().isDependentName() ||
603 isDependentScopeSpecifier(SS) ||
604 (TemplateArgs && llvm::any_of(TemplateArgs->arguments(),
605 [](const TemplateArgumentLoc &Arg) {
606 return Arg.getArgument().isDependent();
607 })));
608
609 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
610 // must have pointer type, and the accessed type is the pointee.
611 return CXXDependentScopeMemberExpr::Create(
612 Ctx: Context, Base: BaseExpr, BaseType, IsArrow, OperatorLoc: OpLoc,
613 QualifierLoc: SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierFoundInScope: FirstQualifierInScope,
614 MemberNameInfo: NameInfo, TemplateArgs);
615}
616
617/// We know that the given qualified member reference points only to
618/// declarations which do not belong to the static type of the base
619/// expression. Diagnose the problem.
620static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
621 Expr *BaseExpr,
622 QualType BaseType,
623 const CXXScopeSpec &SS,
624 NamedDecl *rep,
625 const DeclarationNameInfo &nameInfo) {
626 // If this is an implicit member access, use a different set of
627 // diagnostics.
628 if (!BaseExpr)
629 return diagnoseInstanceReference(SemaRef, SS, Rep: rep, nameInfo);
630
631 SemaRef.Diag(Loc: nameInfo.getLoc(), DiagID: diag::err_qualified_member_of_unrelated)
632 << SS.getRange() << rep << BaseType;
633}
634
635bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
636 QualType BaseType,
637 const CXXScopeSpec &SS,
638 const LookupResult &R) {
639 CXXRecordDecl *BaseRecord =
640 cast_or_null<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
641 if (!BaseRecord) {
642 // We can't check this yet because the base type is still
643 // dependent.
644 assert(BaseType->isDependentType());
645 return false;
646 }
647
648 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
649 // If this is an implicit member reference and we find a
650 // non-instance member, it's not an error.
651 if (!BaseExpr && !(*I)->isCXXInstanceMember())
652 return false;
653
654 // Note that we use the DC of the decl, not the underlying decl.
655 DeclContext *DC = (*I)->getDeclContext()->getNonTransparentContext();
656 if (!DC->isRecord())
657 continue;
658
659 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(Val: DC)->getCanonicalDecl();
660 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
661 !BaseRecord->isProvablyNotDerivedFrom(Base: MemberRecord))
662 return false;
663 }
664
665 DiagnoseQualifiedMemberReference(SemaRef&: *this, BaseExpr, BaseType, SS,
666 rep: R.getRepresentativeDecl(),
667 nameInfo: R.getLookupNameInfo());
668 return true;
669}
670
671static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
672 Expr *BaseExpr, QualType RTy,
673 SourceLocation OpLoc, bool IsArrow,
674 CXXScopeSpec &SS, bool HasTemplateArgs,
675 SourceLocation TemplateKWLoc) {
676 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
677 if (!RTy->isDependentType() &&
678 !SemaRef.isThisOutsideMemberFunctionBody(BaseType: RTy) &&
679 SemaRef.RequireCompleteType(
680 Loc: OpLoc, T: RTy, DiagID: diag::err_typecheck_incomplete_tag, Args: BaseRange))
681 return true;
682
683 // LookupTemplateName/LookupParsedName don't expect these both to exist
684 // simultaneously.
685 QualType ObjectType = SS.isSet() ? QualType() : RTy;
686 if (HasTemplateArgs || TemplateKWLoc.isValid())
687 return SemaRef.LookupTemplateName(R,
688 /*S=*/nullptr, SS, ObjectType,
689 /*EnteringContext=*/false, RequiredTemplate: TemplateKWLoc);
690
691 SemaRef.LookupParsedName(R, /*S=*/nullptr, SS: &SS, ObjectType);
692 return false;
693}
694
695static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
696 ExprResult &BaseExpr, bool &IsArrow,
697 SourceLocation OpLoc, CXXScopeSpec &SS,
698 Decl *ObjCImpDecl, bool HasTemplateArgs,
699 SourceLocation TemplateKWLoc);
700
701ExprResult Sema::BuildMemberReferenceExpr(
702 Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow,
703 CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
704 NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo,
705 const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
706 ActOnMemberAccessExtraArgs *ExtraArgs) {
707 LookupResult R(*this, NameInfo, LookupMemberName);
708
709 // Implicit member accesses.
710 if (!Base) {
711 QualType RecordTy = BaseType;
712 if (IsArrow) RecordTy = RecordTy->castAs<PointerType>()->getPointeeType();
713 if (LookupMemberExprInRecord(SemaRef&: *this, R, BaseExpr: nullptr, RTy: RecordTy, OpLoc, IsArrow,
714 SS, HasTemplateArgs: TemplateArgs != nullptr, TemplateKWLoc))
715 return ExprError();
716
717 // Explicit member accesses.
718 } else {
719 ExprResult BaseResult = Base;
720 ExprResult Result =
721 LookupMemberExpr(S&: *this, R, BaseExpr&: BaseResult, IsArrow, OpLoc, SS,
722 ObjCImpDecl: ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
723 HasTemplateArgs: TemplateArgs != nullptr, TemplateKWLoc);
724
725 if (BaseResult.isInvalid())
726 return ExprError();
727 Base = BaseResult.get();
728
729 if (Result.isInvalid())
730 return ExprError();
731
732 if (Result.get())
733 return Result;
734
735 // LookupMemberExpr can modify Base, and thus change BaseType
736 BaseType = Base->getType();
737 }
738
739 // BuildMemberReferenceExpr expects the nested-name-specifier, if any, to be
740 // valid.
741 if (SS.isInvalid())
742 return ExprError();
743
744 return BuildMemberReferenceExpr(Base, BaseType,
745 OpLoc, IsArrow, SS, TemplateKWLoc,
746 FirstQualifierInScope, R, TemplateArgs, S,
747 SuppressQualifierCheck: false, ExtraArgs);
748}
749
750ExprResult
751Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
752 SourceLocation loc,
753 IndirectFieldDecl *indirectField,
754 DeclAccessPair foundDecl,
755 Expr *baseObjectExpr,
756 SourceLocation opLoc) {
757 // First, build the expression that refers to the base object.
758
759 // Case 1: the base of the indirect field is not a field.
760 VarDecl *baseVariable = indirectField->getVarDecl();
761 CXXScopeSpec EmptySS;
762 if (baseVariable) {
763 assert(baseVariable->getType()->isRecordType());
764
765 // In principle we could have a member access expression that
766 // accesses an anonymous struct/union that's a static member of
767 // the base object's class. However, under the current standard,
768 // static data members cannot be anonymous structs or unions.
769 // Supporting this is as easy as building a MemberExpr here.
770 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
771
772 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
773
774 ExprResult result
775 = BuildDeclarationNameExpr(SS: EmptySS, NameInfo: baseNameInfo, D: baseVariable);
776 if (result.isInvalid()) return ExprError();
777
778 baseObjectExpr = result.get();
779 }
780
781 assert((baseVariable || baseObjectExpr) &&
782 "referencing anonymous struct/union without a base variable or "
783 "expression");
784
785 // Build the implicit member references to the field of the
786 // anonymous struct/union.
787 Expr *result = baseObjectExpr;
788 IndirectFieldDecl::chain_iterator
789 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
790
791 // Case 2: the base of the indirect field is a field and the user
792 // wrote a member expression.
793 if (!baseVariable) {
794 FieldDecl *field = cast<FieldDecl>(Val: *FI);
795
796 bool baseObjectIsPointer = baseObjectExpr->getType()->isPointerType();
797
798 // Make a nameInfo that properly uses the anonymous name.
799 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
800
801 // Build the first member access in the chain with full information.
802 result =
803 BuildFieldReferenceExpr(BaseExpr: result, IsArrow: baseObjectIsPointer, OpLoc: SourceLocation(),
804 SS, Field: field, FoundDecl: foundDecl, MemberNameInfo: memberNameInfo)
805 .get();
806 if (!result)
807 return ExprError();
808 }
809
810 // In all cases, we should now skip the first declaration in the chain.
811 ++FI;
812
813 while (FI != FEnd) {
814 FieldDecl *field = cast<FieldDecl>(Val: *FI++);
815
816 // FIXME: these are somewhat meaningless
817 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
818 DeclAccessPair fakeFoundDecl =
819 DeclAccessPair::make(D: field, AS: field->getAccess());
820
821 result =
822 BuildFieldReferenceExpr(BaseExpr: result, /*isarrow*/ IsArrow: false, OpLoc: SourceLocation(),
823 SS: (FI == FEnd ? SS : EmptySS), Field: field,
824 FoundDecl: fakeFoundDecl, MemberNameInfo: memberNameInfo)
825 .get();
826 }
827
828 return result;
829}
830
831static ExprResult
832BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
833 const CXXScopeSpec &SS,
834 MSPropertyDecl *PD,
835 const DeclarationNameInfo &NameInfo) {
836 // Property names are always simple identifiers and therefore never
837 // require any interesting additional storage.
838 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
839 S.Context.PseudoObjectTy, VK_LValue,
840 SS.getWithLocInContext(Context&: S.Context),
841 NameInfo.getLoc());
842}
843
844MemberExpr *Sema::BuildMemberExpr(
845 Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS,
846 SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl,
847 bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo,
848 QualType Ty, ExprValueKind VK, ExprObjectKind OK,
849 const TemplateArgumentListInfo *TemplateArgs) {
850 assert((!IsArrow || Base->isPRValue()) &&
851 "-> base must be a pointer prvalue");
852 MemberExpr *E =
853 MemberExpr::Create(C: Context, Base, IsArrow, OperatorLoc: OpLoc, QualifierLoc: NNS, TemplateKWLoc,
854 MemberDecl: Member, FoundDecl, MemberNameInfo, TemplateArgs, T: Ty,
855 VK, OK, NOUR: getNonOdrUseReasonInCurrentContext(D: Member));
856 E->setHadMultipleCandidates(HadMultipleCandidates);
857 MarkMemberReferenced(E);
858
859 // C++ [except.spec]p17:
860 // An exception-specification is considered to be needed when:
861 // - in an expression the function is the unique lookup result or the
862 // selected member of a set of overloaded functions
863 if (auto *FPT = Ty->getAs<FunctionProtoType>()) {
864 if (isUnresolvedExceptionSpec(ESpecType: FPT->getExceptionSpecType())) {
865 if (auto *NewFPT = ResolveExceptionSpec(Loc: MemberNameInfo.getLoc(), FPT))
866 E->setType(Context.getQualifiedType(T: NewFPT, Qs: Ty.getQualifiers()));
867 }
868 }
869
870 return E;
871}
872
873/// Determine if the given scope is within a function-try-block handler.
874static bool IsInFnTryBlockHandler(const Scope *S) {
875 // Walk the scope stack until finding a FnTryCatchScope, or leave the
876 // function scope. If a FnTryCatchScope is found, check whether the TryScope
877 // flag is set. If it is not, it's a function-try-block handler.
878 for (; S != S->getFnParent(); S = S->getParent()) {
879 if (S->isFnTryCatchScope())
880 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
881 }
882 return false;
883}
884
885ExprResult
886Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
887 SourceLocation OpLoc, bool IsArrow,
888 const CXXScopeSpec &SS,
889 SourceLocation TemplateKWLoc,
890 NamedDecl *FirstQualifierInScope,
891 LookupResult &R,
892 const TemplateArgumentListInfo *TemplateArgs,
893 const Scope *S,
894 bool SuppressQualifierCheck,
895 ActOnMemberAccessExtraArgs *ExtraArgs) {
896 assert(!SS.isInvalid() && "nested-name-specifier cannot be invalid");
897 // If the member wasn't found in the current instantiation, or if the
898 // arrow operator was used with a dependent non-pointer object expression,
899 // build a CXXDependentScopeMemberExpr.
900 if (R.wasNotFoundInCurrentInstantiation() ||
901 (R.getLookupName().getCXXOverloadedOperator() == OO_Equal &&
902 (SS.isSet() ? SS.getScopeRep().isDependent()
903 : BaseExprType->isDependentType())))
904 return ActOnDependentMemberExpr(BaseExpr, BaseType: BaseExprType, IsArrow, OpLoc, SS,
905 TemplateKWLoc, FirstQualifierInScope,
906 NameInfo: R.getLookupNameInfo(), TemplateArgs);
907
908 QualType BaseType = BaseExprType;
909 if (IsArrow) {
910 assert(BaseType->isPointerType());
911 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
912 }
913 R.setBaseObjectType(BaseType);
914
915 assert((SS.isEmpty()
916 ? !BaseType->isDependentType() || computeDeclContext(BaseType)
917 : !isDependentScopeSpecifier(SS) || computeDeclContext(SS)) &&
918 "dependent lookup context that isn't the current instantiation?");
919
920 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
921 DeclarationName MemberName = MemberNameInfo.getName();
922 SourceLocation MemberLoc = MemberNameInfo.getLoc();
923
924 if (R.isAmbiguous())
925 return ExprError();
926
927 // [except.handle]p10: Referring to any non-static member or base class of an
928 // object in the handler for a function-try-block of a constructor or
929 // destructor for that object results in undefined behavior.
930 const auto *FD = getCurFunctionDecl();
931 if (S && BaseExpr && FD &&
932 (isa<CXXDestructorDecl>(Val: FD) || isa<CXXConstructorDecl>(Val: FD)) &&
933 isa<CXXThisExpr>(Val: BaseExpr->IgnoreImpCasts()) &&
934 IsInFnTryBlockHandler(S))
935 Diag(Loc: MemberLoc, DiagID: diag::warn_cdtor_function_try_handler_mem_expr)
936 << isa<CXXDestructorDecl>(Val: FD);
937
938 if (R.empty()) {
939 ExprResult RetryExpr = ExprError();
940 if (ExtraArgs && !IsArrow && BaseExpr && !BaseExpr->isTypeDependent()) {
941 SFINAETrap Trap(*this, true);
942 ParsedType ObjectType;
943 bool MayBePseudoDestructor = false;
944 RetryExpr = ActOnStartCXXMemberReference(S: getCurScope(), Base: BaseExpr, OpLoc,
945 OpKind: tok::arrow, ObjectType,
946 MayBePseudoDestructor);
947 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
948 CXXScopeSpec TempSS(SS);
949 RetryExpr = ActOnMemberAccessExpr(
950 S: ExtraArgs->S, Base: RetryExpr.get(), OpLoc, OpKind: tok::arrow, SS&: TempSS,
951 TemplateKWLoc, Member&: ExtraArgs->Id, ObjCImpDecl: ExtraArgs->ObjCImpDecl);
952 }
953 if (Trap.hasErrorOccurred())
954 RetryExpr = ExprError();
955 }
956
957 // Rederive where we looked up.
958 DeclContext *DC =
959 (SS.isSet() ? computeDeclContext(SS) : computeDeclContext(T: BaseType));
960 assert(DC);
961
962 if (RetryExpr.isUsable())
963 Diag(Loc: OpLoc, DiagID: diag::err_no_member_overloaded_arrow)
964 << MemberName << DC << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: "->");
965 else
966 Diag(Loc: R.getNameLoc(), DiagID: diag::err_no_member)
967 << MemberName << DC
968 << (SS.isSet()
969 ? SS.getRange()
970 : (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()));
971 return RetryExpr;
972 }
973
974 // Diagnose lookups that find only declarations from a non-base
975 // type. This is possible for either qualified lookups (which may
976 // have been qualified with an unrelated type) or implicit member
977 // expressions (which were found with unqualified lookup and thus
978 // may have come from an enclosing scope). Note that it's okay for
979 // lookup to find declarations from a non-base type as long as those
980 // aren't the ones picked by overload resolution.
981 if ((SS.isSet() || !BaseExpr ||
982 (isa<CXXThisExpr>(Val: BaseExpr) &&
983 cast<CXXThisExpr>(Val: BaseExpr)->isImplicit())) &&
984 !SuppressQualifierCheck &&
985 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
986 return ExprError();
987
988 // Construct an unresolved result if we in fact got an unresolved
989 // result.
990 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
991 // Suppress any lookup-related diagnostics; we'll do these when we
992 // pick a member.
993 R.suppressDiagnostics();
994
995 UnresolvedMemberExpr *MemExpr
996 = UnresolvedMemberExpr::Create(Context, HasUnresolvedUsing: R.isUnresolvableResult(),
997 Base: BaseExpr, BaseType: BaseExprType,
998 IsArrow, OperatorLoc: OpLoc,
999 QualifierLoc: SS.getWithLocInContext(Context),
1000 TemplateKWLoc, MemberNameInfo,
1001 TemplateArgs, Begin: R.begin(), End: R.end());
1002
1003 return MemExpr;
1004 }
1005
1006 assert(R.isSingleResult());
1007 DeclAccessPair FoundDecl = R.begin().getPair();
1008 NamedDecl *MemberDecl = R.getFoundDecl();
1009
1010 // FIXME: diagnose the presence of template arguments now.
1011
1012 // If the decl being referenced had an error, return an error for this
1013 // sub-expr without emitting another error, in order to avoid cascading
1014 // error cases.
1015 if (MemberDecl->isInvalidDecl())
1016 return ExprError();
1017
1018 // Handle the implicit-member-access case.
1019 if (!BaseExpr) {
1020 // If this is not an instance member, convert to a non-member access.
1021 if (!MemberDecl->isCXXInstanceMember()) {
1022 // We might have a variable template specialization (or maybe one day a
1023 // member concept-id).
1024 if (TemplateArgs || TemplateKWLoc.isValid())
1025 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*ADL*/RequiresADL: false, TemplateArgs);
1026
1027 return BuildDeclarationNameExpr(SS, NameInfo: R.getLookupNameInfo(), D: MemberDecl,
1028 FoundD: FoundDecl, TemplateArgs);
1029 }
1030 SourceLocation Loc = R.getNameLoc();
1031 if (SS.getRange().isValid())
1032 Loc = SS.getRange().getBegin();
1033 BaseExpr = BuildCXXThisExpr(Loc, Type: BaseExprType, /*IsImplicit=*/true);
1034 }
1035
1036 // C++17 [expr.ref]p2, per CWG2813:
1037 // For the first option (dot), if the id-expression names a static member or
1038 // an enumerator, the first expression is a discarded-value expression; if
1039 // the id-expression names a non-static data member, the first expression
1040 // shall be a glvalue.
1041 auto ConvertBaseExprToDiscardedValue = [&] {
1042 assert(getLangOpts().CPlusPlus &&
1043 "Static member / member enumerator outside of C++");
1044 if (IsArrow)
1045 return false;
1046 ExprResult Converted = IgnoredValueConversions(E: BaseExpr);
1047 if (Converted.isInvalid())
1048 return true;
1049 BaseExpr = Converted.get();
1050 return false;
1051 };
1052 auto ConvertBaseExprToGLValue = [&] {
1053 if (IsArrow || !BaseExpr->isPRValue())
1054 return false;
1055 ExprResult Converted = TemporaryMaterializationConversion(E: BaseExpr);
1056 if (Converted.isInvalid())
1057 return true;
1058 BaseExpr = Converted.get();
1059 return false;
1060 };
1061
1062 // Check the use of this member.
1063 if (DiagnoseUseOfDecl(D: MemberDecl, Locs: MemberLoc))
1064 return ExprError();
1065
1066 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: MemberDecl)) {
1067 if (ConvertBaseExprToGLValue())
1068 return ExprError();
1069 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, Field: FD, FoundDecl,
1070 MemberNameInfo);
1071 }
1072
1073 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(Val: MemberDecl)) {
1074 // No temporaries are materialized for property references yet.
1075 // They might be materialized when this is transformed into a member call.
1076 // Note that this is slightly different behaviour from MSVC which doesn't
1077 // implement CWG2813 yet: MSVC might materialize an extra temporary if the
1078 // getter or setter function is an explicit object member function.
1079 return BuildMSPropertyRefExpr(S&: *this, BaseExpr, IsArrow, SS, PD,
1080 NameInfo: MemberNameInfo);
1081 }
1082
1083 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(Val: MemberDecl)) {
1084 if (ConvertBaseExprToGLValue())
1085 return ExprError();
1086 // We may have found a field within an anonymous union or struct
1087 // (C++ [class.union]).
1088 return BuildAnonymousStructUnionMemberReference(SS, loc: MemberLoc, indirectField: FD,
1089 foundDecl: FoundDecl, baseObjectExpr: BaseExpr,
1090 opLoc: OpLoc);
1091 }
1092
1093 // Static data member
1094 if (VarDecl *Var = dyn_cast<VarDecl>(Val: MemberDecl)) {
1095 if (ConvertBaseExprToDiscardedValue())
1096 return ExprError();
1097 return BuildMemberExpr(Base: BaseExpr, IsArrow, OpLoc,
1098 NNS: SS.getWithLocInContext(Context), TemplateKWLoc, Member: Var,
1099 FoundDecl, /*HadMultipleCandidates=*/false,
1100 MemberNameInfo, Ty: Var->getType().getNonReferenceType(),
1101 VK: VK_LValue, OK: OK_Ordinary);
1102 }
1103
1104 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(Val: MemberDecl)) {
1105 ExprValueKind valueKind;
1106 QualType type;
1107 if (MemberFn->isInstance()) {
1108 valueKind = VK_PRValue;
1109 type = Context.BoundMemberTy;
1110 if (MemberFn->isImplicitObjectMemberFunction() &&
1111 ConvertBaseExprToGLValue())
1112 return ExprError();
1113 } else {
1114 // Static member function
1115 if (ConvertBaseExprToDiscardedValue())
1116 return ExprError();
1117 valueKind = VK_LValue;
1118 type = MemberFn->getType();
1119 }
1120
1121 return BuildMemberExpr(Base: BaseExpr, IsArrow, OpLoc,
1122 NNS: SS.getWithLocInContext(Context), TemplateKWLoc,
1123 Member: MemberFn, FoundDecl, /*HadMultipleCandidates=*/false,
1124 MemberNameInfo, Ty: type, VK: valueKind, OK: OK_Ordinary);
1125 }
1126 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1127
1128 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(Val: MemberDecl)) {
1129 if (ConvertBaseExprToDiscardedValue())
1130 return ExprError();
1131 return BuildMemberExpr(
1132 Base: BaseExpr, IsArrow, OpLoc, NNS: SS.getWithLocInContext(Context),
1133 TemplateKWLoc, Member: Enum, FoundDecl, /*HadMultipleCandidates=*/false,
1134 MemberNameInfo, Ty: Enum->getType(), VK: VK_PRValue, OK: OK_Ordinary);
1135 }
1136
1137 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(Val: MemberDecl)) {
1138 if (ConvertBaseExprToDiscardedValue())
1139 return ExprError();
1140 if (!TemplateArgs) {
1141 diagnoseMissingTemplateArguments(
1142 SS, /*TemplateKeyword=*/TemplateKWLoc.isValid(), TD: VarTempl, Loc: MemberLoc);
1143 return ExprError();
1144 }
1145
1146 DeclResult VDecl =
1147 CheckVarTemplateId(Template: VarTempl, TemplateLoc: TemplateKWLoc, TemplateNameLoc: MemberNameInfo.getLoc(),
1148 TemplateArgs: *TemplateArgs, /*SetWrittenArgs=*/false);
1149 if (VDecl.isInvalid())
1150 return ExprError();
1151
1152 // Non-dependent member, but dependent template arguments.
1153 if (!VDecl.get())
1154 return ActOnDependentMemberExpr(
1155 BaseExpr, BaseType: BaseExpr->getType(), IsArrow, OpLoc, SS, TemplateKWLoc,
1156 FirstQualifierInScope, NameInfo: MemberNameInfo, TemplateArgs);
1157
1158 VarDecl *Var = cast<VarDecl>(Val: VDecl.get());
1159 if (!Var->getTemplateSpecializationKind())
1160 Var->setTemplateSpecializationKind(TSK: TSK_ImplicitInstantiation, PointOfInstantiation: MemberLoc);
1161
1162 return BuildMemberExpr(Base: BaseExpr, IsArrow, OpLoc,
1163 NNS: SS.getWithLocInContext(Context), TemplateKWLoc, Member: Var,
1164 FoundDecl, /*HadMultipleCandidates=*/false,
1165 MemberNameInfo, Ty: Var->getType().getNonReferenceType(),
1166 VK: VK_LValue, OK: OK_Ordinary, TemplateArgs);
1167 }
1168
1169 // We found something that we didn't expect. Complain.
1170 if (isa<TypeDecl>(Val: MemberDecl))
1171 Diag(Loc: MemberLoc, DiagID: diag::err_typecheck_member_reference_type)
1172 << MemberName << BaseType << int(IsArrow);
1173 else
1174 Diag(Loc: MemberLoc, DiagID: diag::err_typecheck_member_reference_unknown)
1175 << MemberName << BaseType << int(IsArrow);
1176
1177 Diag(Loc: MemberDecl->getLocation(), DiagID: diag::note_member_declared_here)
1178 << MemberName;
1179 R.suppressDiagnostics();
1180 return ExprError();
1181}
1182
1183/// Given that normal member access failed on the given expression,
1184/// and given that the expression's type involves builtin-id or
1185/// builtin-Class, decide whether substituting in the redefinition
1186/// types would be profitable. The redefinition type is whatever
1187/// this translation unit tried to typedef to id/Class; we store
1188/// it to the side and then re-use it in places like this.
1189static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1190 const ObjCObjectPointerType *opty
1191 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1192 if (!opty) return false;
1193
1194 const ObjCObjectType *ty = opty->getObjectType();
1195
1196 QualType redef;
1197 if (ty->isObjCId()) {
1198 redef = S.Context.getObjCIdRedefinitionType();
1199 } else if (ty->isObjCClass()) {
1200 redef = S.Context.getObjCClassRedefinitionType();
1201 } else {
1202 return false;
1203 }
1204
1205 // Do the substitution as long as the redefinition type isn't just a
1206 // possibly-qualified pointer to builtin-id or builtin-Class again.
1207 opty = redef->getAs<ObjCObjectPointerType>();
1208 if (opty && !opty->getObjectType()->getInterface())
1209 return false;
1210
1211 base = S.ImpCastExprToType(E: base.get(), Type: redef, CK: CK_BitCast);
1212 return true;
1213}
1214
1215static bool isRecordType(QualType T) {
1216 return T->isRecordType();
1217}
1218static bool isPointerToRecordType(QualType T) {
1219 if (const PointerType *PT = T->getAs<PointerType>())
1220 return PT->getPointeeType()->isRecordType();
1221 return false;
1222}
1223
1224ExprResult
1225Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1226 if (IsArrow && !Base->getType()->isFunctionType())
1227 return DefaultFunctionArrayLvalueConversion(E: Base);
1228
1229 return CheckPlaceholderExpr(E: Base);
1230}
1231
1232/// Look up the given member of the given non-type-dependent
1233/// expression. This can return in one of two ways:
1234/// * If it returns a sentinel null-but-valid result, the caller will
1235/// assume that lookup was performed and the results written into
1236/// the provided structure. It will take over from there.
1237/// * Otherwise, the returned expression will be produced in place of
1238/// an ordinary member expression.
1239///
1240/// The ObjCImpDecl bit is a gross hack that will need to be properly
1241/// fixed for ObjC++.
1242static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1243 ExprResult &BaseExpr, bool &IsArrow,
1244 SourceLocation OpLoc, CXXScopeSpec &SS,
1245 Decl *ObjCImpDecl, bool HasTemplateArgs,
1246 SourceLocation TemplateKWLoc) {
1247 assert(BaseExpr.get() && "no base expression");
1248
1249 // Perform default conversions.
1250 BaseExpr = S.PerformMemberExprBaseConversion(Base: BaseExpr.get(), IsArrow);
1251 if (BaseExpr.isInvalid())
1252 return ExprError();
1253
1254 QualType BaseType = BaseExpr.get()->getType();
1255
1256 DeclarationName MemberName = R.getLookupName();
1257 SourceLocation MemberLoc = R.getNameLoc();
1258
1259 // For later type-checking purposes, turn arrow accesses into dot
1260 // accesses. The only access type we support that doesn't follow
1261 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1262 // and those never use arrows, so this is unaffected.
1263 if (IsArrow) {
1264 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1265 BaseType = Ptr->getPointeeType();
1266 else if (const ObjCObjectPointerType *Ptr =
1267 BaseType->getAs<ObjCObjectPointerType>())
1268 BaseType = Ptr->getPointeeType();
1269 else if (BaseType->isFunctionType())
1270 goto fail;
1271 else if (BaseType->isDependentType())
1272 BaseType = S.Context.DependentTy;
1273 else if (BaseType->isRecordType()) {
1274 // Recover from arrow accesses to records, e.g.:
1275 // struct MyRecord foo;
1276 // foo->bar
1277 // This is actually well-formed in C++ if MyRecord has an
1278 // overloaded operator->, but that should have been dealt with
1279 // by now--or a diagnostic message already issued if a problem
1280 // was encountered while looking for the overloaded operator->.
1281 if (!S.getLangOpts().CPlusPlus) {
1282 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_suggestion)
1283 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1284 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
1285 }
1286 IsArrow = false;
1287 } else {
1288 S.Diag(Loc: MemberLoc, DiagID: diag::err_typecheck_member_reference_arrow)
1289 << BaseType << BaseExpr.get()->getSourceRange();
1290 return ExprError();
1291 }
1292 }
1293
1294 // If the base type is an atomic type, this access is undefined behavior per
1295 // C11 6.5.2.3p5. Instead of giving a typecheck error, we'll warn the user
1296 // about the UB and recover by converting the atomic lvalue into a non-atomic
1297 // lvalue. Because this is inherently unsafe as an atomic operation, the
1298 // warning defaults to an error.
1299 if (const auto *ATy = BaseType->getAs<AtomicType>()) {
1300 S.DiagRuntimeBehavior(Loc: OpLoc, Statement: BaseExpr.get(),
1301 PD: S.PDiag(DiagID: diag::warn_atomic_member_access));
1302 BaseType = ATy->getValueType().getUnqualifiedType();
1303 BaseExpr = ImplicitCastExpr::Create(
1304 Context: S.Context, T: IsArrow ? S.Context.getPointerType(T: BaseType) : BaseType,
1305 Kind: CK_AtomicToNonAtomic, Operand: BaseExpr.get(), BasePath: nullptr,
1306 Cat: BaseExpr.get()->getValueKind(), FPO: FPOptionsOverride());
1307 }
1308
1309 // In HLSL, the member access on a ConstantBuffer<T> access the members of
1310 // through the handle in the ConstantBuffer<T>. If BaseType is a
1311 // ConstantBuffer, the conversion function to type T is called before trying
1312 // to access the member.
1313 if (S.getLangOpts().HLSL && BaseType->isHLSLResourceRecord()) {
1314 if (std::optional<ExprResult> ConvBase =
1315 S.HLSL().tryPerformConstantBufferConversion(BaseExpr: BaseExpr.get())) {
1316 assert(!ConvBase->isInvalid());
1317 BaseExpr = *ConvBase;
1318 BaseType = BaseExpr.get()->getType();
1319 IsArrow = false;
1320 }
1321 }
1322
1323 // Handle field access to simple records.
1324 if (BaseType->getAsRecordDecl()) {
1325 if (LookupMemberExprInRecord(SemaRef&: S, R, BaseExpr: BaseExpr.get(), RTy: BaseType, OpLoc, IsArrow,
1326 SS, HasTemplateArgs, TemplateKWLoc))
1327 return ExprError();
1328
1329 // Returning valid-but-null is how we indicate to the caller that
1330 // the lookup result was filled in. If typo correction was attempted and
1331 // failed, the lookup result will have been cleared--that combined with the
1332 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1333 return ExprResult{};
1334 } else if (BaseType->isDependentType()) {
1335 R.setNotFoundInCurrentInstantiation();
1336 return ExprEmpty();
1337 }
1338
1339 // Handle ivar access to Objective-C objects.
1340 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1341 if (!SS.isEmpty() && !SS.isInvalid()) {
1342 S.Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_objc_access)
1343 << 1 << SS.getScopeRep()
1344 << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
1345 SS.clear();
1346 }
1347
1348 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1349
1350 // There are three cases for the base type:
1351 // - builtin id (qualified or unqualified)
1352 // - builtin Class (qualified or unqualified)
1353 // - an interface
1354 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1355 if (!IDecl) {
1356 if (S.getLangOpts().ObjCAutoRefCount &&
1357 (OTy->isObjCId() || OTy->isObjCClass()))
1358 goto fail;
1359 // There's an implicit 'isa' ivar on all objects.
1360 // But we only actually find it this way on objects of type 'id',
1361 // apparently.
1362 if (OTy->isObjCId() && Member->isStr(Str: "isa"))
1363 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1364 OpLoc, S.Context.getObjCClassType());
1365 if (ShouldTryAgainWithRedefinitionType(S, base&: BaseExpr))
1366 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1367 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1368 goto fail;
1369 }
1370
1371 if (S.RequireCompleteType(Loc: OpLoc, T: BaseType,
1372 DiagID: diag::err_typecheck_incomplete_tag,
1373 Args: BaseExpr.get()))
1374 return ExprError();
1375
1376 ObjCInterfaceDecl *ClassDeclared = nullptr;
1377 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(IVarName: Member, ClassDeclared);
1378
1379 if (!IV) {
1380 // Attempt to correct for typos in ivar names.
1381 DeclFilterCCC<ObjCIvarDecl> Validator{};
1382 Validator.IsObjCIvarLookup = IsArrow;
1383 if (TypoCorrection Corrected = S.CorrectTypo(
1384 Typo: R.getLookupNameInfo(), LookupKind: Sema::LookupMemberName, S: nullptr, SS: nullptr,
1385 CCC&: Validator, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: IDecl)) {
1386 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1387 S.diagnoseTypo(
1388 Correction: Corrected,
1389 TypoDiag: S.PDiag(DiagID: diag::err_typecheck_member_reference_ivar_suggest)
1390 << IDecl->getDeclName() << MemberName);
1391
1392 // Figure out the class that declares the ivar.
1393 assert(!ClassDeclared);
1394
1395 Decl *D = cast<Decl>(Val: IV->getDeclContext());
1396 if (auto *Category = dyn_cast<ObjCCategoryDecl>(Val: D))
1397 D = Category->getClassInterface();
1398
1399 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(Val: D))
1400 ClassDeclared = Implementation->getClassInterface();
1401 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(Val: D))
1402 ClassDeclared = Interface;
1403
1404 assert(ClassDeclared && "cannot query interface");
1405 } else {
1406 if (IsArrow &&
1407 IDecl->FindPropertyDeclaration(
1408 PropertyId: Member, QueryKind: ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1409 S.Diag(Loc: MemberLoc, DiagID: diag::err_property_found_suggest)
1410 << Member << BaseExpr.get()->getType()
1411 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: ".");
1412 return ExprError();
1413 }
1414
1415 S.Diag(Loc: MemberLoc, DiagID: diag::err_typecheck_member_reference_ivar)
1416 << IDecl->getDeclName() << MemberName
1417 << BaseExpr.get()->getSourceRange();
1418 return ExprError();
1419 }
1420 }
1421
1422 assert(ClassDeclared);
1423
1424 // If the decl being referenced had an error, return an error for this
1425 // sub-expr without emitting another error, in order to avoid cascading
1426 // error cases.
1427 if (IV->isInvalidDecl())
1428 return ExprError();
1429
1430 // Check whether we can reference this field.
1431 if (S.DiagnoseUseOfDecl(D: IV, Locs: MemberLoc))
1432 return ExprError();
1433 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1434 IV->getAccessControl() != ObjCIvarDecl::Package) {
1435 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1436 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1437 ClassOfMethodDecl = MD->getClassInterface();
1438 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1439 // Case of a c-function declared inside an objc implementation.
1440 // FIXME: For a c-style function nested inside an objc implementation
1441 // class, there is no implementation context available, so we pass
1442 // down the context as argument to this routine. Ideally, this context
1443 // need be passed down in the AST node and somehow calculated from the
1444 // AST for a function decl.
1445 if (ObjCImplementationDecl *IMPD =
1446 dyn_cast<ObjCImplementationDecl>(Val: ObjCImpDecl))
1447 ClassOfMethodDecl = IMPD->getClassInterface();
1448 else if (ObjCCategoryImplDecl* CatImplClass =
1449 dyn_cast<ObjCCategoryImplDecl>(Val: ObjCImpDecl))
1450 ClassOfMethodDecl = CatImplClass->getClassInterface();
1451 }
1452 if (!S.getLangOpts().DebuggerSupport) {
1453 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1454 if (!declaresSameEntity(D1: ClassDeclared, D2: IDecl) ||
1455 !declaresSameEntity(D1: ClassOfMethodDecl, D2: ClassDeclared))
1456 S.Diag(Loc: MemberLoc, DiagID: diag::err_private_ivar_access)
1457 << IV->getDeclName();
1458 } else if (!IDecl->isSuperClassOf(I: ClassOfMethodDecl))
1459 // @protected
1460 S.Diag(Loc: MemberLoc, DiagID: diag::err_protected_ivar_access)
1461 << IV->getDeclName();
1462 }
1463 }
1464 bool warn = true;
1465 if (S.getLangOpts().ObjCWeak) {
1466 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1467 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: BaseExp))
1468 if (UO->getOpcode() == UO_Deref)
1469 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1470
1471 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(Val: BaseExp))
1472 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1473 S.Diag(Loc: DE->getLocation(), DiagID: diag::err_arc_weak_ivar_access);
1474 warn = false;
1475 }
1476 }
1477 if (warn) {
1478 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1479 ObjCMethodFamily MF = MD->getMethodFamily();
1480 warn = (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
1481 !S.ObjC().IvarBacksCurrentMethodAccessor(IFace: IDecl, Method: MD, IV));
1482 }
1483 if (warn)
1484 S.Diag(Loc: MemberLoc, DiagID: diag::warn_direct_ivar_access) << IV->getDeclName();
1485 }
1486
1487 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1488 IV, IV->getUsageType(objectType: BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1489 IsArrow);
1490
1491 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1492 if (!S.isUnevaluatedContext() &&
1493 !S.Diags.isIgnored(DiagID: diag::warn_arc_repeated_use_of_weak, Loc: MemberLoc))
1494 S.getCurFunction()->recordUseOfWeak(E: Result);
1495 }
1496
1497 return Result;
1498 }
1499
1500 // Objective-C property access.
1501 const ObjCObjectPointerType *OPT;
1502 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1503 if (!SS.isEmpty() && !SS.isInvalid()) {
1504 S.Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_objc_access)
1505 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
1506 SS.clear();
1507 }
1508
1509 // This actually uses the base as an r-value.
1510 BaseExpr = S.DefaultLvalueConversion(E: BaseExpr.get());
1511 if (BaseExpr.isInvalid())
1512 return ExprError();
1513
1514 assert(S.Context.hasSameUnqualifiedType(BaseType,
1515 BaseExpr.get()->getType()));
1516
1517 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1518
1519 const ObjCObjectType *OT = OPT->getObjectType();
1520
1521 // id, with and without qualifiers.
1522 if (OT->isObjCId()) {
1523 // Check protocols on qualified interfaces.
1524 Selector Sel = S.PP.getSelectorTable().getNullarySelector(ID: Member);
1525 if (Decl *PMDecl =
1526 FindGetterSetterNameDecl(QIdTy: OPT, Member, Sel, Context&: S.Context)) {
1527 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(Val: PMDecl)) {
1528 // Check the use of this declaration
1529 if (S.DiagnoseUseOfDecl(D: PD, Locs: MemberLoc))
1530 return ExprError();
1531
1532 return new (S.Context)
1533 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1534 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1535 }
1536
1537 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(Val: PMDecl)) {
1538 Selector SetterSel =
1539 SelectorTable::constructSetterSelector(Idents&: S.PP.getIdentifierTable(),
1540 SelTable&: S.PP.getSelectorTable(),
1541 Name: Member);
1542 ObjCMethodDecl *SMD = nullptr;
1543 if (Decl *SDecl = FindGetterSetterNameDecl(QIdTy: OPT,
1544 /*Property id*/ Member: nullptr,
1545 Sel: SetterSel, Context&: S.Context))
1546 SMD = dyn_cast<ObjCMethodDecl>(Val: SDecl);
1547
1548 return new (S.Context)
1549 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1550 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1551 }
1552 }
1553 // Use of id.member can only be for a property reference. Do not
1554 // use the 'id' redefinition in this case.
1555 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, base&: BaseExpr))
1556 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1557 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1558
1559 return ExprError(S.Diag(Loc: MemberLoc, DiagID: diag::err_property_not_found)
1560 << MemberName << BaseType);
1561 }
1562
1563 // 'Class', unqualified only.
1564 if (OT->isObjCClass()) {
1565 // Only works in a method declaration (??!).
1566 ObjCMethodDecl *MD = S.getCurMethodDecl();
1567 if (!MD) {
1568 if (ShouldTryAgainWithRedefinitionType(S, base&: BaseExpr))
1569 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1570 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1571
1572 goto fail;
1573 }
1574
1575 // Also must look for a getter name which uses property syntax.
1576 Selector Sel = S.PP.getSelectorTable().getNullarySelector(ID: Member);
1577 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1578 if (!IFace)
1579 goto fail;
1580
1581 ObjCMethodDecl *Getter;
1582 if ((Getter = IFace->lookupClassMethod(Sel))) {
1583 // Check the use of this method.
1584 if (S.DiagnoseUseOfDecl(D: Getter, Locs: MemberLoc))
1585 return ExprError();
1586 } else
1587 Getter = IFace->lookupPrivateMethod(Sel, Instance: false);
1588 // If we found a getter then this may be a valid dot-reference, we
1589 // will look for the matching setter, in case it is needed.
1590 Selector SetterSel =
1591 SelectorTable::constructSetterSelector(Idents&: S.PP.getIdentifierTable(),
1592 SelTable&: S.PP.getSelectorTable(),
1593 Name: Member);
1594 ObjCMethodDecl *Setter = IFace->lookupClassMethod(Sel: SetterSel);
1595 if (!Setter) {
1596 // If this reference is in an @implementation, also check for 'private'
1597 // methods.
1598 Setter = IFace->lookupPrivateMethod(Sel: SetterSel, Instance: false);
1599 }
1600
1601 if (Setter && S.DiagnoseUseOfDecl(D: Setter, Locs: MemberLoc))
1602 return ExprError();
1603
1604 if (Getter || Setter) {
1605 return new (S.Context) ObjCPropertyRefExpr(
1606 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1607 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1608 }
1609
1610 if (ShouldTryAgainWithRedefinitionType(S, base&: BaseExpr))
1611 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1612 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1613
1614 return ExprError(S.Diag(Loc: MemberLoc, DiagID: diag::err_property_not_found)
1615 << MemberName << BaseType);
1616 }
1617
1618 // Normal property access.
1619 return S.ObjC().HandleExprPropertyRefExpr(
1620 OPT, BaseExpr: BaseExpr.get(), OpLoc, MemberName, MemberLoc, SuperLoc: SourceLocation(),
1621 SuperType: QualType(), Super: false);
1622 }
1623
1624 if (BaseType->isPackedVectorBoolType(ctx: S.Context)) {
1625 // We disallow element access for ext_vector_type bool. There is no way to
1626 // materialize a reference to a vector element as a pointer (each element is
1627 // one bit in the vector).
1628 S.Diag(Loc: R.getNameLoc(), DiagID: diag::err_ext_vector_component_name_illegal)
1629 << MemberName
1630 << (BaseExpr.get() ? BaseExpr.get()->getSourceRange() : SourceRange());
1631 return ExprError();
1632 }
1633
1634 // Handle 'field access' to vectors, such as 'V.xx'.
1635 if (BaseType->isExtVectorType()) {
1636 // FIXME: this expr should store IsArrow.
1637 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1638 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1639 QualType ret = CheckExtVectorComponent(S, baseType: BaseType, VK, OpLoc,
1640 CompName: Member, CompLoc: MemberLoc);
1641 if (ret.isNull())
1642 return ExprError();
1643 Qualifiers BaseQ =
1644 S.Context.getCanonicalType(T: BaseExpr.get()->getType()).getQualifiers();
1645 ret = S.Context.getQualifiedType(T: ret, Qs: BaseQ);
1646
1647 return new (S.Context)
1648 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1649 }
1650
1651 if (S.getLangOpts().HLSL && BaseType->isConstantMatrixType()) {
1652 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1653 ExprValueKind VK = BaseExpr.get()->getValueKind();
1654 QualType Ret = S.HLSL().checkMatrixComponent(S, baseType: BaseType, VK, OpLoc, CompName: Member,
1655 CompLoc: MemberLoc);
1656 if (Ret.isNull())
1657 return ExprError();
1658 Qualifiers BaseQ =
1659 S.Context.getCanonicalType(T: BaseExpr.get()->getType()).getQualifiers();
1660 Ret = S.Context.getQualifiedType(T: Ret, Qs: BaseQ);
1661
1662 return new (S.Context)
1663 MatrixElementExpr(Ret, VK, BaseExpr.get(), *Member, MemberLoc);
1664 }
1665
1666 // Adjust builtin-sel to the appropriate redefinition type if that's
1667 // not just a pointer to builtin-sel again.
1668 if (IsArrow && BaseType->isSpecificBuiltinType(K: BuiltinType::ObjCSel) &&
1669 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1670 BaseExpr = S.ImpCastExprToType(
1671 E: BaseExpr.get(), Type: S.Context.getObjCSelRedefinitionType(), CK: CK_BitCast);
1672 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1673 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1674 }
1675
1676 // Failure cases.
1677 fail:
1678
1679 // Recover from dot accesses to pointers, e.g.:
1680 // type *foo;
1681 // foo.bar
1682 // This is actually well-formed in two cases:
1683 // - 'type' is an Objective C type
1684 // - 'bar' is a pseudo-destructor name which happens to refer to
1685 // the appropriate pointer type
1686 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1687 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1688 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1689 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_suggestion)
1690 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1691 << FixItHint::CreateReplacement(RemoveRange: OpLoc, Code: "->");
1692
1693 if (S.isSFINAEContext())
1694 return ExprError();
1695
1696 // Recurse as an -> access.
1697 IsArrow = true;
1698 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1699 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1700 }
1701 }
1702
1703 // If the user is trying to apply -> or . to a function name, it's probably
1704 // because they forgot parentheses to call that function.
1705 if (S.tryToRecoverWithCall(
1706 E&: BaseExpr, PD: S.PDiag(DiagID: diag::err_member_reference_needs_call),
1707 /*complain*/ ForceComplain: false,
1708 IsPlausibleResult: IsArrow ? &isPointerToRecordType : &isRecordType)) {
1709 if (BaseExpr.isInvalid())
1710 return ExprError();
1711 BaseExpr = S.DefaultFunctionArrayConversion(E: BaseExpr.get());
1712 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1713 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1714 }
1715
1716 // HLSL supports implicit conversion of scalar types to single element vector
1717 // rvalues in member expressions.
1718 if (S.getLangOpts().HLSL && BaseType->isScalarType()) {
1719 QualType VectorTy = S.Context.getExtVectorType(VectorType: BaseType, NumElts: 1);
1720 BaseExpr = S.ImpCastExprToType(E: BaseExpr.get(), Type: VectorTy, CK: CK_VectorSplat,
1721 VK: BaseExpr.get()->getValueKind());
1722 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, ObjCImpDecl,
1723 HasTemplateArgs, TemplateKWLoc);
1724 }
1725
1726 S.Diag(Loc: OpLoc, DiagID: diag::err_typecheck_member_reference_struct_union)
1727 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1728
1729 return ExprError();
1730}
1731
1732ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1733 SourceLocation OpLoc,
1734 tok::TokenKind OpKind, CXXScopeSpec &SS,
1735 SourceLocation TemplateKWLoc,
1736 UnqualifiedId &Id, Decl *ObjCImpDecl) {
1737 // Warn about the explicit constructor calls Microsoft extension.
1738 if (getLangOpts().MicrosoftExt &&
1739 Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
1740 Diag(Loc: Id.getSourceRange().getBegin(),
1741 DiagID: diag::ext_ms_explicit_constructor_call);
1742
1743 TemplateArgumentListInfo TemplateArgsBuffer;
1744
1745 // Decompose the name into its component parts.
1746 DeclarationNameInfo NameInfo;
1747 const TemplateArgumentListInfo *TemplateArgs;
1748 DecomposeUnqualifiedId(Id, Buffer&: TemplateArgsBuffer,
1749 NameInfo, TemplateArgs);
1750
1751 bool IsArrow = (OpKind == tok::arrow);
1752
1753 if (getLangOpts().HLSL && IsArrow)
1754 return ExprError(Diag(Loc: OpLoc, DiagID: diag::err_hlsl_operator_unsupported) << 2);
1755
1756 NamedDecl *FirstQualifierInScope
1757 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, NNS: SS.getScopeRep()));
1758
1759 // This is a postfix expression, so get rid of ParenListExprs.
1760 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, ME: Base);
1761 if (Result.isInvalid()) return ExprError();
1762 Base = Result.get();
1763
1764 ActOnMemberAccessExtraArgs ExtraArgs = {.S: S, .Id: Id, .ObjCImpDecl: ObjCImpDecl};
1765 ExprResult Res = BuildMemberReferenceExpr(
1766 Base, BaseType: Base->getType(), OpLoc, IsArrow, SS, TemplateKWLoc,
1767 FirstQualifierInScope, NameInfo, TemplateArgs, S, ExtraArgs: &ExtraArgs);
1768
1769 if (!Res.isInvalid()) {
1770 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: Res.get())) {
1771 CheckMemberAccessOfNoDeref(E: ME);
1772
1773 if (getLangOpts().HLSL) {
1774 QualType Ty = Res.get()->getType();
1775 if (Ty->isHLSLResourceRecord() || Ty->isHLSLResourceRecordArray())
1776 if (!HLSL().ActOnResourceMemberAccessExpr(ME))
1777 Res = ExprError();
1778 }
1779 }
1780 }
1781 return Res;
1782}
1783
1784void Sema::CheckMemberAccessOfNoDeref(const MemberExpr *E) {
1785 if (isUnevaluatedContext())
1786 return;
1787
1788 QualType ResultTy = E->getType();
1789
1790 // Member accesses have four cases:
1791 // 1: non-array member via "->": dereferences
1792 // 2: non-array member via ".": nothing interesting happens
1793 // 3: array member access via "->": nothing interesting happens
1794 // (this returns an array lvalue and does not actually dereference memory)
1795 // 4: array member access via ".": *adds* a layer of indirection
1796 if (ResultTy->isArrayType()) {
1797 if (!E->isArrow()) {
1798 // This might be something like:
1799 // (*structPtr).arrayMember
1800 // which behaves roughly like:
1801 // &(*structPtr).pointerMember
1802 // in that the apparent dereference in the base expression does not
1803 // actually happen.
1804 CheckAddressOfNoDeref(E: E->getBase());
1805 }
1806 } else if (E->isArrow()) {
1807 if (const auto *Ptr = dyn_cast<PointerType>(
1808 Val: E->getBase()->getType().getDesugaredType(Context))) {
1809 if (Ptr->getPointeeType()->hasAttr(AK: attr::NoDeref))
1810 ExprEvalContexts.back().PossibleDerefs.insert(Ptr: E);
1811 }
1812 }
1813}
1814
1815ExprResult
1816Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1817 SourceLocation OpLoc, const CXXScopeSpec &SS,
1818 FieldDecl *Field, DeclAccessPair FoundDecl,
1819 const DeclarationNameInfo &MemberNameInfo) {
1820 // x.a is an l-value if 'a' has a reference type. Otherwise:
1821 // x.a is an l-value/x-value/pr-value if the base is (and note
1822 // that *x is always an l-value), except that if the base isn't
1823 // an ordinary object then we must have an rvalue.
1824 ExprValueKind VK = VK_LValue;
1825 ExprObjectKind OK = OK_Ordinary;
1826 if (!IsArrow) {
1827 if (BaseExpr->getObjectKind() == OK_Ordinary)
1828 VK = BaseExpr->getValueKind();
1829 else
1830 VK = VK_PRValue;
1831 }
1832 if (VK != VK_PRValue && Field->isBitField())
1833 OK = OK_BitField;
1834
1835 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1836 QualType MemberType = Field->getType();
1837 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1838 MemberType = Ref->getPointeeType();
1839 VK = VK_LValue;
1840 } else {
1841 QualType BaseType = BaseExpr->getType();
1842 if (IsArrow) BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1843
1844 Qualifiers BaseQuals = BaseType.getQualifiers();
1845
1846 // GC attributes are never picked up by members.
1847 BaseQuals.removeObjCGCAttr();
1848
1849 // CVR attributes from the base are picked up by members,
1850 // except that 'mutable' members don't pick up 'const'.
1851 if (Field->isMutable()) BaseQuals.removeConst();
1852
1853 // HLSL resource types do not pick up address space qualifiers from the
1854 // base.
1855 if (getLangOpts().HLSL && (MemberType->isHLSLResourceRecord() ||
1856 MemberType->isHLSLResourceRecordArray()))
1857 BaseQuals.removeAddressSpace();
1858
1859 Qualifiers MemberQuals =
1860 Context.getCanonicalType(T: MemberType).getQualifiers();
1861
1862 assert(!MemberQuals.hasAddressSpace());
1863
1864 Qualifiers Combined = BaseQuals + MemberQuals;
1865 if (Combined != MemberQuals)
1866 MemberType = Context.getQualifiedType(T: MemberType, Qs: Combined);
1867
1868 // Pick up NoDeref from the base in case we end up using AddrOf on the
1869 // result. E.g. the expression
1870 // &someNoDerefPtr->pointerMember
1871 // should be a noderef pointer again.
1872 if (BaseType->hasAttr(AK: attr::NoDeref))
1873 MemberType =
1874 Context.getAttributedType(attrKind: attr::NoDeref, modifiedType: MemberType, equivalentType: MemberType);
1875 }
1876
1877 auto isDefaultedSpecialMember = [this](const DeclContext *Ctx) {
1878 auto *Method = dyn_cast<CXXMethodDecl>(Val: CurContext);
1879 if (!Method || !Method->isDefaulted())
1880 return false;
1881
1882 return Method->getDefaultedFunctionKind().isSpecialMember();
1883 };
1884
1885 // Implicit special members should not mark fields as used.
1886 if (!isDefaultedSpecialMember(CurContext))
1887 UnusedPrivateFields.remove(X: Field);
1888
1889 ExprResult Base = PerformObjectMemberConversion(From: BaseExpr, Qualifier: SS.getScopeRep(),
1890 FoundDecl, Member: Field);
1891 if (Base.isInvalid())
1892 return ExprError();
1893
1894 // Build a reference to a private copy for non-static data members in
1895 // non-static member functions, privatized by OpenMP constructs.
1896 if (getLangOpts().OpenMP && IsArrow &&
1897 !CurContext->isDependentContext() &&
1898 isa<CXXThisExpr>(Val: Base.get()->IgnoreParenImpCasts())) {
1899 if (auto *PrivateCopy = OpenMP().isOpenMPCapturedDecl(D: Field)) {
1900 return OpenMP().getOpenMPCapturedExpr(Capture: PrivateCopy, VK, OK,
1901 Loc: MemberNameInfo.getLoc());
1902 }
1903 }
1904
1905 return BuildMemberExpr(
1906 Base: Base.get(), IsArrow, OpLoc, NNS: SS.getWithLocInContext(Context),
1907 /*TemplateKWLoc=*/SourceLocation(), Member: Field, FoundDecl,
1908 /*HadMultipleCandidates=*/false, MemberNameInfo, Ty: MemberType, VK, OK);
1909}
1910
1911ExprResult
1912Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1913 SourceLocation TemplateKWLoc,
1914 LookupResult &R,
1915 const TemplateArgumentListInfo *TemplateArgs,
1916 bool IsKnownInstance, const Scope *S) {
1917 assert(!R.empty() && !R.isAmbiguous());
1918
1919 SourceLocation loc = R.getNameLoc();
1920
1921 // If this is known to be an instance access, go ahead and build an
1922 // implicit 'this' expression now.
1923 QualType ThisTy = getCurrentThisType();
1924 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1925
1926 Expr *baseExpr = nullptr; // null signifies implicit access
1927 if (IsKnownInstance) {
1928 SourceLocation Loc = R.getNameLoc();
1929 if (SS.getRange().isValid())
1930 Loc = SS.getRange().getBegin();
1931 baseExpr = BuildCXXThisExpr(Loc: loc, Type: ThisTy, /*IsImplicit=*/true);
1932 }
1933
1934 return BuildMemberReferenceExpr(
1935 BaseExpr: baseExpr, BaseExprType: ThisTy,
1936 /*OpLoc=*/SourceLocation(),
1937 /*IsArrow=*/!getLangOpts().HLSL, SS, TemplateKWLoc,
1938 /*FirstQualifierInScope=*/nullptr, R, TemplateArgs, S);
1939}
1940