SemaExprMember.cpp 69 KB

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