xref: /openbsd-src/gnu/llvm/clang/lib/Sema/SemaAccess.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file provides Sema routines for C++ access control semantics.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/Basic/Specifiers.h"
14e5dd7070Spatrick #include "clang/Sema/SemaInternal.h"
15e5dd7070Spatrick #include "clang/AST/ASTContext.h"
16e5dd7070Spatrick #include "clang/AST/CXXInheritance.h"
17e5dd7070Spatrick #include "clang/AST/DeclCXX.h"
18e5dd7070Spatrick #include "clang/AST/DeclFriend.h"
19e5dd7070Spatrick #include "clang/AST/DeclObjC.h"
20e5dd7070Spatrick #include "clang/AST/DependentDiagnostic.h"
21e5dd7070Spatrick #include "clang/AST/ExprCXX.h"
22e5dd7070Spatrick #include "clang/Sema/DelayedDiagnostic.h"
23e5dd7070Spatrick #include "clang/Sema/Initialization.h"
24e5dd7070Spatrick #include "clang/Sema/Lookup.h"
25e5dd7070Spatrick 
26e5dd7070Spatrick using namespace clang;
27e5dd7070Spatrick using namespace sema;
28e5dd7070Spatrick 
29e5dd7070Spatrick /// A copy of Sema's enum without AR_delayed.
30e5dd7070Spatrick enum AccessResult {
31e5dd7070Spatrick   AR_accessible,
32e5dd7070Spatrick   AR_inaccessible,
33e5dd7070Spatrick   AR_dependent
34e5dd7070Spatrick };
35e5dd7070Spatrick 
36e5dd7070Spatrick /// SetMemberAccessSpecifier - Set the access specifier of a member.
37e5dd7070Spatrick /// Returns true on error (when the previous member decl access specifier
38e5dd7070Spatrick /// is different from the new member decl access specifier).
SetMemberAccessSpecifier(NamedDecl * MemberDecl,NamedDecl * PrevMemberDecl,AccessSpecifier LexicalAS)39e5dd7070Spatrick bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
40e5dd7070Spatrick                                     NamedDecl *PrevMemberDecl,
41e5dd7070Spatrick                                     AccessSpecifier LexicalAS) {
42e5dd7070Spatrick   if (!PrevMemberDecl) {
43e5dd7070Spatrick     // Use the lexical access specifier.
44e5dd7070Spatrick     MemberDecl->setAccess(LexicalAS);
45e5dd7070Spatrick     return false;
46e5dd7070Spatrick   }
47e5dd7070Spatrick 
48e5dd7070Spatrick   // C++ [class.access.spec]p3: When a member is redeclared its access
49e5dd7070Spatrick   // specifier must be same as its initial declaration.
50e5dd7070Spatrick   if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) {
51e5dd7070Spatrick     Diag(MemberDecl->getLocation(),
52e5dd7070Spatrick          diag::err_class_redeclared_with_different_access)
53e5dd7070Spatrick       << MemberDecl << LexicalAS;
54e5dd7070Spatrick     Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
55e5dd7070Spatrick       << PrevMemberDecl << PrevMemberDecl->getAccess();
56e5dd7070Spatrick 
57e5dd7070Spatrick     MemberDecl->setAccess(LexicalAS);
58e5dd7070Spatrick     return true;
59e5dd7070Spatrick   }
60e5dd7070Spatrick 
61e5dd7070Spatrick   MemberDecl->setAccess(PrevMemberDecl->getAccess());
62e5dd7070Spatrick   return false;
63e5dd7070Spatrick }
64e5dd7070Spatrick 
FindDeclaringClass(NamedDecl * D)65e5dd7070Spatrick static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
66e5dd7070Spatrick   DeclContext *DC = D->getDeclContext();
67e5dd7070Spatrick 
68e5dd7070Spatrick   // This can only happen at top: enum decls only "publish" their
69e5dd7070Spatrick   // immediate members.
70e5dd7070Spatrick   if (isa<EnumDecl>(DC))
71e5dd7070Spatrick     DC = cast<EnumDecl>(DC)->getDeclContext();
72e5dd7070Spatrick 
73e5dd7070Spatrick   CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
74e5dd7070Spatrick   while (DeclaringClass->isAnonymousStructOrUnion())
75e5dd7070Spatrick     DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
76e5dd7070Spatrick   return DeclaringClass;
77e5dd7070Spatrick }
78e5dd7070Spatrick 
79e5dd7070Spatrick namespace {
80e5dd7070Spatrick struct EffectiveContext {
EffectiveContext__anon2935d57e0111::EffectiveContext81e5dd7070Spatrick   EffectiveContext() : Inner(nullptr), Dependent(false) {}
82e5dd7070Spatrick 
EffectiveContext__anon2935d57e0111::EffectiveContext83e5dd7070Spatrick   explicit EffectiveContext(DeclContext *DC)
84e5dd7070Spatrick     : Inner(DC),
85e5dd7070Spatrick       Dependent(DC->isDependentContext()) {
86e5dd7070Spatrick 
87a9ac8606Spatrick     // An implicit deduction guide is semantically in the context enclosing the
88a9ac8606Spatrick     // class template, but for access purposes behaves like the constructor
89a9ac8606Spatrick     // from which it was produced.
90a9ac8606Spatrick     if (auto *DGD = dyn_cast<CXXDeductionGuideDecl>(DC)) {
91a9ac8606Spatrick       if (DGD->isImplicit()) {
92a9ac8606Spatrick         DC = DGD->getCorrespondingConstructor();
93a9ac8606Spatrick         if (!DC) {
94a9ac8606Spatrick           // The copy deduction candidate doesn't have a corresponding
95a9ac8606Spatrick           // constructor.
96a9ac8606Spatrick           DC = cast<DeclContext>(DGD->getDeducedTemplate()->getTemplatedDecl());
97a9ac8606Spatrick         }
98a9ac8606Spatrick       }
99a9ac8606Spatrick     }
100a9ac8606Spatrick 
101e5dd7070Spatrick     // C++11 [class.access.nest]p1:
102e5dd7070Spatrick     //   A nested class is a member and as such has the same access
103e5dd7070Spatrick     //   rights as any other member.
104e5dd7070Spatrick     // C++11 [class.access]p2:
105e5dd7070Spatrick     //   A member of a class can also access all the names to which
106e5dd7070Spatrick     //   the class has access.  A local class of a member function
107e5dd7070Spatrick     //   may access the same names that the member function itself
108e5dd7070Spatrick     //   may access.
109e5dd7070Spatrick     // This almost implies that the privileges of nesting are transitive.
110e5dd7070Spatrick     // Technically it says nothing about the local classes of non-member
111e5dd7070Spatrick     // functions (which can gain privileges through friendship), but we
112e5dd7070Spatrick     // take that as an oversight.
113e5dd7070Spatrick     while (true) {
114e5dd7070Spatrick       // We want to add canonical declarations to the EC lists for
115e5dd7070Spatrick       // simplicity of checking, but we need to walk up through the
116e5dd7070Spatrick       // actual current DC chain.  Otherwise, something like a local
117e5dd7070Spatrick       // extern or friend which happens to be the canonical
118e5dd7070Spatrick       // declaration will really mess us up.
119e5dd7070Spatrick 
120e5dd7070Spatrick       if (isa<CXXRecordDecl>(DC)) {
121e5dd7070Spatrick         CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
122e5dd7070Spatrick         Records.push_back(Record->getCanonicalDecl());
123e5dd7070Spatrick         DC = Record->getDeclContext();
124e5dd7070Spatrick       } else if (isa<FunctionDecl>(DC)) {
125e5dd7070Spatrick         FunctionDecl *Function = cast<FunctionDecl>(DC);
126e5dd7070Spatrick         Functions.push_back(Function->getCanonicalDecl());
127e5dd7070Spatrick         if (Function->getFriendObjectKind())
128e5dd7070Spatrick           DC = Function->getLexicalDeclContext();
129e5dd7070Spatrick         else
130e5dd7070Spatrick           DC = Function->getDeclContext();
131e5dd7070Spatrick       } else if (DC->isFileContext()) {
132e5dd7070Spatrick         break;
133e5dd7070Spatrick       } else {
134e5dd7070Spatrick         DC = DC->getParent();
135e5dd7070Spatrick       }
136e5dd7070Spatrick     }
137e5dd7070Spatrick   }
138e5dd7070Spatrick 
isDependent__anon2935d57e0111::EffectiveContext139e5dd7070Spatrick   bool isDependent() const { return Dependent; }
140e5dd7070Spatrick 
includesClass__anon2935d57e0111::EffectiveContext141e5dd7070Spatrick   bool includesClass(const CXXRecordDecl *R) const {
142e5dd7070Spatrick     R = R->getCanonicalDecl();
143*12c85518Srobert     return llvm::is_contained(Records, R);
144e5dd7070Spatrick   }
145e5dd7070Spatrick 
146e5dd7070Spatrick   /// Retrieves the innermost "useful" context.  Can be null if we're
147e5dd7070Spatrick   /// doing access-control without privileges.
getInnerContext__anon2935d57e0111::EffectiveContext148e5dd7070Spatrick   DeclContext *getInnerContext() const {
149e5dd7070Spatrick     return Inner;
150e5dd7070Spatrick   }
151e5dd7070Spatrick 
152e5dd7070Spatrick   typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
153e5dd7070Spatrick 
154e5dd7070Spatrick   DeclContext *Inner;
155e5dd7070Spatrick   SmallVector<FunctionDecl*, 4> Functions;
156e5dd7070Spatrick   SmallVector<CXXRecordDecl*, 4> Records;
157e5dd7070Spatrick   bool Dependent;
158e5dd7070Spatrick };
159e5dd7070Spatrick 
160e5dd7070Spatrick /// Like sema::AccessedEntity, but kindly lets us scribble all over
161e5dd7070Spatrick /// it.
162e5dd7070Spatrick struct AccessTarget : public AccessedEntity {
AccessTarget__anon2935d57e0111::AccessTarget163e5dd7070Spatrick   AccessTarget(const AccessedEntity &Entity)
164e5dd7070Spatrick     : AccessedEntity(Entity) {
165e5dd7070Spatrick     initialize();
166e5dd7070Spatrick   }
167e5dd7070Spatrick 
AccessTarget__anon2935d57e0111::AccessTarget168e5dd7070Spatrick   AccessTarget(ASTContext &Context,
169e5dd7070Spatrick                MemberNonce _,
170e5dd7070Spatrick                CXXRecordDecl *NamingClass,
171e5dd7070Spatrick                DeclAccessPair FoundDecl,
172e5dd7070Spatrick                QualType BaseObjectType)
173e5dd7070Spatrick     : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
174e5dd7070Spatrick                      FoundDecl, BaseObjectType) {
175e5dd7070Spatrick     initialize();
176e5dd7070Spatrick   }
177e5dd7070Spatrick 
AccessTarget__anon2935d57e0111::AccessTarget178e5dd7070Spatrick   AccessTarget(ASTContext &Context,
179e5dd7070Spatrick                BaseNonce _,
180e5dd7070Spatrick                CXXRecordDecl *BaseClass,
181e5dd7070Spatrick                CXXRecordDecl *DerivedClass,
182e5dd7070Spatrick                AccessSpecifier Access)
183e5dd7070Spatrick     : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
184e5dd7070Spatrick                      Access) {
185e5dd7070Spatrick     initialize();
186e5dd7070Spatrick   }
187e5dd7070Spatrick 
isInstanceMember__anon2935d57e0111::AccessTarget188e5dd7070Spatrick   bool isInstanceMember() const {
189e5dd7070Spatrick     return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
190e5dd7070Spatrick   }
191e5dd7070Spatrick 
hasInstanceContext__anon2935d57e0111::AccessTarget192e5dd7070Spatrick   bool hasInstanceContext() const {
193e5dd7070Spatrick     return HasInstanceContext;
194e5dd7070Spatrick   }
195e5dd7070Spatrick 
196e5dd7070Spatrick   class SavedInstanceContext {
197e5dd7070Spatrick   public:
SavedInstanceContext(SavedInstanceContext && S)198e5dd7070Spatrick     SavedInstanceContext(SavedInstanceContext &&S)
199e5dd7070Spatrick         : Target(S.Target), Has(S.Has) {
200e5dd7070Spatrick       S.Target = nullptr;
201e5dd7070Spatrick     }
~SavedInstanceContext()202e5dd7070Spatrick     ~SavedInstanceContext() {
203e5dd7070Spatrick       if (Target)
204e5dd7070Spatrick         Target->HasInstanceContext = Has;
205e5dd7070Spatrick     }
206e5dd7070Spatrick 
207e5dd7070Spatrick   private:
208e5dd7070Spatrick     friend struct AccessTarget;
SavedInstanceContext(AccessTarget & Target)209e5dd7070Spatrick     explicit SavedInstanceContext(AccessTarget &Target)
210e5dd7070Spatrick         : Target(&Target), Has(Target.HasInstanceContext) {}
211e5dd7070Spatrick     AccessTarget *Target;
212e5dd7070Spatrick     bool Has;
213e5dd7070Spatrick   };
214e5dd7070Spatrick 
saveInstanceContext__anon2935d57e0111::AccessTarget215e5dd7070Spatrick   SavedInstanceContext saveInstanceContext() {
216e5dd7070Spatrick     return SavedInstanceContext(*this);
217e5dd7070Spatrick   }
218e5dd7070Spatrick 
suppressInstanceContext__anon2935d57e0111::AccessTarget219e5dd7070Spatrick   void suppressInstanceContext() {
220e5dd7070Spatrick     HasInstanceContext = false;
221e5dd7070Spatrick   }
222e5dd7070Spatrick 
resolveInstanceContext__anon2935d57e0111::AccessTarget223e5dd7070Spatrick   const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
224e5dd7070Spatrick     assert(HasInstanceContext);
225e5dd7070Spatrick     if (CalculatedInstanceContext)
226e5dd7070Spatrick       return InstanceContext;
227e5dd7070Spatrick 
228e5dd7070Spatrick     CalculatedInstanceContext = true;
229e5dd7070Spatrick     DeclContext *IC = S.computeDeclContext(getBaseObjectType());
230e5dd7070Spatrick     InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
231e5dd7070Spatrick                           : nullptr);
232e5dd7070Spatrick     return InstanceContext;
233e5dd7070Spatrick   }
234e5dd7070Spatrick 
getDeclaringClass__anon2935d57e0111::AccessTarget235e5dd7070Spatrick   const CXXRecordDecl *getDeclaringClass() const {
236e5dd7070Spatrick     return DeclaringClass;
237e5dd7070Spatrick   }
238e5dd7070Spatrick 
239e5dd7070Spatrick   /// The "effective" naming class is the canonical non-anonymous
240e5dd7070Spatrick   /// class containing the actual naming class.
getEffectiveNamingClass__anon2935d57e0111::AccessTarget241e5dd7070Spatrick   const CXXRecordDecl *getEffectiveNamingClass() const {
242e5dd7070Spatrick     const CXXRecordDecl *namingClass = getNamingClass();
243e5dd7070Spatrick     while (namingClass->isAnonymousStructOrUnion())
244e5dd7070Spatrick       namingClass = cast<CXXRecordDecl>(namingClass->getParent());
245e5dd7070Spatrick     return namingClass->getCanonicalDecl();
246e5dd7070Spatrick   }
247e5dd7070Spatrick 
248e5dd7070Spatrick private:
initialize__anon2935d57e0111::AccessTarget249e5dd7070Spatrick   void initialize() {
250e5dd7070Spatrick     HasInstanceContext = (isMemberAccess() &&
251e5dd7070Spatrick                           !getBaseObjectType().isNull() &&
252e5dd7070Spatrick                           getTargetDecl()->isCXXInstanceMember());
253e5dd7070Spatrick     CalculatedInstanceContext = false;
254e5dd7070Spatrick     InstanceContext = nullptr;
255e5dd7070Spatrick 
256e5dd7070Spatrick     if (isMemberAccess())
257e5dd7070Spatrick       DeclaringClass = FindDeclaringClass(getTargetDecl());
258e5dd7070Spatrick     else
259e5dd7070Spatrick       DeclaringClass = getBaseClass();
260e5dd7070Spatrick     DeclaringClass = DeclaringClass->getCanonicalDecl();
261e5dd7070Spatrick   }
262e5dd7070Spatrick 
263e5dd7070Spatrick   bool HasInstanceContext : 1;
264e5dd7070Spatrick   mutable bool CalculatedInstanceContext : 1;
265e5dd7070Spatrick   mutable const CXXRecordDecl *InstanceContext;
266e5dd7070Spatrick   const CXXRecordDecl *DeclaringClass;
267e5dd7070Spatrick };
268e5dd7070Spatrick 
269e5dd7070Spatrick }
270e5dd7070Spatrick 
271e5dd7070Spatrick /// Checks whether one class might instantiate to the other.
MightInstantiateTo(const CXXRecordDecl * From,const CXXRecordDecl * To)272e5dd7070Spatrick static bool MightInstantiateTo(const CXXRecordDecl *From,
273e5dd7070Spatrick                                const CXXRecordDecl *To) {
274e5dd7070Spatrick   // Declaration names are always preserved by instantiation.
275e5dd7070Spatrick   if (From->getDeclName() != To->getDeclName())
276e5dd7070Spatrick     return false;
277e5dd7070Spatrick 
278e5dd7070Spatrick   const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
279e5dd7070Spatrick   const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
280e5dd7070Spatrick   if (FromDC == ToDC) return true;
281e5dd7070Spatrick   if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
282e5dd7070Spatrick 
283e5dd7070Spatrick   // Be conservative.
284e5dd7070Spatrick   return true;
285e5dd7070Spatrick }
286e5dd7070Spatrick 
287e5dd7070Spatrick /// Checks whether one class is derived from another, inclusively.
288e5dd7070Spatrick /// Properly indicates when it couldn't be determined due to
289e5dd7070Spatrick /// dependence.
290e5dd7070Spatrick ///
291e5dd7070Spatrick /// This should probably be donated to AST or at least Sema.
IsDerivedFromInclusive(const CXXRecordDecl * Derived,const CXXRecordDecl * Target)292e5dd7070Spatrick static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
293e5dd7070Spatrick                                            const CXXRecordDecl *Target) {
294e5dd7070Spatrick   assert(Derived->getCanonicalDecl() == Derived);
295e5dd7070Spatrick   assert(Target->getCanonicalDecl() == Target);
296e5dd7070Spatrick 
297e5dd7070Spatrick   if (Derived == Target) return AR_accessible;
298e5dd7070Spatrick 
299e5dd7070Spatrick   bool CheckDependent = Derived->isDependentContext();
300e5dd7070Spatrick   if (CheckDependent && MightInstantiateTo(Derived, Target))
301e5dd7070Spatrick     return AR_dependent;
302e5dd7070Spatrick 
303e5dd7070Spatrick   AccessResult OnFailure = AR_inaccessible;
304e5dd7070Spatrick   SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
305e5dd7070Spatrick 
306e5dd7070Spatrick   while (true) {
307e5dd7070Spatrick     if (Derived->isDependentContext() && !Derived->hasDefinition() &&
308e5dd7070Spatrick         !Derived->isLambda())
309e5dd7070Spatrick       return AR_dependent;
310e5dd7070Spatrick 
311e5dd7070Spatrick     for (const auto &I : Derived->bases()) {
312e5dd7070Spatrick       const CXXRecordDecl *RD;
313e5dd7070Spatrick 
314e5dd7070Spatrick       QualType T = I.getType();
315e5dd7070Spatrick       if (const RecordType *RT = T->getAs<RecordType>()) {
316e5dd7070Spatrick         RD = cast<CXXRecordDecl>(RT->getDecl());
317e5dd7070Spatrick       } else if (const InjectedClassNameType *IT
318e5dd7070Spatrick                    = T->getAs<InjectedClassNameType>()) {
319e5dd7070Spatrick         RD = IT->getDecl();
320e5dd7070Spatrick       } else {
321e5dd7070Spatrick         assert(T->isDependentType() && "non-dependent base wasn't a record?");
322e5dd7070Spatrick         OnFailure = AR_dependent;
323e5dd7070Spatrick         continue;
324e5dd7070Spatrick       }
325e5dd7070Spatrick 
326e5dd7070Spatrick       RD = RD->getCanonicalDecl();
327e5dd7070Spatrick       if (RD == Target) return AR_accessible;
328e5dd7070Spatrick       if (CheckDependent && MightInstantiateTo(RD, Target))
329e5dd7070Spatrick         OnFailure = AR_dependent;
330e5dd7070Spatrick 
331e5dd7070Spatrick       Queue.push_back(RD);
332e5dd7070Spatrick     }
333e5dd7070Spatrick 
334e5dd7070Spatrick     if (Queue.empty()) break;
335e5dd7070Spatrick 
336e5dd7070Spatrick     Derived = Queue.pop_back_val();
337e5dd7070Spatrick   }
338e5dd7070Spatrick 
339e5dd7070Spatrick   return OnFailure;
340e5dd7070Spatrick }
341e5dd7070Spatrick 
342e5dd7070Spatrick 
MightInstantiateTo(Sema & S,DeclContext * Context,DeclContext * Friend)343e5dd7070Spatrick static bool MightInstantiateTo(Sema &S, DeclContext *Context,
344e5dd7070Spatrick                                DeclContext *Friend) {
345e5dd7070Spatrick   if (Friend == Context)
346e5dd7070Spatrick     return true;
347e5dd7070Spatrick 
348e5dd7070Spatrick   assert(!Friend->isDependentContext() &&
349e5dd7070Spatrick          "can't handle friends with dependent contexts here");
350e5dd7070Spatrick 
351e5dd7070Spatrick   if (!Context->isDependentContext())
352e5dd7070Spatrick     return false;
353e5dd7070Spatrick 
354e5dd7070Spatrick   if (Friend->isFileContext())
355e5dd7070Spatrick     return false;
356e5dd7070Spatrick 
357e5dd7070Spatrick   // TODO: this is very conservative
358e5dd7070Spatrick   return true;
359e5dd7070Spatrick }
360e5dd7070Spatrick 
361e5dd7070Spatrick // Asks whether the type in 'context' can ever instantiate to the type
362e5dd7070Spatrick // in 'friend'.
MightInstantiateTo(Sema & S,CanQualType Context,CanQualType Friend)363e5dd7070Spatrick static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
364e5dd7070Spatrick   if (Friend == Context)
365e5dd7070Spatrick     return true;
366e5dd7070Spatrick 
367e5dd7070Spatrick   if (!Friend->isDependentType() && !Context->isDependentType())
368e5dd7070Spatrick     return false;
369e5dd7070Spatrick 
370e5dd7070Spatrick   // TODO: this is very conservative.
371e5dd7070Spatrick   return true;
372e5dd7070Spatrick }
373e5dd7070Spatrick 
MightInstantiateTo(Sema & S,FunctionDecl * Context,FunctionDecl * Friend)374e5dd7070Spatrick static bool MightInstantiateTo(Sema &S,
375e5dd7070Spatrick                                FunctionDecl *Context,
376e5dd7070Spatrick                                FunctionDecl *Friend) {
377e5dd7070Spatrick   if (Context->getDeclName() != Friend->getDeclName())
378e5dd7070Spatrick     return false;
379e5dd7070Spatrick 
380e5dd7070Spatrick   if (!MightInstantiateTo(S,
381e5dd7070Spatrick                           Context->getDeclContext(),
382e5dd7070Spatrick                           Friend->getDeclContext()))
383e5dd7070Spatrick     return false;
384e5dd7070Spatrick 
385e5dd7070Spatrick   CanQual<FunctionProtoType> FriendTy
386e5dd7070Spatrick     = S.Context.getCanonicalType(Friend->getType())
387e5dd7070Spatrick          ->getAs<FunctionProtoType>();
388e5dd7070Spatrick   CanQual<FunctionProtoType> ContextTy
389e5dd7070Spatrick     = S.Context.getCanonicalType(Context->getType())
390e5dd7070Spatrick          ->getAs<FunctionProtoType>();
391e5dd7070Spatrick 
392e5dd7070Spatrick   // There isn't any way that I know of to add qualifiers
393e5dd7070Spatrick   // during instantiation.
394e5dd7070Spatrick   if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
395e5dd7070Spatrick     return false;
396e5dd7070Spatrick 
397e5dd7070Spatrick   if (FriendTy->getNumParams() != ContextTy->getNumParams())
398e5dd7070Spatrick     return false;
399e5dd7070Spatrick 
400e5dd7070Spatrick   if (!MightInstantiateTo(S, ContextTy->getReturnType(),
401e5dd7070Spatrick                           FriendTy->getReturnType()))
402e5dd7070Spatrick     return false;
403e5dd7070Spatrick 
404e5dd7070Spatrick   for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
405e5dd7070Spatrick     if (!MightInstantiateTo(S, ContextTy->getParamType(I),
406e5dd7070Spatrick                             FriendTy->getParamType(I)))
407e5dd7070Spatrick       return false;
408e5dd7070Spatrick 
409e5dd7070Spatrick   return true;
410e5dd7070Spatrick }
411e5dd7070Spatrick 
MightInstantiateTo(Sema & S,FunctionTemplateDecl * Context,FunctionTemplateDecl * Friend)412e5dd7070Spatrick static bool MightInstantiateTo(Sema &S,
413e5dd7070Spatrick                                FunctionTemplateDecl *Context,
414e5dd7070Spatrick                                FunctionTemplateDecl *Friend) {
415e5dd7070Spatrick   return MightInstantiateTo(S,
416e5dd7070Spatrick                             Context->getTemplatedDecl(),
417e5dd7070Spatrick                             Friend->getTemplatedDecl());
418e5dd7070Spatrick }
419e5dd7070Spatrick 
MatchesFriend(Sema & S,const EffectiveContext & EC,const CXXRecordDecl * Friend)420e5dd7070Spatrick static AccessResult MatchesFriend(Sema &S,
421e5dd7070Spatrick                                   const EffectiveContext &EC,
422e5dd7070Spatrick                                   const CXXRecordDecl *Friend) {
423e5dd7070Spatrick   if (EC.includesClass(Friend))
424e5dd7070Spatrick     return AR_accessible;
425e5dd7070Spatrick 
426e5dd7070Spatrick   if (EC.isDependent()) {
427e5dd7070Spatrick     for (const CXXRecordDecl *Context : EC.Records) {
428e5dd7070Spatrick       if (MightInstantiateTo(Context, Friend))
429e5dd7070Spatrick         return AR_dependent;
430e5dd7070Spatrick     }
431e5dd7070Spatrick   }
432e5dd7070Spatrick 
433e5dd7070Spatrick   return AR_inaccessible;
434e5dd7070Spatrick }
435e5dd7070Spatrick 
MatchesFriend(Sema & S,const EffectiveContext & EC,CanQualType Friend)436e5dd7070Spatrick static AccessResult MatchesFriend(Sema &S,
437e5dd7070Spatrick                                   const EffectiveContext &EC,
438e5dd7070Spatrick                                   CanQualType Friend) {
439e5dd7070Spatrick   if (const RecordType *RT = Friend->getAs<RecordType>())
440e5dd7070Spatrick     return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
441e5dd7070Spatrick 
442e5dd7070Spatrick   // TODO: we can do better than this
443e5dd7070Spatrick   if (Friend->isDependentType())
444e5dd7070Spatrick     return AR_dependent;
445e5dd7070Spatrick 
446e5dd7070Spatrick   return AR_inaccessible;
447e5dd7070Spatrick }
448e5dd7070Spatrick 
449e5dd7070Spatrick /// Determines whether the given friend class template matches
450e5dd7070Spatrick /// anything in the effective context.
MatchesFriend(Sema & S,const EffectiveContext & EC,ClassTemplateDecl * Friend)451e5dd7070Spatrick static AccessResult MatchesFriend(Sema &S,
452e5dd7070Spatrick                                   const EffectiveContext &EC,
453e5dd7070Spatrick                                   ClassTemplateDecl *Friend) {
454e5dd7070Spatrick   AccessResult OnFailure = AR_inaccessible;
455e5dd7070Spatrick 
456e5dd7070Spatrick   // Check whether the friend is the template of a class in the
457e5dd7070Spatrick   // context chain.
458e5dd7070Spatrick   for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
459e5dd7070Spatrick          I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
460e5dd7070Spatrick     CXXRecordDecl *Record = *I;
461e5dd7070Spatrick 
462e5dd7070Spatrick     // Figure out whether the current class has a template:
463e5dd7070Spatrick     ClassTemplateDecl *CTD;
464e5dd7070Spatrick 
465e5dd7070Spatrick     // A specialization of the template...
466e5dd7070Spatrick     if (isa<ClassTemplateSpecializationDecl>(Record)) {
467e5dd7070Spatrick       CTD = cast<ClassTemplateSpecializationDecl>(Record)
468e5dd7070Spatrick         ->getSpecializedTemplate();
469e5dd7070Spatrick 
470e5dd7070Spatrick     // ... or the template pattern itself.
471e5dd7070Spatrick     } else {
472e5dd7070Spatrick       CTD = Record->getDescribedClassTemplate();
473e5dd7070Spatrick       if (!CTD) continue;
474e5dd7070Spatrick     }
475e5dd7070Spatrick 
476e5dd7070Spatrick     // It's a match.
477e5dd7070Spatrick     if (Friend == CTD->getCanonicalDecl())
478e5dd7070Spatrick       return AR_accessible;
479e5dd7070Spatrick 
480e5dd7070Spatrick     // If the context isn't dependent, it can't be a dependent match.
481e5dd7070Spatrick     if (!EC.isDependent())
482e5dd7070Spatrick       continue;
483e5dd7070Spatrick 
484e5dd7070Spatrick     // If the template names don't match, it can't be a dependent
485e5dd7070Spatrick     // match.
486e5dd7070Spatrick     if (CTD->getDeclName() != Friend->getDeclName())
487e5dd7070Spatrick       continue;
488e5dd7070Spatrick 
489e5dd7070Spatrick     // If the class's context can't instantiate to the friend's
490e5dd7070Spatrick     // context, it can't be a dependent match.
491e5dd7070Spatrick     if (!MightInstantiateTo(S, CTD->getDeclContext(),
492e5dd7070Spatrick                             Friend->getDeclContext()))
493e5dd7070Spatrick       continue;
494e5dd7070Spatrick 
495e5dd7070Spatrick     // Otherwise, it's a dependent match.
496e5dd7070Spatrick     OnFailure = AR_dependent;
497e5dd7070Spatrick   }
498e5dd7070Spatrick 
499e5dd7070Spatrick   return OnFailure;
500e5dd7070Spatrick }
501e5dd7070Spatrick 
502e5dd7070Spatrick /// Determines whether the given friend function matches anything in
503e5dd7070Spatrick /// the effective context.
MatchesFriend(Sema & S,const EffectiveContext & EC,FunctionDecl * Friend)504e5dd7070Spatrick static AccessResult MatchesFriend(Sema &S,
505e5dd7070Spatrick                                   const EffectiveContext &EC,
506e5dd7070Spatrick                                   FunctionDecl *Friend) {
507e5dd7070Spatrick   AccessResult OnFailure = AR_inaccessible;
508e5dd7070Spatrick 
509e5dd7070Spatrick   for (SmallVectorImpl<FunctionDecl*>::const_iterator
510e5dd7070Spatrick          I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
511e5dd7070Spatrick     if (Friend == *I)
512e5dd7070Spatrick       return AR_accessible;
513e5dd7070Spatrick 
514e5dd7070Spatrick     if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
515e5dd7070Spatrick       OnFailure = AR_dependent;
516e5dd7070Spatrick   }
517e5dd7070Spatrick 
518e5dd7070Spatrick   return OnFailure;
519e5dd7070Spatrick }
520e5dd7070Spatrick 
521e5dd7070Spatrick /// Determines whether the given friend function template matches
522e5dd7070Spatrick /// anything in the effective context.
MatchesFriend(Sema & S,const EffectiveContext & EC,FunctionTemplateDecl * Friend)523e5dd7070Spatrick static AccessResult MatchesFriend(Sema &S,
524e5dd7070Spatrick                                   const EffectiveContext &EC,
525e5dd7070Spatrick                                   FunctionTemplateDecl *Friend) {
526e5dd7070Spatrick   if (EC.Functions.empty()) return AR_inaccessible;
527e5dd7070Spatrick 
528e5dd7070Spatrick   AccessResult OnFailure = AR_inaccessible;
529e5dd7070Spatrick 
530e5dd7070Spatrick   for (SmallVectorImpl<FunctionDecl*>::const_iterator
531e5dd7070Spatrick          I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
532e5dd7070Spatrick 
533e5dd7070Spatrick     FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
534e5dd7070Spatrick     if (!FTD)
535e5dd7070Spatrick       FTD = (*I)->getDescribedFunctionTemplate();
536e5dd7070Spatrick     if (!FTD)
537e5dd7070Spatrick       continue;
538e5dd7070Spatrick 
539e5dd7070Spatrick     FTD = FTD->getCanonicalDecl();
540e5dd7070Spatrick 
541e5dd7070Spatrick     if (Friend == FTD)
542e5dd7070Spatrick       return AR_accessible;
543e5dd7070Spatrick 
544e5dd7070Spatrick     if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
545e5dd7070Spatrick       OnFailure = AR_dependent;
546e5dd7070Spatrick   }
547e5dd7070Spatrick 
548e5dd7070Spatrick   return OnFailure;
549e5dd7070Spatrick }
550e5dd7070Spatrick 
551e5dd7070Spatrick /// Determines whether the given friend declaration matches anything
552e5dd7070Spatrick /// in the effective context.
MatchesFriend(Sema & S,const EffectiveContext & EC,FriendDecl * FriendD)553e5dd7070Spatrick static AccessResult MatchesFriend(Sema &S,
554e5dd7070Spatrick                                   const EffectiveContext &EC,
555e5dd7070Spatrick                                   FriendDecl *FriendD) {
556e5dd7070Spatrick   // Whitelist accesses if there's an invalid or unsupported friend
557e5dd7070Spatrick   // declaration.
558e5dd7070Spatrick   if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
559e5dd7070Spatrick     return AR_accessible;
560e5dd7070Spatrick 
561e5dd7070Spatrick   if (TypeSourceInfo *T = FriendD->getFriendType())
562e5dd7070Spatrick     return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
563e5dd7070Spatrick 
564e5dd7070Spatrick   NamedDecl *Friend
565e5dd7070Spatrick     = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
566e5dd7070Spatrick 
567e5dd7070Spatrick   // FIXME: declarations with dependent or templated scope.
568e5dd7070Spatrick 
569e5dd7070Spatrick   if (isa<ClassTemplateDecl>(Friend))
570e5dd7070Spatrick     return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
571e5dd7070Spatrick 
572e5dd7070Spatrick   if (isa<FunctionTemplateDecl>(Friend))
573e5dd7070Spatrick     return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
574e5dd7070Spatrick 
575e5dd7070Spatrick   if (isa<CXXRecordDecl>(Friend))
576e5dd7070Spatrick     return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
577e5dd7070Spatrick 
578e5dd7070Spatrick   assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
579e5dd7070Spatrick   return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
580e5dd7070Spatrick }
581e5dd7070Spatrick 
GetFriendKind(Sema & S,const EffectiveContext & EC,const CXXRecordDecl * Class)582e5dd7070Spatrick static AccessResult GetFriendKind(Sema &S,
583e5dd7070Spatrick                                   const EffectiveContext &EC,
584e5dd7070Spatrick                                   const CXXRecordDecl *Class) {
585e5dd7070Spatrick   AccessResult OnFailure = AR_inaccessible;
586e5dd7070Spatrick 
587e5dd7070Spatrick   // Okay, check friends.
588e5dd7070Spatrick   for (auto *Friend : Class->friends()) {
589e5dd7070Spatrick     switch (MatchesFriend(S, EC, Friend)) {
590e5dd7070Spatrick     case AR_accessible:
591e5dd7070Spatrick       return AR_accessible;
592e5dd7070Spatrick 
593e5dd7070Spatrick     case AR_inaccessible:
594e5dd7070Spatrick       continue;
595e5dd7070Spatrick 
596e5dd7070Spatrick     case AR_dependent:
597e5dd7070Spatrick       OnFailure = AR_dependent;
598e5dd7070Spatrick       break;
599e5dd7070Spatrick     }
600e5dd7070Spatrick   }
601e5dd7070Spatrick 
602e5dd7070Spatrick   // That's it, give up.
603e5dd7070Spatrick   return OnFailure;
604e5dd7070Spatrick }
605e5dd7070Spatrick 
606e5dd7070Spatrick namespace {
607e5dd7070Spatrick 
608e5dd7070Spatrick /// A helper class for checking for a friend which will grant access
609e5dd7070Spatrick /// to a protected instance member.
610e5dd7070Spatrick struct ProtectedFriendContext {
611e5dd7070Spatrick   Sema &S;
612e5dd7070Spatrick   const EffectiveContext &EC;
613e5dd7070Spatrick   const CXXRecordDecl *NamingClass;
614e5dd7070Spatrick   bool CheckDependent;
615e5dd7070Spatrick   bool EverDependent;
616e5dd7070Spatrick 
617e5dd7070Spatrick   /// The path down to the current base class.
618e5dd7070Spatrick   SmallVector<const CXXRecordDecl*, 20> CurPath;
619e5dd7070Spatrick 
ProtectedFriendContext__anon2935d57e0211::ProtectedFriendContext620e5dd7070Spatrick   ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
621e5dd7070Spatrick                          const CXXRecordDecl *InstanceContext,
622e5dd7070Spatrick                          const CXXRecordDecl *NamingClass)
623e5dd7070Spatrick     : S(S), EC(EC), NamingClass(NamingClass),
624e5dd7070Spatrick       CheckDependent(InstanceContext->isDependentContext() ||
625e5dd7070Spatrick                      NamingClass->isDependentContext()),
626e5dd7070Spatrick       EverDependent(false) {}
627e5dd7070Spatrick 
628e5dd7070Spatrick   /// Check classes in the current path for friendship, starting at
629e5dd7070Spatrick   /// the given index.
checkFriendshipAlongPath__anon2935d57e0211::ProtectedFriendContext630e5dd7070Spatrick   bool checkFriendshipAlongPath(unsigned I) {
631e5dd7070Spatrick     assert(I < CurPath.size());
632e5dd7070Spatrick     for (unsigned E = CurPath.size(); I != E; ++I) {
633e5dd7070Spatrick       switch (GetFriendKind(S, EC, CurPath[I])) {
634e5dd7070Spatrick       case AR_accessible:   return true;
635e5dd7070Spatrick       case AR_inaccessible: continue;
636e5dd7070Spatrick       case AR_dependent:    EverDependent = true; continue;
637e5dd7070Spatrick       }
638e5dd7070Spatrick     }
639e5dd7070Spatrick     return false;
640e5dd7070Spatrick   }
641e5dd7070Spatrick 
642e5dd7070Spatrick   /// Perform a search starting at the given class.
643e5dd7070Spatrick   ///
644e5dd7070Spatrick   /// PrivateDepth is the index of the last (least derived) class
645e5dd7070Spatrick   /// along the current path such that a notional public member of
646e5dd7070Spatrick   /// the final class in the path would have access in that class.
findFriendship__anon2935d57e0211::ProtectedFriendContext647e5dd7070Spatrick   bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
648e5dd7070Spatrick     // If we ever reach the naming class, check the current path for
649e5dd7070Spatrick     // friendship.  We can also stop recursing because we obviously
650e5dd7070Spatrick     // won't find the naming class there again.
651e5dd7070Spatrick     if (Cur == NamingClass)
652e5dd7070Spatrick       return checkFriendshipAlongPath(PrivateDepth);
653e5dd7070Spatrick 
654e5dd7070Spatrick     if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
655e5dd7070Spatrick       EverDependent = true;
656e5dd7070Spatrick 
657e5dd7070Spatrick     // Recurse into the base classes.
658e5dd7070Spatrick     for (const auto &I : Cur->bases()) {
659e5dd7070Spatrick       // If this is private inheritance, then a public member of the
660e5dd7070Spatrick       // base will not have any access in classes derived from Cur.
661e5dd7070Spatrick       unsigned BasePrivateDepth = PrivateDepth;
662e5dd7070Spatrick       if (I.getAccessSpecifier() == AS_private)
663e5dd7070Spatrick         BasePrivateDepth = CurPath.size() - 1;
664e5dd7070Spatrick 
665e5dd7070Spatrick       const CXXRecordDecl *RD;
666e5dd7070Spatrick 
667e5dd7070Spatrick       QualType T = I.getType();
668e5dd7070Spatrick       if (const RecordType *RT = T->getAs<RecordType>()) {
669e5dd7070Spatrick         RD = cast<CXXRecordDecl>(RT->getDecl());
670e5dd7070Spatrick       } else if (const InjectedClassNameType *IT
671e5dd7070Spatrick                    = T->getAs<InjectedClassNameType>()) {
672e5dd7070Spatrick         RD = IT->getDecl();
673e5dd7070Spatrick       } else {
674e5dd7070Spatrick         assert(T->isDependentType() && "non-dependent base wasn't a record?");
675e5dd7070Spatrick         EverDependent = true;
676e5dd7070Spatrick         continue;
677e5dd7070Spatrick       }
678e5dd7070Spatrick 
679e5dd7070Spatrick       // Recurse.  We don't need to clean up if this returns true.
680e5dd7070Spatrick       CurPath.push_back(RD);
681e5dd7070Spatrick       if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
682e5dd7070Spatrick         return true;
683e5dd7070Spatrick       CurPath.pop_back();
684e5dd7070Spatrick     }
685e5dd7070Spatrick 
686e5dd7070Spatrick     return false;
687e5dd7070Spatrick   }
688e5dd7070Spatrick 
findFriendship__anon2935d57e0211::ProtectedFriendContext689e5dd7070Spatrick   bool findFriendship(const CXXRecordDecl *Cur) {
690e5dd7070Spatrick     assert(CurPath.empty());
691e5dd7070Spatrick     CurPath.push_back(Cur);
692e5dd7070Spatrick     return findFriendship(Cur, 0);
693e5dd7070Spatrick   }
694e5dd7070Spatrick };
695e5dd7070Spatrick }
696e5dd7070Spatrick 
697e5dd7070Spatrick /// Search for a class P that EC is a friend of, under the constraint
698e5dd7070Spatrick ///   InstanceContext <= P
699e5dd7070Spatrick /// if InstanceContext exists, or else
700e5dd7070Spatrick ///   NamingClass <= P
701e5dd7070Spatrick /// and with the additional restriction that a protected member of
702e5dd7070Spatrick /// NamingClass would have some natural access in P, which implicitly
703e5dd7070Spatrick /// imposes the constraint that P <= NamingClass.
704e5dd7070Spatrick ///
705e5dd7070Spatrick /// This isn't quite the condition laid out in the standard.
706e5dd7070Spatrick /// Instead of saying that a notional protected member of NamingClass
707e5dd7070Spatrick /// would have to have some natural access in P, it says the actual
708e5dd7070Spatrick /// target has to have some natural access in P, which opens up the
709e5dd7070Spatrick /// possibility that the target (which is not necessarily a member
710e5dd7070Spatrick /// of NamingClass) might be more accessible along some path not
711e5dd7070Spatrick /// passing through it.  That's really a bad idea, though, because it
712e5dd7070Spatrick /// introduces two problems:
713e5dd7070Spatrick ///   - Most importantly, it breaks encapsulation because you can
714e5dd7070Spatrick ///     access a forbidden base class's members by directly subclassing
715e5dd7070Spatrick ///     it elsewhere.
716e5dd7070Spatrick ///   - It also makes access substantially harder to compute because it
717e5dd7070Spatrick ///     breaks the hill-climbing algorithm: knowing that the target is
718e5dd7070Spatrick ///     accessible in some base class would no longer let you change
719e5dd7070Spatrick ///     the question solely to whether the base class is accessible,
720e5dd7070Spatrick ///     because the original target might have been more accessible
721e5dd7070Spatrick ///     because of crazy subclassing.
722e5dd7070Spatrick /// So we don't implement that.
GetProtectedFriendKind(Sema & S,const EffectiveContext & EC,const CXXRecordDecl * InstanceContext,const CXXRecordDecl * NamingClass)723e5dd7070Spatrick static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
724e5dd7070Spatrick                                            const CXXRecordDecl *InstanceContext,
725e5dd7070Spatrick                                            const CXXRecordDecl *NamingClass) {
726e5dd7070Spatrick   assert(InstanceContext == nullptr ||
727e5dd7070Spatrick          InstanceContext->getCanonicalDecl() == InstanceContext);
728e5dd7070Spatrick   assert(NamingClass->getCanonicalDecl() == NamingClass);
729e5dd7070Spatrick 
730e5dd7070Spatrick   // If we don't have an instance context, our constraints give us
731e5dd7070Spatrick   // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
732e5dd7070Spatrick   // This is just the usual friendship check.
733e5dd7070Spatrick   if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
734e5dd7070Spatrick 
735e5dd7070Spatrick   ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
736e5dd7070Spatrick   if (PRC.findFriendship(InstanceContext)) return AR_accessible;
737e5dd7070Spatrick   if (PRC.EverDependent) return AR_dependent;
738e5dd7070Spatrick   return AR_inaccessible;
739e5dd7070Spatrick }
740e5dd7070Spatrick 
HasAccess(Sema & S,const EffectiveContext & EC,const CXXRecordDecl * NamingClass,AccessSpecifier Access,const AccessTarget & Target)741e5dd7070Spatrick static AccessResult HasAccess(Sema &S,
742e5dd7070Spatrick                               const EffectiveContext &EC,
743e5dd7070Spatrick                               const CXXRecordDecl *NamingClass,
744e5dd7070Spatrick                               AccessSpecifier Access,
745e5dd7070Spatrick                               const AccessTarget &Target) {
746e5dd7070Spatrick   assert(NamingClass->getCanonicalDecl() == NamingClass &&
747e5dd7070Spatrick          "declaration should be canonicalized before being passed here");
748e5dd7070Spatrick 
749e5dd7070Spatrick   if (Access == AS_public) return AR_accessible;
750e5dd7070Spatrick   assert(Access == AS_private || Access == AS_protected);
751e5dd7070Spatrick 
752e5dd7070Spatrick   AccessResult OnFailure = AR_inaccessible;
753e5dd7070Spatrick 
754e5dd7070Spatrick   for (EffectiveContext::record_iterator
755e5dd7070Spatrick          I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
756e5dd7070Spatrick     // All the declarations in EC have been canonicalized, so pointer
757e5dd7070Spatrick     // equality from this point on will work fine.
758e5dd7070Spatrick     const CXXRecordDecl *ECRecord = *I;
759e5dd7070Spatrick 
760e5dd7070Spatrick     // [B2] and [M2]
761e5dd7070Spatrick     if (Access == AS_private) {
762e5dd7070Spatrick       if (ECRecord == NamingClass)
763e5dd7070Spatrick         return AR_accessible;
764e5dd7070Spatrick 
765e5dd7070Spatrick       if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
766e5dd7070Spatrick         OnFailure = AR_dependent;
767e5dd7070Spatrick 
768e5dd7070Spatrick     // [B3] and [M3]
769e5dd7070Spatrick     } else {
770e5dd7070Spatrick       assert(Access == AS_protected);
771e5dd7070Spatrick       switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
772e5dd7070Spatrick       case AR_accessible: break;
773e5dd7070Spatrick       case AR_inaccessible: continue;
774e5dd7070Spatrick       case AR_dependent: OnFailure = AR_dependent; continue;
775e5dd7070Spatrick       }
776e5dd7070Spatrick 
777e5dd7070Spatrick       // C++ [class.protected]p1:
778e5dd7070Spatrick       //   An additional access check beyond those described earlier in
779e5dd7070Spatrick       //   [class.access] is applied when a non-static data member or
780e5dd7070Spatrick       //   non-static member function is a protected member of its naming
781e5dd7070Spatrick       //   class.  As described earlier, access to a protected member is
782e5dd7070Spatrick       //   granted because the reference occurs in a friend or member of
783e5dd7070Spatrick       //   some class C.  If the access is to form a pointer to member,
784e5dd7070Spatrick       //   the nested-name-specifier shall name C or a class derived from
785e5dd7070Spatrick       //   C. All other accesses involve a (possibly implicit) object
786e5dd7070Spatrick       //   expression. In this case, the class of the object expression
787e5dd7070Spatrick       //   shall be C or a class derived from C.
788e5dd7070Spatrick       //
789e5dd7070Spatrick       // We interpret this as a restriction on [M3].
790e5dd7070Spatrick 
791e5dd7070Spatrick       // In this part of the code, 'C' is just our context class ECRecord.
792e5dd7070Spatrick 
793e5dd7070Spatrick       // These rules are different if we don't have an instance context.
794e5dd7070Spatrick       if (!Target.hasInstanceContext()) {
795e5dd7070Spatrick         // If it's not an instance member, these restrictions don't apply.
796e5dd7070Spatrick         if (!Target.isInstanceMember()) return AR_accessible;
797e5dd7070Spatrick 
798e5dd7070Spatrick         // If it's an instance member, use the pointer-to-member rule
799e5dd7070Spatrick         // that the naming class has to be derived from the effective
800e5dd7070Spatrick         // context.
801e5dd7070Spatrick 
802e5dd7070Spatrick         // Emulate a MSVC bug where the creation of pointer-to-member
803e5dd7070Spatrick         // to protected member of base class is allowed but only from
804e5dd7070Spatrick         // static member functions.
805e5dd7070Spatrick         if (S.getLangOpts().MSVCCompat && !EC.Functions.empty())
806e5dd7070Spatrick           if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
807e5dd7070Spatrick             if (MD->isStatic()) return AR_accessible;
808e5dd7070Spatrick 
809e5dd7070Spatrick         // Despite the standard's confident wording, there is a case
810e5dd7070Spatrick         // where you can have an instance member that's neither in a
811e5dd7070Spatrick         // pointer-to-member expression nor in a member access:  when
812e5dd7070Spatrick         // it names a field in an unevaluated context that can't be an
813e5dd7070Spatrick         // implicit member.  Pending clarification, we just apply the
814e5dd7070Spatrick         // same naming-class restriction here.
815e5dd7070Spatrick         //   FIXME: we're probably not correctly adding the
816e5dd7070Spatrick         //   protected-member restriction when we retroactively convert
817e5dd7070Spatrick         //   an expression to being evaluated.
818e5dd7070Spatrick 
819e5dd7070Spatrick         // We know that ECRecord derives from NamingClass.  The
820e5dd7070Spatrick         // restriction says to check whether NamingClass derives from
821e5dd7070Spatrick         // ECRecord, but that's not really necessary: two distinct
822e5dd7070Spatrick         // classes can't be recursively derived from each other.  So
823e5dd7070Spatrick         // along this path, we just need to check whether the classes
824e5dd7070Spatrick         // are equal.
825e5dd7070Spatrick         if (NamingClass == ECRecord) return AR_accessible;
826e5dd7070Spatrick 
827e5dd7070Spatrick         // Otherwise, this context class tells us nothing;  on to the next.
828e5dd7070Spatrick         continue;
829e5dd7070Spatrick       }
830e5dd7070Spatrick 
831e5dd7070Spatrick       assert(Target.isInstanceMember());
832e5dd7070Spatrick 
833e5dd7070Spatrick       const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
834e5dd7070Spatrick       if (!InstanceContext) {
835e5dd7070Spatrick         OnFailure = AR_dependent;
836e5dd7070Spatrick         continue;
837e5dd7070Spatrick       }
838e5dd7070Spatrick 
839e5dd7070Spatrick       switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
840e5dd7070Spatrick       case AR_accessible: return AR_accessible;
841e5dd7070Spatrick       case AR_inaccessible: continue;
842e5dd7070Spatrick       case AR_dependent: OnFailure = AR_dependent; continue;
843e5dd7070Spatrick       }
844e5dd7070Spatrick     }
845e5dd7070Spatrick   }
846e5dd7070Spatrick 
847e5dd7070Spatrick   // [M3] and [B3] say that, if the target is protected in N, we grant
848e5dd7070Spatrick   // access if the access occurs in a friend or member of some class P
849e5dd7070Spatrick   // that's a subclass of N and where the target has some natural
850e5dd7070Spatrick   // access in P.  The 'member' aspect is easy to handle because P
851e5dd7070Spatrick   // would necessarily be one of the effective-context records, and we
852e5dd7070Spatrick   // address that above.  The 'friend' aspect is completely ridiculous
853e5dd7070Spatrick   // to implement because there are no restrictions at all on P
854e5dd7070Spatrick   // *unless* the [class.protected] restriction applies.  If it does,
855e5dd7070Spatrick   // however, we should ignore whether the naming class is a friend,
856e5dd7070Spatrick   // and instead rely on whether any potential P is a friend.
857e5dd7070Spatrick   if (Access == AS_protected && Target.isInstanceMember()) {
858e5dd7070Spatrick     // Compute the instance context if possible.
859e5dd7070Spatrick     const CXXRecordDecl *InstanceContext = nullptr;
860e5dd7070Spatrick     if (Target.hasInstanceContext()) {
861e5dd7070Spatrick       InstanceContext = Target.resolveInstanceContext(S);
862e5dd7070Spatrick       if (!InstanceContext) return AR_dependent;
863e5dd7070Spatrick     }
864e5dd7070Spatrick 
865e5dd7070Spatrick     switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
866e5dd7070Spatrick     case AR_accessible: return AR_accessible;
867e5dd7070Spatrick     case AR_inaccessible: return OnFailure;
868e5dd7070Spatrick     case AR_dependent: return AR_dependent;
869e5dd7070Spatrick     }
870e5dd7070Spatrick     llvm_unreachable("impossible friendship kind");
871e5dd7070Spatrick   }
872e5dd7070Spatrick 
873e5dd7070Spatrick   switch (GetFriendKind(S, EC, NamingClass)) {
874e5dd7070Spatrick   case AR_accessible: return AR_accessible;
875e5dd7070Spatrick   case AR_inaccessible: return OnFailure;
876e5dd7070Spatrick   case AR_dependent: return AR_dependent;
877e5dd7070Spatrick   }
878e5dd7070Spatrick 
879e5dd7070Spatrick   // Silence bogus warnings
880e5dd7070Spatrick   llvm_unreachable("impossible friendship kind");
881e5dd7070Spatrick }
882e5dd7070Spatrick 
883e5dd7070Spatrick /// Finds the best path from the naming class to the declaring class,
884e5dd7070Spatrick /// taking friend declarations into account.
885e5dd7070Spatrick ///
886e5dd7070Spatrick /// C++0x [class.access.base]p5:
887e5dd7070Spatrick ///   A member m is accessible at the point R when named in class N if
888e5dd7070Spatrick ///   [M1] m as a member of N is public, or
889e5dd7070Spatrick ///   [M2] m as a member of N is private, and R occurs in a member or
890e5dd7070Spatrick ///        friend of class N, or
891e5dd7070Spatrick ///   [M3] m as a member of N is protected, and R occurs in a member or
892e5dd7070Spatrick ///        friend of class N, or in a member or friend of a class P
893e5dd7070Spatrick ///        derived from N, where m as a member of P is public, private,
894e5dd7070Spatrick ///        or protected, or
895e5dd7070Spatrick ///   [M4] there exists a base class B of N that is accessible at R, and
896e5dd7070Spatrick ///        m is accessible at R when named in class B.
897e5dd7070Spatrick ///
898e5dd7070Spatrick /// C++0x [class.access.base]p4:
899e5dd7070Spatrick ///   A base class B of N is accessible at R, if
900e5dd7070Spatrick ///   [B1] an invented public member of B would be a public member of N, or
901e5dd7070Spatrick ///   [B2] R occurs in a member or friend of class N, and an invented public
902e5dd7070Spatrick ///        member of B would be a private or protected member of N, or
903e5dd7070Spatrick ///   [B3] R occurs in a member or friend of a class P derived from N, and an
904e5dd7070Spatrick ///        invented public member of B would be a private or protected member
905e5dd7070Spatrick ///        of P, or
906e5dd7070Spatrick ///   [B4] there exists a class S such that B is a base class of S accessible
907e5dd7070Spatrick ///        at R and S is a base class of N accessible at R.
908e5dd7070Spatrick ///
909e5dd7070Spatrick /// Along a single inheritance path we can restate both of these
910e5dd7070Spatrick /// iteratively:
911e5dd7070Spatrick ///
912e5dd7070Spatrick /// First, we note that M1-4 are equivalent to B1-4 if the member is
913e5dd7070Spatrick /// treated as a notional base of its declaring class with inheritance
914e5dd7070Spatrick /// access equivalent to the member's access.  Therefore we need only
915e5dd7070Spatrick /// ask whether a class B is accessible from a class N in context R.
916e5dd7070Spatrick ///
917e5dd7070Spatrick /// Let B_1 .. B_n be the inheritance path in question (i.e. where
918e5dd7070Spatrick /// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
919e5dd7070Spatrick /// B_i).  For i in 1..n, we will calculate ACAB(i), the access to the
920e5dd7070Spatrick /// closest accessible base in the path:
921e5dd7070Spatrick ///   Access(a, b) = (* access on the base specifier from a to b *)
922e5dd7070Spatrick ///   Merge(a, forbidden) = forbidden
923e5dd7070Spatrick ///   Merge(a, private) = forbidden
924e5dd7070Spatrick ///   Merge(a, b) = min(a,b)
925e5dd7070Spatrick ///   Accessible(c, forbidden) = false
926e5dd7070Spatrick ///   Accessible(c, private) = (R is c) || IsFriend(c, R)
927e5dd7070Spatrick ///   Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
928e5dd7070Spatrick ///   Accessible(c, public) = true
929e5dd7070Spatrick ///   ACAB(n) = public
930e5dd7070Spatrick ///   ACAB(i) =
931e5dd7070Spatrick ///     let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
932e5dd7070Spatrick ///     if Accessible(B_i, AccessToBase) then public else AccessToBase
933e5dd7070Spatrick ///
934e5dd7070Spatrick /// B is an accessible base of N at R iff ACAB(1) = public.
935e5dd7070Spatrick ///
936e5dd7070Spatrick /// \param FinalAccess the access of the "final step", or AS_public if
937e5dd7070Spatrick ///   there is no final step.
938e5dd7070Spatrick /// \return null if friendship is dependent
FindBestPath(Sema & S,const EffectiveContext & EC,AccessTarget & Target,AccessSpecifier FinalAccess,CXXBasePaths & Paths)939e5dd7070Spatrick static CXXBasePath *FindBestPath(Sema &S,
940e5dd7070Spatrick                                  const EffectiveContext &EC,
941e5dd7070Spatrick                                  AccessTarget &Target,
942e5dd7070Spatrick                                  AccessSpecifier FinalAccess,
943e5dd7070Spatrick                                  CXXBasePaths &Paths) {
944e5dd7070Spatrick   // Derive the paths to the desired base.
945e5dd7070Spatrick   const CXXRecordDecl *Derived = Target.getNamingClass();
946e5dd7070Spatrick   const CXXRecordDecl *Base = Target.getDeclaringClass();
947e5dd7070Spatrick 
948e5dd7070Spatrick   // FIXME: fail correctly when there are dependent paths.
949e5dd7070Spatrick   bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
950e5dd7070Spatrick                                           Paths);
951e5dd7070Spatrick   assert(isDerived && "derived class not actually derived from base");
952e5dd7070Spatrick   (void) isDerived;
953e5dd7070Spatrick 
954e5dd7070Spatrick   CXXBasePath *BestPath = nullptr;
955e5dd7070Spatrick 
956e5dd7070Spatrick   assert(FinalAccess != AS_none && "forbidden access after declaring class");
957e5dd7070Spatrick 
958e5dd7070Spatrick   bool AnyDependent = false;
959e5dd7070Spatrick 
960e5dd7070Spatrick   // Derive the friend-modified access along each path.
961e5dd7070Spatrick   for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
962e5dd7070Spatrick          PI != PE; ++PI) {
963e5dd7070Spatrick     AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
964e5dd7070Spatrick 
965e5dd7070Spatrick     // Walk through the path backwards.
966e5dd7070Spatrick     AccessSpecifier PathAccess = FinalAccess;
967e5dd7070Spatrick     CXXBasePath::iterator I = PI->end(), E = PI->begin();
968e5dd7070Spatrick     while (I != E) {
969e5dd7070Spatrick       --I;
970e5dd7070Spatrick 
971e5dd7070Spatrick       assert(PathAccess != AS_none);
972e5dd7070Spatrick 
973e5dd7070Spatrick       // If the declaration is a private member of a base class, there
974e5dd7070Spatrick       // is no level of friendship in derived classes that can make it
975e5dd7070Spatrick       // accessible.
976e5dd7070Spatrick       if (PathAccess == AS_private) {
977e5dd7070Spatrick         PathAccess = AS_none;
978e5dd7070Spatrick         break;
979e5dd7070Spatrick       }
980e5dd7070Spatrick 
981e5dd7070Spatrick       const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
982e5dd7070Spatrick 
983e5dd7070Spatrick       AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
984e5dd7070Spatrick       PathAccess = std::max(PathAccess, BaseAccess);
985e5dd7070Spatrick 
986e5dd7070Spatrick       switch (HasAccess(S, EC, NC, PathAccess, Target)) {
987e5dd7070Spatrick       case AR_inaccessible: break;
988e5dd7070Spatrick       case AR_accessible:
989e5dd7070Spatrick         PathAccess = AS_public;
990e5dd7070Spatrick 
991e5dd7070Spatrick         // Future tests are not against members and so do not have
992e5dd7070Spatrick         // instance context.
993e5dd7070Spatrick         Target.suppressInstanceContext();
994e5dd7070Spatrick         break;
995e5dd7070Spatrick       case AR_dependent:
996e5dd7070Spatrick         AnyDependent = true;
997e5dd7070Spatrick         goto Next;
998e5dd7070Spatrick       }
999e5dd7070Spatrick     }
1000e5dd7070Spatrick 
1001e5dd7070Spatrick     // Note that we modify the path's Access field to the
1002e5dd7070Spatrick     // friend-modified access.
1003e5dd7070Spatrick     if (BestPath == nullptr || PathAccess < BestPath->Access) {
1004e5dd7070Spatrick       BestPath = &*PI;
1005e5dd7070Spatrick       BestPath->Access = PathAccess;
1006e5dd7070Spatrick 
1007e5dd7070Spatrick       // Short-circuit if we found a public path.
1008e5dd7070Spatrick       if (BestPath->Access == AS_public)
1009e5dd7070Spatrick         return BestPath;
1010e5dd7070Spatrick     }
1011e5dd7070Spatrick 
1012e5dd7070Spatrick   Next: ;
1013e5dd7070Spatrick   }
1014e5dd7070Spatrick 
1015e5dd7070Spatrick   assert((!BestPath || BestPath->Access != AS_public) &&
1016e5dd7070Spatrick          "fell out of loop with public path");
1017e5dd7070Spatrick 
1018e5dd7070Spatrick   // We didn't find a public path, but at least one path was subject
1019e5dd7070Spatrick   // to dependent friendship, so delay the check.
1020e5dd7070Spatrick   if (AnyDependent)
1021e5dd7070Spatrick     return nullptr;
1022e5dd7070Spatrick 
1023e5dd7070Spatrick   return BestPath;
1024e5dd7070Spatrick }
1025e5dd7070Spatrick 
1026e5dd7070Spatrick /// Given that an entity has protected natural access, check whether
1027e5dd7070Spatrick /// access might be denied because of the protected member access
1028e5dd7070Spatrick /// restriction.
1029e5dd7070Spatrick ///
1030e5dd7070Spatrick /// \return true if a note was emitted
TryDiagnoseProtectedAccess(Sema & S,const EffectiveContext & EC,AccessTarget & Target)1031e5dd7070Spatrick static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
1032e5dd7070Spatrick                                        AccessTarget &Target) {
1033e5dd7070Spatrick   // Only applies to instance accesses.
1034e5dd7070Spatrick   if (!Target.isInstanceMember())
1035e5dd7070Spatrick     return false;
1036e5dd7070Spatrick 
1037e5dd7070Spatrick   assert(Target.isMemberAccess());
1038e5dd7070Spatrick 
1039e5dd7070Spatrick   const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
1040e5dd7070Spatrick 
1041e5dd7070Spatrick   for (EffectiveContext::record_iterator
1042e5dd7070Spatrick          I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
1043e5dd7070Spatrick     const CXXRecordDecl *ECRecord = *I;
1044e5dd7070Spatrick     switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
1045e5dd7070Spatrick     case AR_accessible: break;
1046e5dd7070Spatrick     case AR_inaccessible: continue;
1047e5dd7070Spatrick     case AR_dependent: continue;
1048e5dd7070Spatrick     }
1049e5dd7070Spatrick 
1050e5dd7070Spatrick     // The effective context is a subclass of the declaring class.
1051e5dd7070Spatrick     // Check whether the [class.protected] restriction is limiting
1052e5dd7070Spatrick     // access.
1053e5dd7070Spatrick 
1054e5dd7070Spatrick     // To get this exactly right, this might need to be checked more
1055e5dd7070Spatrick     // holistically;  it's not necessarily the case that gaining
1056e5dd7070Spatrick     // access here would grant us access overall.
1057e5dd7070Spatrick 
1058e5dd7070Spatrick     NamedDecl *D = Target.getTargetDecl();
1059e5dd7070Spatrick 
1060e5dd7070Spatrick     // If we don't have an instance context, [class.protected] says the
1061e5dd7070Spatrick     // naming class has to equal the context class.
1062e5dd7070Spatrick     if (!Target.hasInstanceContext()) {
1063e5dd7070Spatrick       // If it does, the restriction doesn't apply.
1064e5dd7070Spatrick       if (NamingClass == ECRecord) continue;
1065e5dd7070Spatrick 
1066e5dd7070Spatrick       // TODO: it would be great to have a fixit here, since this is
1067e5dd7070Spatrick       // such an obvious error.
1068e5dd7070Spatrick       S.Diag(D->getLocation(), diag::note_access_protected_restricted_noobject)
1069e5dd7070Spatrick         << S.Context.getTypeDeclType(ECRecord);
1070e5dd7070Spatrick       return true;
1071e5dd7070Spatrick     }
1072e5dd7070Spatrick 
1073e5dd7070Spatrick     const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
1074e5dd7070Spatrick     assert(InstanceContext && "diagnosing dependent access");
1075e5dd7070Spatrick 
1076e5dd7070Spatrick     switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
1077e5dd7070Spatrick     case AR_accessible: continue;
1078e5dd7070Spatrick     case AR_dependent: continue;
1079e5dd7070Spatrick     case AR_inaccessible:
1080e5dd7070Spatrick       break;
1081e5dd7070Spatrick     }
1082e5dd7070Spatrick 
1083e5dd7070Spatrick     // Okay, the restriction seems to be what's limiting us.
1084e5dd7070Spatrick 
1085e5dd7070Spatrick     // Use a special diagnostic for constructors and destructors.
1086e5dd7070Spatrick     if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D) ||
1087e5dd7070Spatrick         (isa<FunctionTemplateDecl>(D) &&
1088e5dd7070Spatrick          isa<CXXConstructorDecl>(
1089e5dd7070Spatrick                 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
1090e5dd7070Spatrick       return S.Diag(D->getLocation(),
1091e5dd7070Spatrick                     diag::note_access_protected_restricted_ctordtor)
1092e5dd7070Spatrick              << isa<CXXDestructorDecl>(D->getAsFunction());
1093e5dd7070Spatrick     }
1094e5dd7070Spatrick 
1095e5dd7070Spatrick     // Otherwise, use the generic diagnostic.
1096e5dd7070Spatrick     return S.Diag(D->getLocation(),
1097e5dd7070Spatrick                   diag::note_access_protected_restricted_object)
1098e5dd7070Spatrick            << S.Context.getTypeDeclType(ECRecord);
1099e5dd7070Spatrick   }
1100e5dd7070Spatrick 
1101e5dd7070Spatrick   return false;
1102e5dd7070Spatrick }
1103e5dd7070Spatrick 
1104e5dd7070Spatrick /// We are unable to access a given declaration due to its direct
1105e5dd7070Spatrick /// access control;  diagnose that.
diagnoseBadDirectAccess(Sema & S,const EffectiveContext & EC,AccessTarget & entity)1106e5dd7070Spatrick static void diagnoseBadDirectAccess(Sema &S,
1107e5dd7070Spatrick                                     const EffectiveContext &EC,
1108e5dd7070Spatrick                                     AccessTarget &entity) {
1109e5dd7070Spatrick   assert(entity.isMemberAccess());
1110e5dd7070Spatrick   NamedDecl *D = entity.getTargetDecl();
1111e5dd7070Spatrick 
1112e5dd7070Spatrick   if (D->getAccess() == AS_protected &&
1113e5dd7070Spatrick       TryDiagnoseProtectedAccess(S, EC, entity))
1114e5dd7070Spatrick     return;
1115e5dd7070Spatrick 
1116e5dd7070Spatrick   // Find an original declaration.
1117e5dd7070Spatrick   while (D->isOutOfLine()) {
1118e5dd7070Spatrick     NamedDecl *PrevDecl = nullptr;
1119e5dd7070Spatrick     if (VarDecl *VD = dyn_cast<VarDecl>(D))
1120e5dd7070Spatrick       PrevDecl = VD->getPreviousDecl();
1121e5dd7070Spatrick     else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1122e5dd7070Spatrick       PrevDecl = FD->getPreviousDecl();
1123e5dd7070Spatrick     else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
1124e5dd7070Spatrick       PrevDecl = TND->getPreviousDecl();
1125e5dd7070Spatrick     else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1126e5dd7070Spatrick       if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
1127e5dd7070Spatrick         break;
1128e5dd7070Spatrick       PrevDecl = TD->getPreviousDecl();
1129e5dd7070Spatrick     }
1130e5dd7070Spatrick     if (!PrevDecl) break;
1131e5dd7070Spatrick     D = PrevDecl;
1132e5dd7070Spatrick   }
1133e5dd7070Spatrick 
1134e5dd7070Spatrick   CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1135e5dd7070Spatrick   Decl *ImmediateChild;
1136e5dd7070Spatrick   if (D->getDeclContext() == DeclaringClass)
1137e5dd7070Spatrick     ImmediateChild = D;
1138e5dd7070Spatrick   else {
1139e5dd7070Spatrick     DeclContext *DC = D->getDeclContext();
1140e5dd7070Spatrick     while (DC->getParent() != DeclaringClass)
1141e5dd7070Spatrick       DC = DC->getParent();
1142e5dd7070Spatrick     ImmediateChild = cast<Decl>(DC);
1143e5dd7070Spatrick   }
1144e5dd7070Spatrick 
1145e5dd7070Spatrick   // Check whether there's an AccessSpecDecl preceding this in the
1146e5dd7070Spatrick   // chain of the DeclContext.
1147e5dd7070Spatrick   bool isImplicit = true;
1148e5dd7070Spatrick   for (const auto *I : DeclaringClass->decls()) {
1149e5dd7070Spatrick     if (I == ImmediateChild) break;
1150e5dd7070Spatrick     if (isa<AccessSpecDecl>(I)) {
1151e5dd7070Spatrick       isImplicit = false;
1152e5dd7070Spatrick       break;
1153e5dd7070Spatrick     }
1154e5dd7070Spatrick   }
1155e5dd7070Spatrick 
1156e5dd7070Spatrick   S.Diag(D->getLocation(), diag::note_access_natural)
1157e5dd7070Spatrick     << (unsigned) (D->getAccess() == AS_protected)
1158e5dd7070Spatrick     << isImplicit;
1159e5dd7070Spatrick }
1160e5dd7070Spatrick 
1161e5dd7070Spatrick /// Diagnose the path which caused the given declaration or base class
1162e5dd7070Spatrick /// to become inaccessible.
DiagnoseAccessPath(Sema & S,const EffectiveContext & EC,AccessTarget & entity)1163e5dd7070Spatrick static void DiagnoseAccessPath(Sema &S,
1164e5dd7070Spatrick                                const EffectiveContext &EC,
1165e5dd7070Spatrick                                AccessTarget &entity) {
1166e5dd7070Spatrick   // Save the instance context to preserve invariants.
1167e5dd7070Spatrick   AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
1168e5dd7070Spatrick 
1169e5dd7070Spatrick   // This basically repeats the main algorithm but keeps some more
1170e5dd7070Spatrick   // information.
1171e5dd7070Spatrick 
1172e5dd7070Spatrick   // The natural access so far.
1173e5dd7070Spatrick   AccessSpecifier accessSoFar = AS_public;
1174e5dd7070Spatrick 
1175e5dd7070Spatrick   // Check whether we have special rights to the declaring class.
1176e5dd7070Spatrick   if (entity.isMemberAccess()) {
1177e5dd7070Spatrick     NamedDecl *D = entity.getTargetDecl();
1178e5dd7070Spatrick     accessSoFar = D->getAccess();
1179e5dd7070Spatrick     const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
1180e5dd7070Spatrick 
1181e5dd7070Spatrick     switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1182e5dd7070Spatrick     // If the declaration is accessible when named in its declaring
1183e5dd7070Spatrick     // class, then we must be constrained by the path.
1184e5dd7070Spatrick     case AR_accessible:
1185e5dd7070Spatrick       accessSoFar = AS_public;
1186e5dd7070Spatrick       entity.suppressInstanceContext();
1187e5dd7070Spatrick       break;
1188e5dd7070Spatrick 
1189e5dd7070Spatrick     case AR_inaccessible:
1190e5dd7070Spatrick       if (accessSoFar == AS_private ||
1191e5dd7070Spatrick           declaringClass == entity.getEffectiveNamingClass())
1192e5dd7070Spatrick         return diagnoseBadDirectAccess(S, EC, entity);
1193e5dd7070Spatrick       break;
1194e5dd7070Spatrick 
1195e5dd7070Spatrick     case AR_dependent:
1196e5dd7070Spatrick       llvm_unreachable("cannot diagnose dependent access");
1197e5dd7070Spatrick     }
1198e5dd7070Spatrick   }
1199e5dd7070Spatrick 
1200e5dd7070Spatrick   CXXBasePaths paths;
1201e5dd7070Spatrick   CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1202e5dd7070Spatrick   assert(path.Access != AS_public);
1203e5dd7070Spatrick 
1204e5dd7070Spatrick   CXXBasePath::iterator i = path.end(), e = path.begin();
1205e5dd7070Spatrick   CXXBasePath::iterator constrainingBase = i;
1206e5dd7070Spatrick   while (i != e) {
1207e5dd7070Spatrick     --i;
1208e5dd7070Spatrick 
1209e5dd7070Spatrick     assert(accessSoFar != AS_none && accessSoFar != AS_private);
1210e5dd7070Spatrick 
1211e5dd7070Spatrick     // Is the entity accessible when named in the deriving class, as
1212e5dd7070Spatrick     // modified by the base specifier?
1213e5dd7070Spatrick     const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1214e5dd7070Spatrick     const CXXBaseSpecifier *base = i->Base;
1215e5dd7070Spatrick 
1216e5dd7070Spatrick     // If the access to this base is worse than the access we have to
1217e5dd7070Spatrick     // the declaration, remember it.
1218e5dd7070Spatrick     AccessSpecifier baseAccess = base->getAccessSpecifier();
1219e5dd7070Spatrick     if (baseAccess > accessSoFar) {
1220e5dd7070Spatrick       constrainingBase = i;
1221e5dd7070Spatrick       accessSoFar = baseAccess;
1222e5dd7070Spatrick     }
1223e5dd7070Spatrick 
1224e5dd7070Spatrick     switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
1225e5dd7070Spatrick     case AR_inaccessible: break;
1226e5dd7070Spatrick     case AR_accessible:
1227e5dd7070Spatrick       accessSoFar = AS_public;
1228e5dd7070Spatrick       entity.suppressInstanceContext();
1229e5dd7070Spatrick       constrainingBase = nullptr;
1230e5dd7070Spatrick       break;
1231e5dd7070Spatrick     case AR_dependent:
1232e5dd7070Spatrick       llvm_unreachable("cannot diagnose dependent access");
1233e5dd7070Spatrick     }
1234e5dd7070Spatrick 
1235e5dd7070Spatrick     // If this was private inheritance, but we don't have access to
1236e5dd7070Spatrick     // the deriving class, we're done.
1237e5dd7070Spatrick     if (accessSoFar == AS_private) {
1238e5dd7070Spatrick       assert(baseAccess == AS_private);
1239e5dd7070Spatrick       assert(constrainingBase == i);
1240e5dd7070Spatrick       break;
1241e5dd7070Spatrick     }
1242e5dd7070Spatrick   }
1243e5dd7070Spatrick 
1244e5dd7070Spatrick   // If we don't have a constraining base, the access failure must be
1245e5dd7070Spatrick   // due to the original declaration.
1246e5dd7070Spatrick   if (constrainingBase == path.end())
1247e5dd7070Spatrick     return diagnoseBadDirectAccess(S, EC, entity);
1248e5dd7070Spatrick 
1249e5dd7070Spatrick   // We're constrained by inheritance, but we want to say
1250e5dd7070Spatrick   // "declared private here" if we're diagnosing a hierarchy
1251e5dd7070Spatrick   // conversion and this is the final step.
1252e5dd7070Spatrick   unsigned diagnostic;
1253e5dd7070Spatrick   if (entity.isMemberAccess() ||
1254e5dd7070Spatrick       constrainingBase + 1 != path.end()) {
1255e5dd7070Spatrick     diagnostic = diag::note_access_constrained_by_path;
1256e5dd7070Spatrick   } else {
1257e5dd7070Spatrick     diagnostic = diag::note_access_natural;
1258e5dd7070Spatrick   }
1259e5dd7070Spatrick 
1260e5dd7070Spatrick   const CXXBaseSpecifier *base = constrainingBase->Base;
1261e5dd7070Spatrick 
1262e5dd7070Spatrick   S.Diag(base->getSourceRange().getBegin(), diagnostic)
1263e5dd7070Spatrick     << base->getSourceRange()
1264e5dd7070Spatrick     << (base->getAccessSpecifier() == AS_protected)
1265e5dd7070Spatrick     << (base->getAccessSpecifierAsWritten() == AS_none);
1266e5dd7070Spatrick 
1267e5dd7070Spatrick   if (entity.isMemberAccess())
1268e5dd7070Spatrick     S.Diag(entity.getTargetDecl()->getLocation(),
1269e5dd7070Spatrick            diag::note_member_declared_at);
1270e5dd7070Spatrick }
1271e5dd7070Spatrick 
DiagnoseBadAccess(Sema & S,SourceLocation Loc,const EffectiveContext & EC,AccessTarget & Entity)1272e5dd7070Spatrick static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
1273e5dd7070Spatrick                               const EffectiveContext &EC,
1274e5dd7070Spatrick                               AccessTarget &Entity) {
1275e5dd7070Spatrick   const CXXRecordDecl *NamingClass = Entity.getNamingClass();
1276e5dd7070Spatrick   const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1277e5dd7070Spatrick   NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : nullptr);
1278e5dd7070Spatrick 
1279e5dd7070Spatrick   S.Diag(Loc, Entity.getDiag())
1280e5dd7070Spatrick     << (Entity.getAccess() == AS_protected)
1281e5dd7070Spatrick     << (D ? D->getDeclName() : DeclarationName())
1282e5dd7070Spatrick     << S.Context.getTypeDeclType(NamingClass)
1283e5dd7070Spatrick     << S.Context.getTypeDeclType(DeclaringClass);
1284e5dd7070Spatrick   DiagnoseAccessPath(S, EC, Entity);
1285e5dd7070Spatrick }
1286e5dd7070Spatrick 
1287e5dd7070Spatrick /// MSVC has a bug where if during an using declaration name lookup,
1288e5dd7070Spatrick /// the declaration found is unaccessible (private) and that declaration
1289e5dd7070Spatrick /// was bring into scope via another using declaration whose target
1290e5dd7070Spatrick /// declaration is accessible (public) then no error is generated.
1291e5dd7070Spatrick /// Example:
1292e5dd7070Spatrick ///   class A {
1293e5dd7070Spatrick ///   public:
1294e5dd7070Spatrick ///     int f();
1295e5dd7070Spatrick ///   };
1296e5dd7070Spatrick ///   class B : public A {
1297e5dd7070Spatrick ///   private:
1298e5dd7070Spatrick ///     using A::f;
1299e5dd7070Spatrick ///   };
1300e5dd7070Spatrick ///   class C : public B {
1301e5dd7070Spatrick ///   private:
1302e5dd7070Spatrick ///     using B::f;
1303e5dd7070Spatrick ///   };
1304e5dd7070Spatrick ///
1305e5dd7070Spatrick /// Here, B::f is private so this should fail in Standard C++, but
1306e5dd7070Spatrick /// because B::f refers to A::f which is public MSVC accepts it.
IsMicrosoftUsingDeclarationAccessBug(Sema & S,SourceLocation AccessLoc,AccessTarget & Entity)1307e5dd7070Spatrick static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
1308e5dd7070Spatrick                                                  SourceLocation AccessLoc,
1309e5dd7070Spatrick                                                  AccessTarget &Entity) {
1310e5dd7070Spatrick   if (UsingShadowDecl *Shadow =
1311a9ac8606Spatrick           dyn_cast<UsingShadowDecl>(Entity.getTargetDecl()))
1312a9ac8606Spatrick     if (UsingDecl *UD = dyn_cast<UsingDecl>(Shadow->getIntroducer())) {
1313e5dd7070Spatrick       const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
1314e5dd7070Spatrick       if (Entity.getTargetDecl()->getAccess() == AS_private &&
1315e5dd7070Spatrick           (OrigDecl->getAccess() == AS_public ||
1316e5dd7070Spatrick            OrigDecl->getAccess() == AS_protected)) {
1317e5dd7070Spatrick         S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
1318a9ac8606Spatrick             << UD->getQualifiedNameAsString()
1319e5dd7070Spatrick             << OrigDecl->getQualifiedNameAsString();
1320e5dd7070Spatrick         return true;
1321e5dd7070Spatrick       }
1322e5dd7070Spatrick     }
1323e5dd7070Spatrick   return false;
1324e5dd7070Spatrick }
1325e5dd7070Spatrick 
1326e5dd7070Spatrick /// Determines whether the accessed entity is accessible.  Public members
1327e5dd7070Spatrick /// have been weeded out by this point.
IsAccessible(Sema & S,const EffectiveContext & EC,AccessTarget & Entity)1328e5dd7070Spatrick static AccessResult IsAccessible(Sema &S,
1329e5dd7070Spatrick                                  const EffectiveContext &EC,
1330e5dd7070Spatrick                                  AccessTarget &Entity) {
1331e5dd7070Spatrick   // Determine the actual naming class.
1332e5dd7070Spatrick   const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
1333e5dd7070Spatrick 
1334e5dd7070Spatrick   AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1335e5dd7070Spatrick   assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1336e5dd7070Spatrick 
1337e5dd7070Spatrick   // Before we try to recalculate access paths, try to white-list
1338e5dd7070Spatrick   // accesses which just trade in on the final step, i.e. accesses
1339e5dd7070Spatrick   // which don't require [M4] or [B4]. These are by far the most
1340e5dd7070Spatrick   // common forms of privileged access.
1341e5dd7070Spatrick   if (UnprivilegedAccess != AS_none) {
1342e5dd7070Spatrick     switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1343e5dd7070Spatrick     case AR_dependent:
1344e5dd7070Spatrick       // This is actually an interesting policy decision.  We don't
1345e5dd7070Spatrick       // *have* to delay immediately here: we can do the full access
1346e5dd7070Spatrick       // calculation in the hope that friendship on some intermediate
1347e5dd7070Spatrick       // class will make the declaration accessible non-dependently.
1348e5dd7070Spatrick       // But that's not cheap, and odds are very good (note: assertion
1349e5dd7070Spatrick       // made without data) that the friend declaration will determine
1350e5dd7070Spatrick       // access.
1351e5dd7070Spatrick       return AR_dependent;
1352e5dd7070Spatrick 
1353e5dd7070Spatrick     case AR_accessible: return AR_accessible;
1354e5dd7070Spatrick     case AR_inaccessible: break;
1355e5dd7070Spatrick     }
1356e5dd7070Spatrick   }
1357e5dd7070Spatrick 
1358e5dd7070Spatrick   AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
1359e5dd7070Spatrick 
1360e5dd7070Spatrick   // We lower member accesses to base accesses by pretending that the
1361e5dd7070Spatrick   // member is a base class of its declaring class.
1362e5dd7070Spatrick   AccessSpecifier FinalAccess;
1363e5dd7070Spatrick 
1364e5dd7070Spatrick   if (Entity.isMemberAccess()) {
1365e5dd7070Spatrick     // Determine if the declaration is accessible from EC when named
1366e5dd7070Spatrick     // in its declaring class.
1367e5dd7070Spatrick     NamedDecl *Target = Entity.getTargetDecl();
1368e5dd7070Spatrick     const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1369e5dd7070Spatrick 
1370e5dd7070Spatrick     FinalAccess = Target->getAccess();
1371e5dd7070Spatrick     switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1372e5dd7070Spatrick     case AR_accessible:
1373e5dd7070Spatrick       // Target is accessible at EC when named in its declaring class.
1374e5dd7070Spatrick       // We can now hill-climb and simply check whether the declaring
1375e5dd7070Spatrick       // class is accessible as a base of the naming class.  This is
1376e5dd7070Spatrick       // equivalent to checking the access of a notional public
1377e5dd7070Spatrick       // member with no instance context.
1378e5dd7070Spatrick       FinalAccess = AS_public;
1379e5dd7070Spatrick       Entity.suppressInstanceContext();
1380e5dd7070Spatrick       break;
1381e5dd7070Spatrick     case AR_inaccessible: break;
1382e5dd7070Spatrick     case AR_dependent: return AR_dependent; // see above
1383e5dd7070Spatrick     }
1384e5dd7070Spatrick 
1385e5dd7070Spatrick     if (DeclaringClass == NamingClass)
1386e5dd7070Spatrick       return (FinalAccess == AS_public ? AR_accessible : AR_inaccessible);
1387e5dd7070Spatrick   } else {
1388e5dd7070Spatrick     FinalAccess = AS_public;
1389e5dd7070Spatrick   }
1390e5dd7070Spatrick 
1391e5dd7070Spatrick   assert(Entity.getDeclaringClass() != NamingClass);
1392e5dd7070Spatrick 
1393e5dd7070Spatrick   // Append the declaration's access if applicable.
1394e5dd7070Spatrick   CXXBasePaths Paths;
1395e5dd7070Spatrick   CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
1396e5dd7070Spatrick   if (!Path)
1397e5dd7070Spatrick     return AR_dependent;
1398e5dd7070Spatrick 
1399e5dd7070Spatrick   assert(Path->Access <= UnprivilegedAccess &&
1400e5dd7070Spatrick          "access along best path worse than direct?");
1401e5dd7070Spatrick   if (Path->Access == AS_public)
1402e5dd7070Spatrick     return AR_accessible;
1403e5dd7070Spatrick   return AR_inaccessible;
1404e5dd7070Spatrick }
1405e5dd7070Spatrick 
DelayDependentAccess(Sema & S,const EffectiveContext & EC,SourceLocation Loc,const AccessTarget & Entity)1406e5dd7070Spatrick static void DelayDependentAccess(Sema &S,
1407e5dd7070Spatrick                                  const EffectiveContext &EC,
1408e5dd7070Spatrick                                  SourceLocation Loc,
1409e5dd7070Spatrick                                  const AccessTarget &Entity) {
1410e5dd7070Spatrick   assert(EC.isDependent() && "delaying non-dependent access");
1411e5dd7070Spatrick   DeclContext *DC = EC.getInnerContext();
1412e5dd7070Spatrick   assert(DC->isDependentContext() && "delaying non-dependent access");
1413e5dd7070Spatrick   DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1414e5dd7070Spatrick                               Loc,
1415e5dd7070Spatrick                               Entity.isMemberAccess(),
1416e5dd7070Spatrick                               Entity.getAccess(),
1417e5dd7070Spatrick                               Entity.getTargetDecl(),
1418e5dd7070Spatrick                               Entity.getNamingClass(),
1419e5dd7070Spatrick                               Entity.getBaseObjectType(),
1420e5dd7070Spatrick                               Entity.getDiag());
1421e5dd7070Spatrick }
1422e5dd7070Spatrick 
1423e5dd7070Spatrick /// Checks access to an entity from the given effective context.
CheckEffectiveAccess(Sema & S,const EffectiveContext & EC,SourceLocation Loc,AccessTarget & Entity)1424e5dd7070Spatrick static AccessResult CheckEffectiveAccess(Sema &S,
1425e5dd7070Spatrick                                          const EffectiveContext &EC,
1426e5dd7070Spatrick                                          SourceLocation Loc,
1427e5dd7070Spatrick                                          AccessTarget &Entity) {
1428e5dd7070Spatrick   assert(Entity.getAccess() != AS_public && "called for public access!");
1429e5dd7070Spatrick 
1430e5dd7070Spatrick   switch (IsAccessible(S, EC, Entity)) {
1431e5dd7070Spatrick   case AR_dependent:
1432e5dd7070Spatrick     DelayDependentAccess(S, EC, Loc, Entity);
1433e5dd7070Spatrick     return AR_dependent;
1434e5dd7070Spatrick 
1435e5dd7070Spatrick   case AR_inaccessible:
1436e5dd7070Spatrick     if (S.getLangOpts().MSVCCompat &&
1437e5dd7070Spatrick         IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
1438e5dd7070Spatrick       return AR_accessible;
1439e5dd7070Spatrick     if (!Entity.isQuiet())
1440e5dd7070Spatrick       DiagnoseBadAccess(S, Loc, EC, Entity);
1441e5dd7070Spatrick     return AR_inaccessible;
1442e5dd7070Spatrick 
1443e5dd7070Spatrick   case AR_accessible:
1444e5dd7070Spatrick     return AR_accessible;
1445e5dd7070Spatrick   }
1446e5dd7070Spatrick 
1447e5dd7070Spatrick   // silence unnecessary warning
1448e5dd7070Spatrick   llvm_unreachable("invalid access result");
1449e5dd7070Spatrick }
1450e5dd7070Spatrick 
CheckAccess(Sema & S,SourceLocation Loc,AccessTarget & Entity)1451e5dd7070Spatrick static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
1452e5dd7070Spatrick                                       AccessTarget &Entity) {
1453e5dd7070Spatrick   // If the access path is public, it's accessible everywhere.
1454e5dd7070Spatrick   if (Entity.getAccess() == AS_public)
1455e5dd7070Spatrick     return Sema::AR_accessible;
1456e5dd7070Spatrick 
1457e5dd7070Spatrick   // If we're currently parsing a declaration, we may need to delay
1458e5dd7070Spatrick   // access control checking, because our effective context might be
1459e5dd7070Spatrick   // different based on what the declaration comes out as.
1460e5dd7070Spatrick   //
1461e5dd7070Spatrick   // For example, we might be parsing a declaration with a scope
1462e5dd7070Spatrick   // specifier, like this:
1463e5dd7070Spatrick   //   A::private_type A::foo() { ... }
1464e5dd7070Spatrick   //
1465e5dd7070Spatrick   // Or we might be parsing something that will turn out to be a friend:
1466e5dd7070Spatrick   //   void foo(A::private_type);
1467e5dd7070Spatrick   //   void B::foo(A::private_type);
1468e5dd7070Spatrick   if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1469e5dd7070Spatrick     S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
1470e5dd7070Spatrick     return Sema::AR_delayed;
1471e5dd7070Spatrick   }
1472e5dd7070Spatrick 
1473e5dd7070Spatrick   EffectiveContext EC(S.CurContext);
1474e5dd7070Spatrick   switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1475e5dd7070Spatrick   case AR_accessible: return Sema::AR_accessible;
1476e5dd7070Spatrick   case AR_inaccessible: return Sema::AR_inaccessible;
1477e5dd7070Spatrick   case AR_dependent: return Sema::AR_dependent;
1478e5dd7070Spatrick   }
1479e5dd7070Spatrick   llvm_unreachable("invalid access result");
1480e5dd7070Spatrick }
1481e5dd7070Spatrick 
HandleDelayedAccessCheck(DelayedDiagnostic & DD,Decl * D)1482e5dd7070Spatrick void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
1483e5dd7070Spatrick   // Access control for names used in the declarations of functions
1484e5dd7070Spatrick   // and function templates should normally be evaluated in the context
1485e5dd7070Spatrick   // of the declaration, just in case it's a friend of something.
1486e5dd7070Spatrick   // However, this does not apply to local extern declarations.
1487e5dd7070Spatrick 
1488e5dd7070Spatrick   DeclContext *DC = D->getDeclContext();
1489e5dd7070Spatrick   if (D->isLocalExternDecl()) {
1490e5dd7070Spatrick     DC = D->getLexicalDeclContext();
1491e5dd7070Spatrick   } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1492e5dd7070Spatrick     DC = FN;
1493e5dd7070Spatrick   } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1494a9ac8606Spatrick     if (isa<DeclContext>(TD->getTemplatedDecl()))
1495e5dd7070Spatrick       DC = cast<DeclContext>(TD->getTemplatedDecl());
1496*12c85518Srobert   } else if (auto *RD = dyn_cast<RequiresExprBodyDecl>(D)) {
1497*12c85518Srobert     DC = RD;
1498e5dd7070Spatrick   }
1499e5dd7070Spatrick 
1500e5dd7070Spatrick   EffectiveContext EC(DC);
1501e5dd7070Spatrick 
1502e5dd7070Spatrick   AccessTarget Target(DD.getAccessData());
1503e5dd7070Spatrick 
1504e5dd7070Spatrick   if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
1505e5dd7070Spatrick     DD.Triggered = true;
1506e5dd7070Spatrick }
1507e5dd7070Spatrick 
HandleDependentAccessCheck(const DependentDiagnostic & DD,const MultiLevelTemplateArgumentList & TemplateArgs)1508e5dd7070Spatrick void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1509e5dd7070Spatrick                         const MultiLevelTemplateArgumentList &TemplateArgs) {
1510e5dd7070Spatrick   SourceLocation Loc = DD.getAccessLoc();
1511e5dd7070Spatrick   AccessSpecifier Access = DD.getAccess();
1512e5dd7070Spatrick 
1513e5dd7070Spatrick   Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1514e5dd7070Spatrick                                        TemplateArgs);
1515e5dd7070Spatrick   if (!NamingD) return;
1516e5dd7070Spatrick   Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1517e5dd7070Spatrick                                        TemplateArgs);
1518e5dd7070Spatrick   if (!TargetD) return;
1519e5dd7070Spatrick 
1520e5dd7070Spatrick   if (DD.isAccessToMember()) {
1521e5dd7070Spatrick     CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1522e5dd7070Spatrick     NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1523e5dd7070Spatrick     QualType BaseObjectType = DD.getAccessBaseObjectType();
1524e5dd7070Spatrick     if (!BaseObjectType.isNull()) {
1525e5dd7070Spatrick       BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1526e5dd7070Spatrick                                  DeclarationName());
1527e5dd7070Spatrick       if (BaseObjectType.isNull()) return;
1528e5dd7070Spatrick     }
1529e5dd7070Spatrick 
1530e5dd7070Spatrick     AccessTarget Entity(Context,
1531e5dd7070Spatrick                         AccessTarget::Member,
1532e5dd7070Spatrick                         NamingClass,
1533e5dd7070Spatrick                         DeclAccessPair::make(TargetDecl, Access),
1534e5dd7070Spatrick                         BaseObjectType);
1535e5dd7070Spatrick     Entity.setDiag(DD.getDiagnostic());
1536e5dd7070Spatrick     CheckAccess(*this, Loc, Entity);
1537e5dd7070Spatrick   } else {
1538e5dd7070Spatrick     AccessTarget Entity(Context,
1539e5dd7070Spatrick                         AccessTarget::Base,
1540e5dd7070Spatrick                         cast<CXXRecordDecl>(TargetD),
1541e5dd7070Spatrick                         cast<CXXRecordDecl>(NamingD),
1542e5dd7070Spatrick                         Access);
1543e5dd7070Spatrick     Entity.setDiag(DD.getDiagnostic());
1544e5dd7070Spatrick     CheckAccess(*this, Loc, Entity);
1545e5dd7070Spatrick   }
1546e5dd7070Spatrick }
1547e5dd7070Spatrick 
CheckUnresolvedLookupAccess(UnresolvedLookupExpr * E,DeclAccessPair Found)1548e5dd7070Spatrick Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1549e5dd7070Spatrick                                                      DeclAccessPair Found) {
1550e5dd7070Spatrick   if (!getLangOpts().AccessControl ||
1551e5dd7070Spatrick       !E->getNamingClass() ||
1552e5dd7070Spatrick       Found.getAccess() == AS_public)
1553e5dd7070Spatrick     return AR_accessible;
1554e5dd7070Spatrick 
1555e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1556e5dd7070Spatrick                       Found, QualType());
1557e5dd7070Spatrick   Entity.setDiag(diag::err_access) << E->getSourceRange();
1558e5dd7070Spatrick 
1559e5dd7070Spatrick   return CheckAccess(*this, E->getNameLoc(), Entity);
1560e5dd7070Spatrick }
1561e5dd7070Spatrick 
1562e5dd7070Spatrick /// Perform access-control checking on a previously-unresolved member
1563e5dd7070Spatrick /// access which has now been resolved to a member.
CheckUnresolvedMemberAccess(UnresolvedMemberExpr * E,DeclAccessPair Found)1564e5dd7070Spatrick Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1565e5dd7070Spatrick                                                      DeclAccessPair Found) {
1566e5dd7070Spatrick   if (!getLangOpts().AccessControl ||
1567e5dd7070Spatrick       Found.getAccess() == AS_public)
1568e5dd7070Spatrick     return AR_accessible;
1569e5dd7070Spatrick 
1570e5dd7070Spatrick   QualType BaseType = E->getBaseType();
1571e5dd7070Spatrick   if (E->isArrow())
1572e5dd7070Spatrick     BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1573e5dd7070Spatrick 
1574e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1575e5dd7070Spatrick                       Found, BaseType);
1576e5dd7070Spatrick   Entity.setDiag(diag::err_access) << E->getSourceRange();
1577e5dd7070Spatrick 
1578e5dd7070Spatrick   return CheckAccess(*this, E->getMemberLoc(), Entity);
1579e5dd7070Spatrick }
1580e5dd7070Spatrick 
1581e5dd7070Spatrick /// Is the given member accessible for the purposes of deciding whether to
1582e5dd7070Spatrick /// define a special member function as deleted?
isMemberAccessibleForDeletion(CXXRecordDecl * NamingClass,DeclAccessPair Found,QualType ObjectType,SourceLocation Loc,const PartialDiagnostic & Diag)1583e5dd7070Spatrick bool Sema::isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1584e5dd7070Spatrick                                          DeclAccessPair Found,
1585e5dd7070Spatrick                                          QualType ObjectType,
1586e5dd7070Spatrick                                          SourceLocation Loc,
1587e5dd7070Spatrick                                          const PartialDiagnostic &Diag) {
1588e5dd7070Spatrick   // Fast path.
1589e5dd7070Spatrick   if (Found.getAccess() == AS_public || !getLangOpts().AccessControl)
1590e5dd7070Spatrick     return true;
1591e5dd7070Spatrick 
1592e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1593e5dd7070Spatrick                       ObjectType);
1594e5dd7070Spatrick 
1595e5dd7070Spatrick   // Suppress diagnostics.
1596e5dd7070Spatrick   Entity.setDiag(Diag);
1597e5dd7070Spatrick 
1598e5dd7070Spatrick   switch (CheckAccess(*this, Loc, Entity)) {
1599e5dd7070Spatrick   case AR_accessible: return true;
1600e5dd7070Spatrick   case AR_inaccessible: return false;
1601e5dd7070Spatrick   case AR_dependent: llvm_unreachable("dependent for =delete computation");
1602e5dd7070Spatrick   case AR_delayed: llvm_unreachable("cannot delay =delete computation");
1603e5dd7070Spatrick   }
1604e5dd7070Spatrick   llvm_unreachable("bad access result");
1605e5dd7070Spatrick }
1606e5dd7070Spatrick 
CheckDestructorAccess(SourceLocation Loc,CXXDestructorDecl * Dtor,const PartialDiagnostic & PDiag,QualType ObjectTy)1607e5dd7070Spatrick Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
1608e5dd7070Spatrick                                                CXXDestructorDecl *Dtor,
1609e5dd7070Spatrick                                                const PartialDiagnostic &PDiag,
1610e5dd7070Spatrick                                                QualType ObjectTy) {
1611e5dd7070Spatrick   if (!getLangOpts().AccessControl)
1612e5dd7070Spatrick     return AR_accessible;
1613e5dd7070Spatrick 
1614e5dd7070Spatrick   // There's never a path involved when checking implicit destructor access.
1615e5dd7070Spatrick   AccessSpecifier Access = Dtor->getAccess();
1616e5dd7070Spatrick   if (Access == AS_public)
1617e5dd7070Spatrick     return AR_accessible;
1618e5dd7070Spatrick 
1619e5dd7070Spatrick   CXXRecordDecl *NamingClass = Dtor->getParent();
1620e5dd7070Spatrick   if (ObjectTy.isNull()) ObjectTy = Context.getTypeDeclType(NamingClass);
1621e5dd7070Spatrick 
1622e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1623e5dd7070Spatrick                       DeclAccessPair::make(Dtor, Access),
1624e5dd7070Spatrick                       ObjectTy);
1625e5dd7070Spatrick   Entity.setDiag(PDiag); // TODO: avoid copy
1626e5dd7070Spatrick 
1627e5dd7070Spatrick   return CheckAccess(*this, Loc, Entity);
1628e5dd7070Spatrick }
1629e5dd7070Spatrick 
1630e5dd7070Spatrick /// Checks access to a constructor.
CheckConstructorAccess(SourceLocation UseLoc,CXXConstructorDecl * Constructor,DeclAccessPair Found,const InitializedEntity & Entity,bool IsCopyBindingRefToTemp)1631e5dd7070Spatrick Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1632e5dd7070Spatrick                                                 CXXConstructorDecl *Constructor,
1633e5dd7070Spatrick                                                 DeclAccessPair Found,
1634e5dd7070Spatrick                                                 const InitializedEntity &Entity,
1635e5dd7070Spatrick                                                 bool IsCopyBindingRefToTemp) {
1636e5dd7070Spatrick   if (!getLangOpts().AccessControl || Found.getAccess() == AS_public)
1637e5dd7070Spatrick     return AR_accessible;
1638e5dd7070Spatrick 
1639e5dd7070Spatrick   PartialDiagnostic PD(PDiag());
1640e5dd7070Spatrick   switch (Entity.getKind()) {
1641e5dd7070Spatrick   default:
1642e5dd7070Spatrick     PD = PDiag(IsCopyBindingRefToTemp
1643e5dd7070Spatrick                  ? diag::ext_rvalue_to_reference_access_ctor
1644e5dd7070Spatrick                  : diag::err_access_ctor);
1645e5dd7070Spatrick 
1646e5dd7070Spatrick     break;
1647e5dd7070Spatrick 
1648e5dd7070Spatrick   case InitializedEntity::EK_Base:
1649e5dd7070Spatrick     PD = PDiag(diag::err_access_base_ctor);
1650e5dd7070Spatrick     PD << Entity.isInheritedVirtualBase()
1651e5dd7070Spatrick        << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
1652e5dd7070Spatrick     break;
1653e5dd7070Spatrick 
1654*12c85518Srobert   case InitializedEntity::EK_Member:
1655*12c85518Srobert   case InitializedEntity::EK_ParenAggInitMember: {
1656e5dd7070Spatrick     const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
1657e5dd7070Spatrick     PD = PDiag(diag::err_access_field_ctor);
1658e5dd7070Spatrick     PD << Field->getType() << getSpecialMember(Constructor);
1659e5dd7070Spatrick     break;
1660e5dd7070Spatrick   }
1661e5dd7070Spatrick 
1662e5dd7070Spatrick   case InitializedEntity::EK_LambdaCapture: {
1663e5dd7070Spatrick     StringRef VarName = Entity.getCapturedVarName();
1664e5dd7070Spatrick     PD = PDiag(diag::err_access_lambda_capture);
1665e5dd7070Spatrick     PD << VarName << Entity.getType() << getSpecialMember(Constructor);
1666e5dd7070Spatrick     break;
1667e5dd7070Spatrick   }
1668e5dd7070Spatrick 
1669e5dd7070Spatrick   }
1670e5dd7070Spatrick 
1671e5dd7070Spatrick   return CheckConstructorAccess(UseLoc, Constructor, Found, Entity, PD);
1672e5dd7070Spatrick }
1673e5dd7070Spatrick 
1674e5dd7070Spatrick /// Checks access to a constructor.
CheckConstructorAccess(SourceLocation UseLoc,CXXConstructorDecl * Constructor,DeclAccessPair Found,const InitializedEntity & Entity,const PartialDiagnostic & PD)1675e5dd7070Spatrick Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1676e5dd7070Spatrick                                                 CXXConstructorDecl *Constructor,
1677e5dd7070Spatrick                                                 DeclAccessPair Found,
1678e5dd7070Spatrick                                                 const InitializedEntity &Entity,
1679e5dd7070Spatrick                                                 const PartialDiagnostic &PD) {
1680e5dd7070Spatrick   if (!getLangOpts().AccessControl ||
1681e5dd7070Spatrick       Found.getAccess() == AS_public)
1682e5dd7070Spatrick     return AR_accessible;
1683e5dd7070Spatrick 
1684e5dd7070Spatrick   CXXRecordDecl *NamingClass = Constructor->getParent();
1685e5dd7070Spatrick 
1686e5dd7070Spatrick   // Initializing a base sub-object is an instance method call on an
1687e5dd7070Spatrick   // object of the derived class.  Otherwise, we have an instance method
1688e5dd7070Spatrick   // call on an object of the constructed type.
1689e5dd7070Spatrick   //
1690e5dd7070Spatrick   // FIXME: If we have a parent, we're initializing the base class subobject
1691e5dd7070Spatrick   // in aggregate initialization. It's not clear whether the object class
1692e5dd7070Spatrick   // should be the base class or the derived class in that case.
1693e5dd7070Spatrick   CXXRecordDecl *ObjectClass;
1694e5dd7070Spatrick   if ((Entity.getKind() == InitializedEntity::EK_Base ||
1695e5dd7070Spatrick        Entity.getKind() == InitializedEntity::EK_Delegating) &&
1696e5dd7070Spatrick       !Entity.getParent()) {
1697e5dd7070Spatrick     ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
1698e5dd7070Spatrick   } else if (auto *Shadow =
1699e5dd7070Spatrick                  dyn_cast<ConstructorUsingShadowDecl>(Found.getDecl())) {
1700e5dd7070Spatrick     // If we're using an inheriting constructor to construct an object,
1701e5dd7070Spatrick     // the object class is the derived class, not the base class.
1702e5dd7070Spatrick     ObjectClass = Shadow->getParent();
1703e5dd7070Spatrick   } else {
1704e5dd7070Spatrick     ObjectClass = NamingClass;
1705e5dd7070Spatrick   }
1706e5dd7070Spatrick 
1707e5dd7070Spatrick   AccessTarget AccessEntity(
1708e5dd7070Spatrick       Context, AccessTarget::Member, NamingClass,
1709e5dd7070Spatrick       DeclAccessPair::make(Constructor, Found.getAccess()),
1710e5dd7070Spatrick       Context.getTypeDeclType(ObjectClass));
1711e5dd7070Spatrick   AccessEntity.setDiag(PD);
1712e5dd7070Spatrick 
1713e5dd7070Spatrick   return CheckAccess(*this, UseLoc, AccessEntity);
1714e5dd7070Spatrick }
1715e5dd7070Spatrick 
1716e5dd7070Spatrick /// Checks access to an overloaded operator new or delete.
CheckAllocationAccess(SourceLocation OpLoc,SourceRange PlacementRange,CXXRecordDecl * NamingClass,DeclAccessPair Found,bool Diagnose)1717e5dd7070Spatrick Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1718e5dd7070Spatrick                                                SourceRange PlacementRange,
1719e5dd7070Spatrick                                                CXXRecordDecl *NamingClass,
1720e5dd7070Spatrick                                                DeclAccessPair Found,
1721e5dd7070Spatrick                                                bool Diagnose) {
1722e5dd7070Spatrick   if (!getLangOpts().AccessControl ||
1723e5dd7070Spatrick       !NamingClass ||
1724e5dd7070Spatrick       Found.getAccess() == AS_public)
1725e5dd7070Spatrick     return AR_accessible;
1726e5dd7070Spatrick 
1727e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1728e5dd7070Spatrick                       QualType());
1729e5dd7070Spatrick   if (Diagnose)
1730e5dd7070Spatrick     Entity.setDiag(diag::err_access)
1731e5dd7070Spatrick       << PlacementRange;
1732e5dd7070Spatrick 
1733e5dd7070Spatrick   return CheckAccess(*this, OpLoc, Entity);
1734e5dd7070Spatrick }
1735e5dd7070Spatrick 
1736e5dd7070Spatrick /// Checks access to a member.
CheckMemberAccess(SourceLocation UseLoc,CXXRecordDecl * NamingClass,DeclAccessPair Found)1737e5dd7070Spatrick Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1738e5dd7070Spatrick                                            CXXRecordDecl *NamingClass,
1739e5dd7070Spatrick                                            DeclAccessPair Found) {
1740e5dd7070Spatrick   if (!getLangOpts().AccessControl ||
1741e5dd7070Spatrick       !NamingClass ||
1742e5dd7070Spatrick       Found.getAccess() == AS_public)
1743e5dd7070Spatrick     return AR_accessible;
1744e5dd7070Spatrick 
1745e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1746e5dd7070Spatrick                       Found, QualType());
1747e5dd7070Spatrick 
1748e5dd7070Spatrick   return CheckAccess(*this, UseLoc, Entity);
1749e5dd7070Spatrick }
1750e5dd7070Spatrick 
1751e5dd7070Spatrick /// Checks implicit access to a member in a structured binding.
1752e5dd7070Spatrick Sema::AccessResult
CheckStructuredBindingMemberAccess(SourceLocation UseLoc,CXXRecordDecl * DecomposedClass,DeclAccessPair Field)1753e5dd7070Spatrick Sema::CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1754e5dd7070Spatrick                                          CXXRecordDecl *DecomposedClass,
1755e5dd7070Spatrick                                          DeclAccessPair Field) {
1756e5dd7070Spatrick   if (!getLangOpts().AccessControl ||
1757e5dd7070Spatrick       Field.getAccess() == AS_public)
1758e5dd7070Spatrick     return AR_accessible;
1759e5dd7070Spatrick 
1760e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, DecomposedClass, Field,
1761e5dd7070Spatrick                       Context.getRecordType(DecomposedClass));
1762e5dd7070Spatrick   Entity.setDiag(diag::err_decomp_decl_inaccessible_field);
1763e5dd7070Spatrick 
1764e5dd7070Spatrick   return CheckAccess(*this, UseLoc, Entity);
1765e5dd7070Spatrick }
1766e5dd7070Spatrick 
CheckMemberOperatorAccess(SourceLocation OpLoc,Expr * ObjectExpr,const SourceRange & Range,DeclAccessPair Found)1767e5dd7070Spatrick Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1768e5dd7070Spatrick                                                    Expr *ObjectExpr,
1769*12c85518Srobert                                                    const SourceRange &Range,
1770e5dd7070Spatrick                                                    DeclAccessPair Found) {
1771*12c85518Srobert   if (!getLangOpts().AccessControl || Found.getAccess() == AS_public)
1772e5dd7070Spatrick     return AR_accessible;
1773e5dd7070Spatrick 
1774e5dd7070Spatrick   const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
1775e5dd7070Spatrick   CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1776e5dd7070Spatrick 
1777e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1778e5dd7070Spatrick                       ObjectExpr->getType());
1779*12c85518Srobert   Entity.setDiag(diag::err_access) << ObjectExpr->getSourceRange() << Range;
1780e5dd7070Spatrick 
1781e5dd7070Spatrick   return CheckAccess(*this, OpLoc, Entity);
1782e5dd7070Spatrick }
1783e5dd7070Spatrick 
1784*12c85518Srobert /// Checks access to an overloaded member operator, including
1785*12c85518Srobert /// conversion operators.
CheckMemberOperatorAccess(SourceLocation OpLoc,Expr * ObjectExpr,Expr * ArgExpr,DeclAccessPair Found)1786*12c85518Srobert Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1787*12c85518Srobert                                                    Expr *ObjectExpr,
1788*12c85518Srobert                                                    Expr *ArgExpr,
1789*12c85518Srobert                                                    DeclAccessPair Found) {
1790*12c85518Srobert   return CheckMemberOperatorAccess(
1791*12c85518Srobert       OpLoc, ObjectExpr, ArgExpr ? ArgExpr->getSourceRange() : SourceRange(),
1792*12c85518Srobert       Found);
1793*12c85518Srobert }
1794*12c85518Srobert 
CheckMemberOperatorAccess(SourceLocation OpLoc,Expr * ObjectExpr,ArrayRef<Expr * > ArgExprs,DeclAccessPair FoundDecl)1795*12c85518Srobert Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1796*12c85518Srobert                                                    Expr *ObjectExpr,
1797*12c85518Srobert                                                    ArrayRef<Expr *> ArgExprs,
1798*12c85518Srobert                                                    DeclAccessPair FoundDecl) {
1799*12c85518Srobert   SourceRange R;
1800*12c85518Srobert   if (!ArgExprs.empty()) {
1801*12c85518Srobert     R = SourceRange(ArgExprs.front()->getBeginLoc(),
1802*12c85518Srobert                     ArgExprs.back()->getEndLoc());
1803*12c85518Srobert   }
1804*12c85518Srobert 
1805*12c85518Srobert   return CheckMemberOperatorAccess(OpLoc, ObjectExpr, R, FoundDecl);
1806*12c85518Srobert }
1807*12c85518Srobert 
1808e5dd7070Spatrick /// Checks access to the target of a friend declaration.
CheckFriendAccess(NamedDecl * target)1809e5dd7070Spatrick Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
1810e5dd7070Spatrick   assert(isa<CXXMethodDecl>(target->getAsFunction()));
1811e5dd7070Spatrick 
1812e5dd7070Spatrick   // Friendship lookup is a redeclaration lookup, so there's never an
1813e5dd7070Spatrick   // inheritance path modifying access.
1814e5dd7070Spatrick   AccessSpecifier access = target->getAccess();
1815e5dd7070Spatrick 
1816e5dd7070Spatrick   if (!getLangOpts().AccessControl || access == AS_public)
1817e5dd7070Spatrick     return AR_accessible;
1818e5dd7070Spatrick 
1819e5dd7070Spatrick   CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
1820e5dd7070Spatrick 
1821e5dd7070Spatrick   AccessTarget entity(Context, AccessTarget::Member,
1822e5dd7070Spatrick                       cast<CXXRecordDecl>(target->getDeclContext()),
1823e5dd7070Spatrick                       DeclAccessPair::make(target, access),
1824e5dd7070Spatrick                       /*no instance context*/ QualType());
1825e5dd7070Spatrick   entity.setDiag(diag::err_access_friend_function)
1826e5dd7070Spatrick       << (method->getQualifier() ? method->getQualifierLoc().getSourceRange()
1827e5dd7070Spatrick                                  : method->getNameInfo().getSourceRange());
1828e5dd7070Spatrick 
1829e5dd7070Spatrick   // We need to bypass delayed-diagnostics because we might be called
1830e5dd7070Spatrick   // while the ParsingDeclarator is active.
1831e5dd7070Spatrick   EffectiveContext EC(CurContext);
1832e5dd7070Spatrick   switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
1833e5dd7070Spatrick   case ::AR_accessible: return Sema::AR_accessible;
1834e5dd7070Spatrick   case ::AR_inaccessible: return Sema::AR_inaccessible;
1835e5dd7070Spatrick   case ::AR_dependent: return Sema::AR_dependent;
1836e5dd7070Spatrick   }
1837e5dd7070Spatrick   llvm_unreachable("invalid access result");
1838e5dd7070Spatrick }
1839e5dd7070Spatrick 
CheckAddressOfMemberAccess(Expr * OvlExpr,DeclAccessPair Found)1840e5dd7070Spatrick Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1841e5dd7070Spatrick                                                     DeclAccessPair Found) {
1842e5dd7070Spatrick   if (!getLangOpts().AccessControl ||
1843e5dd7070Spatrick       Found.getAccess() == AS_none ||
1844e5dd7070Spatrick       Found.getAccess() == AS_public)
1845e5dd7070Spatrick     return AR_accessible;
1846e5dd7070Spatrick 
1847e5dd7070Spatrick   OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
1848e5dd7070Spatrick   CXXRecordDecl *NamingClass = Ovl->getNamingClass();
1849e5dd7070Spatrick 
1850e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1851e5dd7070Spatrick                       /*no instance context*/ QualType());
1852e5dd7070Spatrick   Entity.setDiag(diag::err_access)
1853e5dd7070Spatrick     << Ovl->getSourceRange();
1854e5dd7070Spatrick 
1855e5dd7070Spatrick   return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1856e5dd7070Spatrick }
1857e5dd7070Spatrick 
1858e5dd7070Spatrick /// Checks access for a hierarchy conversion.
1859e5dd7070Spatrick ///
1860e5dd7070Spatrick /// \param ForceCheck true if this check should be performed even if access
1861e5dd7070Spatrick ///     control is disabled;  some things rely on this for semantics
1862e5dd7070Spatrick /// \param ForceUnprivileged true if this check should proceed as if the
1863e5dd7070Spatrick ///     context had no special privileges
CheckBaseClassAccess(SourceLocation AccessLoc,QualType Base,QualType Derived,const CXXBasePath & Path,unsigned DiagID,bool ForceCheck,bool ForceUnprivileged)1864e5dd7070Spatrick Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
1865e5dd7070Spatrick                                               QualType Base,
1866e5dd7070Spatrick                                               QualType Derived,
1867e5dd7070Spatrick                                               const CXXBasePath &Path,
1868e5dd7070Spatrick                                               unsigned DiagID,
1869e5dd7070Spatrick                                               bool ForceCheck,
1870e5dd7070Spatrick                                               bool ForceUnprivileged) {
1871e5dd7070Spatrick   if (!ForceCheck && !getLangOpts().AccessControl)
1872e5dd7070Spatrick     return AR_accessible;
1873e5dd7070Spatrick 
1874e5dd7070Spatrick   if (Path.Access == AS_public)
1875e5dd7070Spatrick     return AR_accessible;
1876e5dd7070Spatrick 
1877e5dd7070Spatrick   CXXRecordDecl *BaseD, *DerivedD;
1878e5dd7070Spatrick   BaseD = cast<CXXRecordDecl>(Base->castAs<RecordType>()->getDecl());
1879e5dd7070Spatrick   DerivedD = cast<CXXRecordDecl>(Derived->castAs<RecordType>()->getDecl());
1880e5dd7070Spatrick 
1881e5dd7070Spatrick   AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1882e5dd7070Spatrick                       Path.Access);
1883e5dd7070Spatrick   if (DiagID)
1884e5dd7070Spatrick     Entity.setDiag(DiagID) << Derived << Base;
1885e5dd7070Spatrick 
1886e5dd7070Spatrick   if (ForceUnprivileged) {
1887e5dd7070Spatrick     switch (CheckEffectiveAccess(*this, EffectiveContext(),
1888e5dd7070Spatrick                                  AccessLoc, Entity)) {
1889e5dd7070Spatrick     case ::AR_accessible: return Sema::AR_accessible;
1890e5dd7070Spatrick     case ::AR_inaccessible: return Sema::AR_inaccessible;
1891e5dd7070Spatrick     case ::AR_dependent: return Sema::AR_dependent;
1892e5dd7070Spatrick     }
1893e5dd7070Spatrick     llvm_unreachable("unexpected result from CheckEffectiveAccess");
1894e5dd7070Spatrick   }
1895e5dd7070Spatrick   return CheckAccess(*this, AccessLoc, Entity);
1896e5dd7070Spatrick }
1897e5dd7070Spatrick 
1898e5dd7070Spatrick /// Checks access to all the declarations in the given result set.
CheckLookupAccess(const LookupResult & R)1899e5dd7070Spatrick void Sema::CheckLookupAccess(const LookupResult &R) {
1900e5dd7070Spatrick   assert(getLangOpts().AccessControl
1901e5dd7070Spatrick          && "performing access check without access control");
1902e5dd7070Spatrick   assert(R.getNamingClass() && "performing access check without naming class");
1903e5dd7070Spatrick 
1904e5dd7070Spatrick   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1905e5dd7070Spatrick     if (I.getAccess() != AS_public) {
1906e5dd7070Spatrick       AccessTarget Entity(Context, AccessedEntity::Member,
1907e5dd7070Spatrick                           R.getNamingClass(), I.getPair(),
1908e5dd7070Spatrick                           R.getBaseObjectType());
1909e5dd7070Spatrick       Entity.setDiag(diag::err_access);
1910e5dd7070Spatrick       CheckAccess(*this, R.getNameLoc(), Entity);
1911e5dd7070Spatrick     }
1912e5dd7070Spatrick   }
1913e5dd7070Spatrick }
1914e5dd7070Spatrick 
1915e5dd7070Spatrick /// Checks access to Target from the given class. The check will take access
1916e5dd7070Spatrick /// specifiers into account, but no member access expressions and such.
1917e5dd7070Spatrick ///
1918e5dd7070Spatrick /// \param Target the declaration to check if it can be accessed
1919e5dd7070Spatrick /// \param NamingClass the class in which the lookup was started.
1920e5dd7070Spatrick /// \param BaseType type of the left side of member access expression.
1921e5dd7070Spatrick ///        \p BaseType and \p NamingClass are used for C++ access control.
1922e5dd7070Spatrick ///        Depending on the lookup case, they should be set to the following:
1923e5dd7070Spatrick ///        - lhs.target (member access without a qualifier):
1924e5dd7070Spatrick ///          \p BaseType and \p NamingClass are both the type of 'lhs'.
1925e5dd7070Spatrick ///        - lhs.X::target (member access with a qualifier):
1926e5dd7070Spatrick ///          BaseType is the type of 'lhs', NamingClass is 'X'
1927e5dd7070Spatrick ///        - X::target (qualified lookup without member access):
1928e5dd7070Spatrick ///          BaseType is null, NamingClass is 'X'.
1929e5dd7070Spatrick ///        - target (unqualified lookup).
1930e5dd7070Spatrick ///          BaseType is null, NamingClass is the parent class of 'target'.
1931e5dd7070Spatrick /// \return true if the Target is accessible from the Class, false otherwise.
IsSimplyAccessible(NamedDecl * Target,CXXRecordDecl * NamingClass,QualType BaseType)1932e5dd7070Spatrick bool Sema::IsSimplyAccessible(NamedDecl *Target, CXXRecordDecl *NamingClass,
1933e5dd7070Spatrick                               QualType BaseType) {
1934e5dd7070Spatrick   // Perform the C++ accessibility checks first.
1935e5dd7070Spatrick   if (Target->isCXXClassMember() && NamingClass) {
1936e5dd7070Spatrick     if (!getLangOpts().CPlusPlus)
1937e5dd7070Spatrick       return false;
1938e5dd7070Spatrick     // The unprivileged access is AS_none as we don't know how the member was
1939e5dd7070Spatrick     // accessed, which is described by the access in DeclAccessPair.
1940e5dd7070Spatrick     // `IsAccessible` will examine the actual access of Target (i.e.
1941e5dd7070Spatrick     // Decl->getAccess()) when calculating the access.
1942e5dd7070Spatrick     AccessTarget Entity(Context, AccessedEntity::Member, NamingClass,
1943e5dd7070Spatrick                         DeclAccessPair::make(Target, AS_none), BaseType);
1944e5dd7070Spatrick     EffectiveContext EC(CurContext);
1945e5dd7070Spatrick     return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1946e5dd7070Spatrick   }
1947e5dd7070Spatrick 
1948e5dd7070Spatrick   if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Target)) {
1949e5dd7070Spatrick     // @public and @package ivars are always accessible.
1950e5dd7070Spatrick     if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1951e5dd7070Spatrick         Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
1952e5dd7070Spatrick       return true;
1953e5dd7070Spatrick 
1954e5dd7070Spatrick     // If we are inside a class or category implementation, determine the
1955e5dd7070Spatrick     // interface we're in.
1956e5dd7070Spatrick     ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1957e5dd7070Spatrick     if (ObjCMethodDecl *MD = getCurMethodDecl())
1958e5dd7070Spatrick       ClassOfMethodDecl =  MD->getClassInterface();
1959e5dd7070Spatrick     else if (FunctionDecl *FD = getCurFunctionDecl()) {
1960e5dd7070Spatrick       if (ObjCImplDecl *Impl
1961e5dd7070Spatrick             = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1962e5dd7070Spatrick         if (ObjCImplementationDecl *IMPD
1963e5dd7070Spatrick               = dyn_cast<ObjCImplementationDecl>(Impl))
1964e5dd7070Spatrick           ClassOfMethodDecl = IMPD->getClassInterface();
1965e5dd7070Spatrick         else if (ObjCCategoryImplDecl* CatImplClass
1966e5dd7070Spatrick                    = dyn_cast<ObjCCategoryImplDecl>(Impl))
1967e5dd7070Spatrick           ClassOfMethodDecl = CatImplClass->getClassInterface();
1968e5dd7070Spatrick       }
1969e5dd7070Spatrick     }
1970e5dd7070Spatrick 
1971e5dd7070Spatrick     // If we're not in an interface, this ivar is inaccessible.
1972e5dd7070Spatrick     if (!ClassOfMethodDecl)
1973e5dd7070Spatrick       return false;
1974e5dd7070Spatrick 
1975e5dd7070Spatrick     // If we're inside the same interface that owns the ivar, we're fine.
1976e5dd7070Spatrick     if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
1977e5dd7070Spatrick       return true;
1978e5dd7070Spatrick 
1979e5dd7070Spatrick     // If the ivar is private, it's inaccessible.
1980e5dd7070Spatrick     if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1981e5dd7070Spatrick       return false;
1982e5dd7070Spatrick 
1983e5dd7070Spatrick     return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1984e5dd7070Spatrick   }
1985e5dd7070Spatrick 
1986e5dd7070Spatrick   return true;
1987e5dd7070Spatrick }
1988