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