1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements semantic analysis member access expressions. 11 // 12 //===----------------------------------------------------------------------===// 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" 25 26 using namespace clang; 27 using namespace sema; 28 29 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet; 30 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()); 37 }; 38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet); 39 } 40 41 enum IMAKind { 42 /// The reference is definitely not an instance member access. 43 IMA_Static, 44 45 /// The reference may be an implicit instance member access. 46 IMA_Mixed, 47 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, 51 52 /// The reference may be to an instance member, but it is invalid if 53 /// so, because the context is from an unrelated class. 54 IMA_Mixed_Unrelated, 55 56 /// The reference is definitely an implicit instance member access. 57 IMA_Instance, 58 59 /// The reference may be to an unresolved using declaration. 60 IMA_Unresolved, 61 62 /// The reference is a contextually-permitted abstract member reference. 63 IMA_Abstract, 64 65 /// The reference may be to an unresolved using declaration and the 66 /// context is not an instance method. 67 IMA_Unresolved_StaticContext, 68 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 71 // unevaluated. 72 IMA_Field_Uneval_Context, 73 74 /// All possible referrents are instance members and the current 75 /// context is not an instance method. 76 IMA_Error_StaticContext, 77 78 /// All possible referrents are instance members of an unrelated 79 /// class. 80 IMA_Error_Unrelated 81 }; 82 83 /// The given lookup names class member(s) and is not being used for 84 /// an address-of-member expression. Classify the type of access 85 /// according to whether it's possible that this reference names an 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()); 92 93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext(); 94 95 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() && 96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic()); 97 98 if (R.isUnresolvableResult()) 99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved; 100 101 // Collect all the declaring classes of instance members we find. 102 bool hasNonInstance = false; 103 bool isField = false; 104 BaseSet Classes; 105 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 106 NamedDecl *D = *I; 107 108 if (D->isCXXInstanceMember()) { 109 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) || 110 isa<IndirectFieldDecl>(D); 111 112 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext()); 113 Classes.insert(R->getCanonicalDecl()); 114 } 115 else 116 hasNonInstance = true; 117 } 118 119 // If we didn't find any instance members, it can't be an implicit 120 // member reference. 121 if (Classes.empty()) 122 return IMA_Static; 123 124 // C++11 [expr.prim.general]p12: 125 // An id-expression that denotes a non-static data member or non-static 126 // member function of a class can only be used: 127 // (...) 128 // - if that id-expression denotes a non-static data member and it 129 // appears in an unevaluated operand. 130 // 131 // This rule is specific to C++11. However, we also permit this form 132 // in unevaluated inline assembly operands, like the operand to a SIZE. 133 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false' 134 assert(!AbstractInstanceResult); 135 switch (SemaRef.ExprEvalContexts.back().Context) { 136 case Sema::Unevaluated: 137 if (isField && SemaRef.getLangOpts().CPlusPlus11) 138 AbstractInstanceResult = IMA_Field_Uneval_Context; 139 break; 140 141 case Sema::UnevaluatedAbstract: 142 AbstractInstanceResult = IMA_Abstract; 143 break; 144 145 case Sema::ConstantEvaluated: 146 case Sema::PotentiallyEvaluated: 147 case Sema::PotentiallyEvaluatedIfUsed: 148 break; 149 } 150 151 // If the current context is not an instance method, it can't be 152 // an implicit member reference. 153 if (isStaticContext) { 154 if (hasNonInstance) 155 return IMA_Mixed_StaticContext; 156 157 return AbstractInstanceResult ? AbstractInstanceResult 158 : IMA_Error_StaticContext; 159 } 160 161 CXXRecordDecl *contextClass; 162 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) 163 contextClass = MD->getParent()->getCanonicalDecl(); 164 else 165 contextClass = cast<CXXRecordDecl>(DC); 166 167 // [class.mfct.non-static]p3: 168 // ...is used in the body of a non-static member function of class X, 169 // if name lookup (3.4.1) resolves the name in the id-expression to a 170 // non-static non-type member of some class C [...] 171 // ...if C is not X or a base class of X, the class member access expression 172 // is ill-formed. 173 if (R.getNamingClass() && 174 contextClass->getCanonicalDecl() != 175 R.getNamingClass()->getCanonicalDecl()) { 176 // If the naming class is not the current context, this was a qualified 177 // member name lookup, and it's sufficient to check that we have the naming 178 // class as a base class. 179 Classes.clear(); 180 Classes.insert(R.getNamingClass()->getCanonicalDecl()); 181 } 182 183 // If we can prove that the current context is unrelated to all the 184 // declaring classes, it can't be an implicit member reference (in 185 // which case it's an error if any of those members are selected). 186 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes)) 187 return hasNonInstance ? IMA_Mixed_Unrelated : 188 AbstractInstanceResult ? AbstractInstanceResult : 189 IMA_Error_Unrelated; 190 191 return (hasNonInstance ? IMA_Mixed : IMA_Instance); 192 } 193 194 /// Diagnose a reference to a field with no object available. 195 static void diagnoseInstanceReference(Sema &SemaRef, 196 const CXXScopeSpec &SS, 197 NamedDecl *Rep, 198 const DeclarationNameInfo &nameInfo) { 199 SourceLocation Loc = nameInfo.getLoc(); 200 SourceRange Range(Loc); 201 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin()); 202 203 // Look through using shadow decls and aliases. 204 Rep = Rep->getUnderlyingDecl(); 205 206 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext(); 207 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC); 208 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr; 209 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext()); 210 211 bool InStaticMethod = Method && Method->isStatic(); 212 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep); 213 214 if (IsField && InStaticMethod) 215 // "invalid use of member 'x' in static member function" 216 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method) 217 << Range << nameInfo.getName(); 218 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod && 219 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass)) 220 // Unqualified lookup in a non-static member function found a member of an 221 // enclosing class. 222 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use) 223 << IsField << RepClass << nameInfo.getName() << ContextClass << Range; 224 else if (IsField) 225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use) 226 << nameInfo.getName() << Range; 227 else 228 SemaRef.Diag(Loc, diag::err_member_call_without_object) 229 << Range; 230 } 231 232 /// Builds an expression which might be an implicit member expression. 233 ExprResult 234 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 235 SourceLocation TemplateKWLoc, 236 LookupResult &R, 237 const TemplateArgumentListInfo *TemplateArgs) { 238 switch (ClassifyImplicitMemberAccess(*this, R)) { 239 case IMA_Instance: 240 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true); 241 242 case IMA_Mixed: 243 case IMA_Mixed_Unrelated: 244 case IMA_Unresolved: 245 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false); 246 247 case IMA_Field_Uneval_Context: 248 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use) 249 << R.getLookupNameInfo().getName(); 250 // Fall through. 251 case IMA_Static: 252 case IMA_Abstract: 253 case IMA_Mixed_StaticContext: 254 case IMA_Unresolved_StaticContext: 255 if (TemplateArgs || TemplateKWLoc.isValid()) 256 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs); 257 return BuildDeclarationNameExpr(SS, R, false); 258 259 case IMA_Error_StaticContext: 260 case IMA_Error_Unrelated: 261 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(), 262 R.getLookupNameInfo()); 263 return ExprError(); 264 } 265 266 llvm_unreachable("unexpected instance member access kind"); 267 } 268 269 /// Check an ext-vector component access expression. 270 /// 271 /// VK should be set in advance to the value kind of the base 272 /// expression. 273 static QualType 274 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK, 275 SourceLocation OpLoc, const IdentifierInfo *CompName, 276 SourceLocation CompLoc) { 277 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements, 278 // see FIXME there. 279 // 280 // FIXME: This logic can be greatly simplified by splitting it along 281 // halving/not halving and reworking the component checking. 282 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>(); 283 284 // The vector accessor can't exceed the number of elements. 285 const char *compStr = CompName->getNameStart(); 286 287 // This flag determines whether or not the component is one of the four 288 // special names that indicate a subset of exactly half the elements are 289 // to be selected. 290 bool HalvingSwizzle = false; 291 292 // This flag determines whether or not CompName has an 's' char prefix, 293 // indicating that it is a string of hex values to be used as vector indices. 294 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1]; 295 296 bool HasRepeated = false; 297 bool HasIndex[16] = {}; 298 299 int Idx; 300 301 // Check that we've found one of the special components, or that the component 302 // names must come from the same set. 303 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 304 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 305 HalvingSwizzle = true; 306 } else if (!HexSwizzle && 307 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) { 308 do { 309 if (HasIndex[Idx]) HasRepeated = true; 310 HasIndex[Idx] = true; 311 compStr++; 312 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1); 313 } else { 314 if (HexSwizzle) compStr++; 315 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) { 316 if (HasIndex[Idx]) HasRepeated = true; 317 HasIndex[Idx] = true; 318 compStr++; 319 } 320 } 321 322 if (!HalvingSwizzle && *compStr) { 323 // We didn't get to the end of the string. This means the component names 324 // didn't come from the same set *or* we encountered an illegal name. 325 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 326 << StringRef(compStr, 1) << SourceRange(CompLoc); 327 return QualType(); 328 } 329 330 // Ensure no component accessor exceeds the width of the vector type it 331 // operates on. 332 if (!HalvingSwizzle) { 333 compStr = CompName->getNameStart(); 334 335 if (HexSwizzle) 336 compStr++; 337 338 while (*compStr) { 339 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 340 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 341 << baseType << SourceRange(CompLoc); 342 return QualType(); 343 } 344 } 345 } 346 347 // The component accessor looks fine - now we need to compute the actual type. 348 // The vector type is implied by the component accessor. For example, 349 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 350 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 351 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 352 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2 353 : CompName->getLength(); 354 if (HexSwizzle) 355 CompSize--; 356 357 if (CompSize == 1) 358 return vecType->getElementType(); 359 360 if (HasRepeated) VK = VK_RValue; 361 362 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize); 363 // Now look up the TypeDefDecl from the vector type. Without this, 364 // diagostics look bad. We want extended vector types to appear built-in. 365 for (Sema::ExtVectorDeclsType::iterator 366 I = S.ExtVectorDecls.begin(S.getExternalSource()), 367 E = S.ExtVectorDecls.end(); 368 I != E; ++I) { 369 if ((*I)->getUnderlyingType() == VT) 370 return S.Context.getTypedefType(*I); 371 } 372 373 return VT; // should never get here (a typedef type should always be found). 374 } 375 376 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 377 IdentifierInfo *Member, 378 const Selector &Sel, 379 ASTContext &Context) { 380 if (Member) 381 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 382 return PD; 383 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 384 return OMD; 385 386 for (const auto *I : PDecl->protocols()) { 387 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, 388 Context)) 389 return D; 390 } 391 return nullptr; 392 } 393 394 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy, 395 IdentifierInfo *Member, 396 const Selector &Sel, 397 ASTContext &Context) { 398 // Check protocols on qualified interfaces. 399 Decl *GDecl = nullptr; 400 for (const auto *I : QIdTy->quals()) { 401 if (Member) 402 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) { 403 GDecl = PD; 404 break; 405 } 406 // Also must look for a getter or setter name which uses property syntax. 407 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) { 408 GDecl = OMD; 409 break; 410 } 411 } 412 if (!GDecl) { 413 for (const auto *I : QIdTy->quals()) { 414 // Search in the protocol-qualifier list of current protocol. 415 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context); 416 if (GDecl) 417 return GDecl; 418 } 419 } 420 return GDecl; 421 } 422 423 ExprResult 424 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType, 425 bool IsArrow, SourceLocation OpLoc, 426 const CXXScopeSpec &SS, 427 SourceLocation TemplateKWLoc, 428 NamedDecl *FirstQualifierInScope, 429 const DeclarationNameInfo &NameInfo, 430 const TemplateArgumentListInfo *TemplateArgs) { 431 // Even in dependent contexts, try to diagnose base expressions with 432 // obviously wrong types, e.g.: 433 // 434 // T* t; 435 // t.f; 436 // 437 // In Obj-C++, however, the above expression is valid, since it could be 438 // accessing the 'f' property if T is an Obj-C interface. The extra check 439 // allows this, while still reporting an error if T is a struct pointer. 440 if (!IsArrow) { 441 const PointerType *PT = BaseType->getAs<PointerType>(); 442 if (PT && (!getLangOpts().ObjC1 || 443 PT->getPointeeType()->isRecordType())) { 444 assert(BaseExpr && "cannot happen with implicit member accesses"); 445 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union) 446 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange(); 447 return ExprError(); 448 } 449 } 450 451 assert(BaseType->isDependentType() || 452 NameInfo.getName().isDependentName() || 453 isDependentScopeSpecifier(SS)); 454 455 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 456 // must have pointer type, and the accessed type is the pointee. 457 return CXXDependentScopeMemberExpr::Create( 458 Context, BaseExpr, BaseType, IsArrow, OpLoc, 459 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope, 460 NameInfo, TemplateArgs); 461 } 462 463 /// We know that the given qualified member reference points only to 464 /// declarations which do not belong to the static type of the base 465 /// expression. Diagnose the problem. 466 static void DiagnoseQualifiedMemberReference(Sema &SemaRef, 467 Expr *BaseExpr, 468 QualType BaseType, 469 const CXXScopeSpec &SS, 470 NamedDecl *rep, 471 const DeclarationNameInfo &nameInfo) { 472 // If this is an implicit member access, use a different set of 473 // diagnostics. 474 if (!BaseExpr) 475 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo); 476 477 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated) 478 << SS.getRange() << rep << BaseType; 479 } 480 481 // Check whether the declarations we found through a nested-name 482 // specifier in a member expression are actually members of the base 483 // type. The restriction here is: 484 // 485 // C++ [expr.ref]p2: 486 // ... In these cases, the id-expression shall name a 487 // member of the class or of one of its base classes. 488 // 489 // So it's perfectly legitimate for the nested-name specifier to name 490 // an unrelated class, and for us to find an overload set including 491 // decls from classes which are not superclasses, as long as the decl 492 // we actually pick through overload resolution is from a superclass. 493 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr, 494 QualType BaseType, 495 const CXXScopeSpec &SS, 496 const LookupResult &R) { 497 CXXRecordDecl *BaseRecord = 498 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType)); 499 if (!BaseRecord) { 500 // We can't check this yet because the base type is still 501 // dependent. 502 assert(BaseType->isDependentType()); 503 return false; 504 } 505 506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 507 // If this is an implicit member reference and we find a 508 // non-instance member, it's not an error. 509 if (!BaseExpr && !(*I)->isCXXInstanceMember()) 510 return false; 511 512 // Note that we use the DC of the decl, not the underlying decl. 513 DeclContext *DC = (*I)->getDeclContext(); 514 while (DC->isTransparentContext()) 515 DC = DC->getParent(); 516 517 if (!DC->isRecord()) 518 continue; 519 520 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl(); 521 if (BaseRecord->getCanonicalDecl() == MemberRecord || 522 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord)) 523 return false; 524 } 525 526 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, 527 R.getRepresentativeDecl(), 528 R.getLookupNameInfo()); 529 return true; 530 } 531 532 namespace { 533 534 // Callback to only accept typo corrections that are either a ValueDecl or a 535 // FunctionTemplateDecl and are declared in the current record or, for a C++ 536 // classes, one of its base classes. 537 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback { 538 public: 539 explicit RecordMemberExprValidatorCCC(const RecordType *RTy) 540 : Record(RTy->getDecl()) { 541 // Don't add bare keywords to the consumer since they will always fail 542 // validation by virtue of not being associated with any decls. 543 WantTypeSpecifiers = false; 544 WantExpressionKeywords = false; 545 WantCXXNamedCasts = false; 546 WantFunctionLikeCasts = false; 547 WantRemainingKeywords = false; 548 } 549 550 bool ValidateCandidate(const TypoCorrection &candidate) override { 551 NamedDecl *ND = candidate.getCorrectionDecl(); 552 // Don't accept candidates that cannot be member functions, constants, 553 // variables, or templates. 554 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))) 555 return false; 556 557 // Accept candidates that occur in the current record. 558 if (Record->containsDecl(ND)) 559 return true; 560 561 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) { 562 // Accept candidates that occur in any of the current class' base classes. 563 for (const auto &BS : RD->bases()) { 564 if (const RecordType *BSTy = 565 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) { 566 if (BSTy->getDecl()->containsDecl(ND)) 567 return true; 568 } 569 } 570 } 571 572 return false; 573 } 574 575 private: 576 const RecordDecl *const Record; 577 }; 578 579 } 580 581 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, 582 Expr *BaseExpr, 583 const RecordType *RTy, 584 SourceLocation OpLoc, bool IsArrow, 585 CXXScopeSpec &SS, bool HasTemplateArgs, 586 TypoExpr *&TE) { 587 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange(); 588 RecordDecl *RDecl = RTy->getDecl(); 589 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) && 590 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0), 591 diag::err_typecheck_incomplete_tag, 592 BaseRange)) 593 return true; 594 595 if (HasTemplateArgs) { 596 // LookupTemplateName doesn't expect these both to exist simultaneously. 597 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0); 598 599 bool MOUS; 600 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS); 601 return false; 602 } 603 604 DeclContext *DC = RDecl; 605 if (SS.isSet()) { 606 // If the member name was a qualified-id, look into the 607 // nested-name-specifier. 608 DC = SemaRef.computeDeclContext(SS, false); 609 610 if (SemaRef.RequireCompleteDeclContext(SS, DC)) { 611 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag) 612 << SS.getRange() << DC; 613 return true; 614 } 615 616 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 617 618 if (!isa<TypeDecl>(DC)) { 619 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass) 620 << DC << SS.getRange(); 621 return true; 622 } 623 } 624 625 // The record definition is complete, now look up the member. 626 SemaRef.LookupQualifiedName(R, DC, SS); 627 628 if (!R.empty()) 629 return false; 630 631 DeclarationName Typo = R.getLookupName(); 632 SourceLocation TypoLoc = R.getNameLoc(); 633 TE = SemaRef.CorrectTypoDelayed( 634 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS, 635 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy), 636 [=, &SemaRef](const TypoCorrection &TC) { 637 if (TC) { 638 assert(!TC.isKeyword() && 639 "Got a keyword as a correction for a member!"); 640 bool DroppedSpecifier = 641 TC.WillReplaceSpecifier() && 642 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts()); 643 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest) 644 << Typo << DC << DroppedSpecifier 645 << SS.getRange()); 646 } else { 647 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange; 648 } 649 }, 650 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable { 651 R.clear(); // Ensure there's no decls lingering in the shared state. 652 R.suppressDiagnostics(); 653 R.setLookupName(TC.getCorrection()); 654 for (NamedDecl *ND : TC) 655 R.addDecl(ND); 656 R.resolveKind(); 657 return SemaRef.BuildMemberReferenceExpr( 658 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(), 659 nullptr, R, nullptr); 660 }, 661 Sema::CTK_ErrorRecovery, DC); 662 663 return false; 664 } 665 666 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, 667 ExprResult &BaseExpr, bool &IsArrow, 668 SourceLocation OpLoc, CXXScopeSpec &SS, 669 Decl *ObjCImpDecl, bool HasTemplateArgs); 670 671 ExprResult 672 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 673 SourceLocation OpLoc, bool IsArrow, 674 CXXScopeSpec &SS, 675 SourceLocation TemplateKWLoc, 676 NamedDecl *FirstQualifierInScope, 677 const DeclarationNameInfo &NameInfo, 678 const TemplateArgumentListInfo *TemplateArgs, 679 ActOnMemberAccessExtraArgs *ExtraArgs) { 680 if (BaseType->isDependentType() || 681 (SS.isSet() && isDependentScopeSpecifier(SS))) 682 return ActOnDependentMemberExpr(Base, BaseType, 683 IsArrow, OpLoc, 684 SS, TemplateKWLoc, FirstQualifierInScope, 685 NameInfo, TemplateArgs); 686 687 LookupResult R(*this, NameInfo, LookupMemberName); 688 689 // Implicit member accesses. 690 if (!Base) { 691 TypoExpr *TE = nullptr; 692 QualType RecordTy = BaseType; 693 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType(); 694 if (LookupMemberExprInRecord(*this, R, nullptr, 695 RecordTy->getAs<RecordType>(), OpLoc, IsArrow, 696 SS, TemplateArgs != nullptr, TE)) 697 return ExprError(); 698 if (TE) 699 return TE; 700 701 // Explicit member accesses. 702 } else { 703 ExprResult BaseResult = Base; 704 ExprResult Result = LookupMemberExpr( 705 *this, R, BaseResult, IsArrow, OpLoc, SS, 706 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr, 707 TemplateArgs != nullptr); 708 709 if (BaseResult.isInvalid()) 710 return ExprError(); 711 Base = BaseResult.get(); 712 713 if (Result.isInvalid()) 714 return ExprError(); 715 716 if (Result.get()) 717 return Result; 718 719 // LookupMemberExpr can modify Base, and thus change BaseType 720 BaseType = Base->getType(); 721 } 722 723 return BuildMemberReferenceExpr(Base, BaseType, 724 OpLoc, IsArrow, SS, TemplateKWLoc, 725 FirstQualifierInScope, R, TemplateArgs, 726 false, ExtraArgs); 727 } 728 729 static ExprResult 730 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 731 SourceLocation OpLoc, const CXXScopeSpec &SS, 732 FieldDecl *Field, DeclAccessPair FoundDecl, 733 const DeclarationNameInfo &MemberNameInfo); 734 735 ExprResult 736 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 737 SourceLocation loc, 738 IndirectFieldDecl *indirectField, 739 DeclAccessPair foundDecl, 740 Expr *baseObjectExpr, 741 SourceLocation opLoc) { 742 // First, build the expression that refers to the base object. 743 744 bool baseObjectIsPointer = false; 745 Qualifiers baseQuals; 746 747 // Case 1: the base of the indirect field is not a field. 748 VarDecl *baseVariable = indirectField->getVarDecl(); 749 CXXScopeSpec EmptySS; 750 if (baseVariable) { 751 assert(baseVariable->getType()->isRecordType()); 752 753 // In principle we could have a member access expression that 754 // accesses an anonymous struct/union that's a static member of 755 // the base object's class. However, under the current standard, 756 // static data members cannot be anonymous structs or unions. 757 // Supporting this is as easy as building a MemberExpr here. 758 assert(!baseObjectExpr && "anonymous struct/union is static data member?"); 759 760 DeclarationNameInfo baseNameInfo(DeclarationName(), loc); 761 762 ExprResult result 763 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable); 764 if (result.isInvalid()) return ExprError(); 765 766 baseObjectExpr = result.get(); 767 baseObjectIsPointer = false; 768 baseQuals = baseObjectExpr->getType().getQualifiers(); 769 770 // Case 2: the base of the indirect field is a field and the user 771 // wrote a member expression. 772 } else if (baseObjectExpr) { 773 // The caller provided the base object expression. Determine 774 // whether its a pointer and whether it adds any qualifiers to the 775 // anonymous struct/union fields we're looking into. 776 QualType objectType = baseObjectExpr->getType(); 777 778 if (const PointerType *ptr = objectType->getAs<PointerType>()) { 779 baseObjectIsPointer = true; 780 objectType = ptr->getPointeeType(); 781 } else { 782 baseObjectIsPointer = false; 783 } 784 baseQuals = objectType.getQualifiers(); 785 786 // Case 3: the base of the indirect field is a field and we should 787 // build an implicit member access. 788 } else { 789 // We've found a member of an anonymous struct/union that is 790 // inside a non-anonymous struct/union, so in a well-formed 791 // program our base object expression is "this". 792 QualType ThisTy = getCurrentThisType(); 793 if (ThisTy.isNull()) { 794 Diag(loc, diag::err_invalid_member_use_in_static_method) 795 << indirectField->getDeclName(); 796 return ExprError(); 797 } 798 799 // Our base object expression is "this". 800 CheckCXXThisCapture(loc); 801 baseObjectExpr 802 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true); 803 baseObjectIsPointer = true; 804 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers(); 805 } 806 807 // Build the implicit member references to the field of the 808 // anonymous struct/union. 809 Expr *result = baseObjectExpr; 810 IndirectFieldDecl::chain_iterator 811 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end(); 812 813 // Build the first member access in the chain with full information. 814 if (!baseVariable) { 815 FieldDecl *field = cast<FieldDecl>(*FI); 816 817 // Make a nameInfo that properly uses the anonymous name. 818 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 819 820 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer, 821 SourceLocation(), EmptySS, field, 822 foundDecl, memberNameInfo).get(); 823 if (!result) 824 return ExprError(); 825 826 // FIXME: check qualified member access 827 } 828 829 // In all cases, we should now skip the first declaration in the chain. 830 ++FI; 831 832 while (FI != FEnd) { 833 FieldDecl *field = cast<FieldDecl>(*FI++); 834 835 // FIXME: these are somewhat meaningless 836 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 837 DeclAccessPair fakeFoundDecl = 838 DeclAccessPair::make(field, field->getAccess()); 839 840 result = 841 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false, 842 SourceLocation(), (FI == FEnd ? SS : EmptySS), 843 field, fakeFoundDecl, memberNameInfo).get(); 844 } 845 846 return result; 847 } 848 849 static ExprResult 850 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 851 const CXXScopeSpec &SS, 852 MSPropertyDecl *PD, 853 const DeclarationNameInfo &NameInfo) { 854 // Property names are always simple identifiers and therefore never 855 // require any interesting additional storage. 856 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow, 857 S.Context.PseudoObjectTy, VK_LValue, 858 SS.getWithLocInContext(S.Context), 859 NameInfo.getLoc()); 860 } 861 862 /// \brief Build a MemberExpr AST node. 863 static MemberExpr *BuildMemberExpr( 864 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow, 865 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, 866 ValueDecl *Member, DeclAccessPair FoundDecl, 867 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, 868 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) { 869 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue"); 870 MemberExpr *E = MemberExpr::Create( 871 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member, 872 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK); 873 SemaRef.MarkMemberReferenced(E); 874 return E; 875 } 876 877 ExprResult 878 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, 879 SourceLocation OpLoc, bool IsArrow, 880 const CXXScopeSpec &SS, 881 SourceLocation TemplateKWLoc, 882 NamedDecl *FirstQualifierInScope, 883 LookupResult &R, 884 const TemplateArgumentListInfo *TemplateArgs, 885 bool SuppressQualifierCheck, 886 ActOnMemberAccessExtraArgs *ExtraArgs) { 887 QualType BaseType = BaseExprType; 888 if (IsArrow) { 889 assert(BaseType->isPointerType()); 890 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 891 } 892 R.setBaseObjectType(BaseType); 893 894 LambdaScopeInfo *const CurLSI = getCurLambda(); 895 // If this is an implicit member reference and the overloaded 896 // name refers to both static and non-static member functions 897 // (i.e. BaseExpr is null) and if we are currently processing a lambda, 898 // check if we should/can capture 'this'... 899 // Keep this example in mind: 900 // struct X { 901 // void f(int) { } 902 // static void f(double) { } 903 // 904 // int g() { 905 // auto L = [=](auto a) { 906 // return [](int i) { 907 // return [=](auto b) { 908 // f(b); 909 // //f(decltype(a){}); 910 // }; 911 // }; 912 // }; 913 // auto M = L(0.0); 914 // auto N = M(3); 915 // N(5.32); // OK, must not error. 916 // return 0; 917 // } 918 // }; 919 // 920 if (!BaseExpr && CurLSI) { 921 SourceLocation Loc = R.getNameLoc(); 922 if (SS.getRange().isValid()) 923 Loc = SS.getRange().getBegin(); 924 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent(); 925 // If the enclosing function is not dependent, then this lambda is 926 // capture ready, so if we can capture this, do so. 927 if (!EnclosingFunctionCtx->isDependentContext()) { 928 // If the current lambda and all enclosing lambdas can capture 'this' - 929 // then go ahead and capture 'this' (since our unresolved overload set 930 // contains both static and non-static member functions). 931 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false)) 932 CheckCXXThisCapture(Loc); 933 } else if (CurContext->isDependentContext()) { 934 // ... since this is an implicit member reference, that might potentially 935 // involve a 'this' capture, mark 'this' for potential capture in 936 // enclosing lambdas. 937 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 938 CurLSI->addPotentialThisCapture(Loc); 939 } 940 } 941 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); 942 DeclarationName MemberName = MemberNameInfo.getName(); 943 SourceLocation MemberLoc = MemberNameInfo.getLoc(); 944 945 if (R.isAmbiguous()) 946 return ExprError(); 947 948 if (R.empty()) { 949 // Rederive where we looked up. 950 DeclContext *DC = (SS.isSet() 951 ? computeDeclContext(SS, false) 952 : BaseType->getAs<RecordType>()->getDecl()); 953 954 if (ExtraArgs) { 955 ExprResult RetryExpr; 956 if (!IsArrow && BaseExpr) { 957 SFINAETrap Trap(*this, true); 958 ParsedType ObjectType; 959 bool MayBePseudoDestructor = false; 960 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr, 961 OpLoc, tok::arrow, ObjectType, 962 MayBePseudoDestructor); 963 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) { 964 CXXScopeSpec TempSS(SS); 965 RetryExpr = ActOnMemberAccessExpr( 966 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS, 967 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl); 968 } 969 if (Trap.hasErrorOccurred()) 970 RetryExpr = ExprError(); 971 } 972 if (RetryExpr.isUsable()) { 973 Diag(OpLoc, diag::err_no_member_overloaded_arrow) 974 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->"); 975 return RetryExpr; 976 } 977 } 978 979 Diag(R.getNameLoc(), diag::err_no_member) 980 << MemberName << DC 981 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); 982 return ExprError(); 983 } 984 985 // Diagnose lookups that find only declarations from a non-base 986 // type. This is possible for either qualified lookups (which may 987 // have been qualified with an unrelated type) or implicit member 988 // expressions (which were found with unqualified lookup and thus 989 // may have come from an enclosing scope). Note that it's okay for 990 // lookup to find declarations from a non-base type as long as those 991 // aren't the ones picked by overload resolution. 992 if ((SS.isSet() || !BaseExpr || 993 (isa<CXXThisExpr>(BaseExpr) && 994 cast<CXXThisExpr>(BaseExpr)->isImplicit())) && 995 !SuppressQualifierCheck && 996 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) 997 return ExprError(); 998 999 // Construct an unresolved result if we in fact got an unresolved 1000 // result. 1001 if (R.isOverloadedResult() || R.isUnresolvableResult()) { 1002 // Suppress any lookup-related diagnostics; we'll do these when we 1003 // pick a member. 1004 R.suppressDiagnostics(); 1005 1006 UnresolvedMemberExpr *MemExpr 1007 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(), 1008 BaseExpr, BaseExprType, 1009 IsArrow, OpLoc, 1010 SS.getWithLocInContext(Context), 1011 TemplateKWLoc, MemberNameInfo, 1012 TemplateArgs, R.begin(), R.end()); 1013 1014 return MemExpr; 1015 } 1016 1017 assert(R.isSingleResult()); 1018 DeclAccessPair FoundDecl = R.begin().getPair(); 1019 NamedDecl *MemberDecl = R.getFoundDecl(); 1020 1021 // FIXME: diagnose the presence of template arguments now. 1022 1023 // If the decl being referenced had an error, return an error for this 1024 // sub-expr without emitting another error, in order to avoid cascading 1025 // error cases. 1026 if (MemberDecl->isInvalidDecl()) 1027 return ExprError(); 1028 1029 // Handle the implicit-member-access case. 1030 if (!BaseExpr) { 1031 // If this is not an instance member, convert to a non-member access. 1032 if (!MemberDecl->isCXXInstanceMember()) 1033 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl); 1034 1035 SourceLocation Loc = R.getNameLoc(); 1036 if (SS.getRange().isValid()) 1037 Loc = SS.getRange().getBegin(); 1038 CheckCXXThisCapture(Loc); 1039 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true); 1040 } 1041 1042 // Check the use of this member. 1043 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc)) 1044 return ExprError(); 1045 1046 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) 1047 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD, 1048 FoundDecl, MemberNameInfo); 1049 1050 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl)) 1051 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD, 1052 MemberNameInfo); 1053 1054 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl)) 1055 // We may have found a field within an anonymous union or struct 1056 // (C++ [class.union]). 1057 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD, 1058 FoundDecl, BaseExpr, 1059 OpLoc); 1060 1061 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 1062 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS, 1063 TemplateKWLoc, Var, FoundDecl, MemberNameInfo, 1064 Var->getType().getNonReferenceType(), VK_LValue, 1065 OK_Ordinary); 1066 } 1067 1068 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) { 1069 ExprValueKind valueKind; 1070 QualType type; 1071 if (MemberFn->isInstance()) { 1072 valueKind = VK_RValue; 1073 type = Context.BoundMemberTy; 1074 } else { 1075 valueKind = VK_LValue; 1076 type = MemberFn->getType(); 1077 } 1078 1079 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS, 1080 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo, 1081 type, valueKind, OK_Ordinary); 1082 } 1083 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?"); 1084 1085 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 1086 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS, 1087 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo, 1088 Enum->getType(), VK_RValue, OK_Ordinary); 1089 } 1090 1091 // We found something that we didn't expect. Complain. 1092 if (isa<TypeDecl>(MemberDecl)) 1093 Diag(MemberLoc, diag::err_typecheck_member_reference_type) 1094 << MemberName << BaseType << int(IsArrow); 1095 else 1096 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown) 1097 << MemberName << BaseType << int(IsArrow); 1098 1099 Diag(MemberDecl->getLocation(), diag::note_member_declared_here) 1100 << MemberName; 1101 R.suppressDiagnostics(); 1102 return ExprError(); 1103 } 1104 1105 /// Given that normal member access failed on the given expression, 1106 /// and given that the expression's type involves builtin-id or 1107 /// builtin-Class, decide whether substituting in the redefinition 1108 /// types would be profitable. The redefinition type is whatever 1109 /// this translation unit tried to typedef to id/Class; we store 1110 /// it to the side and then re-use it in places like this. 1111 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) { 1112 const ObjCObjectPointerType *opty 1113 = base.get()->getType()->getAs<ObjCObjectPointerType>(); 1114 if (!opty) return false; 1115 1116 const ObjCObjectType *ty = opty->getObjectType(); 1117 1118 QualType redef; 1119 if (ty->isObjCId()) { 1120 redef = S.Context.getObjCIdRedefinitionType(); 1121 } else if (ty->isObjCClass()) { 1122 redef = S.Context.getObjCClassRedefinitionType(); 1123 } else { 1124 return false; 1125 } 1126 1127 // Do the substitution as long as the redefinition type isn't just a 1128 // possibly-qualified pointer to builtin-id or builtin-Class again. 1129 opty = redef->getAs<ObjCObjectPointerType>(); 1130 if (opty && !opty->getObjectType()->getInterface()) 1131 return false; 1132 1133 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast); 1134 return true; 1135 } 1136 1137 static bool isRecordType(QualType T) { 1138 return T->isRecordType(); 1139 } 1140 static bool isPointerToRecordType(QualType T) { 1141 if (const PointerType *PT = T->getAs<PointerType>()) 1142 return PT->getPointeeType()->isRecordType(); 1143 return false; 1144 } 1145 1146 /// Perform conversions on the LHS of a member access expression. 1147 ExprResult 1148 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) { 1149 if (IsArrow && !Base->getType()->isFunctionType()) 1150 return DefaultFunctionArrayLvalueConversion(Base); 1151 1152 return CheckPlaceholderExpr(Base); 1153 } 1154 1155 /// Look up the given member of the given non-type-dependent 1156 /// expression. This can return in one of two ways: 1157 /// * If it returns a sentinel null-but-valid result, the caller will 1158 /// assume that lookup was performed and the results written into 1159 /// the provided structure. It will take over from there. 1160 /// * Otherwise, the returned expression will be produced in place of 1161 /// an ordinary member expression. 1162 /// 1163 /// The ObjCImpDecl bit is a gross hack that will need to be properly 1164 /// fixed for ObjC++. 1165 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R, 1166 ExprResult &BaseExpr, bool &IsArrow, 1167 SourceLocation OpLoc, CXXScopeSpec &SS, 1168 Decl *ObjCImpDecl, bool HasTemplateArgs) { 1169 assert(BaseExpr.get() && "no base expression"); 1170 1171 // Perform default conversions. 1172 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow); 1173 if (BaseExpr.isInvalid()) 1174 return ExprError(); 1175 1176 QualType BaseType = BaseExpr.get()->getType(); 1177 assert(!BaseType->isDependentType()); 1178 1179 DeclarationName MemberName = R.getLookupName(); 1180 SourceLocation MemberLoc = R.getNameLoc(); 1181 1182 // For later type-checking purposes, turn arrow accesses into dot 1183 // accesses. The only access type we support that doesn't follow 1184 // the C equivalence "a->b === (*a).b" is ObjC property accesses, 1185 // and those never use arrows, so this is unaffected. 1186 if (IsArrow) { 1187 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 1188 BaseType = Ptr->getPointeeType(); 1189 else if (const ObjCObjectPointerType *Ptr 1190 = BaseType->getAs<ObjCObjectPointerType>()) 1191 BaseType = Ptr->getPointeeType(); 1192 else if (BaseType->isRecordType()) { 1193 // Recover from arrow accesses to records, e.g.: 1194 // struct MyRecord foo; 1195 // foo->bar 1196 // This is actually well-formed in C++ if MyRecord has an 1197 // overloaded operator->, but that should have been dealt with 1198 // by now--or a diagnostic message already issued if a problem 1199 // was encountered while looking for the overloaded operator->. 1200 if (!S.getLangOpts().CPlusPlus) { 1201 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 1202 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() 1203 << FixItHint::CreateReplacement(OpLoc, "."); 1204 } 1205 IsArrow = false; 1206 } else if (BaseType->isFunctionType()) { 1207 goto fail; 1208 } else { 1209 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 1210 << BaseType << BaseExpr.get()->getSourceRange(); 1211 return ExprError(); 1212 } 1213 } 1214 1215 // Handle field access to simple records. 1216 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 1217 TypoExpr *TE = nullptr; 1218 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy, 1219 OpLoc, IsArrow, SS, HasTemplateArgs, TE)) 1220 return ExprError(); 1221 1222 // Returning valid-but-null is how we indicate to the caller that 1223 // the lookup result was filled in. If typo correction was attempted and 1224 // failed, the lookup result will have been cleared--that combined with the 1225 // valid-but-null ExprResult will trigger the appropriate diagnostics. 1226 return ExprResult(TE); 1227 } 1228 1229 // Handle ivar access to Objective-C objects. 1230 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) { 1231 if (!SS.isEmpty() && !SS.isInvalid()) { 1232 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access) 1233 << 1 << SS.getScopeRep() 1234 << FixItHint::CreateRemoval(SS.getRange()); 1235 SS.clear(); 1236 } 1237 1238 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1239 1240 // There are three cases for the base type: 1241 // - builtin id (qualified or unqualified) 1242 // - builtin Class (qualified or unqualified) 1243 // - an interface 1244 ObjCInterfaceDecl *IDecl = OTy->getInterface(); 1245 if (!IDecl) { 1246 if (S.getLangOpts().ObjCAutoRefCount && 1247 (OTy->isObjCId() || OTy->isObjCClass())) 1248 goto fail; 1249 // There's an implicit 'isa' ivar on all objects. 1250 // But we only actually find it this way on objects of type 'id', 1251 // apparently. 1252 if (OTy->isObjCId() && Member->isStr("isa")) 1253 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc, 1254 OpLoc, S.Context.getObjCClassType()); 1255 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr)) 1256 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, 1257 ObjCImpDecl, HasTemplateArgs); 1258 goto fail; 1259 } 1260 1261 if (S.RequireCompleteType(OpLoc, BaseType, 1262 diag::err_typecheck_incomplete_tag, 1263 BaseExpr.get())) 1264 return ExprError(); 1265 1266 ObjCInterfaceDecl *ClassDeclared = nullptr; 1267 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 1268 1269 if (!IV) { 1270 // Attempt to correct for typos in ivar names. 1271 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>(); 1272 Validator->IsObjCIvarLookup = IsArrow; 1273 if (TypoCorrection Corrected = S.CorrectTypo( 1274 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr, 1275 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) { 1276 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>(); 1277 S.diagnoseTypo( 1278 Corrected, 1279 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest) 1280 << IDecl->getDeclName() << MemberName); 1281 1282 // Figure out the class that declares the ivar. 1283 assert(!ClassDeclared); 1284 Decl *D = cast<Decl>(IV->getDeclContext()); 1285 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D)) 1286 D = CAT->getClassInterface(); 1287 ClassDeclared = cast<ObjCInterfaceDecl>(D); 1288 } else { 1289 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) { 1290 S.Diag(MemberLoc, diag::err_property_found_suggest) 1291 << Member << BaseExpr.get()->getType() 1292 << FixItHint::CreateReplacement(OpLoc, "."); 1293 return ExprError(); 1294 } 1295 1296 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 1297 << IDecl->getDeclName() << MemberName 1298 << BaseExpr.get()->getSourceRange(); 1299 return ExprError(); 1300 } 1301 } 1302 1303 assert(ClassDeclared); 1304 1305 // If the decl being referenced had an error, return an error for this 1306 // sub-expr without emitting another error, in order to avoid cascading 1307 // error cases. 1308 if (IV->isInvalidDecl()) 1309 return ExprError(); 1310 1311 // Check whether we can reference this field. 1312 if (S.DiagnoseUseOfDecl(IV, MemberLoc)) 1313 return ExprError(); 1314 if (IV->getAccessControl() != ObjCIvarDecl::Public && 1315 IV->getAccessControl() != ObjCIvarDecl::Package) { 1316 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr; 1317 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) 1318 ClassOfMethodDecl = MD->getClassInterface(); 1319 else if (ObjCImpDecl && S.getCurFunctionDecl()) { 1320 // Case of a c-function declared inside an objc implementation. 1321 // FIXME: For a c-style function nested inside an objc implementation 1322 // class, there is no implementation context available, so we pass 1323 // down the context as argument to this routine. Ideally, this context 1324 // need be passed down in the AST node and somehow calculated from the 1325 // AST for a function decl. 1326 if (ObjCImplementationDecl *IMPD = 1327 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl)) 1328 ClassOfMethodDecl = IMPD->getClassInterface(); 1329 else if (ObjCCategoryImplDecl* CatImplClass = 1330 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl)) 1331 ClassOfMethodDecl = CatImplClass->getClassInterface(); 1332 } 1333 if (!S.getLangOpts().DebuggerSupport) { 1334 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 1335 if (!declaresSameEntity(ClassDeclared, IDecl) || 1336 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared)) 1337 S.Diag(MemberLoc, diag::error_private_ivar_access) 1338 << IV->getDeclName(); 1339 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 1340 // @protected 1341 S.Diag(MemberLoc, diag::error_protected_ivar_access) 1342 << IV->getDeclName(); 1343 } 1344 } 1345 bool warn = true; 1346 if (S.getLangOpts().ObjCAutoRefCount) { 1347 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts(); 1348 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp)) 1349 if (UO->getOpcode() == UO_Deref) 1350 BaseExp = UO->getSubExpr()->IgnoreParenCasts(); 1351 1352 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp)) 1353 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 1354 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access); 1355 warn = false; 1356 } 1357 } 1358 if (warn) { 1359 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) { 1360 ObjCMethodFamily MF = MD->getMethodFamily(); 1361 warn = (MF != OMF_init && MF != OMF_dealloc && 1362 MF != OMF_finalize && 1363 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV)); 1364 } 1365 if (warn) 1366 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName(); 1367 } 1368 1369 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr( 1370 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(), 1371 IsArrow); 1372 1373 if (S.getLangOpts().ObjCAutoRefCount) { 1374 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 1375 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc)) 1376 S.recordUseOfEvaluatedWeak(Result); 1377 } 1378 } 1379 1380 return Result; 1381 } 1382 1383 // Objective-C property access. 1384 const ObjCObjectPointerType *OPT; 1385 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) { 1386 if (!SS.isEmpty() && !SS.isInvalid()) { 1387 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access) 1388 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange()); 1389 SS.clear(); 1390 } 1391 1392 // This actually uses the base as an r-value. 1393 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get()); 1394 if (BaseExpr.isInvalid()) 1395 return ExprError(); 1396 1397 assert(S.Context.hasSameUnqualifiedType(BaseType, 1398 BaseExpr.get()->getType())); 1399 1400 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1401 1402 const ObjCObjectType *OT = OPT->getObjectType(); 1403 1404 // id, with and without qualifiers. 1405 if (OT->isObjCId()) { 1406 // Check protocols on qualified interfaces. 1407 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member); 1408 if (Decl *PMDecl = 1409 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) { 1410 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 1411 // Check the use of this declaration 1412 if (S.DiagnoseUseOfDecl(PD, MemberLoc)) 1413 return ExprError(); 1414 1415 return new (S.Context) 1416 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue, 1417 OK_ObjCProperty, MemberLoc, BaseExpr.get()); 1418 } 1419 1420 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 1421 // Check the use of this method. 1422 if (S.DiagnoseUseOfDecl(OMD, MemberLoc)) 1423 return ExprError(); 1424 Selector SetterSel = 1425 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(), 1426 S.PP.getSelectorTable(), 1427 Member); 1428 ObjCMethodDecl *SMD = nullptr; 1429 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, 1430 /*Property id*/ nullptr, 1431 SetterSel, S.Context)) 1432 SMD = dyn_cast<ObjCMethodDecl>(SDecl); 1433 1434 return new (S.Context) 1435 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue, 1436 OK_ObjCProperty, MemberLoc, BaseExpr.get()); 1437 } 1438 } 1439 // Use of id.member can only be for a property reference. Do not 1440 // use the 'id' redefinition in this case. 1441 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr)) 1442 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, 1443 ObjCImpDecl, HasTemplateArgs); 1444 1445 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found) 1446 << MemberName << BaseType); 1447 } 1448 1449 // 'Class', unqualified only. 1450 if (OT->isObjCClass()) { 1451 // Only works in a method declaration (??!). 1452 ObjCMethodDecl *MD = S.getCurMethodDecl(); 1453 if (!MD) { 1454 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr)) 1455 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, 1456 ObjCImpDecl, HasTemplateArgs); 1457 1458 goto fail; 1459 } 1460 1461 // Also must look for a getter name which uses property syntax. 1462 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member); 1463 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 1464 ObjCMethodDecl *Getter; 1465 if ((Getter = IFace->lookupClassMethod(Sel))) { 1466 // Check the use of this method. 1467 if (S.DiagnoseUseOfDecl(Getter, MemberLoc)) 1468 return ExprError(); 1469 } else 1470 Getter = IFace->lookupPrivateMethod(Sel, false); 1471 // If we found a getter then this may be a valid dot-reference, we 1472 // will look for the matching setter, in case it is needed. 1473 Selector SetterSel = 1474 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(), 1475 S.PP.getSelectorTable(), 1476 Member); 1477 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 1478 if (!Setter) { 1479 // If this reference is in an @implementation, also check for 'private' 1480 // methods. 1481 Setter = IFace->lookupPrivateMethod(SetterSel, false); 1482 } 1483 1484 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc)) 1485 return ExprError(); 1486 1487 if (Getter || Setter) { 1488 return new (S.Context) ObjCPropertyRefExpr( 1489 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue, 1490 OK_ObjCProperty, MemberLoc, BaseExpr.get()); 1491 } 1492 1493 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr)) 1494 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, 1495 ObjCImpDecl, HasTemplateArgs); 1496 1497 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found) 1498 << MemberName << BaseType); 1499 } 1500 1501 // Normal property access. 1502 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName, 1503 MemberLoc, SourceLocation(), QualType(), 1504 false); 1505 } 1506 1507 // Handle 'field access' to vectors, such as 'V.xx'. 1508 if (BaseType->isExtVectorType()) { 1509 // FIXME: this expr should store IsArrow. 1510 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1511 ExprValueKind VK; 1512 if (IsArrow) 1513 VK = VK_LValue; 1514 else { 1515 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get())) 1516 VK = POE->getSyntacticForm()->getValueKind(); 1517 else 1518 VK = BaseExpr.get()->getValueKind(); 1519 } 1520 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc, 1521 Member, MemberLoc); 1522 if (ret.isNull()) 1523 return ExprError(); 1524 1525 return new (S.Context) 1526 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc); 1527 } 1528 1529 // Adjust builtin-sel to the appropriate redefinition type if that's 1530 // not just a pointer to builtin-sel again. 1531 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) && 1532 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) { 1533 BaseExpr = S.ImpCastExprToType( 1534 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast); 1535 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, 1536 ObjCImpDecl, HasTemplateArgs); 1537 } 1538 1539 // Failure cases. 1540 fail: 1541 1542 // Recover from dot accesses to pointers, e.g.: 1543 // type *foo; 1544 // foo.bar 1545 // This is actually well-formed in two cases: 1546 // - 'type' is an Objective C type 1547 // - 'bar' is a pseudo-destructor name which happens to refer to 1548 // the appropriate pointer type 1549 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 1550 if (!IsArrow && Ptr->getPointeeType()->isRecordType() && 1551 MemberName.getNameKind() != DeclarationName::CXXDestructorName) { 1552 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 1553 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() 1554 << FixItHint::CreateReplacement(OpLoc, "->"); 1555 1556 // Recurse as an -> access. 1557 IsArrow = true; 1558 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, 1559 ObjCImpDecl, HasTemplateArgs); 1560 } 1561 } 1562 1563 // If the user is trying to apply -> or . to a function name, it's probably 1564 // because they forgot parentheses to call that function. 1565 if (S.tryToRecoverWithCall( 1566 BaseExpr, S.PDiag(diag::err_member_reference_needs_call), 1567 /*complain*/ false, 1568 IsArrow ? &isPointerToRecordType : &isRecordType)) { 1569 if (BaseExpr.isInvalid()) 1570 return ExprError(); 1571 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get()); 1572 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS, 1573 ObjCImpDecl, HasTemplateArgs); 1574 } 1575 1576 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union) 1577 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc; 1578 1579 return ExprError(); 1580 } 1581 1582 /// The main callback when the parser finds something like 1583 /// expression . [nested-name-specifier] identifier 1584 /// expression -> [nested-name-specifier] identifier 1585 /// where 'identifier' encompasses a fairly broad spectrum of 1586 /// possibilities, including destructor and operator references. 1587 /// 1588 /// \param OpKind either tok::arrow or tok::period 1589 /// \param ObjCImpDecl the current Objective-C \@implementation 1590 /// decl; this is an ugly hack around the fact that Objective-C 1591 /// \@implementations aren't properly put in the context chain 1592 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, 1593 SourceLocation OpLoc, 1594 tok::TokenKind OpKind, 1595 CXXScopeSpec &SS, 1596 SourceLocation TemplateKWLoc, 1597 UnqualifiedId &Id, 1598 Decl *ObjCImpDecl) { 1599 if (SS.isSet() && SS.isInvalid()) 1600 return ExprError(); 1601 1602 // Warn about the explicit constructor calls Microsoft extension. 1603 if (getLangOpts().MicrosoftExt && 1604 Id.getKind() == UnqualifiedId::IK_ConstructorName) 1605 Diag(Id.getSourceRange().getBegin(), 1606 diag::ext_ms_explicit_constructor_call); 1607 1608 TemplateArgumentListInfo TemplateArgsBuffer; 1609 1610 // Decompose the name into its component parts. 1611 DeclarationNameInfo NameInfo; 1612 const TemplateArgumentListInfo *TemplateArgs; 1613 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, 1614 NameInfo, TemplateArgs); 1615 1616 DeclarationName Name = NameInfo.getName(); 1617 bool IsArrow = (OpKind == tok::arrow); 1618 1619 NamedDecl *FirstQualifierInScope 1620 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep())); 1621 1622 // This is a postfix expression, so get rid of ParenListExprs. 1623 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 1624 if (Result.isInvalid()) return ExprError(); 1625 Base = Result.get(); 1626 1627 if (Base->getType()->isDependentType() || Name.isDependentName() || 1628 isDependentScopeSpecifier(SS)) { 1629 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS, 1630 TemplateKWLoc, FirstQualifierInScope, 1631 NameInfo, TemplateArgs); 1632 } 1633 1634 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl}; 1635 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS, 1636 TemplateKWLoc, FirstQualifierInScope, 1637 NameInfo, TemplateArgs, &ExtraArgs); 1638 } 1639 1640 static ExprResult 1641 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 1642 SourceLocation OpLoc, const CXXScopeSpec &SS, 1643 FieldDecl *Field, DeclAccessPair FoundDecl, 1644 const DeclarationNameInfo &MemberNameInfo) { 1645 // x.a is an l-value if 'a' has a reference type. Otherwise: 1646 // x.a is an l-value/x-value/pr-value if the base is (and note 1647 // that *x is always an l-value), except that if the base isn't 1648 // an ordinary object then we must have an rvalue. 1649 ExprValueKind VK = VK_LValue; 1650 ExprObjectKind OK = OK_Ordinary; 1651 if (!IsArrow) { 1652 if (BaseExpr->getObjectKind() == OK_Ordinary) 1653 VK = BaseExpr->getValueKind(); 1654 else 1655 VK = VK_RValue; 1656 } 1657 if (VK != VK_RValue && Field->isBitField()) 1658 OK = OK_BitField; 1659 1660 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 1661 QualType MemberType = Field->getType(); 1662 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) { 1663 MemberType = Ref->getPointeeType(); 1664 VK = VK_LValue; 1665 } else { 1666 QualType BaseType = BaseExpr->getType(); 1667 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 1668 1669 Qualifiers BaseQuals = BaseType.getQualifiers(); 1670 1671 // GC attributes are never picked up by members. 1672 BaseQuals.removeObjCGCAttr(); 1673 1674 // CVR attributes from the base are picked up by members, 1675 // except that 'mutable' members don't pick up 'const'. 1676 if (Field->isMutable()) BaseQuals.removeConst(); 1677 1678 Qualifiers MemberQuals 1679 = S.Context.getCanonicalType(MemberType).getQualifiers(); 1680 1681 assert(!MemberQuals.hasAddressSpace()); 1682 1683 1684 Qualifiers Combined = BaseQuals + MemberQuals; 1685 if (Combined != MemberQuals) 1686 MemberType = S.Context.getQualifiedType(MemberType, Combined); 1687 } 1688 1689 S.UnusedPrivateFields.remove(Field); 1690 1691 ExprResult Base = 1692 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(), 1693 FoundDecl, Field); 1694 if (Base.isInvalid()) 1695 return ExprError(); 1696 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS, 1697 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl, 1698 MemberNameInfo, MemberType, VK, OK); 1699 } 1700 1701 /// Builds an implicit member access expression. The current context 1702 /// is known to be an instance method, and the given unqualified lookup 1703 /// set is known to contain only instance members, at least one of which 1704 /// is from an appropriate type. 1705 ExprResult 1706 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, 1707 SourceLocation TemplateKWLoc, 1708 LookupResult &R, 1709 const TemplateArgumentListInfo *TemplateArgs, 1710 bool IsKnownInstance) { 1711 assert(!R.empty() && !R.isAmbiguous()); 1712 1713 SourceLocation loc = R.getNameLoc(); 1714 1715 // If this is known to be an instance access, go ahead and build an 1716 // implicit 'this' expression now. 1717 // 'this' expression now. 1718 QualType ThisTy = getCurrentThisType(); 1719 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'"); 1720 1721 Expr *baseExpr = nullptr; // null signifies implicit access 1722 if (IsKnownInstance) { 1723 SourceLocation Loc = R.getNameLoc(); 1724 if (SS.getRange().isValid()) 1725 Loc = SS.getRange().getBegin(); 1726 CheckCXXThisCapture(Loc); 1727 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true); 1728 } 1729 1730 return BuildMemberReferenceExpr(baseExpr, ThisTy, 1731 /*OpLoc*/ SourceLocation(), 1732 /*IsArrow*/ true, 1733 SS, TemplateKWLoc, 1734 /*FirstQualifierInScope*/ nullptr, 1735 R, TemplateArgs); 1736 } 1737