1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis member access expressions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/ScopeInfo.h"
24 #include "clang/Sema/SemaInternal.h"
26 using namespace clang;
29 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
31 /// Determines if the given class is provably not derived from all of
32 /// the prospective base classes.
33 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
34 const BaseSet &Bases) {
35 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
36 return !Bases.count(Base->getCanonicalDecl());
38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
42 /// The reference is definitely not an instance member access.
45 /// The reference may be an implicit instance member access.
48 /// The reference may be to an instance member, but it might be invalid if
49 /// so, because the context is not an instance method.
50 IMA_Mixed_StaticContext,
52 /// The reference may be to an instance member, but it is invalid if
53 /// so, because the context is from an unrelated class.
56 /// The reference is definitely an implicit instance member access.
59 /// The reference may be to an unresolved using declaration.
62 /// The reference is a contextually-permitted abstract member reference.
65 /// The reference may be to an unresolved using declaration and the
66 /// context is not an instance method.
67 IMA_Unresolved_StaticContext,
69 // The reference refers to a field which is not a member of the containing
70 // class, which is allowed because we're in C++11 mode and the context is
72 IMA_Field_Uneval_Context,
74 /// All possible referrents are instance members and the current
75 /// context is not an instance method.
76 IMA_Error_StaticContext,
78 /// All possible referrents are instance members of an unrelated
83 /// The given lookup names class member(s) and is not being used for
84 /// an address-of-member expression. Classify the type of access
85 /// according to whether it's possible that this reference names an
86 /// instance member. This is best-effort in dependent contexts; it is okay to
87 /// conservatively answer "yes", in which case some errors will simply
88 /// not be caught until template-instantiation.
89 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
90 const LookupResult &R) {
91 assert(!R.empty() && (*R.begin())->isCXXClassMember());
93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
95 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
98 if (R.isUnresolvableResult())
99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
101 // Collect all the declaring classes of instance members we find.
102 bool hasNonInstance = false;
103 bool isField = false;
105 for (NamedDecl *D : R) {
106 // Look through any using decls.
107 D = D->getUnderlyingDecl();
109 if (D->isCXXInstanceMember()) {
110 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
111 isa<IndirectFieldDecl>(D);
113 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
114 Classes.insert(R->getCanonicalDecl());
116 hasNonInstance = true;
119 // If we didn't find any instance members, it can't be an implicit
124 // C++11 [expr.prim.general]p12:
125 // An id-expression that denotes a non-static data member or non-static
126 // member function of a class can only be used:
128 // - if that id-expression denotes a non-static data member and it
129 // appears in an unevaluated operand.
131 // This rule is specific to C++11. However, we also permit this form
132 // in unevaluated inline assembly operands, like the operand to a SIZE.
133 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
134 assert(!AbstractInstanceResult);
135 switch (SemaRef.ExprEvalContexts.back().Context) {
136 case Sema::Unevaluated:
137 case Sema::UnevaluatedList:
138 if (isField && SemaRef.getLangOpts().CPlusPlus11)
139 AbstractInstanceResult = IMA_Field_Uneval_Context;
142 case Sema::UnevaluatedAbstract:
143 AbstractInstanceResult = IMA_Abstract;
146 case Sema::DiscardedStatement:
147 case Sema::ConstantEvaluated:
148 case Sema::PotentiallyEvaluated:
149 case Sema::PotentiallyEvaluatedIfUsed:
153 // If the current context is not an instance method, it can't be
154 // an implicit member reference.
155 if (isStaticContext) {
157 return IMA_Mixed_StaticContext;
159 return AbstractInstanceResult ? AbstractInstanceResult
160 : IMA_Error_StaticContext;
163 CXXRecordDecl *contextClass;
164 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
165 contextClass = MD->getParent()->getCanonicalDecl();
167 contextClass = cast<CXXRecordDecl>(DC);
169 // [class.mfct.non-static]p3:
170 // ...is used in the body of a non-static member function of class X,
171 // if name lookup (3.4.1) resolves the name in the id-expression to a
172 // non-static non-type member of some class C [...]
173 // ...if C is not X or a base class of X, the class member access expression
175 if (R.getNamingClass() &&
176 contextClass->getCanonicalDecl() !=
177 R.getNamingClass()->getCanonicalDecl()) {
178 // If the naming class is not the current context, this was a qualified
179 // member name lookup, and it's sufficient to check that we have the naming
180 // class as a base class.
182 Classes.insert(R.getNamingClass()->getCanonicalDecl());
185 // If we can prove that the current context is unrelated to all the
186 // declaring classes, it can't be an implicit member reference (in
187 // which case it's an error if any of those members are selected).
188 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
189 return hasNonInstance ? IMA_Mixed_Unrelated :
190 AbstractInstanceResult ? AbstractInstanceResult :
193 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
196 /// Diagnose a reference to a field with no object available.
197 static void diagnoseInstanceReference(Sema &SemaRef,
198 const CXXScopeSpec &SS,
200 const DeclarationNameInfo &nameInfo) {
201 SourceLocation Loc = nameInfo.getLoc();
202 SourceRange Range(Loc);
203 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
205 // Look through using shadow decls and aliases.
206 Rep = Rep->getUnderlyingDecl();
208 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
209 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
210 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
211 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
213 bool InStaticMethod = Method && Method->isStatic();
214 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
216 if (IsField && InStaticMethod)
217 // "invalid use of member 'x' in static member function"
218 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
219 << Range << nameInfo.getName();
220 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
221 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
222 // Unqualified lookup in a non-static member function found a member of an
224 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
225 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
227 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
228 << nameInfo.getName() << Range;
230 SemaRef.Diag(Loc, diag::err_member_call_without_object)
234 /// Builds an expression which might be an implicit member expression.
236 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
237 SourceLocation TemplateKWLoc,
239 const TemplateArgumentListInfo *TemplateArgs,
241 switch (ClassifyImplicitMemberAccess(*this, R)) {
243 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
246 case IMA_Mixed_Unrelated:
248 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
251 case IMA_Field_Uneval_Context:
252 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
253 << R.getLookupNameInfo().getName();
257 case IMA_Mixed_StaticContext:
258 case IMA_Unresolved_StaticContext:
259 if (TemplateArgs || TemplateKWLoc.isValid())
260 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
261 return BuildDeclarationNameExpr(SS, R, false);
263 case IMA_Error_StaticContext:
264 case IMA_Error_Unrelated:
265 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
266 R.getLookupNameInfo());
270 llvm_unreachable("unexpected instance member access kind");
273 /// Determine whether input char is from rgba component set.
287 /// Check an ext-vector component access expression.
289 /// VK should be set in advance to the value kind of the base
292 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
293 SourceLocation OpLoc, const IdentifierInfo *CompName,
294 SourceLocation CompLoc) {
295 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
298 // FIXME: This logic can be greatly simplified by splitting it along
299 // halving/not halving and reworking the component checking.
300 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
302 // The vector accessor can't exceed the number of elements.
303 const char *compStr = CompName->getNameStart();
305 // This flag determines whether or not the component is one of the four
306 // special names that indicate a subset of exactly half the elements are
308 bool HalvingSwizzle = false;
310 // This flag determines whether or not CompName has an 's' char prefix,
311 // indicating that it is a string of hex values to be used as vector indices.
312 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
314 bool HasRepeated = false;
315 bool HasIndex[16] = {};
319 // Check that we've found one of the special components, or that the component
320 // names must come from the same set.
321 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
322 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
323 HalvingSwizzle = true;
324 } else if (!HexSwizzle &&
325 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
326 bool HasRGBA = IsRGBA(*compStr);
328 // Ensure that xyzw and rgba components don't intermingle.
329 if (HasRGBA != IsRGBA(*compStr))
331 if (HasIndex[Idx]) HasRepeated = true;
332 HasIndex[Idx] = true;
334 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
336 // Emit a warning if an rgba selector is used earlier than OpenCL 2.2
337 if (HasRGBA || (*compStr && IsRGBA(*compStr))) {
338 if (S.getLangOpts().OpenCL && S.getLangOpts().OpenCLVersion < 220) {
339 const char *DiagBegin = HasRGBA ? CompName->getNameStart() : compStr;
340 S.Diag(OpLoc, diag::ext_opencl_ext_vector_type_rgba_selector)
341 << StringRef(DiagBegin, 1)
342 << S.getLangOpts().OpenCLVersion << SourceRange(CompLoc);
346 if (HexSwizzle) compStr++;
347 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
348 if (HasIndex[Idx]) HasRepeated = true;
349 HasIndex[Idx] = true;
354 if (!HalvingSwizzle && *compStr) {
355 // We didn't get to the end of the string. This means the component names
356 // didn't come from the same set *or* we encountered an illegal name.
357 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
358 << StringRef(compStr, 1) << SourceRange(CompLoc);
362 // Ensure no component accessor exceeds the width of the vector type it
364 if (!HalvingSwizzle) {
365 compStr = CompName->getNameStart();
371 if (!vecType->isAccessorWithinNumElements(*compStr++, HexSwizzle)) {
372 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
373 << baseType << SourceRange(CompLoc);
379 // The component accessor looks fine - now we need to compute the actual type.
380 // The vector type is implied by the component accessor. For example,
381 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
382 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
383 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
384 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
385 : CompName->getLength();
390 return vecType->getElementType();
392 if (HasRepeated) VK = VK_RValue;
394 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
395 // Now look up the TypeDefDecl from the vector type. Without this,
396 // diagostics look bad. We want extended vector types to appear built-in.
397 for (Sema::ExtVectorDeclsType::iterator
398 I = S.ExtVectorDecls.begin(S.getExternalSource()),
399 E = S.ExtVectorDecls.end();
401 if ((*I)->getUnderlyingType() == VT)
402 return S.Context.getTypedefType(*I);
405 return VT; // should never get here (a typedef type should always be found).
408 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
409 IdentifierInfo *Member,
411 ASTContext &Context) {
413 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
414 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
416 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
419 for (const auto *I : PDecl->protocols()) {
420 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
427 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
428 IdentifierInfo *Member,
430 ASTContext &Context) {
431 // Check protocols on qualified interfaces.
432 Decl *GDecl = nullptr;
433 for (const auto *I : QIdTy->quals()) {
435 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
436 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
440 // Also must look for a getter or setter name which uses property syntax.
441 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
447 for (const auto *I : QIdTy->quals()) {
448 // Search in the protocol-qualifier list of current protocol.
449 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
458 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
459 bool IsArrow, SourceLocation OpLoc,
460 const CXXScopeSpec &SS,
461 SourceLocation TemplateKWLoc,
462 NamedDecl *FirstQualifierInScope,
463 const DeclarationNameInfo &NameInfo,
464 const TemplateArgumentListInfo *TemplateArgs) {
465 // Even in dependent contexts, try to diagnose base expressions with
466 // obviously wrong types, e.g.:
471 // In Obj-C++, however, the above expression is valid, since it could be
472 // accessing the 'f' property if T is an Obj-C interface. The extra check
473 // allows this, while still reporting an error if T is a struct pointer.
475 const PointerType *PT = BaseType->getAs<PointerType>();
476 if (PT && (!getLangOpts().ObjC1 ||
477 PT->getPointeeType()->isRecordType())) {
478 assert(BaseExpr && "cannot happen with implicit member accesses");
479 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
480 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
485 assert(BaseType->isDependentType() ||
486 NameInfo.getName().isDependentName() ||
487 isDependentScopeSpecifier(SS));
489 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
490 // must have pointer type, and the accessed type is the pointee.
491 return CXXDependentScopeMemberExpr::Create(
492 Context, BaseExpr, BaseType, IsArrow, OpLoc,
493 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
494 NameInfo, TemplateArgs);
497 /// We know that the given qualified member reference points only to
498 /// declarations which do not belong to the static type of the base
499 /// expression. Diagnose the problem.
500 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
503 const CXXScopeSpec &SS,
505 const DeclarationNameInfo &nameInfo) {
506 // If this is an implicit member access, use a different set of
509 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
511 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
512 << SS.getRange() << rep << BaseType;
515 // Check whether the declarations we found through a nested-name
516 // specifier in a member expression are actually members of the base
517 // type. The restriction here is:
520 // ... In these cases, the id-expression shall name a
521 // member of the class or of one of its base classes.
523 // So it's perfectly legitimate for the nested-name specifier to name
524 // an unrelated class, and for us to find an overload set including
525 // decls from classes which are not superclasses, as long as the decl
526 // we actually pick through overload resolution is from a superclass.
527 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
529 const CXXScopeSpec &SS,
530 const LookupResult &R) {
531 CXXRecordDecl *BaseRecord =
532 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
534 // We can't check this yet because the base type is still
536 assert(BaseType->isDependentType());
540 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
541 // If this is an implicit member reference and we find a
542 // non-instance member, it's not an error.
543 if (!BaseExpr && !(*I)->isCXXInstanceMember())
546 // Note that we use the DC of the decl, not the underlying decl.
547 DeclContext *DC = (*I)->getDeclContext();
548 while (DC->isTransparentContext())
549 DC = DC->getParent();
554 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
555 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
556 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
560 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
561 R.getRepresentativeDecl(),
562 R.getLookupNameInfo());
568 // Callback to only accept typo corrections that are either a ValueDecl or a
569 // FunctionTemplateDecl and are declared in the current record or, for a C++
570 // classes, one of its base classes.
571 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
573 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
574 : Record(RTy->getDecl()) {
575 // Don't add bare keywords to the consumer since they will always fail
576 // validation by virtue of not being associated with any decls.
577 WantTypeSpecifiers = false;
578 WantExpressionKeywords = false;
579 WantCXXNamedCasts = false;
580 WantFunctionLikeCasts = false;
581 WantRemainingKeywords = false;
584 bool ValidateCandidate(const TypoCorrection &candidate) override {
585 NamedDecl *ND = candidate.getCorrectionDecl();
586 // Don't accept candidates that cannot be member functions, constants,
587 // variables, or templates.
588 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
591 // Accept candidates that occur in the current record.
592 if (Record->containsDecl(ND))
595 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
596 // Accept candidates that occur in any of the current class' base classes.
597 for (const auto &BS : RD->bases()) {
598 if (const RecordType *BSTy =
599 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
600 if (BSTy->getDecl()->containsDecl(ND))
610 const RecordDecl *const Record;
615 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
617 const RecordType *RTy,
618 SourceLocation OpLoc, bool IsArrow,
619 CXXScopeSpec &SS, bool HasTemplateArgs,
621 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
622 RecordDecl *RDecl = RTy->getDecl();
623 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
624 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
625 diag::err_typecheck_incomplete_tag,
629 if (HasTemplateArgs) {
630 // LookupTemplateName doesn't expect these both to exist simultaneously.
631 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
634 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
638 DeclContext *DC = RDecl;
640 // If the member name was a qualified-id, look into the
641 // nested-name-specifier.
642 DC = SemaRef.computeDeclContext(SS, false);
644 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
645 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
646 << SS.getRange() << DC;
650 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
652 if (!isa<TypeDecl>(DC)) {
653 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
654 << DC << SS.getRange();
659 // The record definition is complete, now look up the member.
660 SemaRef.LookupQualifiedName(R, DC, SS);
665 DeclarationName Typo = R.getLookupName();
666 SourceLocation TypoLoc = R.getNameLoc();
670 DeclarationNameInfo NameInfo;
671 Sema::LookupNameKind LookupKind;
672 Sema::RedeclarationKind Redecl;
674 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
675 R.isForRedeclaration() ? Sema::ForRedeclaration
676 : Sema::NotForRedeclaration};
677 TE = SemaRef.CorrectTypoDelayed(
678 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
679 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
680 [=, &SemaRef](const TypoCorrection &TC) {
682 assert(!TC.isKeyword() &&
683 "Got a keyword as a correction for a member!");
684 bool DroppedSpecifier =
685 TC.WillReplaceSpecifier() &&
686 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
687 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
688 << Typo << DC << DroppedSpecifier
691 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
694 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
695 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
696 R.clear(); // Ensure there's no decls lingering in the shared state.
697 R.suppressDiagnostics();
698 R.setLookupName(TC.getCorrection());
699 for (NamedDecl *ND : TC)
702 return SemaRef.BuildMemberReferenceExpr(
703 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
704 nullptr, R, nullptr, nullptr);
706 Sema::CTK_ErrorRecovery, DC);
711 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
712 ExprResult &BaseExpr, bool &IsArrow,
713 SourceLocation OpLoc, CXXScopeSpec &SS,
714 Decl *ObjCImpDecl, bool HasTemplateArgs);
717 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
718 SourceLocation OpLoc, bool IsArrow,
720 SourceLocation TemplateKWLoc,
721 NamedDecl *FirstQualifierInScope,
722 const DeclarationNameInfo &NameInfo,
723 const TemplateArgumentListInfo *TemplateArgs,
725 ActOnMemberAccessExtraArgs *ExtraArgs) {
726 if (BaseType->isDependentType() ||
727 (SS.isSet() && isDependentScopeSpecifier(SS)))
728 return ActOnDependentMemberExpr(Base, BaseType,
730 SS, TemplateKWLoc, FirstQualifierInScope,
731 NameInfo, TemplateArgs);
733 LookupResult R(*this, NameInfo, LookupMemberName);
735 // Implicit member accesses.
737 TypoExpr *TE = nullptr;
738 QualType RecordTy = BaseType;
739 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
740 if (LookupMemberExprInRecord(*this, R, nullptr,
741 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
742 SS, TemplateArgs != nullptr, TE))
747 // Explicit member accesses.
749 ExprResult BaseResult = Base;
750 ExprResult Result = LookupMemberExpr(
751 *this, R, BaseResult, IsArrow, OpLoc, SS,
752 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
753 TemplateArgs != nullptr);
755 if (BaseResult.isInvalid())
757 Base = BaseResult.get();
759 if (Result.isInvalid())
765 // LookupMemberExpr can modify Base, and thus change BaseType
766 BaseType = Base->getType();
769 return BuildMemberReferenceExpr(Base, BaseType,
770 OpLoc, IsArrow, SS, TemplateKWLoc,
771 FirstQualifierInScope, R, TemplateArgs, S,
776 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
778 IndirectFieldDecl *indirectField,
779 DeclAccessPair foundDecl,
780 Expr *baseObjectExpr,
781 SourceLocation opLoc) {
782 // First, build the expression that refers to the base object.
784 bool baseObjectIsPointer = false;
785 Qualifiers baseQuals;
787 // Case 1: the base of the indirect field is not a field.
788 VarDecl *baseVariable = indirectField->getVarDecl();
789 CXXScopeSpec EmptySS;
791 assert(baseVariable->getType()->isRecordType());
793 // In principle we could have a member access expression that
794 // accesses an anonymous struct/union that's a static member of
795 // the base object's class. However, under the current standard,
796 // static data members cannot be anonymous structs or unions.
797 // Supporting this is as easy as building a MemberExpr here.
798 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
800 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
803 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
804 if (result.isInvalid()) return ExprError();
806 baseObjectExpr = result.get();
807 baseObjectIsPointer = false;
808 baseQuals = baseObjectExpr->getType().getQualifiers();
810 // Case 2: the base of the indirect field is a field and the user
811 // wrote a member expression.
812 } else if (baseObjectExpr) {
813 // The caller provided the base object expression. Determine
814 // whether its a pointer and whether it adds any qualifiers to the
815 // anonymous struct/union fields we're looking into.
816 QualType objectType = baseObjectExpr->getType();
818 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
819 baseObjectIsPointer = true;
820 objectType = ptr->getPointeeType();
822 baseObjectIsPointer = false;
824 baseQuals = objectType.getQualifiers();
826 // Case 3: the base of the indirect field is a field and we should
827 // build an implicit member access.
829 // We've found a member of an anonymous struct/union that is
830 // inside a non-anonymous struct/union, so in a well-formed
831 // program our base object expression is "this".
832 QualType ThisTy = getCurrentThisType();
833 if (ThisTy.isNull()) {
834 Diag(loc, diag::err_invalid_member_use_in_static_method)
835 << indirectField->getDeclName();
839 // Our base object expression is "this".
840 CheckCXXThisCapture(loc);
842 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
843 baseObjectIsPointer = true;
844 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
847 // Build the implicit member references to the field of the
848 // anonymous struct/union.
849 Expr *result = baseObjectExpr;
850 IndirectFieldDecl::chain_iterator
851 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
853 // Build the first member access in the chain with full information.
855 FieldDecl *field = cast<FieldDecl>(*FI);
857 // Make a nameInfo that properly uses the anonymous name.
858 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
860 result = BuildFieldReferenceExpr(result, baseObjectIsPointer,
861 SourceLocation(), EmptySS, field,
862 foundDecl, memberNameInfo).get();
866 // FIXME: check qualified member access
869 // In all cases, we should now skip the first declaration in the chain.
873 FieldDecl *field = cast<FieldDecl>(*FI++);
875 // FIXME: these are somewhat meaningless
876 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
877 DeclAccessPair fakeFoundDecl =
878 DeclAccessPair::make(field, field->getAccess());
881 BuildFieldReferenceExpr(result, /*isarrow*/ false, SourceLocation(),
882 (FI == FEnd ? SS : EmptySS), field,
883 fakeFoundDecl, memberNameInfo)
891 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
892 const CXXScopeSpec &SS,
894 const DeclarationNameInfo &NameInfo) {
895 // Property names are always simple identifiers and therefore never
896 // require any interesting additional storage.
897 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
898 S.Context.PseudoObjectTy, VK_LValue,
899 SS.getWithLocInContext(S.Context),
903 /// \brief Build a MemberExpr AST node.
904 static MemberExpr *BuildMemberExpr(
905 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
906 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
907 ValueDecl *Member, DeclAccessPair FoundDecl,
908 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
909 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
910 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
911 MemberExpr *E = MemberExpr::Create(
912 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
913 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
914 SemaRef.MarkMemberReferenced(E);
918 /// \brief Determine if the given scope is within a function-try-block handler.
919 static bool IsInFnTryBlockHandler(const Scope *S) {
920 // Walk the scope stack until finding a FnTryCatchScope, or leave the
921 // function scope. If a FnTryCatchScope is found, check whether the TryScope
922 // flag is set. If it is not, it's a function-try-block handler.
923 for (; S != S->getFnParent(); S = S->getParent()) {
924 if (S->getFlags() & Scope::FnTryCatchScope)
925 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
931 getVarTemplateSpecialization(Sema &S, VarTemplateDecl *VarTempl,
932 const TemplateArgumentListInfo *TemplateArgs,
933 const DeclarationNameInfo &MemberNameInfo,
934 SourceLocation TemplateKWLoc) {
937 S.Diag(MemberNameInfo.getBeginLoc(), diag::err_template_decl_ref)
938 << /*Variable template*/ 1 << MemberNameInfo.getName()
939 << MemberNameInfo.getSourceRange();
941 S.Diag(VarTempl->getLocation(), diag::note_template_decl_here);
945 DeclResult VDecl = S.CheckVarTemplateId(
946 VarTempl, TemplateKWLoc, MemberNameInfo.getLoc(), *TemplateArgs);
947 if (VDecl.isInvalid())
949 VarDecl *Var = cast<VarDecl>(VDecl.get());
950 if (!Var->getTemplateSpecializationKind())
951 Var->setTemplateSpecializationKind(TSK_ImplicitInstantiation,
952 MemberNameInfo.getLoc());
957 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
958 SourceLocation OpLoc, bool IsArrow,
959 const CXXScopeSpec &SS,
960 SourceLocation TemplateKWLoc,
961 NamedDecl *FirstQualifierInScope,
963 const TemplateArgumentListInfo *TemplateArgs,
965 bool SuppressQualifierCheck,
966 ActOnMemberAccessExtraArgs *ExtraArgs) {
967 QualType BaseType = BaseExprType;
969 assert(BaseType->isPointerType());
970 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
972 R.setBaseObjectType(BaseType);
974 // C++1z [expr.ref]p2:
975 // For the first option (dot) the first expression shall be a glvalue [...]
976 if (!IsArrow && BaseExpr->isRValue()) {
977 ExprResult Converted = TemporaryMaterializationConversion(BaseExpr);
978 if (Converted.isInvalid())
980 BaseExpr = Converted.get();
983 LambdaScopeInfo *const CurLSI = getCurLambda();
984 // If this is an implicit member reference and the overloaded
985 // name refers to both static and non-static member functions
986 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
987 // check if we should/can capture 'this'...
988 // Keep this example in mind:
991 // static void f(double) { }
994 // auto L = [=](auto a) {
995 // return [](int i) {
996 // return [=](auto b) {
998 // //f(decltype(a){});
1004 // N(5.32); // OK, must not error.
1009 if (!BaseExpr && CurLSI) {
1010 SourceLocation Loc = R.getNameLoc();
1011 if (SS.getRange().isValid())
1012 Loc = SS.getRange().getBegin();
1013 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
1014 // If the enclosing function is not dependent, then this lambda is
1015 // capture ready, so if we can capture this, do so.
1016 if (!EnclosingFunctionCtx->isDependentContext()) {
1017 // If the current lambda and all enclosing lambdas can capture 'this' -
1018 // then go ahead and capture 'this' (since our unresolved overload set
1019 // contains both static and non-static member functions).
1020 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
1021 CheckCXXThisCapture(Loc);
1022 } else if (CurContext->isDependentContext()) {
1023 // ... since this is an implicit member reference, that might potentially
1024 // involve a 'this' capture, mark 'this' for potential capture in
1025 // enclosing lambdas.
1026 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
1027 CurLSI->addPotentialThisCapture(Loc);
1030 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
1031 DeclarationName MemberName = MemberNameInfo.getName();
1032 SourceLocation MemberLoc = MemberNameInfo.getLoc();
1034 if (R.isAmbiguous())
1037 // [except.handle]p10: Referring to any non-static member or base class of an
1038 // object in the handler for a function-try-block of a constructor or
1039 // destructor for that object results in undefined behavior.
1040 const auto *FD = getCurFunctionDecl();
1041 if (S && BaseExpr && FD &&
1042 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
1043 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
1044 IsInFnTryBlockHandler(S))
1045 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
1046 << isa<CXXDestructorDecl>(FD);
1049 // Rederive where we looked up.
1050 DeclContext *DC = (SS.isSet()
1051 ? computeDeclContext(SS, false)
1052 : BaseType->getAs<RecordType>()->getDecl());
1055 ExprResult RetryExpr;
1056 if (!IsArrow && BaseExpr) {
1057 SFINAETrap Trap(*this, true);
1058 ParsedType ObjectType;
1059 bool MayBePseudoDestructor = false;
1060 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1061 OpLoc, tok::arrow, ObjectType,
1062 MayBePseudoDestructor);
1063 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1064 CXXScopeSpec TempSS(SS);
1065 RetryExpr = ActOnMemberAccessExpr(
1066 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
1067 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
1069 if (Trap.hasErrorOccurred())
1070 RetryExpr = ExprError();
1072 if (RetryExpr.isUsable()) {
1073 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1074 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1079 Diag(R.getNameLoc(), diag::err_no_member)
1081 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1085 // Diagnose lookups that find only declarations from a non-base
1086 // type. This is possible for either qualified lookups (which may
1087 // have been qualified with an unrelated type) or implicit member
1088 // expressions (which were found with unqualified lookup and thus
1089 // may have come from an enclosing scope). Note that it's okay for
1090 // lookup to find declarations from a non-base type as long as those
1091 // aren't the ones picked by overload resolution.
1092 if ((SS.isSet() || !BaseExpr ||
1093 (isa<CXXThisExpr>(BaseExpr) &&
1094 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1095 !SuppressQualifierCheck &&
1096 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1099 // Construct an unresolved result if we in fact got an unresolved
1101 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1102 // Suppress any lookup-related diagnostics; we'll do these when we
1104 R.suppressDiagnostics();
1106 UnresolvedMemberExpr *MemExpr
1107 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1108 BaseExpr, BaseExprType,
1110 SS.getWithLocInContext(Context),
1111 TemplateKWLoc, MemberNameInfo,
1112 TemplateArgs, R.begin(), R.end());
1117 assert(R.isSingleResult());
1118 DeclAccessPair FoundDecl = R.begin().getPair();
1119 NamedDecl *MemberDecl = R.getFoundDecl();
1121 // FIXME: diagnose the presence of template arguments now.
1123 // If the decl being referenced had an error, return an error for this
1124 // sub-expr without emitting another error, in order to avoid cascading
1126 if (MemberDecl->isInvalidDecl())
1129 // Handle the implicit-member-access case.
1131 // If this is not an instance member, convert to a non-member access.
1132 if (!MemberDecl->isCXXInstanceMember()) {
1133 // If this is a variable template, get the instantiated variable
1134 // declaration corresponding to the supplied template arguments
1135 // (while emitting diagnostics as necessary) that will be referenced
1136 // by this expression.
1137 assert((!TemplateArgs || isa<VarTemplateDecl>(MemberDecl)) &&
1138 "How did we get template arguments here sans a variable template");
1139 if (isa<VarTemplateDecl>(MemberDecl)) {
1140 MemberDecl = getVarTemplateSpecialization(
1141 *this, cast<VarTemplateDecl>(MemberDecl), TemplateArgs,
1142 R.getLookupNameInfo(), TemplateKWLoc);
1146 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl,
1147 FoundDecl, TemplateArgs);
1149 SourceLocation Loc = R.getNameLoc();
1150 if (SS.getRange().isValid())
1151 Loc = SS.getRange().getBegin();
1152 CheckCXXThisCapture(Loc);
1153 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1156 // Check the use of this member.
1157 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1160 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1161 return BuildFieldReferenceExpr(BaseExpr, IsArrow, OpLoc, SS, FD, FoundDecl,
1164 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1165 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1168 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1169 // We may have found a field within an anonymous union or struct
1170 // (C++ [class.union]).
1171 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
1172 FoundDecl, BaseExpr,
1175 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
1176 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1177 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1178 Var->getType().getNonReferenceType(), VK_LValue,
1182 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1183 ExprValueKind valueKind;
1185 if (MemberFn->isInstance()) {
1186 valueKind = VK_RValue;
1187 type = Context.BoundMemberTy;
1189 valueKind = VK_LValue;
1190 type = MemberFn->getType();
1193 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1194 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1195 type, valueKind, OK_Ordinary);
1197 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1199 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1200 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1201 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1202 Enum->getType(), VK_RValue, OK_Ordinary);
1204 if (VarTemplateDecl *VarTempl = dyn_cast<VarTemplateDecl>(MemberDecl)) {
1205 if (VarDecl *Var = getVarTemplateSpecialization(
1206 *this, VarTempl, TemplateArgs, MemberNameInfo, TemplateKWLoc))
1207 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1208 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1209 Var->getType().getNonReferenceType(), VK_LValue,
1214 // We found something that we didn't expect. Complain.
1215 if (isa<TypeDecl>(MemberDecl))
1216 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1217 << MemberName << BaseType << int(IsArrow);
1219 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1220 << MemberName << BaseType << int(IsArrow);
1222 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1224 R.suppressDiagnostics();
1228 /// Given that normal member access failed on the given expression,
1229 /// and given that the expression's type involves builtin-id or
1230 /// builtin-Class, decide whether substituting in the redefinition
1231 /// types would be profitable. The redefinition type is whatever
1232 /// this translation unit tried to typedef to id/Class; we store
1233 /// it to the side and then re-use it in places like this.
1234 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1235 const ObjCObjectPointerType *opty
1236 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1237 if (!opty) return false;
1239 const ObjCObjectType *ty = opty->getObjectType();
1242 if (ty->isObjCId()) {
1243 redef = S.Context.getObjCIdRedefinitionType();
1244 } else if (ty->isObjCClass()) {
1245 redef = S.Context.getObjCClassRedefinitionType();
1250 // Do the substitution as long as the redefinition type isn't just a
1251 // possibly-qualified pointer to builtin-id or builtin-Class again.
1252 opty = redef->getAs<ObjCObjectPointerType>();
1253 if (opty && !opty->getObjectType()->getInterface())
1256 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1260 static bool isRecordType(QualType T) {
1261 return T->isRecordType();
1263 static bool isPointerToRecordType(QualType T) {
1264 if (const PointerType *PT = T->getAs<PointerType>())
1265 return PT->getPointeeType()->isRecordType();
1269 /// Perform conversions on the LHS of a member access expression.
1271 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1272 if (IsArrow && !Base->getType()->isFunctionType())
1273 return DefaultFunctionArrayLvalueConversion(Base);
1275 return CheckPlaceholderExpr(Base);
1278 /// Look up the given member of the given non-type-dependent
1279 /// expression. This can return in one of two ways:
1280 /// * If it returns a sentinel null-but-valid result, the caller will
1281 /// assume that lookup was performed and the results written into
1282 /// the provided structure. It will take over from there.
1283 /// * Otherwise, the returned expression will be produced in place of
1284 /// an ordinary member expression.
1286 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1287 /// fixed for ObjC++.
1288 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1289 ExprResult &BaseExpr, bool &IsArrow,
1290 SourceLocation OpLoc, CXXScopeSpec &SS,
1291 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1292 assert(BaseExpr.get() && "no base expression");
1294 // Perform default conversions.
1295 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1296 if (BaseExpr.isInvalid())
1299 QualType BaseType = BaseExpr.get()->getType();
1300 assert(!BaseType->isDependentType());
1302 DeclarationName MemberName = R.getLookupName();
1303 SourceLocation MemberLoc = R.getNameLoc();
1305 // For later type-checking purposes, turn arrow accesses into dot
1306 // accesses. The only access type we support that doesn't follow
1307 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1308 // and those never use arrows, so this is unaffected.
1310 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1311 BaseType = Ptr->getPointeeType();
1312 else if (const ObjCObjectPointerType *Ptr
1313 = BaseType->getAs<ObjCObjectPointerType>())
1314 BaseType = Ptr->getPointeeType();
1315 else if (BaseType->isRecordType()) {
1316 // Recover from arrow accesses to records, e.g.:
1317 // struct MyRecord foo;
1319 // This is actually well-formed in C++ if MyRecord has an
1320 // overloaded operator->, but that should have been dealt with
1321 // by now--or a diagnostic message already issued if a problem
1322 // was encountered while looking for the overloaded operator->.
1323 if (!S.getLangOpts().CPlusPlus) {
1324 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1325 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1326 << FixItHint::CreateReplacement(OpLoc, ".");
1329 } else if (BaseType->isFunctionType()) {
1332 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1333 << BaseType << BaseExpr.get()->getSourceRange();
1338 // Handle field access to simple records.
1339 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1340 TypoExpr *TE = nullptr;
1341 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
1342 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
1345 // Returning valid-but-null is how we indicate to the caller that
1346 // the lookup result was filled in. If typo correction was attempted and
1347 // failed, the lookup result will have been cleared--that combined with the
1348 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1349 return ExprResult(TE);
1352 // Handle ivar access to Objective-C objects.
1353 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1354 if (!SS.isEmpty() && !SS.isInvalid()) {
1355 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1356 << 1 << SS.getScopeRep()
1357 << FixItHint::CreateRemoval(SS.getRange());
1361 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1363 // There are three cases for the base type:
1364 // - builtin id (qualified or unqualified)
1365 // - builtin Class (qualified or unqualified)
1367 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1369 if (S.getLangOpts().ObjCAutoRefCount &&
1370 (OTy->isObjCId() || OTy->isObjCClass()))
1372 // There's an implicit 'isa' ivar on all objects.
1373 // But we only actually find it this way on objects of type 'id',
1375 if (OTy->isObjCId() && Member->isStr("isa"))
1376 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1377 OpLoc, S.Context.getObjCClassType());
1378 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1379 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1380 ObjCImpDecl, HasTemplateArgs);
1384 if (S.RequireCompleteType(OpLoc, BaseType,
1385 diag::err_typecheck_incomplete_tag,
1389 ObjCInterfaceDecl *ClassDeclared = nullptr;
1390 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1393 // Attempt to correct for typos in ivar names.
1394 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1395 Validator->IsObjCIvarLookup = IsArrow;
1396 if (TypoCorrection Corrected = S.CorrectTypo(
1397 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
1398 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
1399 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1402 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1403 << IDecl->getDeclName() << MemberName);
1405 // Figure out the class that declares the ivar.
1406 assert(!ClassDeclared);
1408 Decl *D = cast<Decl>(IV->getDeclContext());
1409 if (auto *Category = dyn_cast<ObjCCategoryDecl>(D))
1410 D = Category->getClassInterface();
1412 if (auto *Implementation = dyn_cast<ObjCImplementationDecl>(D))
1413 ClassDeclared = Implementation->getClassInterface();
1414 else if (auto *Interface = dyn_cast<ObjCInterfaceDecl>(D))
1415 ClassDeclared = Interface;
1417 assert(ClassDeclared && "cannot query interface");
1420 IDecl->FindPropertyDeclaration(
1421 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
1422 S.Diag(MemberLoc, diag::err_property_found_suggest)
1423 << Member << BaseExpr.get()->getType()
1424 << FixItHint::CreateReplacement(OpLoc, ".");
1428 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1429 << IDecl->getDeclName() << MemberName
1430 << BaseExpr.get()->getSourceRange();
1435 assert(ClassDeclared);
1437 // If the decl being referenced had an error, return an error for this
1438 // sub-expr without emitting another error, in order to avoid cascading
1440 if (IV->isInvalidDecl())
1443 // Check whether we can reference this field.
1444 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
1446 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1447 IV->getAccessControl() != ObjCIvarDecl::Package) {
1448 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1449 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1450 ClassOfMethodDecl = MD->getClassInterface();
1451 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1452 // Case of a c-function declared inside an objc implementation.
1453 // FIXME: For a c-style function nested inside an objc implementation
1454 // class, there is no implementation context available, so we pass
1455 // down the context as argument to this routine. Ideally, this context
1456 // need be passed down in the AST node and somehow calculated from the
1457 // AST for a function decl.
1458 if (ObjCImplementationDecl *IMPD =
1459 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1460 ClassOfMethodDecl = IMPD->getClassInterface();
1461 else if (ObjCCategoryImplDecl* CatImplClass =
1462 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1463 ClassOfMethodDecl = CatImplClass->getClassInterface();
1465 if (!S.getLangOpts().DebuggerSupport) {
1466 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1467 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1468 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1469 S.Diag(MemberLoc, diag::err_private_ivar_access)
1470 << IV->getDeclName();
1471 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1473 S.Diag(MemberLoc, diag::err_protected_ivar_access)
1474 << IV->getDeclName();
1478 if (S.getLangOpts().ObjCAutoRefCount) {
1479 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1480 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1481 if (UO->getOpcode() == UO_Deref)
1482 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1484 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1485 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1486 S.Diag(DE->getLocation(), diag::err_arc_weak_ivar_access);
1491 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1492 ObjCMethodFamily MF = MD->getMethodFamily();
1493 warn = (MF != OMF_init && MF != OMF_dealloc &&
1494 MF != OMF_finalize &&
1495 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1498 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1501 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1502 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1505 if (S.getLangOpts().ObjCAutoRefCount) {
1506 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1507 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1508 S.recordUseOfEvaluatedWeak(Result);
1515 // Objective-C property access.
1516 const ObjCObjectPointerType *OPT;
1517 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1518 if (!SS.isEmpty() && !SS.isInvalid()) {
1519 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1520 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
1524 // This actually uses the base as an r-value.
1525 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1526 if (BaseExpr.isInvalid())
1529 assert(S.Context.hasSameUnqualifiedType(BaseType,
1530 BaseExpr.get()->getType()));
1532 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1534 const ObjCObjectType *OT = OPT->getObjectType();
1536 // id, with and without qualifiers.
1537 if (OT->isObjCId()) {
1538 // Check protocols on qualified interfaces.
1539 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1541 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
1542 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1543 // Check the use of this declaration
1544 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
1547 return new (S.Context)
1548 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1549 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1552 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1553 // Check the use of this method.
1554 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
1556 Selector SetterSel =
1557 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1558 S.PP.getSelectorTable(),
1560 ObjCMethodDecl *SMD = nullptr;
1561 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1562 /*Property id*/ nullptr,
1563 SetterSel, S.Context))
1564 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1566 return new (S.Context)
1567 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1568 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1571 // Use of id.member can only be for a property reference. Do not
1572 // use the 'id' redefinition in this case.
1573 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1574 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1575 ObjCImpDecl, HasTemplateArgs);
1577 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1578 << MemberName << BaseType);
1581 // 'Class', unqualified only.
1582 if (OT->isObjCClass()) {
1583 // Only works in a method declaration (??!).
1584 ObjCMethodDecl *MD = S.getCurMethodDecl();
1586 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1587 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1588 ObjCImpDecl, HasTemplateArgs);
1593 // Also must look for a getter name which uses property syntax.
1594 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1595 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1596 ObjCMethodDecl *Getter;
1597 if ((Getter = IFace->lookupClassMethod(Sel))) {
1598 // Check the use of this method.
1599 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
1602 Getter = IFace->lookupPrivateMethod(Sel, false);
1603 // If we found a getter then this may be a valid dot-reference, we
1604 // will look for the matching setter, in case it is needed.
1605 Selector SetterSel =
1606 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1607 S.PP.getSelectorTable(),
1609 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1611 // If this reference is in an @implementation, also check for 'private'
1613 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1616 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1619 if (Getter || Setter) {
1620 return new (S.Context) ObjCPropertyRefExpr(
1621 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1622 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1625 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1626 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1627 ObjCImpDecl, HasTemplateArgs);
1629 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1630 << MemberName << BaseType);
1633 // Normal property access.
1634 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1635 MemberLoc, SourceLocation(), QualType(),
1639 // Handle 'field access' to vectors, such as 'V.xx'.
1640 if (BaseType->isExtVectorType()) {
1641 // FIXME: this expr should store IsArrow.
1642 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1647 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1648 VK = POE->getSyntacticForm()->getValueKind();
1650 VK = BaseExpr.get()->getValueKind();
1652 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1657 return new (S.Context)
1658 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1661 // Adjust builtin-sel to the appropriate redefinition type if that's
1662 // not just a pointer to builtin-sel again.
1663 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1664 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1665 BaseExpr = S.ImpCastExprToType(
1666 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1667 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1668 ObjCImpDecl, HasTemplateArgs);
1674 // Recover from dot accesses to pointers, e.g.:
1677 // This is actually well-formed in two cases:
1678 // - 'type' is an Objective C type
1679 // - 'bar' is a pseudo-destructor name which happens to refer to
1680 // the appropriate pointer type
1681 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1682 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1683 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1684 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1685 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1686 << FixItHint::CreateReplacement(OpLoc, "->");
1688 // Recurse as an -> access.
1690 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1691 ObjCImpDecl, HasTemplateArgs);
1695 // If the user is trying to apply -> or . to a function name, it's probably
1696 // because they forgot parentheses to call that function.
1697 if (S.tryToRecoverWithCall(
1698 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1700 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1701 if (BaseExpr.isInvalid())
1703 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1704 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1705 ObjCImpDecl, HasTemplateArgs);
1708 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1709 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1714 /// The main callback when the parser finds something like
1715 /// expression . [nested-name-specifier] identifier
1716 /// expression -> [nested-name-specifier] identifier
1717 /// where 'identifier' encompasses a fairly broad spectrum of
1718 /// possibilities, including destructor and operator references.
1720 /// \param OpKind either tok::arrow or tok::period
1721 /// \param ObjCImpDecl the current Objective-C \@implementation
1722 /// decl; this is an ugly hack around the fact that Objective-C
1723 /// \@implementations aren't properly put in the context chain
1724 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1725 SourceLocation OpLoc,
1726 tok::TokenKind OpKind,
1728 SourceLocation TemplateKWLoc,
1730 Decl *ObjCImpDecl) {
1731 if (SS.isSet() && SS.isInvalid())
1734 // Warn about the explicit constructor calls Microsoft extension.
1735 if (getLangOpts().MicrosoftExt &&
1736 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1737 Diag(Id.getSourceRange().getBegin(),
1738 diag::ext_ms_explicit_constructor_call);
1740 TemplateArgumentListInfo TemplateArgsBuffer;
1742 // Decompose the name into its component parts.
1743 DeclarationNameInfo NameInfo;
1744 const TemplateArgumentListInfo *TemplateArgs;
1745 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1746 NameInfo, TemplateArgs);
1748 DeclarationName Name = NameInfo.getName();
1749 bool IsArrow = (OpKind == tok::arrow);
1751 NamedDecl *FirstQualifierInScope
1752 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
1754 // This is a postfix expression, so get rid of ParenListExprs.
1755 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1756 if (Result.isInvalid()) return ExprError();
1757 Base = Result.get();
1759 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1760 isDependentScopeSpecifier(SS)) {
1761 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1762 TemplateKWLoc, FirstQualifierInScope,
1763 NameInfo, TemplateArgs);
1766 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1767 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1768 TemplateKWLoc, FirstQualifierInScope,
1769 NameInfo, TemplateArgs, S, &ExtraArgs);
1773 Sema::BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow,
1774 SourceLocation OpLoc, const CXXScopeSpec &SS,
1775 FieldDecl *Field, DeclAccessPair FoundDecl,
1776 const DeclarationNameInfo &MemberNameInfo) {
1777 // x.a is an l-value if 'a' has a reference type. Otherwise:
1778 // x.a is an l-value/x-value/pr-value if the base is (and note
1779 // that *x is always an l-value), except that if the base isn't
1780 // an ordinary object then we must have an rvalue.
1781 ExprValueKind VK = VK_LValue;
1782 ExprObjectKind OK = OK_Ordinary;
1784 if (BaseExpr->getObjectKind() == OK_Ordinary)
1785 VK = BaseExpr->getValueKind();
1789 if (VK != VK_RValue && Field->isBitField())
1792 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1793 QualType MemberType = Field->getType();
1794 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1795 MemberType = Ref->getPointeeType();
1798 QualType BaseType = BaseExpr->getType();
1799 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1801 Qualifiers BaseQuals = BaseType.getQualifiers();
1803 // GC attributes are never picked up by members.
1804 BaseQuals.removeObjCGCAttr();
1806 // CVR attributes from the base are picked up by members,
1807 // except that 'mutable' members don't pick up 'const'.
1808 if (Field->isMutable()) BaseQuals.removeConst();
1810 Qualifiers MemberQuals =
1811 Context.getCanonicalType(MemberType).getQualifiers();
1813 assert(!MemberQuals.hasAddressSpace());
1815 Qualifiers Combined = BaseQuals + MemberQuals;
1816 if (Combined != MemberQuals)
1817 MemberType = Context.getQualifiedType(MemberType, Combined);
1820 UnusedPrivateFields.remove(Field);
1822 ExprResult Base = PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1824 if (Base.isInvalid())
1827 BuildMemberExpr(*this, Context, Base.get(), IsArrow, OpLoc, SS,
1828 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1829 MemberNameInfo, MemberType, VK, OK);
1831 // Build a reference to a private copy for non-static data members in
1832 // non-static member functions, privatized by OpenMP constructs.
1833 if (getLangOpts().OpenMP && IsArrow &&
1834 !CurContext->isDependentContext() &&
1835 isa<CXXThisExpr>(Base.get()->IgnoreParenImpCasts())) {
1836 if (auto *PrivateCopy = IsOpenMPCapturedDecl(Field))
1837 return getOpenMPCapturedExpr(PrivateCopy, VK, OK, OpLoc);
1842 /// Builds an implicit member access expression. The current context
1843 /// is known to be an instance method, and the given unqualified lookup
1844 /// set is known to contain only instance members, at least one of which
1845 /// is from an appropriate type.
1847 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1848 SourceLocation TemplateKWLoc,
1850 const TemplateArgumentListInfo *TemplateArgs,
1851 bool IsKnownInstance, const Scope *S) {
1852 assert(!R.empty() && !R.isAmbiguous());
1854 SourceLocation loc = R.getNameLoc();
1856 // If this is known to be an instance access, go ahead and build an
1857 // implicit 'this' expression now.
1858 // 'this' expression now.
1859 QualType ThisTy = getCurrentThisType();
1860 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1862 Expr *baseExpr = nullptr; // null signifies implicit access
1863 if (IsKnownInstance) {
1864 SourceLocation Loc = R.getNameLoc();
1865 if (SS.getRange().isValid())
1866 Loc = SS.getRange().getBegin();
1867 CheckCXXThisCapture(Loc);
1868 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1871 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1872 /*OpLoc*/ SourceLocation(),
1875 /*FirstQualifierInScope*/ nullptr,
1876 R, TemplateArgs, S);