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