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