1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis member access expressions.
11 //===----------------------------------------------------------------------===//
12 #include "clang/Sema/Overload.h"
13 #include "clang/AST/ASTLambda.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/Sema/ScopeInfo.h"
23 #include "clang/Sema/SemaInternal.h"
25 using namespace clang;
28 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
30 /// Determines if the given class is provably not derived from all of
31 /// the prospective base classes.
32 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
33 const BaseSet &Bases) {
34 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
35 return !Bases.count(Base->getCanonicalDecl());
37 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
41 /// The reference is definitely not an instance member access.
44 /// The reference may be an implicit instance member access.
47 /// The reference may be to an instance member, but it might be invalid if
48 /// so, because the context is not an instance method.
49 IMA_Mixed_StaticContext,
51 /// The reference may be to an instance member, but it is invalid if
52 /// so, because the context is from an unrelated class.
55 /// The reference is definitely an implicit instance member access.
58 /// The reference may be to an unresolved using declaration.
61 /// The reference is a contextually-permitted abstract member reference.
64 /// The reference may be to an unresolved using declaration and the
65 /// context is not an instance method.
66 IMA_Unresolved_StaticContext,
68 // The reference refers to a field which is not a member of the containing
69 // class, which is allowed because we're in C++11 mode and the context is
71 IMA_Field_Uneval_Context,
73 /// All possible referrents are instance members and the current
74 /// context is not an instance method.
75 IMA_Error_StaticContext,
77 /// All possible referrents are instance members of an unrelated
82 /// The given lookup names class member(s) and is not being used for
83 /// an address-of-member expression. Classify the type of access
84 /// according to whether it's possible that this reference names an
85 /// instance member. This is best-effort in dependent contexts; it is okay to
86 /// conservatively answer "yes", in which case some errors will simply
87 /// not be caught until template-instantiation.
88 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
89 const LookupResult &R) {
90 assert(!R.empty() && (*R.begin())->isCXXClassMember());
92 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
94 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
95 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
97 if (R.isUnresolvableResult())
98 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
100 // Collect all the declaring classes of instance members we find.
101 bool hasNonInstance = false;
102 bool isField = false;
104 for (NamedDecl *D : R) {
105 // Look through any using decls.
106 D = D->getUnderlyingDecl();
108 if (D->isCXXInstanceMember()) {
109 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
110 isa<IndirectFieldDecl>(D);
112 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
113 Classes.insert(R->getCanonicalDecl());
115 hasNonInstance = true;
118 // If we didn't find any instance members, it can't be an implicit
123 // C++11 [expr.prim.general]p12:
124 // An id-expression that denotes a non-static data member or non-static
125 // member function of a class can only be used:
127 // - if that id-expression denotes a non-static data member and it
128 // appears in an unevaluated operand.
130 // This rule is specific to C++11. However, we also permit this form
131 // in unevaluated inline assembly operands, like the operand to a SIZE.
132 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
133 assert(!AbstractInstanceResult);
134 switch (SemaRef.ExprEvalContexts.back().Context) {
135 case Sema::ExpressionEvaluationContext::Unevaluated:
136 case Sema::ExpressionEvaluationContext::UnevaluatedList:
137 if (isField && SemaRef.getLangOpts().CPlusPlus11)
138 AbstractInstanceResult = IMA_Field_Uneval_Context;
141 case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
142 AbstractInstanceResult = IMA_Abstract;
145 case Sema::ExpressionEvaluationContext::DiscardedStatement:
146 case Sema::ExpressionEvaluationContext::ConstantEvaluated:
147 case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
148 case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
152 // If the current context is not an instance method, it can't be
153 // an implicit member reference.
154 if (isStaticContext) {
156 return IMA_Mixed_StaticContext;
158 return AbstractInstanceResult ? AbstractInstanceResult
159 : IMA_Error_StaticContext;
162 CXXRecordDecl *contextClass;
163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
164 contextClass = MD->getParent()->getCanonicalDecl();
166 contextClass = cast<CXXRecordDecl>(DC);
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
174 if (R.getNamingClass() &&
175 contextClass->getCanonicalDecl() !=
176 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.
181 Classes.insert(R.getNamingClass()->getCanonicalDecl());
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).
187 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
188 return hasNonInstance ? IMA_Mixed_Unrelated :
189 AbstractInstanceResult ? AbstractInstanceResult :
192 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
195 /// Diagnose a reference to a field with no object available.
196 static void diagnoseInstanceReference(Sema &SemaRef,
197 const CXXScopeSpec &SS,
199 const DeclarationNameInfo &nameInfo) {
200 SourceLocation Loc = nameInfo.getLoc();
201 SourceRange Range(Loc);
202 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
204 // Look through using shadow decls and aliases.
205 Rep = Rep->getUnderlyingDecl();
207 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
209 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
210 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
212 bool InStaticMethod = Method && Method->isStatic();
213 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
215 if (IsField && InStaticMethod)
216 // "invalid use of member 'x' in static member function"
217 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
218 << 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
223 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
224 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
226 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
227 << nameInfo.getName() << Range;
229 SemaRef.Diag(Loc, diag::err_member_call_without_object)
233 /// Builds an expression which might be an implicit member expression.
235 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
236 SourceLocation TemplateKWLoc,
238 const TemplateArgumentListInfo *TemplateArgs,
240 switch (ClassifyImplicitMemberAccess(*this, R)) {
242 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
245 case IMA_Mixed_Unrelated:
247 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
256 case IMA_Mixed_StaticContext:
257 case IMA_Unresolved_StaticContext:
258 if (TemplateArgs || TemplateKWLoc.isValid())
259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
260 return BuildDeclarationNameExpr(SS, R, false);
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
265 R.getLookupNameInfo());
269 llvm_unreachable("unexpected instance member access kind");
272 /// Determine whether input char is from rgba component set.
286 // OpenCL v1.1, s6.1.7
287 // The component swizzle length must be in accordance with the acceptable
289 static bool IsValidOpenCLComponentSwizzleLength(unsigned len)
291 return (len >= 1 && len <= 4) || len == 8 || len == 16;
294 /// Check an ext-vector component access expression.
296 /// VK should be set in advance to the value kind of the base
299 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
300 SourceLocation OpLoc, const IdentifierInfo *CompName,
301 SourceLocation CompLoc) {
302 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
305 // FIXME: This logic can be greatly simplified by splitting it along
306 // halving/not halving and reworking the component checking.
307 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
309 // The vector accessor can't exceed the number of elements.
310 const char *compStr = CompName->getNameStart();
312 // This flag determines whether or not the component is one of the four
313 // special names that indicate a subset of exactly half the elements are
315 bool HalvingSwizzle = false;
317 // This flag determines whether or not CompName has an 's' char prefix,
318 // indicating that it is a string of hex values to be used as vector indices.
319 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
321 bool HasRepeated = false;
322 bool HasIndex[16] = {};
326 // Check that we've found one of the special components, or that the component
327 // names must come from the same set.
328 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
329 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
330 HalvingSwizzle = true;
331 } else if (!HexSwizzle &&
332 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
333 bool HasRGBA = IsRGBA(*compStr);
335 // Ensure that xyzw and rgba components don't intermingle.
336 if (HasRGBA != IsRGBA(*compStr))
338 if (HasIndex[Idx]) HasRepeated = true;
339 HasIndex[Idx] = true;
341 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
343 // Emit a warning if an rgba selector is used earlier than OpenCL 2.2
344 if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
345 if (S.getLangOpts().OpenCL && S.getLangOpts().OpenCLVersion < 220) {
346 const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
347 S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
348 << StringRef(DiagBegin, 1)
349 << S.getLangOpts().OpenCLVersion << SourceRange(CompLoc);
353 if (HexSwizzle) compStr++;
354 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
355 if (HasIndex[Idx]) HasRepeated = true;
356 HasIndex[Idx] = true;
361 if (!HalvingSwizzle && *compStr) {
362 // We didn't get to the end of the string. This means the component names
363 // didn't come from the same set *or* we encountered an illegal name.
364 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
365 << StringRef(compStr, 1) << SourceRange(CompLoc);
369 // Ensure no component accessor exceeds the width of the vector type it
371 if (!HalvingSwizzle) {
372 compStr = CompName->getNameStart();
378 if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
379 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
380 << baseType << SourceRange(CompLoc);
386 // OpenCL mode requires swizzle length to be in accordance with accepted
387 // sizes. Clang however supports arbitrary lengths for other languages.
388 if (S.getLangOpts().OpenCL && !HalvingSwizzle) {
389 unsigned SwizzleLength = CompName->getLength();
394 if (IsValidOpenCLComponentSwizzleLength(SwizzleLength) == false) {
395 S.Diag(OpLoc, diag::err_opencl_ext_vector_component_invalid_length)
396 << SwizzleLength << SourceRange(CompLoc);
401 // The component accessor looks fine - now we need to compute the actual type.
402 // The vector type is implied by the component accessor. For example,
403 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
404 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
405 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
406 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
407 : CompName->getLength();
412 return vecType->getElementType();
414 if (HasRepeated) VK = VK_RValue;
416 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
417 // Now look up the TypeDefDecl from the vector type. Without this,
418 // diagostics look bad. We want extended vector types to appear built-in.
419 for (Sema::ExtVectorDeclsType::iterator
420 I = S.ExtVectorDecls.begin(S.getExternalSource()),
421 E = S.ExtVectorDecls.end();
423 if ((*I)->getUnderlyingType() == VT)
424 return S.Context.getTypedefType(*I);
427 return VT; // should never get here (a typedef type should always be found).
430 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
431 IdentifierInfo *Member,
433 ASTContext &Context) {
435 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
436 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
438 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
441 for (const auto *I : PDecl->protocols()) {
442 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
449 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
450 IdentifierInfo *Member,
452 ASTContext &Context) {
453 // Check protocols on qualified interfaces.
454 Decl *GDecl = nullptr;
455 for (const auto *I : QIdTy->quals()) {
457 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
458 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
462 // Also must look for a getter or setter name which uses property syntax.
463 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
469 for (const auto *I : QIdTy->quals()) {
470 // Search in the protocol-qualifier list of current protocol.
471 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
480 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
481 bool IsArrow, SourceLocation OpLoc,
482 const CXXScopeSpec &SS,
483 SourceLocation TemplateKWLoc,
484 NamedDecl *FirstQualifierInScope,
485 const DeclarationNameInfo &NameInfo,
486 const TemplateArgumentListInfo *TemplateArgs) {
487 // Even in dependent contexts, try to diagnose base expressions with
488 // obviously wrong types, e.g.:
493 // In Obj-C++, however, the above expression is valid, since it could be
494 // accessing the 'f' property if T is an Obj-C interface. The extra check
495 // allows this, while still reporting an error if T is a struct pointer.
497 const PointerType *PT = BaseType->getAs<PointerType>();
498 if (PT && (!getLangOpts().ObjC ||
499 PT->getPointeeType()->isRecordType())) {
500 assert(BaseExpr && "cannot happen with implicit member accesses");
501 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
502 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
507 assert(BaseType->isDependentType() ||
508 NameInfo.getName().isDependentName() ||
509 isDependentScopeSpecifier(SS));
511 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
512 // must have pointer type, and the accessed type is the pointee.
513 return CXXDependentScopeMemberExpr::Create(
514 Context, BaseExpr, BaseType, IsArrow, OpLoc,
515 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
516 NameInfo, TemplateArgs);
519 /// We know that the given qualified member reference points only to
520 /// declarations which do not belong to the static type of the base
521 /// expression. Diagnose the problem.
522 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
525 const CXXScopeSpec &SS,
527 const DeclarationNameInfo &nameInfo) {
528 // If this is an implicit member access, use a different set of
531 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
533 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
534 << SS.getRange() << rep << BaseType;
537 // Check whether the declarations we found through a nested-name
538 // specifier in a member expression are actually members of the base
539 // type. The restriction here is:
542 // ... In these cases, the id-expression shall name a
543 // member of the class or of one of its base classes.
545 // So it's perfectly legitimate for the nested-name specifier to name
546 // an unrelated class, and for us to find an overload set including
547 // decls from classes which are not superclasses, as long as the decl
548 // we actually pick through overload resolution is from a superclass.
549 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
551 const CXXScopeSpec &SS,
552 const LookupResult &R) {
553 CXXRecordDecl *BaseRecord =
554 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
556 // We can't check this yet because the base type is still
558 assert(BaseType->isDependentType());
562 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
563 // If this is an implicit member reference and we find a
564 // non-instance member, it's not an error.
565 if (!BaseExpr && !(*I)->isCXXInstanceMember())
568 // Note that we use the DC of the decl, not the underlying decl.
569 DeclContext *DC = (*I)->getDeclContext();
570 while (DC->isTransparentContext())
571 DC = DC->getParent();
576 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
577 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
578 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
582 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
583 R.getRepresentativeDecl(),
584 R.getLookupNameInfo());
590 // Callback to only accept typo corrections that are either a ValueDecl or a
591 // FunctionTemplateDecl and are declared in the current record or, for a C++
592 // classes, one of its base classes.
593 class RecordMemberExprValidatorCCC final : public CorrectionCandidateCallback {
595 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
596 : Record(RTy->getDecl()) {
597 // Don't add bare keywords to the consumer since they will always fail
598 // validation by virtue of not being associated with any decls.
599 WantTypeSpecifiers = false;
600 WantExpressionKeywords = false;
601 WantCXXNamedCasts = false;
602 WantFunctionLikeCasts = false;
603 WantRemainingKeywords = false;
606 bool ValidateCandidate(const TypoCorrection &candidate) override {
607 NamedDecl *ND = candidate.getCorrectionDecl();
608 // Don't accept candidates that cannot be member functions, constants,
609 // variables, or templates.
610 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
613 // Accept candidates that occur in the current record.
614 if (Record->containsDecl(ND))
617 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
618 // Accept candidates that occur in any of the current class' base classes.
619 for (const auto &BS : RD->bases()) {
620 if (const RecordType *BSTy =
621 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
622 if (BSTy->getDecl()->containsDecl(ND))
631 std::unique_ptr<CorrectionCandidateCallback> clone() override {
632 return llvm::make_unique<RecordMemberExprValidatorCCC>(*this);
636 const RecordDecl *const Record;
641 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
643 const RecordType *RTy,
644 SourceLocation OpLoc, bool IsArrow,
645 CXXScopeSpec &SS, bool HasTemplateArgs,
646 SourceLocation TemplateKWLoc,
648 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
649 RecordDecl *RDecl = RTy->getDecl();
650 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
651 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
652 diag::err_typecheck_incomplete_tag,
656 if (HasTemplateArgs || TemplateKWLoc.isValid()) {
657 // LookupTemplateName doesn't expect these both to exist simultaneously.
658 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
661 return SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS,
665 DeclContext *DC = RDecl;
667 // If the member name was a qualified-id, look into the
668 // nested-name-specifier.
669 DC = SemaRef.computeDeclContext(SS, false);
671 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
672 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
673 << SS.getRange() << DC;
677 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
679 if (!isa<TypeDecl>(DC)) {
680 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
681 << DC << SS.getRange();
686 // The record definition is complete, now look up the member.
687 SemaRef.LookupQualifiedName(R, DC, SS);
692 DeclarationName Typo = R.getLookupName();
693 SourceLocation TypoLoc = R.getNameLoc();
697 DeclarationNameInfo NameInfo;
698 Sema::LookupNameKind LookupKind;
699 Sema::RedeclarationKind Redecl;
701 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
702 R.redeclarationKind()};
703 RecordMemberExprValidatorCCC CCC(RTy);
704 TE = SemaRef.CorrectTypoDelayed(
705 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS, CCC,
706 [=, &SemaRef](const TypoCorrection &TC) {
708 assert(!TC.isKeyword() &&
709 "Got a keyword as a correction for a member!");
710 bool DroppedSpecifier =
711 TC.WillReplaceSpecifier() &&
712 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
713 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
714 << Typo << DC << DroppedSpecifier
717 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
720 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
721 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
722 R.clear(); // Ensure there's no decls lingering in the shared state.
723 R.suppressDiagnostics();
724 R.setLookupName(TC.getCorrection());
725 for (NamedDecl *ND : TC)
728 return SemaRef.BuildMemberReferenceExpr(
729 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
730 nullptr, R, nullptr, nullptr);
732 Sema::CTK_ErrorRecovery, DC);
737 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
738 ExprResult &BaseExpr, bool &IsArrow,
739 SourceLocation OpLoc, CXXScopeSpec &SS,
740 Decl *ObjCImpDecl, bool HasTemplateArgs,
741 SourceLocation TemplateKWLoc);
744 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
745 SourceLocation OpLoc, bool IsArrow,
747 SourceLocation TemplateKWLoc,
748 NamedDecl *FirstQualifierInScope,
749 const DeclarationNameInfo &NameInfo,
750 const TemplateArgumentListInfo *TemplateArgs,
752 ActOnMemberAccessExtraArgs *ExtraArgs) {
753 if (BaseType->isDependentType() ||
754 (SS.isSet() && isDependentScopeSpecifier(SS)))
755 return ActOnDependentMemberExpr(Base, BaseType,
757 SS, TemplateKWLoc, FirstQualifierInScope,
758 NameInfo, TemplateArgs);
760 LookupResult R(*this, NameInfo, LookupMemberName);
762 // Implicit member accesses.
764 TypoExpr *TE = nullptr;
765 QualType RecordTy = BaseType;
766 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
767 if (LookupMemberExprInRecord(
768 *this, R, nullptr, RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
769 SS, TemplateArgs != nullptr, TemplateKWLoc, TE))
774 // Explicit member accesses.
776 ExprResult BaseResult = Base;
778 LookupMemberExpr(*this, R, BaseResult, IsArrow, OpLoc, SS,
779 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
780 TemplateArgs != nullptr, TemplateKWLoc);
782 if (BaseResult.isInvalid())
784 Base = BaseResult.get();
786 if (Result.isInvalid())
792 // LookupMemberExpr can modify Base, and thus change BaseType
793 BaseType = Base->getType();
796 return BuildMemberReferenceExpr(Base, BaseType,
797 OpLoc, IsArrow, SS, TemplateKWLoc,
798 FirstQualifierInScope, R, TemplateArgs, S,
803 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
805 IndirectFieldDecl *indirectField,
806 DeclAccessPair foundDecl,
807 Expr *baseObjectExpr,
808 SourceLocation opLoc) {
809 // First, build the expression that refers to the base object.
811 // Case 1: the base of the indirect field is not a field.
812 VarDecl *baseVariable = indirectField->getVarDecl();
813 CXXScopeSpec EmptySS;
815 assert(baseVariable->getType()->isRecordType());
817 // In principle we could have a member access expression that
818 // accesses an anonymous struct/union that's a static member of
819 // the base object's class. However, under the current standard,
820 // static data members cannot be anonymous structs or unions.
821 // Supporting this is as easy as building a MemberExpr here.
822 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
824 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
827 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
828 if (result.isInvalid()) return ExprError();
830 baseObjectExpr = result.get();
833 assert((baseVariable || baseObjectExpr) &&
834 "referencing anonymous struct/union without a base variable or "
837 // Build the implicit member references to the field of the
838 // anonymous struct/union.
839 Expr *result = baseObjectExpr;
840 IndirectFieldDecl::chain_iterator
841 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
843 // Case 2: the base of the indirect field is a field and the user
844 // wrote a member expression.
846 FieldDecl *field = cast<FieldDecl>(*FI);
848 bool baseObjectIsPointer = baseObjectExpr->getType()->isPointerType();
850 // Make a nameInfo that properly uses the anonymous name.
851 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
853 // Build the first member access in the chain with full information.
855 BuildFieldReferenceExpr(result, baseObjectIsPointer, SourceLocation(),
856 SS, field, foundDecl, memberNameInfo)
862 // In all cases, we should now skip the first declaration in the chain.
866 FieldDecl *field = cast<FieldDecl>(*FI++);
868 // FIXME: these are somewhat meaningless
869 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
870 DeclAccessPair fakeFoundDecl =
871 DeclAccessPair::make(field, field->getAccess());
874 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
875 (FI == FEnd ? SS : EmptySS), field,
876 fakeFoundDecl, memberNameInfo)
884 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
885 const CXXScopeSpec &SS,
887 const DeclarationNameInfo &NameInfo) {
888 // Property names are always simple identifiers and therefore never
889 // require any interesting additional storage.
890 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
891 S.Context.PseudoObjectTy, VK_LValue,
892 SS.getWithLocInContext(S.Context),
896 MemberExpr *Sema::BuildMemberExpr(
897 Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS,
898 SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl,
899 bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo,
900 QualType Ty, ExprValueKind VK, ExprObjectKind OK,
901 const TemplateArgumentListInfo *TemplateArgs) {
902 NestedNameSpecifierLoc NNS =
903 SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc();
904 return BuildMemberExpr(Base, IsArrow, OpLoc, NNS, TemplateKWLoc, Member,
905 FoundDecl, HadMultipleCandidates, MemberNameInfo, Ty,
906 VK, OK, TemplateArgs);
909 MemberExpr *Sema::BuildMemberExpr(
910 Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS,
911 SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl,
912 bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo,
913 QualType Ty, ExprValueKind VK, ExprObjectKind OK,
914 const TemplateArgumentListInfo *TemplateArgs) {
915 assert((!IsArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
917 MemberExpr::Create(Context, Base, IsArrow, OpLoc, NNS, TemplateKWLoc,
918 Member, FoundDecl, MemberNameInfo, TemplateArgs, Ty,
919 VK, OK, getNonOdrUseReasonInCurrentContext(Member));
920 E->setHadMultipleCandidates(HadMultipleCandidates);
921 MarkMemberReferenced(E);
925 /// Determine if the given scope is within a function-try-block handler.
926 static bool IsInFnTryBlockHandler(const Scope *S) {
927 // Walk the scope stack until finding a FnTryCatchScope, or leave the
928 // function scope. If a FnTryCatchScope is found, check whether the TryScope
929 // flag is set. If it is not, it's a function-try-block handler.
930 for (; S != S->getFnParent(); S = S->getParent()) {
931 if (S->getFlags() & Scope::FnTryCatchScope)
932 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
938 getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
939 const TemplateArgumentListInfo *TemplateArgs,
940 const DeclarationNameInfo &MemberNameInfo,
941 SourceLocation TemplateKWLoc) {
943 S.diagnoseMissingTemplateArguments(TemplateName(VarTempl),
944 MemberNameInfo.getBeginLoc());
948 DeclResult VDecl = S.CheckVarTemplateId(
949 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
950 if (VDecl.isInvalid())
952 VarDecl *Var = cast<VarDecl>(VDecl.get());
953 if (!Var->getTemplateSpecializationKind())
954 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
955 MemberNameInfo.getLoc());
960 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
961 SourceLocation OpLoc, bool IsArrow,
962 const CXXScopeSpec &SS,
963 SourceLocation TemplateKWLoc,
964 NamedDecl *FirstQualifierInScope,
966 const TemplateArgumentListInfo *TemplateArgs,
968 bool SuppressQualifierCheck,
969 ActOnMemberAccessExtraArgs *ExtraArgs) {
970 QualType BaseType = BaseExprType;
972 assert(BaseType->isPointerType());
973 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
975 R.setBaseObjectType(BaseType);
977 // C++1z [expr.ref]p2:
978 // For the first option (dot) the first expression shall be a glvalue [...]
979 if (!IsArrow && BaseExpr && BaseExpr->isRValue()) {
980 ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
981 if (Converted.isInvalid())
983 BaseExpr = Converted.get();
987 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
988 DeclarationName MemberName = MemberNameInfo.getName();
989 SourceLocation MemberLoc = MemberNameInfo.getLoc();
994 // [except.handle]p10: Referring to any non-static member or base class of an
995 // object in the handler for a function-try-block of a constructor or
996 // destructor for that object results in undefined behavior.
997 const auto *FD = getCurFunctionDecl();
998 if (S && BaseExpr && FD &&
999 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1000 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1001 IsInFnTryBlockHandler(S))
1002 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1003 << isa<CXXDestructorDecl>(FD);
1006 // Rederive where we looked up.
1007 DeclContext *DC = (SS.isSet()
1008 ? computeDeclContext(SS, false)
1009 : BaseType->getAs<RecordType>()->getDecl());
1012 ExprResult RetryExpr;
1013 if (!IsArrow && BaseExpr) {
1014 SFINAETrap Trap(*this, true);
1015 ParsedType ObjectType;
1016 bool MayBePseudoDestructor = false;
1017 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1018 OpLoc, tok::arrow, ObjectType,
1019 MayBePseudoDestructor);
1020 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1021 CXXScopeSpec TempSS(SS);
1022 RetryExpr = ActOnMemberAccessExpr(
1023 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
1024 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
1026 if (Trap.hasErrorOccurred())
1027 RetryExpr = ExprError();
1029 if (RetryExpr.isUsable()) {
1030 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1031 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1036 Diag(R.getNameLoc(), diag::err_no_member)
1038 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1042 // Diagnose lookups that find only declarations from a non-base
1043 // type. This is possible for either qualified lookups (which may
1044 // have been qualified with an unrelated type) or implicit member
1045 // expressions (which were found with unqualified lookup and thus
1046 // may have come from an enclosing scope). Note that it's okay for
1047 // lookup to find declarations from a non-base type as long as those
1048 // aren't the ones picked by overload resolution.
1049 if ((SS.isSet() || !BaseExpr ||
1050 (isa<CXXThisExpr>(BaseExpr) &&
1051 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1052 !SuppressQualifierCheck &&
1053 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1056 // Construct an unresolved result if we in fact got an unresolved
1058 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1059 // Suppress any lookup-related diagnostics; we'll do these when we
1061 R.suppressDiagnostics();
1063 UnresolvedMemberExpr *MemExpr
1064 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1065 BaseExpr, BaseExprType,
1067 SS.getWithLocInContext(Context),
1068 TemplateKWLoc, MemberNameInfo,
1069 TemplateArgs, R.begin(), R.end());
1074 assert(R.isSingleResult());
1075 DeclAccessPair FoundDecl = R.begin().getPair();
1076 NamedDecl *MemberDecl = R.getFoundDecl();
1078 // FIXME: diagnose the presence of template arguments now.
1080 // If the decl being referenced had an error, return an error for this
1081 // sub-expr without emitting another error, in order to avoid cascading
1083 if (MemberDecl->isInvalidDecl())
1086 // Handle the implicit-member-access case.
1088 // If this is not an instance member, convert to a non-member access.
1089 if (!MemberDecl->isCXXInstanceMember()) {
1090 // If this is a variable template, get the instantiated variable
1091 // declaration corresponding to the supplied template arguments
1092 // (while emitting diagnostics as necessary) that will be referenced
1093 // by this expression.
1094 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1095 "How did we get template arguments here sans a variable template");
1096 if (isa<VarTemplateDecl>(MemberDecl)) {
1097 MemberDecl = getVarTemplateSpecialization(
1098 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1099 R.getLookupNameInfo(), TemplateKWLoc);
1103 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1104 FoundDecl, TemplateArgs);
1106 SourceLocation Loc = R.getNameLoc();
1107 if (SS.getRange().isValid())
1108 Loc = SS.getRange().getBegin();
1109 BaseExpr = BuildCXXThisExpr(Loc, BaseExprType, /*IsImplicit=*/true);
1112 // Check the use of this member.
1113 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1116 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1117 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1120 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1121 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1124 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1125 // We may have found a field within an anonymous union or struct
1126 // (C++ [class.union]).
1127 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
1128 FoundDecl, BaseExpr,
1131 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
1132 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var,
1133 FoundDecl, /*HadMultipleCandidates=*/false,
1134 MemberNameInfo, Var->getType().getNonReferenceType(),
1135 VK_LValue, OK_Ordinary);
1138 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1139 ExprValueKind valueKind;
1141 if (MemberFn->isInstance()) {
1142 valueKind = VK_RValue;
1143 type = Context.BoundMemberTy;
1145 valueKind = VK_LValue;
1146 type = MemberFn->getType();
1149 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc,
1150 MemberFn, FoundDecl, /*HadMultipleCandidates=*/false,
1151 MemberNameInfo, type, valueKind, OK_Ordinary);
1153 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1155 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1156 return BuildMemberExpr(BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Enum,
1157 FoundDecl, /*HadMultipleCandidates=*/false,
1158 MemberNameInfo, Enum->getType(), VK_RValue,
1161 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1162 if (VarDecl *Var = getVarTemplateSpecialization(
1163 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1164 return BuildMemberExpr(
1165 BaseExpr, IsArrow, OpLoc, &SS, TemplateKWLoc, Var, FoundDecl,
1166 /*HadMultipleCandidates=*/false, MemberNameInfo,
1167 Var->getType().getNonReferenceType(), VK_LValue, OK_Ordinary);
1171 // We found something that we didn't expect. Complain.
1172 if (isa<TypeDecl>(MemberDecl))
1173 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1174 << MemberName << BaseType << int(IsArrow);
1176 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1177 << MemberName << BaseType << int(IsArrow);
1179 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1181 R.suppressDiagnostics();
1185 /// Given that normal member access failed on the given expression,
1186 /// and given that the expression's type involves builtin-id or
1187 /// builtin-Class, decide whether substituting in the redefinition
1188 /// types would be profitable. The redefinition type is whatever
1189 /// this translation unit tried to typedef to id/Class; we store
1190 /// it to the side and then re-use it in places like this.
1191 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1192 const ObjCObjectPointerType *opty
1193 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1194 if (!opty) return false;
1196 const ObjCObjectType *ty = opty->getObjectType();
1199 if (ty->isObjCId()) {
1200 redef = S.Context.getObjCIdRedefinitionType();
1201 } else if (ty->isObjCClass()) {
1202 redef = S.Context.getObjCClassRedefinitionType();
1207 // Do the substitution as long as the redefinition type isn't just a
1208 // possibly-qualified pointer to builtin-id or builtin-Class again.
1209 opty = redef->getAs<ObjCObjectPointerType>();
1210 if (opty && !opty->getObjectType()->getInterface())
1213 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1217 static bool isRecordType(QualType T) {
1218 return T->isRecordType();
1220 static bool isPointerToRecordType(QualType T) {
1221 if (const PointerType *PT = T->getAs<PointerType>())
1222 return PT->getPointeeType()->isRecordType();
1226 /// Perform conversions on the LHS of a member access expression.
1228 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1229 if (IsArrow && !Base->getType()->isFunctionType())
1230 return DefaultFunctionArrayLvalueConversion(Base);
1232 return CheckPlaceholderExpr(Base);
1235 /// Look up the given member of the given non-type-dependent
1236 /// expression. This can return in one of two ways:
1237 /// * If it returns a sentinel null-but-valid result, the caller will
1238 /// assume that lookup was performed and the results written into
1239 /// the provided structure. It will take over from there.
1240 /// * Otherwise, the returned expression will be produced in place of
1241 /// an ordinary member expression.
1243 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1244 /// fixed for ObjC++.
1245 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1246 ExprResult &BaseExpr, bool &IsArrow,
1247 SourceLocation OpLoc, CXXScopeSpec &SS,
1248 Decl *ObjCImpDecl, bool HasTemplateArgs,
1249 SourceLocation TemplateKWLoc) {
1250 assert(BaseExpr.get() && "no base expression");
1252 // Perform default conversions.
1253 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1254 if (BaseExpr.isInvalid())
1257 QualType BaseType = BaseExpr.get()->getType();
1258 assert(!BaseType->isDependentType());
1260 DeclarationName MemberName = R.getLookupName();
1261 SourceLocation MemberLoc = R.getNameLoc();
1263 // For later type-checking purposes, turn arrow accesses into dot
1264 // accesses. The only access type we support that doesn't follow
1265 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1266 // and those never use arrows, so this is unaffected.
1268 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1269 BaseType = Ptr->getPointeeType();
1270 else if (const ObjCObjectPointerType *Ptr
1271 = BaseType->getAs<ObjCObjectPointerType>())
1272 BaseType = Ptr->getPointeeType();
1273 else if (BaseType->isRecordType()) {
1274 // Recover from arrow accesses to records, e.g.:
1275 // struct MyRecord foo;
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(OpLoc, diag::err_typecheck_member_reference_suggestion)
1283 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1284 << FixItHint::CreateReplacement(OpLoc, ".");
1287 } else if (BaseType->isFunctionType()) {
1290 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1291 << BaseType << BaseExpr.get()->getSourceRange();
1296 // Handle field access to simple records.
1297 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1298 TypoExpr *TE = nullptr;
1299 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy, OpLoc, IsArrow, SS,
1300 HasTemplateArgs, TemplateKWLoc, TE))
1303 // Returning valid-but-null is how we indicate to the caller that
1304 // the lookup result was filled in. If typo correction was attempted and
1305 // failed, the lookup result will have been cleared--that combined with the
1306 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1307 return ExprResult(TE);
1310 // Handle ivar access to Objective-C objects.
1311 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1312 if (!SS.isEmpty() && !SS.isInvalid()) {
1313 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1314 << 1 << SS.getScopeRep()
1315 << FixItHint::CreateRemoval(SS.getRange());
1319 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1321 // There are three cases for the base type:
1322 // - builtin id (qualified or unqualified)
1323 // - builtin Class (qualified or unqualified)
1325 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1327 if (S.getLangOpts().ObjCAutoRefCount &&
1328 (OTy->isObjCId() || OTy->isObjCClass()))
1330 // There's an implicit 'isa' ivar on all objects.
1331 // But we only actually find it this way on objects of type 'id',
1333 if (OTy->isObjCId() && Member->isStr("isa"))
1334 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1335 OpLoc, S.Context.getObjCClassType());
1336 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1337 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1338 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1342 if (S.RequireCompleteType(OpLoc, BaseType,
1343 diag::err_typecheck_incomplete_tag,
1347 ObjCInterfaceDecl *ClassDeclared = nullptr;
1348 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1351 // Attempt to correct for typos in ivar names.
1352 DeclFilterCCC<ObjCIvarDecl> Validator{};
1353 Validator.IsObjCIvarLookup = IsArrow;
1354 if (TypoCorrection Corrected = S.CorrectTypo(
1355 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
1356 Validator, Sema::CTK_ErrorRecovery, IDecl)) {
1357 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1360 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1361 << IDecl->getDeclName() << MemberName);
1363 // Figure out the class that declares the ivar.
1364 assert(!ClassDeclared);
1366 Decl *D = cast<Decl>(IV->getDeclContext());
1367 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1368 D = Category->getClassInterface();
1370 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1371 ClassDeclared = Implementation->getClassInterface();
1372 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1373 ClassDeclared = Interface;
1375 assert(ClassDeclared && "cannot query interface");
1378 IDecl->FindPropertyDeclaration(
1379 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1380 S.Diag(MemberLoc, diag::err_property_found_suggest)
1381 << Member << BaseExpr.get()->getType()
1382 << FixItHint::CreateReplacement(OpLoc, ".");
1386 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1387 << IDecl->getDeclName() << MemberName
1388 << BaseExpr.get()->getSourceRange();
1393 assert(ClassDeclared);
1395 // If the decl being referenced had an error, return an error for this
1396 // sub-expr without emitting another error, in order to avoid cascading
1398 if (IV->isInvalidDecl())
1401 // Check whether we can reference this field.
1402 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
1404 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1405 IV->getAccessControl() != ObjCIvarDecl::Package) {
1406 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1407 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1408 ClassOfMethodDecl = MD->getClassInterface();
1409 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1410 // Case of a c-function declared inside an objc implementation.
1411 // FIXME: For a c-style function nested inside an objc implementation
1412 // class, there is no implementation context available, so we pass
1413 // down the context as argument to this routine. Ideally, this context
1414 // need be passed down in the AST node and somehow calculated from the
1415 // AST for a function decl.
1416 if (ObjCImplementationDecl *IMPD =
1417 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1418 ClassOfMethodDecl = IMPD->getClassInterface();
1419 else if (ObjCCategoryImplDecl* CatImplClass =
1420 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1421 ClassOfMethodDecl = CatImplClass->getClassInterface();
1423 if (!S.getLangOpts().DebuggerSupport) {
1424 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1425 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1426 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1427 S.Diag(MemberLoc, diag::err_private_ivar_access)
1428 << IV->getDeclName();
1429 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1431 S.Diag(MemberLoc, diag::err_protected_ivar_access)
1432 << IV->getDeclName();
1436 if (S.getLangOpts().ObjCWeak) {
1437 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1438 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1439 if (UO->getOpcode() == UO_Deref)
1440 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1442 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1443 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1444 S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
1449 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1450 ObjCMethodFamily MF = MD->getMethodFamily();
1451 warn = (MF != OMF_init && MF != OMF_dealloc &&
1452 MF != OMF_finalize &&
1453 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1456 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1459 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1460 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1463 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1464 if (!S.isUnevaluatedContext() &&
1465 !S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1466 S.getCurFunction()->recordUseOfWeak(Result);
1472 // Objective-C property access.
1473 const ObjCObjectPointerType *OPT;
1474 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1475 if (!SS.isEmpty() && !SS.isInvalid()) {
1476 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1477 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
1481 // This actually uses the base as an r-value.
1482 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1483 if (BaseExpr.isInvalid())
1486 assert(S.Context.hasSameUnqualifiedType(BaseType,
1487 BaseExpr.get()->getType()));
1489 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1491 const ObjCObjectType *OT = OPT->getObjectType();
1493 // id, with and without qualifiers.
1494 if (OT->isObjCId()) {
1495 // Check protocols on qualified interfaces.
1496 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1498 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
1499 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1500 // Check the use of this declaration
1501 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
1504 return new (S.Context)
1505 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1506 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1509 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1510 Selector SetterSel =
1511 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1512 S.PP.getSelectorTable(),
1514 ObjCMethodDecl *SMD = nullptr;
1515 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1516 /*Property id*/ nullptr,
1517 SetterSel, S.Context))
1518 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1520 return new (S.Context)
1521 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1522 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1525 // Use of id.member can only be for a property reference. Do not
1526 // use the 'id' redefinition in this case.
1527 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1528 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1529 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1531 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1532 << MemberName << BaseType);
1535 // 'Class', unqualified only.
1536 if (OT->isObjCClass()) {
1537 // Only works in a method declaration (??!).
1538 ObjCMethodDecl *MD = S.getCurMethodDecl();
1540 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1541 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1542 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1547 // Also must look for a getter name which uses property syntax.
1548 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1549 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1553 ObjCMethodDecl *Getter;
1554 if ((Getter = IFace->lookupClassMethod(Sel))) {
1555 // Check the use of this method.
1556 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
1559 Getter = IFace->lookupPrivateMethod(Sel, false);
1560 // If we found a getter then this may be a valid dot-reference, we
1561 // will look for the matching setter, in case it is needed.
1562 Selector SetterSel =
1563 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1564 S.PP.getSelectorTable(),
1566 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1568 // If this reference is in an @implementation, also check for 'private'
1570 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1573 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1576 if (Getter || Setter) {
1577 return new (S.Context) ObjCPropertyRefExpr(
1578 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1579 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1582 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1583 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1584 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1586 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1587 << MemberName << BaseType);
1590 // Normal property access.
1591 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1592 MemberLoc, SourceLocation(), QualType(),
1596 // Handle 'field access' to vectors, such as 'V.xx'.
1597 if (BaseType->isExtVectorType()) {
1598 // FIXME: this expr should store IsArrow.
1599 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1604 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1605 VK = POE->getSyntacticForm()->getValueKind();
1607 VK = BaseExpr.get()->getValueKind();
1610 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1615 S.Context.getCanonicalType(BaseExpr.get()->getType()).getQualifiers();
1616 ret = S.Context.getQualifiedType(ret, BaseQ);
1618 return new (S.Context)
1619 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1622 // Adjust builtin-sel to the appropriate redefinition type if that's
1623 // not just a pointer to builtin-sel again.
1624 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1625 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1626 BaseExpr = S.ImpCastExprToType(
1627 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1628 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1629 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1635 // Recover from dot accesses to pointers, e.g.:
1638 // This is actually well-formed in two cases:
1639 // - 'type' is an Objective C type
1640 // - 'bar' is a pseudo-destructor name which happens to refer to
1641 // the appropriate pointer type
1642 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1643 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1644 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1645 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1646 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1647 << FixItHint::CreateReplacement(OpLoc, "->");
1649 // Recurse as an -> access.
1651 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1652 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1656 // If the user is trying to apply -> or . to a function name, it's probably
1657 // because they forgot parentheses to call that function.
1658 if (S.tryToRecoverWithCall(
1659 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1661 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1662 if (BaseExpr.isInvalid())
1664 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1665 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1666 ObjCImpDecl, HasTemplateArgs, TemplateKWLoc);
1669 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1670 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1675 /// The main callback when the parser finds something like
1676 /// expression . [nested-name-specifier] identifier
1677 /// expression -> [nested-name-specifier] identifier
1678 /// where 'identifier' encompasses a fairly broad spectrum of
1679 /// possibilities, including destructor and operator references.
1681 /// \param OpKind either tok::arrow or tok::period
1682 /// \param ObjCImpDecl the current Objective-C \@implementation
1683 /// decl; this is an ugly hack around the fact that Objective-C
1684 /// \@implementations aren't properly put in the context chain
1685 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1686 SourceLocation OpLoc,
1687 tok::TokenKind OpKind,
1689 SourceLocation TemplateKWLoc,
1691 Decl *ObjCImpDecl) {
1692 if (SS.isSet() && SS.isInvalid())
1695 // Warn about the explicit constructor calls Microsoft extension.
1696 if (getLangOpts().MicrosoftExt &&
1697 Id.getKind() == UnqualifiedIdKind::IK_ConstructorName)
1698 Diag(Id.getSourceRange().getBegin(),
1699 diag::ext_ms_explicit_constructor_call);
1701 TemplateArgumentListInfo TemplateArgsBuffer;
1703 // Decompose the name into its component parts.
1704 DeclarationNameInfo NameInfo;
1705 const TemplateArgumentListInfo *TemplateArgs;
1706 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1707 NameInfo, TemplateArgs);
1709 DeclarationName Name = NameInfo.getName();
1710 bool IsArrow = (OpKind == tok::arrow);
1712 NamedDecl *FirstQualifierInScope
1713 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
1715 // This is a postfix expression, so get rid of ParenListExprs.
1716 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1717 if (Result.isInvalid()) return ExprError();
1718 Base = Result.get();
1720 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1721 isDependentScopeSpecifier(SS)) {
1722 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1723 TemplateKWLoc, FirstQualifierInScope,
1724 NameInfo, TemplateArgs);
1727 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1728 ExprResult Res = BuildMemberReferenceExpr(
1729 Base, Base->getType(), OpLoc, IsArrow, SS, TemplateKWLoc,
1730 FirstQualifierInScope, NameInfo, TemplateArgs, S, &ExtraArgs);
1732 if (!Res.isInvalid() && isa<MemberExpr>(Res.get()))
1733 CheckMemberAccessOfNoDeref(cast<MemberExpr>(Res.get()));
1738 void Sema::CheckMemberAccessOfNoDeref(const MemberExpr *E) {
1739 QualType ResultTy = E->getType();
1741 // Do not warn on member accesses to arrays since this returns an array
1742 // lvalue and does not actually dereference memory.
1743 if (isa<ArrayType>(ResultTy))
1747 if (const auto *Ptr = dyn_cast<PointerType>(
1748 E->getBase()->getType().getDesugaredType(Context))) {
1749 if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
1750 ExprEvalContexts.back().PossibleDerefs.insert(E);
1756 Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1757 SourceLocation OpLoc, const CXXScopeSpec &SS,
1758 FieldDecl *Field, DeclAccessPair FoundDecl,
1759 const DeclarationNameInfo &MemberNameInfo) {
1760 // x.a is an l-value if 'a' has a reference type. Otherwise:
1761 // x.a is an l-value/x-value/pr-value if the base is (and note
1762 // that *x is always an l-value), except that if the base isn't
1763 // an ordinary object then we must have an rvalue.
1764 ExprValueKind VK = VK_LValue;
1765 ExprObjectKind OK = OK_Ordinary;
1767 if (BaseExpr->getObjectKind() == OK_Ordinary)
1768 VK = BaseExpr->getValueKind();
1772 if (VK != VK_RValue && Field->isBitField())
1775 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1776 QualType MemberType = Field->getType();
1777 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1778 MemberType = Ref->getPointeeType();
1781 QualType BaseType = BaseExpr->getType();
1782 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1784 Qualifiers BaseQuals = BaseType.getQualifiers();
1786 // GC attributes are never picked up by members.
1787 BaseQuals.removeObjCGCAttr();
1789 // CVR attributes from the base are picked up by members,
1790 // except that 'mutable' members don't pick up 'const'.
1791 if (Field->isMutable()) BaseQuals.removeConst();
1793 Qualifiers MemberQuals =
1794 Context.getCanonicalType(MemberType).getQualifiers();
1796 assert(!MemberQuals.hasAddressSpace());
1798 Qualifiers Combined = BaseQuals + MemberQuals;
1799 if (Combined != MemberQuals)
1800 MemberType = Context.getQualifiedType(MemberType, Combined);
1803 auto *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1804 if (!(CurMethod && CurMethod->isDefaulted()))
1805 UnusedPrivateFields.remove(Field);
1807 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1809 if (Base.isInvalid())
1812 // Build a reference to a private copy for non-static data members in
1813 // non-static member functions, privatized by OpenMP constructs.
1814 if (getLangOpts().OpenMP && IsArrow &&
1815 !CurContext->isDependentContext() &&
1816 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
1817 if (auto *PrivateCopy = isOpenMPCapturedDecl(Field)) {
1818 return getOpenMPCapturedExpr(PrivateCopy, VK, OK,
1819 MemberNameInfo.getLoc());
1823 return BuildMemberExpr(Base.get(), IsArrow, OpLoc, &SS,
1824 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1825 /*HadMultipleCandidates=*/false, MemberNameInfo,
1826 MemberType, VK, OK);
1829 /// Builds an implicit member access expression. The current context
1830 /// is known to be an instance method, and the given unqualified lookup
1831 /// set is known to contain only instance members, at least one of which
1832 /// is from an appropriate type.
1834 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1835 SourceLocation TemplateKWLoc,
1837 const TemplateArgumentListInfo *TemplateArgs,
1838 bool IsKnownInstance, const Scope *S) {
1839 assert(!R.empty() && !R.isAmbiguous());
1841 SourceLocation loc = R.getNameLoc();
1843 // If this is known to be an instance access, go ahead and build an
1844 // implicit 'this' expression now.
1845 // 'this' expression now.
1846 QualType ThisTy = getCurrentThisType();
1847 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1849 Expr *baseExpr = nullptr; // null signifies implicit access
1850 if (IsKnownInstance) {
1851 SourceLocation Loc = R.getNameLoc();
1852 if (SS.getRange().isValid())
1853 Loc = SS.getRange().getBegin();
1854 baseExpr = BuildCXXThisExpr(loc, ThisTy, /*IsImplicit=*/true);
1857 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1858 /*OpLoc*/ SourceLocation(),
1861 /*FirstQualifierInScope*/ nullptr,
1862 R, TemplateArgs, S);