17330f729Sjoerg //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements name lookup for C, C++, Objective-C, and
107330f729Sjoerg // Objective-C++.
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "clang/AST/ASTContext.h"
157330f729Sjoerg #include "clang/AST/CXXInheritance.h"
167330f729Sjoerg #include "clang/AST/Decl.h"
177330f729Sjoerg #include "clang/AST/DeclCXX.h"
187330f729Sjoerg #include "clang/AST/DeclLookups.h"
197330f729Sjoerg #include "clang/AST/DeclObjC.h"
207330f729Sjoerg #include "clang/AST/DeclTemplate.h"
217330f729Sjoerg #include "clang/AST/Expr.h"
227330f729Sjoerg #include "clang/AST/ExprCXX.h"
237330f729Sjoerg #include "clang/Basic/Builtins.h"
247330f729Sjoerg #include "clang/Basic/FileManager.h"
257330f729Sjoerg #include "clang/Basic/LangOptions.h"
267330f729Sjoerg #include "clang/Lex/HeaderSearch.h"
277330f729Sjoerg #include "clang/Lex/ModuleLoader.h"
287330f729Sjoerg #include "clang/Lex/Preprocessor.h"
297330f729Sjoerg #include "clang/Sema/DeclSpec.h"
307330f729Sjoerg #include "clang/Sema/Lookup.h"
317330f729Sjoerg #include "clang/Sema/Overload.h"
327330f729Sjoerg #include "clang/Sema/Scope.h"
337330f729Sjoerg #include "clang/Sema/ScopeInfo.h"
347330f729Sjoerg #include "clang/Sema/Sema.h"
357330f729Sjoerg #include "clang/Sema/SemaInternal.h"
367330f729Sjoerg #include "clang/Sema/TemplateDeduction.h"
377330f729Sjoerg #include "clang/Sema/TypoCorrection.h"
387330f729Sjoerg #include "llvm/ADT/STLExtras.h"
397330f729Sjoerg #include "llvm/ADT/SmallPtrSet.h"
407330f729Sjoerg #include "llvm/ADT/TinyPtrVector.h"
417330f729Sjoerg #include "llvm/ADT/edit_distance.h"
427330f729Sjoerg #include "llvm/Support/ErrorHandling.h"
437330f729Sjoerg #include <algorithm>
447330f729Sjoerg #include <iterator>
457330f729Sjoerg #include <list>
467330f729Sjoerg #include <set>
477330f729Sjoerg #include <utility>
487330f729Sjoerg #include <vector>
497330f729Sjoerg
507330f729Sjoerg #include "OpenCLBuiltins.inc"
517330f729Sjoerg
527330f729Sjoerg using namespace clang;
537330f729Sjoerg using namespace sema;
547330f729Sjoerg
557330f729Sjoerg namespace {
567330f729Sjoerg class UnqualUsingEntry {
577330f729Sjoerg const DeclContext *Nominated;
587330f729Sjoerg const DeclContext *CommonAncestor;
597330f729Sjoerg
607330f729Sjoerg public:
UnqualUsingEntry(const DeclContext * Nominated,const DeclContext * CommonAncestor)617330f729Sjoerg UnqualUsingEntry(const DeclContext *Nominated,
627330f729Sjoerg const DeclContext *CommonAncestor)
637330f729Sjoerg : Nominated(Nominated), CommonAncestor(CommonAncestor) {
647330f729Sjoerg }
657330f729Sjoerg
getCommonAncestor() const667330f729Sjoerg const DeclContext *getCommonAncestor() const {
677330f729Sjoerg return CommonAncestor;
687330f729Sjoerg }
697330f729Sjoerg
getNominatedNamespace() const707330f729Sjoerg const DeclContext *getNominatedNamespace() const {
717330f729Sjoerg return Nominated;
727330f729Sjoerg }
737330f729Sjoerg
747330f729Sjoerg // Sort by the pointer value of the common ancestor.
757330f729Sjoerg struct Comparator {
operator ()__anon8d9d45fa0111::UnqualUsingEntry::Comparator767330f729Sjoerg bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
777330f729Sjoerg return L.getCommonAncestor() < R.getCommonAncestor();
787330f729Sjoerg }
797330f729Sjoerg
operator ()__anon8d9d45fa0111::UnqualUsingEntry::Comparator807330f729Sjoerg bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
817330f729Sjoerg return E.getCommonAncestor() < DC;
827330f729Sjoerg }
837330f729Sjoerg
operator ()__anon8d9d45fa0111::UnqualUsingEntry::Comparator847330f729Sjoerg bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
857330f729Sjoerg return DC < E.getCommonAncestor();
867330f729Sjoerg }
877330f729Sjoerg };
887330f729Sjoerg };
897330f729Sjoerg
907330f729Sjoerg /// A collection of using directives, as used by C++ unqualified
917330f729Sjoerg /// lookup.
927330f729Sjoerg class UnqualUsingDirectiveSet {
937330f729Sjoerg Sema &SemaRef;
947330f729Sjoerg
957330f729Sjoerg typedef SmallVector<UnqualUsingEntry, 8> ListTy;
967330f729Sjoerg
977330f729Sjoerg ListTy list;
987330f729Sjoerg llvm::SmallPtrSet<DeclContext*, 8> visited;
997330f729Sjoerg
1007330f729Sjoerg public:
UnqualUsingDirectiveSet(Sema & SemaRef)1017330f729Sjoerg UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
1027330f729Sjoerg
visitScopeChain(Scope * S,Scope * InnermostFileScope)1037330f729Sjoerg void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
1047330f729Sjoerg // C++ [namespace.udir]p1:
1057330f729Sjoerg // During unqualified name lookup, the names appear as if they
1067330f729Sjoerg // were declared in the nearest enclosing namespace which contains
1077330f729Sjoerg // both the using-directive and the nominated namespace.
1087330f729Sjoerg DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
1097330f729Sjoerg assert(InnermostFileDC && InnermostFileDC->isFileContext());
1107330f729Sjoerg
1117330f729Sjoerg for (; S; S = S->getParent()) {
1127330f729Sjoerg // C++ [namespace.udir]p1:
1137330f729Sjoerg // A using-directive shall not appear in class scope, but may
1147330f729Sjoerg // appear in namespace scope or in block scope.
1157330f729Sjoerg DeclContext *Ctx = S->getEntity();
1167330f729Sjoerg if (Ctx && Ctx->isFileContext()) {
1177330f729Sjoerg visit(Ctx, Ctx);
1187330f729Sjoerg } else if (!Ctx || Ctx->isFunctionOrMethod()) {
1197330f729Sjoerg for (auto *I : S->using_directives())
1207330f729Sjoerg if (SemaRef.isVisible(I))
1217330f729Sjoerg visit(I, InnermostFileDC);
1227330f729Sjoerg }
1237330f729Sjoerg }
1247330f729Sjoerg }
1257330f729Sjoerg
1267330f729Sjoerg // Visits a context and collect all of its using directives
1277330f729Sjoerg // recursively. Treats all using directives as if they were
1287330f729Sjoerg // declared in the context.
1297330f729Sjoerg //
1307330f729Sjoerg // A given context is only every visited once, so it is important
1317330f729Sjoerg // that contexts be visited from the inside out in order to get
1327330f729Sjoerg // the effective DCs right.
visit(DeclContext * DC,DeclContext * EffectiveDC)1337330f729Sjoerg void visit(DeclContext *DC, DeclContext *EffectiveDC) {
1347330f729Sjoerg if (!visited.insert(DC).second)
1357330f729Sjoerg return;
1367330f729Sjoerg
1377330f729Sjoerg addUsingDirectives(DC, EffectiveDC);
1387330f729Sjoerg }
1397330f729Sjoerg
1407330f729Sjoerg // Visits a using directive and collects all of its using
1417330f729Sjoerg // directives recursively. Treats all using directives as if they
1427330f729Sjoerg // were declared in the effective DC.
visit(UsingDirectiveDecl * UD,DeclContext * EffectiveDC)1437330f729Sjoerg void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
1447330f729Sjoerg DeclContext *NS = UD->getNominatedNamespace();
1457330f729Sjoerg if (!visited.insert(NS).second)
1467330f729Sjoerg return;
1477330f729Sjoerg
1487330f729Sjoerg addUsingDirective(UD, EffectiveDC);
1497330f729Sjoerg addUsingDirectives(NS, EffectiveDC);
1507330f729Sjoerg }
1517330f729Sjoerg
1527330f729Sjoerg // Adds all the using directives in a context (and those nominated
1537330f729Sjoerg // by its using directives, transitively) as if they appeared in
1547330f729Sjoerg // the given effective context.
addUsingDirectives(DeclContext * DC,DeclContext * EffectiveDC)1557330f729Sjoerg void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
1567330f729Sjoerg SmallVector<DeclContext*, 4> queue;
1577330f729Sjoerg while (true) {
1587330f729Sjoerg for (auto UD : DC->using_directives()) {
1597330f729Sjoerg DeclContext *NS = UD->getNominatedNamespace();
1607330f729Sjoerg if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
1617330f729Sjoerg addUsingDirective(UD, EffectiveDC);
1627330f729Sjoerg queue.push_back(NS);
1637330f729Sjoerg }
1647330f729Sjoerg }
1657330f729Sjoerg
1667330f729Sjoerg if (queue.empty())
1677330f729Sjoerg return;
1687330f729Sjoerg
1697330f729Sjoerg DC = queue.pop_back_val();
1707330f729Sjoerg }
1717330f729Sjoerg }
1727330f729Sjoerg
1737330f729Sjoerg // Add a using directive as if it had been declared in the given
1747330f729Sjoerg // context. This helps implement C++ [namespace.udir]p3:
1757330f729Sjoerg // The using-directive is transitive: if a scope contains a
1767330f729Sjoerg // using-directive that nominates a second namespace that itself
1777330f729Sjoerg // contains using-directives, the effect is as if the
1787330f729Sjoerg // using-directives from the second namespace also appeared in
1797330f729Sjoerg // the first.
addUsingDirective(UsingDirectiveDecl * UD,DeclContext * EffectiveDC)1807330f729Sjoerg void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
1817330f729Sjoerg // Find the common ancestor between the effective context and
1827330f729Sjoerg // the nominated namespace.
1837330f729Sjoerg DeclContext *Common = UD->getNominatedNamespace();
1847330f729Sjoerg while (!Common->Encloses(EffectiveDC))
1857330f729Sjoerg Common = Common->getParent();
1867330f729Sjoerg Common = Common->getPrimaryContext();
1877330f729Sjoerg
1887330f729Sjoerg list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
1897330f729Sjoerg }
1907330f729Sjoerg
done()1917330f729Sjoerg void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
1927330f729Sjoerg
1937330f729Sjoerg typedef ListTy::const_iterator const_iterator;
1947330f729Sjoerg
begin() const1957330f729Sjoerg const_iterator begin() const { return list.begin(); }
end() const1967330f729Sjoerg const_iterator end() const { return list.end(); }
1977330f729Sjoerg
1987330f729Sjoerg llvm::iterator_range<const_iterator>
getNamespacesFor(DeclContext * DC) const1997330f729Sjoerg getNamespacesFor(DeclContext *DC) const {
2007330f729Sjoerg return llvm::make_range(std::equal_range(begin(), end(),
2017330f729Sjoerg DC->getPrimaryContext(),
2027330f729Sjoerg UnqualUsingEntry::Comparator()));
2037330f729Sjoerg }
2047330f729Sjoerg };
2057330f729Sjoerg } // end anonymous namespace
2067330f729Sjoerg
2077330f729Sjoerg // Retrieve the set of identifier namespaces that correspond to a
2087330f729Sjoerg // specific kind of name lookup.
getIDNS(Sema::LookupNameKind NameKind,bool CPlusPlus,bool Redeclaration)2097330f729Sjoerg static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
2107330f729Sjoerg bool CPlusPlus,
2117330f729Sjoerg bool Redeclaration) {
2127330f729Sjoerg unsigned IDNS = 0;
2137330f729Sjoerg switch (NameKind) {
2147330f729Sjoerg case Sema::LookupObjCImplicitSelfParam:
2157330f729Sjoerg case Sema::LookupOrdinaryName:
2167330f729Sjoerg case Sema::LookupRedeclarationWithLinkage:
2177330f729Sjoerg case Sema::LookupLocalFriendName:
218*e038c9c4Sjoerg case Sema::LookupDestructorName:
2197330f729Sjoerg IDNS = Decl::IDNS_Ordinary;
2207330f729Sjoerg if (CPlusPlus) {
2217330f729Sjoerg IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
2227330f729Sjoerg if (Redeclaration)
2237330f729Sjoerg IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
2247330f729Sjoerg }
2257330f729Sjoerg if (Redeclaration)
2267330f729Sjoerg IDNS |= Decl::IDNS_LocalExtern;
2277330f729Sjoerg break;
2287330f729Sjoerg
2297330f729Sjoerg case Sema::LookupOperatorName:
2307330f729Sjoerg // Operator lookup is its own crazy thing; it is not the same
2317330f729Sjoerg // as (e.g.) looking up an operator name for redeclaration.
2327330f729Sjoerg assert(!Redeclaration && "cannot do redeclaration operator lookup");
2337330f729Sjoerg IDNS = Decl::IDNS_NonMemberOperator;
2347330f729Sjoerg break;
2357330f729Sjoerg
2367330f729Sjoerg case Sema::LookupTagName:
2377330f729Sjoerg if (CPlusPlus) {
2387330f729Sjoerg IDNS = Decl::IDNS_Type;
2397330f729Sjoerg
2407330f729Sjoerg // When looking for a redeclaration of a tag name, we add:
2417330f729Sjoerg // 1) TagFriend to find undeclared friend decls
2427330f729Sjoerg // 2) Namespace because they can't "overload" with tag decls.
2437330f729Sjoerg // 3) Tag because it includes class templates, which can't
2447330f729Sjoerg // "overload" with tag decls.
2457330f729Sjoerg if (Redeclaration)
2467330f729Sjoerg IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
2477330f729Sjoerg } else {
2487330f729Sjoerg IDNS = Decl::IDNS_Tag;
2497330f729Sjoerg }
2507330f729Sjoerg break;
2517330f729Sjoerg
2527330f729Sjoerg case Sema::LookupLabel:
2537330f729Sjoerg IDNS = Decl::IDNS_Label;
2547330f729Sjoerg break;
2557330f729Sjoerg
2567330f729Sjoerg case Sema::LookupMemberName:
2577330f729Sjoerg IDNS = Decl::IDNS_Member;
2587330f729Sjoerg if (CPlusPlus)
2597330f729Sjoerg IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
2607330f729Sjoerg break;
2617330f729Sjoerg
2627330f729Sjoerg case Sema::LookupNestedNameSpecifierName:
2637330f729Sjoerg IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
2647330f729Sjoerg break;
2657330f729Sjoerg
2667330f729Sjoerg case Sema::LookupNamespaceName:
2677330f729Sjoerg IDNS = Decl::IDNS_Namespace;
2687330f729Sjoerg break;
2697330f729Sjoerg
2707330f729Sjoerg case Sema::LookupUsingDeclName:
2717330f729Sjoerg assert(Redeclaration && "should only be used for redecl lookup");
2727330f729Sjoerg IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
2737330f729Sjoerg Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
2747330f729Sjoerg Decl::IDNS_LocalExtern;
2757330f729Sjoerg break;
2767330f729Sjoerg
2777330f729Sjoerg case Sema::LookupObjCProtocolName:
2787330f729Sjoerg IDNS = Decl::IDNS_ObjCProtocol;
2797330f729Sjoerg break;
2807330f729Sjoerg
2817330f729Sjoerg case Sema::LookupOMPReductionName:
2827330f729Sjoerg IDNS = Decl::IDNS_OMPReduction;
2837330f729Sjoerg break;
2847330f729Sjoerg
2857330f729Sjoerg case Sema::LookupOMPMapperName:
2867330f729Sjoerg IDNS = Decl::IDNS_OMPMapper;
2877330f729Sjoerg break;
2887330f729Sjoerg
2897330f729Sjoerg case Sema::LookupAnyName:
2907330f729Sjoerg IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
2917330f729Sjoerg | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
2927330f729Sjoerg | Decl::IDNS_Type;
2937330f729Sjoerg break;
2947330f729Sjoerg }
2957330f729Sjoerg return IDNS;
2967330f729Sjoerg }
2977330f729Sjoerg
configure()2987330f729Sjoerg void LookupResult::configure() {
2997330f729Sjoerg IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
3007330f729Sjoerg isForRedeclaration());
3017330f729Sjoerg
3027330f729Sjoerg // If we're looking for one of the allocation or deallocation
3037330f729Sjoerg // operators, make sure that the implicitly-declared new and delete
3047330f729Sjoerg // operators can be found.
3057330f729Sjoerg switch (NameInfo.getName().getCXXOverloadedOperator()) {
3067330f729Sjoerg case OO_New:
3077330f729Sjoerg case OO_Delete:
3087330f729Sjoerg case OO_Array_New:
3097330f729Sjoerg case OO_Array_Delete:
3107330f729Sjoerg getSema().DeclareGlobalNewDelete();
3117330f729Sjoerg break;
3127330f729Sjoerg
3137330f729Sjoerg default:
3147330f729Sjoerg break;
3157330f729Sjoerg }
3167330f729Sjoerg
3177330f729Sjoerg // Compiler builtins are always visible, regardless of where they end
3187330f729Sjoerg // up being declared.
3197330f729Sjoerg if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
3207330f729Sjoerg if (unsigned BuiltinID = Id->getBuiltinID()) {
3217330f729Sjoerg if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3227330f729Sjoerg AllowHidden = true;
3237330f729Sjoerg }
3247330f729Sjoerg }
3257330f729Sjoerg }
3267330f729Sjoerg
sanity() const3277330f729Sjoerg bool LookupResult::sanity() const {
3287330f729Sjoerg // This function is never called by NDEBUG builds.
3297330f729Sjoerg assert(ResultKind != NotFound || Decls.size() == 0);
3307330f729Sjoerg assert(ResultKind != Found || Decls.size() == 1);
3317330f729Sjoerg assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
3327330f729Sjoerg (Decls.size() == 1 &&
3337330f729Sjoerg isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
3347330f729Sjoerg assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
3357330f729Sjoerg assert(ResultKind != Ambiguous || Decls.size() > 1 ||
3367330f729Sjoerg (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
3377330f729Sjoerg Ambiguity == AmbiguousBaseSubobjectTypes)));
3387330f729Sjoerg assert((Paths != nullptr) == (ResultKind == Ambiguous &&
3397330f729Sjoerg (Ambiguity == AmbiguousBaseSubobjectTypes ||
3407330f729Sjoerg Ambiguity == AmbiguousBaseSubobjects)));
3417330f729Sjoerg return true;
3427330f729Sjoerg }
3437330f729Sjoerg
3447330f729Sjoerg // Necessary because CXXBasePaths is not complete in Sema.h
deletePaths(CXXBasePaths * Paths)3457330f729Sjoerg void LookupResult::deletePaths(CXXBasePaths *Paths) {
3467330f729Sjoerg delete Paths;
3477330f729Sjoerg }
3487330f729Sjoerg
3497330f729Sjoerg /// Get a representative context for a declaration such that two declarations
3507330f729Sjoerg /// will have the same context if they were found within the same scope.
getContextForScopeMatching(Decl * D)3517330f729Sjoerg static DeclContext *getContextForScopeMatching(Decl *D) {
3527330f729Sjoerg // For function-local declarations, use that function as the context. This
3537330f729Sjoerg // doesn't account for scopes within the function; the caller must deal with
3547330f729Sjoerg // those.
3557330f729Sjoerg DeclContext *DC = D->getLexicalDeclContext();
3567330f729Sjoerg if (DC->isFunctionOrMethod())
3577330f729Sjoerg return DC;
3587330f729Sjoerg
3597330f729Sjoerg // Otherwise, look at the semantic context of the declaration. The
3607330f729Sjoerg // declaration must have been found there.
3617330f729Sjoerg return D->getDeclContext()->getRedeclContext();
3627330f729Sjoerg }
3637330f729Sjoerg
3647330f729Sjoerg /// Determine whether \p D is a better lookup result than \p Existing,
3657330f729Sjoerg /// given that they declare the same entity.
isPreferredLookupResult(Sema & S,Sema::LookupNameKind Kind,NamedDecl * D,NamedDecl * Existing)3667330f729Sjoerg static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
3677330f729Sjoerg NamedDecl *D, NamedDecl *Existing) {
3687330f729Sjoerg // When looking up redeclarations of a using declaration, prefer a using
3697330f729Sjoerg // shadow declaration over any other declaration of the same entity.
3707330f729Sjoerg if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
3717330f729Sjoerg !isa<UsingShadowDecl>(Existing))
3727330f729Sjoerg return true;
3737330f729Sjoerg
3747330f729Sjoerg auto *DUnderlying = D->getUnderlyingDecl();
3757330f729Sjoerg auto *EUnderlying = Existing->getUnderlyingDecl();
3767330f729Sjoerg
3777330f729Sjoerg // If they have different underlying declarations, prefer a typedef over the
3787330f729Sjoerg // original type (this happens when two type declarations denote the same
3797330f729Sjoerg // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
3807330f729Sjoerg // might carry additional semantic information, such as an alignment override.
3817330f729Sjoerg // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
382*e038c9c4Sjoerg // declaration over a typedef. Also prefer a tag over a typedef for
383*e038c9c4Sjoerg // destructor name lookup because in some contexts we only accept a
384*e038c9c4Sjoerg // class-name in a destructor declaration.
3857330f729Sjoerg if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
3867330f729Sjoerg assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
3877330f729Sjoerg bool HaveTag = isa<TagDecl>(EUnderlying);
388*e038c9c4Sjoerg bool WantTag =
389*e038c9c4Sjoerg Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;
3907330f729Sjoerg return HaveTag != WantTag;
3917330f729Sjoerg }
3927330f729Sjoerg
3937330f729Sjoerg // Pick the function with more default arguments.
3947330f729Sjoerg // FIXME: In the presence of ambiguous default arguments, we should keep both,
3957330f729Sjoerg // so we can diagnose the ambiguity if the default argument is needed.
3967330f729Sjoerg // See C++ [over.match.best]p3.
3977330f729Sjoerg if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
3987330f729Sjoerg auto *EFD = cast<FunctionDecl>(EUnderlying);
3997330f729Sjoerg unsigned DMin = DFD->getMinRequiredArguments();
4007330f729Sjoerg unsigned EMin = EFD->getMinRequiredArguments();
4017330f729Sjoerg // If D has more default arguments, it is preferred.
4027330f729Sjoerg if (DMin != EMin)
4037330f729Sjoerg return DMin < EMin;
4047330f729Sjoerg // FIXME: When we track visibility for default function arguments, check
4057330f729Sjoerg // that we pick the declaration with more visible default arguments.
4067330f729Sjoerg }
4077330f729Sjoerg
4087330f729Sjoerg // Pick the template with more default template arguments.
4097330f729Sjoerg if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
4107330f729Sjoerg auto *ETD = cast<TemplateDecl>(EUnderlying);
4117330f729Sjoerg unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
4127330f729Sjoerg unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
4137330f729Sjoerg // If D has more default arguments, it is preferred. Note that default
4147330f729Sjoerg // arguments (and their visibility) is monotonically increasing across the
4157330f729Sjoerg // redeclaration chain, so this is a quick proxy for "is more recent".
4167330f729Sjoerg if (DMin != EMin)
4177330f729Sjoerg return DMin < EMin;
4187330f729Sjoerg // If D has more *visible* default arguments, it is preferred. Note, an
4197330f729Sjoerg // earlier default argument being visible does not imply that a later
4207330f729Sjoerg // default argument is visible, so we can't just check the first one.
4217330f729Sjoerg for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
4227330f729Sjoerg I != N; ++I) {
4237330f729Sjoerg if (!S.hasVisibleDefaultArgument(
4247330f729Sjoerg ETD->getTemplateParameters()->getParam(I)) &&
4257330f729Sjoerg S.hasVisibleDefaultArgument(
4267330f729Sjoerg DTD->getTemplateParameters()->getParam(I)))
4277330f729Sjoerg return true;
4287330f729Sjoerg }
4297330f729Sjoerg }
4307330f729Sjoerg
4317330f729Sjoerg // VarDecl can have incomplete array types, prefer the one with more complete
4327330f729Sjoerg // array type.
4337330f729Sjoerg if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
4347330f729Sjoerg VarDecl *EVD = cast<VarDecl>(EUnderlying);
4357330f729Sjoerg if (EVD->getType()->isIncompleteType() &&
4367330f729Sjoerg !DVD->getType()->isIncompleteType()) {
4377330f729Sjoerg // Prefer the decl with a more complete type if visible.
4387330f729Sjoerg return S.isVisible(DVD);
4397330f729Sjoerg }
4407330f729Sjoerg return false; // Avoid picking up a newer decl, just because it was newer.
4417330f729Sjoerg }
4427330f729Sjoerg
4437330f729Sjoerg // For most kinds of declaration, it doesn't really matter which one we pick.
4447330f729Sjoerg if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
4457330f729Sjoerg // If the existing declaration is hidden, prefer the new one. Otherwise,
4467330f729Sjoerg // keep what we've got.
4477330f729Sjoerg return !S.isVisible(Existing);
4487330f729Sjoerg }
4497330f729Sjoerg
4507330f729Sjoerg // Pick the newer declaration; it might have a more precise type.
4517330f729Sjoerg for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
4527330f729Sjoerg Prev = Prev->getPreviousDecl())
4537330f729Sjoerg if (Prev == EUnderlying)
4547330f729Sjoerg return true;
4557330f729Sjoerg return false;
4567330f729Sjoerg }
4577330f729Sjoerg
4587330f729Sjoerg /// Determine whether \p D can hide a tag declaration.
canHideTag(NamedDecl * D)4597330f729Sjoerg static bool canHideTag(NamedDecl *D) {
4607330f729Sjoerg // C++ [basic.scope.declarative]p4:
4617330f729Sjoerg // Given a set of declarations in a single declarative region [...]
4627330f729Sjoerg // exactly one declaration shall declare a class name or enumeration name
4637330f729Sjoerg // that is not a typedef name and the other declarations shall all refer to
4647330f729Sjoerg // the same variable, non-static data member, or enumerator, or all refer
4657330f729Sjoerg // to functions and function templates; in this case the class name or
4667330f729Sjoerg // enumeration name is hidden.
4677330f729Sjoerg // C++ [basic.scope.hiding]p2:
4687330f729Sjoerg // A class name or enumeration name can be hidden by the name of a
4697330f729Sjoerg // variable, data member, function, or enumerator declared in the same
4707330f729Sjoerg // scope.
4717330f729Sjoerg // An UnresolvedUsingValueDecl always instantiates to one of these.
4727330f729Sjoerg D = D->getUnderlyingDecl();
4737330f729Sjoerg return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
4747330f729Sjoerg isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
4757330f729Sjoerg isa<UnresolvedUsingValueDecl>(D);
4767330f729Sjoerg }
4777330f729Sjoerg
4787330f729Sjoerg /// Resolves the result kind of this lookup.
resolveKind()4797330f729Sjoerg void LookupResult::resolveKind() {
4807330f729Sjoerg unsigned N = Decls.size();
4817330f729Sjoerg
4827330f729Sjoerg // Fast case: no possible ambiguity.
4837330f729Sjoerg if (N == 0) {
4847330f729Sjoerg assert(ResultKind == NotFound ||
4857330f729Sjoerg ResultKind == NotFoundInCurrentInstantiation);
4867330f729Sjoerg return;
4877330f729Sjoerg }
4887330f729Sjoerg
4897330f729Sjoerg // If there's a single decl, we need to examine it to decide what
4907330f729Sjoerg // kind of lookup this is.
4917330f729Sjoerg if (N == 1) {
4927330f729Sjoerg NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
4937330f729Sjoerg if (isa<FunctionTemplateDecl>(D))
4947330f729Sjoerg ResultKind = FoundOverloaded;
4957330f729Sjoerg else if (isa<UnresolvedUsingValueDecl>(D))
4967330f729Sjoerg ResultKind = FoundUnresolvedValue;
4977330f729Sjoerg return;
4987330f729Sjoerg }
4997330f729Sjoerg
5007330f729Sjoerg // Don't do any extra resolution if we've already resolved as ambiguous.
5017330f729Sjoerg if (ResultKind == Ambiguous) return;
5027330f729Sjoerg
5037330f729Sjoerg llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
5047330f729Sjoerg llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
5057330f729Sjoerg
5067330f729Sjoerg bool Ambiguous = false;
5077330f729Sjoerg bool HasTag = false, HasFunction = false;
5087330f729Sjoerg bool HasFunctionTemplate = false, HasUnresolved = false;
5097330f729Sjoerg NamedDecl *HasNonFunction = nullptr;
5107330f729Sjoerg
5117330f729Sjoerg llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
5127330f729Sjoerg
5137330f729Sjoerg unsigned UniqueTagIndex = 0;
5147330f729Sjoerg
5157330f729Sjoerg unsigned I = 0;
5167330f729Sjoerg while (I < N) {
5177330f729Sjoerg NamedDecl *D = Decls[I]->getUnderlyingDecl();
5187330f729Sjoerg D = cast<NamedDecl>(D->getCanonicalDecl());
5197330f729Sjoerg
5207330f729Sjoerg // Ignore an invalid declaration unless it's the only one left.
5217330f729Sjoerg if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
5227330f729Sjoerg Decls[I] = Decls[--N];
5237330f729Sjoerg continue;
5247330f729Sjoerg }
5257330f729Sjoerg
5267330f729Sjoerg llvm::Optional<unsigned> ExistingI;
5277330f729Sjoerg
5287330f729Sjoerg // Redeclarations of types via typedef can occur both within a scope
5297330f729Sjoerg // and, through using declarations and directives, across scopes. There is
5307330f729Sjoerg // no ambiguity if they all refer to the same type, so unique based on the
5317330f729Sjoerg // canonical type.
5327330f729Sjoerg if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
5337330f729Sjoerg QualType T = getSema().Context.getTypeDeclType(TD);
5347330f729Sjoerg auto UniqueResult = UniqueTypes.insert(
5357330f729Sjoerg std::make_pair(getSema().Context.getCanonicalType(T), I));
5367330f729Sjoerg if (!UniqueResult.second) {
5377330f729Sjoerg // The type is not unique.
5387330f729Sjoerg ExistingI = UniqueResult.first->second;
5397330f729Sjoerg }
5407330f729Sjoerg }
5417330f729Sjoerg
5427330f729Sjoerg // For non-type declarations, check for a prior lookup result naming this
5437330f729Sjoerg // canonical declaration.
5447330f729Sjoerg if (!ExistingI) {
5457330f729Sjoerg auto UniqueResult = Unique.insert(std::make_pair(D, I));
5467330f729Sjoerg if (!UniqueResult.second) {
5477330f729Sjoerg // We've seen this entity before.
5487330f729Sjoerg ExistingI = UniqueResult.first->second;
5497330f729Sjoerg }
5507330f729Sjoerg }
5517330f729Sjoerg
5527330f729Sjoerg if (ExistingI) {
5537330f729Sjoerg // This is not a unique lookup result. Pick one of the results and
5547330f729Sjoerg // discard the other.
5557330f729Sjoerg if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
5567330f729Sjoerg Decls[*ExistingI]))
5577330f729Sjoerg Decls[*ExistingI] = Decls[I];
5587330f729Sjoerg Decls[I] = Decls[--N];
5597330f729Sjoerg continue;
5607330f729Sjoerg }
5617330f729Sjoerg
5627330f729Sjoerg // Otherwise, do some decl type analysis and then continue.
5637330f729Sjoerg
5647330f729Sjoerg if (isa<UnresolvedUsingValueDecl>(D)) {
5657330f729Sjoerg HasUnresolved = true;
5667330f729Sjoerg } else if (isa<TagDecl>(D)) {
5677330f729Sjoerg if (HasTag)
5687330f729Sjoerg Ambiguous = true;
5697330f729Sjoerg UniqueTagIndex = I;
5707330f729Sjoerg HasTag = true;
5717330f729Sjoerg } else if (isa<FunctionTemplateDecl>(D)) {
5727330f729Sjoerg HasFunction = true;
5737330f729Sjoerg HasFunctionTemplate = true;
5747330f729Sjoerg } else if (isa<FunctionDecl>(D)) {
5757330f729Sjoerg HasFunction = true;
5767330f729Sjoerg } else {
5777330f729Sjoerg if (HasNonFunction) {
5787330f729Sjoerg // If we're about to create an ambiguity between two declarations that
5797330f729Sjoerg // are equivalent, but one is an internal linkage declaration from one
5807330f729Sjoerg // module and the other is an internal linkage declaration from another
5817330f729Sjoerg // module, just skip it.
5827330f729Sjoerg if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
5837330f729Sjoerg D)) {
5847330f729Sjoerg EquivalentNonFunctions.push_back(D);
5857330f729Sjoerg Decls[I] = Decls[--N];
5867330f729Sjoerg continue;
5877330f729Sjoerg }
5887330f729Sjoerg
5897330f729Sjoerg Ambiguous = true;
5907330f729Sjoerg }
5917330f729Sjoerg HasNonFunction = D;
5927330f729Sjoerg }
5937330f729Sjoerg I++;
5947330f729Sjoerg }
5957330f729Sjoerg
5967330f729Sjoerg // C++ [basic.scope.hiding]p2:
5977330f729Sjoerg // A class name or enumeration name can be hidden by the name of
5987330f729Sjoerg // an object, function, or enumerator declared in the same
5997330f729Sjoerg // scope. If a class or enumeration name and an object, function,
6007330f729Sjoerg // or enumerator are declared in the same scope (in any order)
6017330f729Sjoerg // with the same name, the class or enumeration name is hidden
6027330f729Sjoerg // wherever the object, function, or enumerator name is visible.
6037330f729Sjoerg // But it's still an error if there are distinct tag types found,
6047330f729Sjoerg // even if they're not visible. (ref?)
6057330f729Sjoerg if (N > 1 && HideTags && HasTag && !Ambiguous &&
6067330f729Sjoerg (HasFunction || HasNonFunction || HasUnresolved)) {
6077330f729Sjoerg NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
6087330f729Sjoerg if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
6097330f729Sjoerg getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
6107330f729Sjoerg getContextForScopeMatching(OtherDecl)) &&
6117330f729Sjoerg canHideTag(OtherDecl))
6127330f729Sjoerg Decls[UniqueTagIndex] = Decls[--N];
6137330f729Sjoerg else
6147330f729Sjoerg Ambiguous = true;
6157330f729Sjoerg }
6167330f729Sjoerg
6177330f729Sjoerg // FIXME: This diagnostic should really be delayed until we're done with
6187330f729Sjoerg // the lookup result, in case the ambiguity is resolved by the caller.
6197330f729Sjoerg if (!EquivalentNonFunctions.empty() && !Ambiguous)
6207330f729Sjoerg getSema().diagnoseEquivalentInternalLinkageDeclarations(
6217330f729Sjoerg getNameLoc(), HasNonFunction, EquivalentNonFunctions);
6227330f729Sjoerg
6237330f729Sjoerg Decls.set_size(N);
6247330f729Sjoerg
6257330f729Sjoerg if (HasNonFunction && (HasFunction || HasUnresolved))
6267330f729Sjoerg Ambiguous = true;
6277330f729Sjoerg
6287330f729Sjoerg if (Ambiguous)
6297330f729Sjoerg setAmbiguous(LookupResult::AmbiguousReference);
6307330f729Sjoerg else if (HasUnresolved)
6317330f729Sjoerg ResultKind = LookupResult::FoundUnresolvedValue;
6327330f729Sjoerg else if (N > 1 || HasFunctionTemplate)
6337330f729Sjoerg ResultKind = LookupResult::FoundOverloaded;
6347330f729Sjoerg else
6357330f729Sjoerg ResultKind = LookupResult::Found;
6367330f729Sjoerg }
6377330f729Sjoerg
addDeclsFromBasePaths(const CXXBasePaths & P)6387330f729Sjoerg void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
6397330f729Sjoerg CXXBasePaths::const_paths_iterator I, E;
6407330f729Sjoerg for (I = P.begin(), E = P.end(); I != E; ++I)
641*e038c9c4Sjoerg for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
642*e038c9c4Sjoerg ++DI)
6437330f729Sjoerg addDecl(*DI);
6447330f729Sjoerg }
6457330f729Sjoerg
setAmbiguousBaseSubobjects(CXXBasePaths & P)6467330f729Sjoerg void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
6477330f729Sjoerg Paths = new CXXBasePaths;
6487330f729Sjoerg Paths->swap(P);
6497330f729Sjoerg addDeclsFromBasePaths(*Paths);
6507330f729Sjoerg resolveKind();
6517330f729Sjoerg setAmbiguous(AmbiguousBaseSubobjects);
6527330f729Sjoerg }
6537330f729Sjoerg
setAmbiguousBaseSubobjectTypes(CXXBasePaths & P)6547330f729Sjoerg void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
6557330f729Sjoerg Paths = new CXXBasePaths;
6567330f729Sjoerg Paths->swap(P);
6577330f729Sjoerg addDeclsFromBasePaths(*Paths);
6587330f729Sjoerg resolveKind();
6597330f729Sjoerg setAmbiguous(AmbiguousBaseSubobjectTypes);
6607330f729Sjoerg }
6617330f729Sjoerg
print(raw_ostream & Out)6627330f729Sjoerg void LookupResult::print(raw_ostream &Out) {
6637330f729Sjoerg Out << Decls.size() << " result(s)";
6647330f729Sjoerg if (isAmbiguous()) Out << ", ambiguous";
6657330f729Sjoerg if (Paths) Out << ", base paths present";
6667330f729Sjoerg
6677330f729Sjoerg for (iterator I = begin(), E = end(); I != E; ++I) {
6687330f729Sjoerg Out << "\n";
6697330f729Sjoerg (*I)->print(Out, 2);
6707330f729Sjoerg }
6717330f729Sjoerg }
6727330f729Sjoerg
dump()6737330f729Sjoerg LLVM_DUMP_METHOD void LookupResult::dump() {
6747330f729Sjoerg llvm::errs() << "lookup results for " << getLookupName().getAsString()
6757330f729Sjoerg << ":\n";
6767330f729Sjoerg for (NamedDecl *D : *this)
6777330f729Sjoerg D->dump();
6787330f729Sjoerg }
6797330f729Sjoerg
680*e038c9c4Sjoerg /// Diagnose a missing builtin type.
diagOpenCLBuiltinTypeError(Sema & S,llvm::StringRef TypeClass,llvm::StringRef Name)681*e038c9c4Sjoerg static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
682*e038c9c4Sjoerg llvm::StringRef Name) {
683*e038c9c4Sjoerg S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
684*e038c9c4Sjoerg << TypeClass << Name;
685*e038c9c4Sjoerg return S.Context.VoidTy;
686*e038c9c4Sjoerg }
687*e038c9c4Sjoerg
688*e038c9c4Sjoerg /// Lookup an OpenCL enum type.
getOpenCLEnumType(Sema & S,llvm::StringRef Name)689*e038c9c4Sjoerg static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
690*e038c9c4Sjoerg LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
691*e038c9c4Sjoerg Sema::LookupTagName);
692*e038c9c4Sjoerg S.LookupName(Result, S.TUScope);
693*e038c9c4Sjoerg if (Result.empty())
694*e038c9c4Sjoerg return diagOpenCLBuiltinTypeError(S, "enum", Name);
695*e038c9c4Sjoerg EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
696*e038c9c4Sjoerg if (!Decl)
697*e038c9c4Sjoerg return diagOpenCLBuiltinTypeError(S, "enum", Name);
698*e038c9c4Sjoerg return S.Context.getEnumType(Decl);
699*e038c9c4Sjoerg }
700*e038c9c4Sjoerg
701*e038c9c4Sjoerg /// Lookup an OpenCL typedef type.
getOpenCLTypedefType(Sema & S,llvm::StringRef Name)702*e038c9c4Sjoerg static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
703*e038c9c4Sjoerg LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
704*e038c9c4Sjoerg Sema::LookupOrdinaryName);
705*e038c9c4Sjoerg S.LookupName(Result, S.TUScope);
706*e038c9c4Sjoerg if (Result.empty())
707*e038c9c4Sjoerg return diagOpenCLBuiltinTypeError(S, "typedef", Name);
708*e038c9c4Sjoerg TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
709*e038c9c4Sjoerg if (!Decl)
710*e038c9c4Sjoerg return diagOpenCLBuiltinTypeError(S, "typedef", Name);
711*e038c9c4Sjoerg return S.Context.getTypedefType(Decl);
712*e038c9c4Sjoerg }
713*e038c9c4Sjoerg
7147330f729Sjoerg /// Get the QualType instances of the return type and arguments for an OpenCL
7157330f729Sjoerg /// builtin function signature.
716*e038c9c4Sjoerg /// \param S (in) The Sema instance.
7177330f729Sjoerg /// \param OpenCLBuiltin (in) The signature currently handled.
7187330f729Sjoerg /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
7197330f729Sjoerg /// type used as return type or as argument.
7207330f729Sjoerg /// Only meaningful for generic types, otherwise equals 1.
7217330f729Sjoerg /// \param RetTypes (out) List of the possible return types.
7227330f729Sjoerg /// \param ArgTypes (out) List of the possible argument types. For each
7237330f729Sjoerg /// argument, ArgTypes contains QualTypes for the Cartesian product
7247330f729Sjoerg /// of (vector sizes) x (types) .
GetQualTypesForOpenCLBuiltin(Sema & S,const OpenCLBuiltinStruct & OpenCLBuiltin,unsigned & GenTypeMaxCnt,SmallVector<QualType,1> & RetTypes,SmallVector<SmallVector<QualType,1>,5> & ArgTypes)7257330f729Sjoerg static void GetQualTypesForOpenCLBuiltin(
726*e038c9c4Sjoerg Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
727*e038c9c4Sjoerg SmallVector<QualType, 1> &RetTypes,
7287330f729Sjoerg SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
7297330f729Sjoerg // Get the QualType instances of the return types.
7307330f729Sjoerg unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
731*e038c9c4Sjoerg OCL2Qual(S, TypeTable[Sig], RetTypes);
7327330f729Sjoerg GenTypeMaxCnt = RetTypes.size();
7337330f729Sjoerg
7347330f729Sjoerg // Get the QualType instances of the arguments.
7357330f729Sjoerg // First type is the return type, skip it.
7367330f729Sjoerg for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
7377330f729Sjoerg SmallVector<QualType, 1> Ty;
738*e038c9c4Sjoerg OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
739*e038c9c4Sjoerg Ty);
7407330f729Sjoerg GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
7417330f729Sjoerg ArgTypes.push_back(std::move(Ty));
7427330f729Sjoerg }
7437330f729Sjoerg }
7447330f729Sjoerg
7457330f729Sjoerg /// Create a list of the candidate function overloads for an OpenCL builtin
7467330f729Sjoerg /// function.
7477330f729Sjoerg /// \param Context (in) The ASTContext instance.
7487330f729Sjoerg /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
7497330f729Sjoerg /// type used as return type or as argument.
7507330f729Sjoerg /// Only meaningful for generic types, otherwise equals 1.
7517330f729Sjoerg /// \param FunctionList (out) List of FunctionTypes.
7527330f729Sjoerg /// \param RetTypes (in) List of the possible return types.
7537330f729Sjoerg /// \param ArgTypes (in) List of the possible types for the arguments.
GetOpenCLBuiltinFctOverloads(ASTContext & Context,unsigned GenTypeMaxCnt,std::vector<QualType> & FunctionList,SmallVector<QualType,1> & RetTypes,SmallVector<SmallVector<QualType,1>,5> & ArgTypes)7547330f729Sjoerg static void GetOpenCLBuiltinFctOverloads(
7557330f729Sjoerg ASTContext &Context, unsigned GenTypeMaxCnt,
7567330f729Sjoerg std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
7577330f729Sjoerg SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
758*e038c9c4Sjoerg FunctionProtoType::ExtProtoInfo PI(
759*e038c9c4Sjoerg Context.getDefaultCallingConvention(false, false, true));
7607330f729Sjoerg PI.Variadic = false;
7617330f729Sjoerg
762*e038c9c4Sjoerg // Do not attempt to create any FunctionTypes if there are no return types,
763*e038c9c4Sjoerg // which happens when a type belongs to a disabled extension.
764*e038c9c4Sjoerg if (RetTypes.size() == 0)
765*e038c9c4Sjoerg return;
766*e038c9c4Sjoerg
7677330f729Sjoerg // Create FunctionTypes for each (gen)type.
7687330f729Sjoerg for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
7697330f729Sjoerg SmallVector<QualType, 5> ArgList;
7707330f729Sjoerg
7717330f729Sjoerg for (unsigned A = 0; A < ArgTypes.size(); A++) {
772*e038c9c4Sjoerg // Bail out if there is an argument that has no available types.
773*e038c9c4Sjoerg if (ArgTypes[A].size() == 0)
774*e038c9c4Sjoerg return;
775*e038c9c4Sjoerg
7767330f729Sjoerg // Builtins such as "max" have an "sgentype" argument that represents
7777330f729Sjoerg // the corresponding scalar type of a gentype. The number of gentypes
7787330f729Sjoerg // must be a multiple of the number of sgentypes.
7797330f729Sjoerg assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
7807330f729Sjoerg "argument type count not compatible with gentype type count");
7817330f729Sjoerg unsigned Idx = IGenType % ArgTypes[A].size();
7827330f729Sjoerg ArgList.push_back(ArgTypes[A][Idx]);
7837330f729Sjoerg }
7847330f729Sjoerg
7857330f729Sjoerg FunctionList.push_back(Context.getFunctionType(
7867330f729Sjoerg RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
7877330f729Sjoerg }
7887330f729Sjoerg }
7897330f729Sjoerg
7907330f729Sjoerg /// When trying to resolve a function name, if isOpenCLBuiltin() returns a
7917330f729Sjoerg /// non-null <Index, Len> pair, then the name is referencing an OpenCL
7927330f729Sjoerg /// builtin function. Add all candidate signatures to the LookUpResult.
7937330f729Sjoerg ///
7947330f729Sjoerg /// \param S (in) The Sema instance.
7957330f729Sjoerg /// \param LR (inout) The LookupResult instance.
7967330f729Sjoerg /// \param II (in) The identifier being resolved.
7977330f729Sjoerg /// \param FctIndex (in) Starting index in the BuiltinTable.
7987330f729Sjoerg /// \param Len (in) The signature list has Len elements.
InsertOCLBuiltinDeclarationsFromTable(Sema & S,LookupResult & LR,IdentifierInfo * II,const unsigned FctIndex,const unsigned Len)7997330f729Sjoerg static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,
8007330f729Sjoerg IdentifierInfo *II,
8017330f729Sjoerg const unsigned FctIndex,
8027330f729Sjoerg const unsigned Len) {
8037330f729Sjoerg // The builtin function declaration uses generic types (gentype).
8047330f729Sjoerg bool HasGenType = false;
8057330f729Sjoerg
8067330f729Sjoerg // Maximum number of types contained in a generic type used as return type or
8077330f729Sjoerg // as argument. Only meaningful for generic types, otherwise equals 1.
8087330f729Sjoerg unsigned GenTypeMaxCnt;
8097330f729Sjoerg
810*e038c9c4Sjoerg ASTContext &Context = S.Context;
811*e038c9c4Sjoerg
8127330f729Sjoerg for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
8137330f729Sjoerg const OpenCLBuiltinStruct &OpenCLBuiltin =
8147330f729Sjoerg BuiltinTable[FctIndex + SignatureIndex];
8157330f729Sjoerg
816*e038c9c4Sjoerg // Ignore this builtin function if it is not available in the currently
817*e038c9c4Sjoerg // selected language version.
818*e038c9c4Sjoerg if (!isOpenCLVersionContainedInMask(Context.getLangOpts(),
819*e038c9c4Sjoerg OpenCLBuiltin.Versions))
8207330f729Sjoerg continue;
821*e038c9c4Sjoerg
822*e038c9c4Sjoerg // Ignore this builtin function if it carries an extension macro that is
823*e038c9c4Sjoerg // not defined. This indicates that the extension is not supported by the
824*e038c9c4Sjoerg // target, so the builtin function should not be available.
825*e038c9c4Sjoerg StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
826*e038c9c4Sjoerg if (!Extensions.empty()) {
827*e038c9c4Sjoerg SmallVector<StringRef, 2> ExtVec;
828*e038c9c4Sjoerg Extensions.split(ExtVec, " ");
829*e038c9c4Sjoerg bool AllExtensionsDefined = true;
830*e038c9c4Sjoerg for (StringRef Ext : ExtVec) {
831*e038c9c4Sjoerg if (!S.getPreprocessor().isMacroDefined(Ext)) {
832*e038c9c4Sjoerg AllExtensionsDefined = false;
833*e038c9c4Sjoerg break;
834*e038c9c4Sjoerg }
835*e038c9c4Sjoerg }
836*e038c9c4Sjoerg if (!AllExtensionsDefined)
8377330f729Sjoerg continue;
838*e038c9c4Sjoerg }
8397330f729Sjoerg
8407330f729Sjoerg SmallVector<QualType, 1> RetTypes;
8417330f729Sjoerg SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;
8427330f729Sjoerg
8437330f729Sjoerg // Obtain QualType lists for the function signature.
844*e038c9c4Sjoerg GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
845*e038c9c4Sjoerg ArgTypes);
8467330f729Sjoerg if (GenTypeMaxCnt > 1) {
8477330f729Sjoerg HasGenType = true;
8487330f729Sjoerg }
8497330f729Sjoerg
8507330f729Sjoerg // Create function overload for each type combination.
8517330f729Sjoerg std::vector<QualType> FunctionList;
8527330f729Sjoerg GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
8537330f729Sjoerg ArgTypes);
8547330f729Sjoerg
8557330f729Sjoerg SourceLocation Loc = LR.getNameLoc();
8567330f729Sjoerg DeclContext *Parent = Context.getTranslationUnitDecl();
8577330f729Sjoerg FunctionDecl *NewOpenCLBuiltin;
8587330f729Sjoerg
859*e038c9c4Sjoerg for (const auto &FTy : FunctionList) {
8607330f729Sjoerg NewOpenCLBuiltin = FunctionDecl::Create(
861*e038c9c4Sjoerg Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
862*e038c9c4Sjoerg false, FTy->isFunctionProtoType());
8637330f729Sjoerg NewOpenCLBuiltin->setImplicit();
8647330f729Sjoerg
8657330f729Sjoerg // Create Decl objects for each parameter, adding them to the
8667330f729Sjoerg // FunctionDecl.
867*e038c9c4Sjoerg const auto *FP = cast<FunctionProtoType>(FTy);
868*e038c9c4Sjoerg SmallVector<ParmVarDecl *, 4> ParmList;
8697330f729Sjoerg for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
8707330f729Sjoerg ParmVarDecl *Parm = ParmVarDecl::Create(
8717330f729Sjoerg Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
872*e038c9c4Sjoerg nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
8737330f729Sjoerg Parm->setScopeInfo(0, IParm);
8747330f729Sjoerg ParmList.push_back(Parm);
8757330f729Sjoerg }
8767330f729Sjoerg NewOpenCLBuiltin->setParams(ParmList);
877*e038c9c4Sjoerg
878*e038c9c4Sjoerg // Add function attributes.
879*e038c9c4Sjoerg if (OpenCLBuiltin.IsPure)
880*e038c9c4Sjoerg NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));
881*e038c9c4Sjoerg if (OpenCLBuiltin.IsConst)
882*e038c9c4Sjoerg NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));
883*e038c9c4Sjoerg if (OpenCLBuiltin.IsConv)
884*e038c9c4Sjoerg NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));
885*e038c9c4Sjoerg
886*e038c9c4Sjoerg if (!S.getLangOpts().OpenCLCPlusPlus)
8877330f729Sjoerg NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
888*e038c9c4Sjoerg
8897330f729Sjoerg LR.addDecl(NewOpenCLBuiltin);
8907330f729Sjoerg }
8917330f729Sjoerg }
8927330f729Sjoerg
8937330f729Sjoerg // If we added overloads, need to resolve the lookup result.
8947330f729Sjoerg if (Len > 1 || HasGenType)
8957330f729Sjoerg LR.resolveKind();
8967330f729Sjoerg }
8977330f729Sjoerg
8987330f729Sjoerg /// Lookup a builtin function, when name lookup would otherwise
8997330f729Sjoerg /// fail.
LookupBuiltin(LookupResult & R)9007330f729Sjoerg bool Sema::LookupBuiltin(LookupResult &R) {
9017330f729Sjoerg Sema::LookupNameKind NameKind = R.getLookupKind();
9027330f729Sjoerg
9037330f729Sjoerg // If we didn't find a use of this identifier, and if the identifier
9047330f729Sjoerg // corresponds to a compiler builtin, create the decl object for the builtin
9057330f729Sjoerg // now, injecting it into translation unit scope, and return it.
9067330f729Sjoerg if (NameKind == Sema::LookupOrdinaryName ||
9077330f729Sjoerg NameKind == Sema::LookupRedeclarationWithLinkage) {
9087330f729Sjoerg IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
9097330f729Sjoerg if (II) {
9107330f729Sjoerg if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
9117330f729Sjoerg if (II == getASTContext().getMakeIntegerSeqName()) {
9127330f729Sjoerg R.addDecl(getASTContext().getMakeIntegerSeqDecl());
9137330f729Sjoerg return true;
9147330f729Sjoerg } else if (II == getASTContext().getTypePackElementName()) {
9157330f729Sjoerg R.addDecl(getASTContext().getTypePackElementDecl());
9167330f729Sjoerg return true;
9177330f729Sjoerg }
9187330f729Sjoerg }
9197330f729Sjoerg
9207330f729Sjoerg // Check if this is an OpenCL Builtin, and if so, insert its overloads.
9217330f729Sjoerg if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
9227330f729Sjoerg auto Index = isOpenCLBuiltin(II->getName());
9237330f729Sjoerg if (Index.first) {
9247330f729Sjoerg InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
9257330f729Sjoerg Index.second);
9267330f729Sjoerg return true;
9277330f729Sjoerg }
9287330f729Sjoerg }
9297330f729Sjoerg
9307330f729Sjoerg // If this is a builtin on this (or all) targets, create the decl.
9317330f729Sjoerg if (unsigned BuiltinID = II->getBuiltinID()) {
9327330f729Sjoerg // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
9337330f729Sjoerg // library functions like 'malloc'. Instead, we'll just error.
9347330f729Sjoerg if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) &&
9357330f729Sjoerg Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
9367330f729Sjoerg return false;
9377330f729Sjoerg
938*e038c9c4Sjoerg if (NamedDecl *D =
939*e038c9c4Sjoerg LazilyCreateBuiltin(II, BuiltinID, TUScope,
940*e038c9c4Sjoerg R.isForRedeclaration(), R.getNameLoc())) {
9417330f729Sjoerg R.addDecl(D);
9427330f729Sjoerg return true;
9437330f729Sjoerg }
9447330f729Sjoerg }
9457330f729Sjoerg }
9467330f729Sjoerg }
9477330f729Sjoerg
9487330f729Sjoerg return false;
9497330f729Sjoerg }
9507330f729Sjoerg
951*e038c9c4Sjoerg /// Looks up the declaration of "struct objc_super" and
952*e038c9c4Sjoerg /// saves it for later use in building builtin declaration of
953*e038c9c4Sjoerg /// objc_msgSendSuper and objc_msgSendSuper_stret.
LookupPredefedObjCSuperType(Sema & Sema,Scope * S)954*e038c9c4Sjoerg static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {
955*e038c9c4Sjoerg ASTContext &Context = Sema.Context;
956*e038c9c4Sjoerg LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
957*e038c9c4Sjoerg Sema::LookupTagName);
958*e038c9c4Sjoerg Sema.LookupName(Result, S);
959*e038c9c4Sjoerg if (Result.getResultKind() == LookupResult::Found)
960*e038c9c4Sjoerg if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
961*e038c9c4Sjoerg Context.setObjCSuperType(Context.getTagDeclType(TD));
962*e038c9c4Sjoerg }
963*e038c9c4Sjoerg
LookupNecessaryTypesForBuiltin(Scope * S,unsigned ID)964*e038c9c4Sjoerg void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {
965*e038c9c4Sjoerg if (ID == Builtin::BIobjc_msgSendSuper)
966*e038c9c4Sjoerg LookupPredefedObjCSuperType(*this, S);
967*e038c9c4Sjoerg }
968*e038c9c4Sjoerg
9697330f729Sjoerg /// Determine whether we can declare a special member function within
9707330f729Sjoerg /// the class at this point.
CanDeclareSpecialMemberFunction(const CXXRecordDecl * Class)9717330f729Sjoerg static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
9727330f729Sjoerg // We need to have a definition for the class.
9737330f729Sjoerg if (!Class->getDefinition() || Class->isDependentContext())
9747330f729Sjoerg return false;
9757330f729Sjoerg
9767330f729Sjoerg // We can't be in the middle of defining the class.
9777330f729Sjoerg return !Class->isBeingDefined();
9787330f729Sjoerg }
9797330f729Sjoerg
ForceDeclarationOfImplicitMembers(CXXRecordDecl * Class)9807330f729Sjoerg void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
9817330f729Sjoerg if (!CanDeclareSpecialMemberFunction(Class))
9827330f729Sjoerg return;
9837330f729Sjoerg
9847330f729Sjoerg // If the default constructor has not yet been declared, do so now.
9857330f729Sjoerg if (Class->needsImplicitDefaultConstructor())
9867330f729Sjoerg DeclareImplicitDefaultConstructor(Class);
9877330f729Sjoerg
9887330f729Sjoerg // If the copy constructor has not yet been declared, do so now.
9897330f729Sjoerg if (Class->needsImplicitCopyConstructor())
9907330f729Sjoerg DeclareImplicitCopyConstructor(Class);
9917330f729Sjoerg
9927330f729Sjoerg // If the copy assignment operator has not yet been declared, do so now.
9937330f729Sjoerg if (Class->needsImplicitCopyAssignment())
9947330f729Sjoerg DeclareImplicitCopyAssignment(Class);
9957330f729Sjoerg
9967330f729Sjoerg if (getLangOpts().CPlusPlus11) {
9977330f729Sjoerg // If the move constructor has not yet been declared, do so now.
9987330f729Sjoerg if (Class->needsImplicitMoveConstructor())
9997330f729Sjoerg DeclareImplicitMoveConstructor(Class);
10007330f729Sjoerg
10017330f729Sjoerg // If the move assignment operator has not yet been declared, do so now.
10027330f729Sjoerg if (Class->needsImplicitMoveAssignment())
10037330f729Sjoerg DeclareImplicitMoveAssignment(Class);
10047330f729Sjoerg }
10057330f729Sjoerg
10067330f729Sjoerg // If the destructor has not yet been declared, do so now.
10077330f729Sjoerg if (Class->needsImplicitDestructor())
10087330f729Sjoerg DeclareImplicitDestructor(Class);
10097330f729Sjoerg }
10107330f729Sjoerg
10117330f729Sjoerg /// Determine whether this is the name of an implicitly-declared
10127330f729Sjoerg /// special member function.
isImplicitlyDeclaredMemberFunctionName(DeclarationName Name)10137330f729Sjoerg static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
10147330f729Sjoerg switch (Name.getNameKind()) {
10157330f729Sjoerg case DeclarationName::CXXConstructorName:
10167330f729Sjoerg case DeclarationName::CXXDestructorName:
10177330f729Sjoerg return true;
10187330f729Sjoerg
10197330f729Sjoerg case DeclarationName::CXXOperatorName:
10207330f729Sjoerg return Name.getCXXOverloadedOperator() == OO_Equal;
10217330f729Sjoerg
10227330f729Sjoerg default:
10237330f729Sjoerg break;
10247330f729Sjoerg }
10257330f729Sjoerg
10267330f729Sjoerg return false;
10277330f729Sjoerg }
10287330f729Sjoerg
10297330f729Sjoerg /// If there are any implicit member functions with the given name
10307330f729Sjoerg /// that need to be declared in the given declaration context, do so.
DeclareImplicitMemberFunctionsWithName(Sema & S,DeclarationName Name,SourceLocation Loc,const DeclContext * DC)10317330f729Sjoerg static void DeclareImplicitMemberFunctionsWithName(Sema &S,
10327330f729Sjoerg DeclarationName Name,
10337330f729Sjoerg SourceLocation Loc,
10347330f729Sjoerg const DeclContext *DC) {
10357330f729Sjoerg if (!DC)
10367330f729Sjoerg return;
10377330f729Sjoerg
10387330f729Sjoerg switch (Name.getNameKind()) {
10397330f729Sjoerg case DeclarationName::CXXConstructorName:
10407330f729Sjoerg if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
10417330f729Sjoerg if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
10427330f729Sjoerg CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
10437330f729Sjoerg if (Record->needsImplicitDefaultConstructor())
10447330f729Sjoerg S.DeclareImplicitDefaultConstructor(Class);
10457330f729Sjoerg if (Record->needsImplicitCopyConstructor())
10467330f729Sjoerg S.DeclareImplicitCopyConstructor(Class);
10477330f729Sjoerg if (S.getLangOpts().CPlusPlus11 &&
10487330f729Sjoerg Record->needsImplicitMoveConstructor())
10497330f729Sjoerg S.DeclareImplicitMoveConstructor(Class);
10507330f729Sjoerg }
10517330f729Sjoerg break;
10527330f729Sjoerg
10537330f729Sjoerg case DeclarationName::CXXDestructorName:
10547330f729Sjoerg if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
10557330f729Sjoerg if (Record->getDefinition() && Record->needsImplicitDestructor() &&
10567330f729Sjoerg CanDeclareSpecialMemberFunction(Record))
10577330f729Sjoerg S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
10587330f729Sjoerg break;
10597330f729Sjoerg
10607330f729Sjoerg case DeclarationName::CXXOperatorName:
10617330f729Sjoerg if (Name.getCXXOverloadedOperator() != OO_Equal)
10627330f729Sjoerg break;
10637330f729Sjoerg
10647330f729Sjoerg if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
10657330f729Sjoerg if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
10667330f729Sjoerg CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
10677330f729Sjoerg if (Record->needsImplicitCopyAssignment())
10687330f729Sjoerg S.DeclareImplicitCopyAssignment(Class);
10697330f729Sjoerg if (S.getLangOpts().CPlusPlus11 &&
10707330f729Sjoerg Record->needsImplicitMoveAssignment())
10717330f729Sjoerg S.DeclareImplicitMoveAssignment(Class);
10727330f729Sjoerg }
10737330f729Sjoerg }
10747330f729Sjoerg break;
10757330f729Sjoerg
10767330f729Sjoerg case DeclarationName::CXXDeductionGuideName:
10777330f729Sjoerg S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
10787330f729Sjoerg break;
10797330f729Sjoerg
10807330f729Sjoerg default:
10817330f729Sjoerg break;
10827330f729Sjoerg }
10837330f729Sjoerg }
10847330f729Sjoerg
10857330f729Sjoerg // Adds all qualifying matches for a name within a decl context to the
10867330f729Sjoerg // given lookup result. Returns true if any matches were found.
LookupDirect(Sema & S,LookupResult & R,const DeclContext * DC)10877330f729Sjoerg static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
10887330f729Sjoerg bool Found = false;
10897330f729Sjoerg
10907330f729Sjoerg // Lazily declare C++ special member functions.
10917330f729Sjoerg if (S.getLangOpts().CPlusPlus)
10927330f729Sjoerg DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
10937330f729Sjoerg DC);
10947330f729Sjoerg
10957330f729Sjoerg // Perform lookup into this declaration context.
10967330f729Sjoerg DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
10977330f729Sjoerg for (NamedDecl *D : DR) {
10987330f729Sjoerg if ((D = R.getAcceptableDecl(D))) {
10997330f729Sjoerg R.addDecl(D);
11007330f729Sjoerg Found = true;
11017330f729Sjoerg }
11027330f729Sjoerg }
11037330f729Sjoerg
11047330f729Sjoerg if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
11057330f729Sjoerg return true;
11067330f729Sjoerg
11077330f729Sjoerg if (R.getLookupName().getNameKind()
11087330f729Sjoerg != DeclarationName::CXXConversionFunctionName ||
11097330f729Sjoerg R.getLookupName().getCXXNameType()->isDependentType() ||
11107330f729Sjoerg !isa<CXXRecordDecl>(DC))
11117330f729Sjoerg return Found;
11127330f729Sjoerg
11137330f729Sjoerg // C++ [temp.mem]p6:
11147330f729Sjoerg // A specialization of a conversion function template is not found by
11157330f729Sjoerg // name lookup. Instead, any conversion function templates visible in the
11167330f729Sjoerg // context of the use are considered. [...]
11177330f729Sjoerg const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
11187330f729Sjoerg if (!Record->isCompleteDefinition())
11197330f729Sjoerg return Found;
11207330f729Sjoerg
11217330f729Sjoerg // For conversion operators, 'operator auto' should only match
11227330f729Sjoerg // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
11237330f729Sjoerg // as a candidate for template substitution.
11247330f729Sjoerg auto *ContainedDeducedType =
11257330f729Sjoerg R.getLookupName().getCXXNameType()->getContainedDeducedType();
11267330f729Sjoerg if (R.getLookupName().getNameKind() ==
11277330f729Sjoerg DeclarationName::CXXConversionFunctionName &&
11287330f729Sjoerg ContainedDeducedType && ContainedDeducedType->isUndeducedType())
11297330f729Sjoerg return Found;
11307330f729Sjoerg
11317330f729Sjoerg for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
11327330f729Sjoerg UEnd = Record->conversion_end(); U != UEnd; ++U) {
11337330f729Sjoerg FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
11347330f729Sjoerg if (!ConvTemplate)
11357330f729Sjoerg continue;
11367330f729Sjoerg
11377330f729Sjoerg // When we're performing lookup for the purposes of redeclaration, just
11387330f729Sjoerg // add the conversion function template. When we deduce template
11397330f729Sjoerg // arguments for specializations, we'll end up unifying the return
11407330f729Sjoerg // type of the new declaration with the type of the function template.
11417330f729Sjoerg if (R.isForRedeclaration()) {
11427330f729Sjoerg R.addDecl(ConvTemplate);
11437330f729Sjoerg Found = true;
11447330f729Sjoerg continue;
11457330f729Sjoerg }
11467330f729Sjoerg
11477330f729Sjoerg // C++ [temp.mem]p6:
11487330f729Sjoerg // [...] For each such operator, if argument deduction succeeds
11497330f729Sjoerg // (14.9.2.3), the resulting specialization is used as if found by
11507330f729Sjoerg // name lookup.
11517330f729Sjoerg //
11527330f729Sjoerg // When referencing a conversion function for any purpose other than
11537330f729Sjoerg // a redeclaration (such that we'll be building an expression with the
11547330f729Sjoerg // result), perform template argument deduction and place the
11557330f729Sjoerg // specialization into the result set. We do this to avoid forcing all
11567330f729Sjoerg // callers to perform special deduction for conversion functions.
11577330f729Sjoerg TemplateDeductionInfo Info(R.getNameLoc());
11587330f729Sjoerg FunctionDecl *Specialization = nullptr;
11597330f729Sjoerg
11607330f729Sjoerg const FunctionProtoType *ConvProto
11617330f729Sjoerg = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
11627330f729Sjoerg assert(ConvProto && "Nonsensical conversion function template type");
11637330f729Sjoerg
11647330f729Sjoerg // Compute the type of the function that we would expect the conversion
11657330f729Sjoerg // function to have, if it were to match the name given.
11667330f729Sjoerg // FIXME: Calling convention!
11677330f729Sjoerg FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
11687330f729Sjoerg EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
11697330f729Sjoerg EPI.ExceptionSpec = EST_None;
11707330f729Sjoerg QualType ExpectedType
11717330f729Sjoerg = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
11727330f729Sjoerg None, EPI);
11737330f729Sjoerg
11747330f729Sjoerg // Perform template argument deduction against the type that we would
11757330f729Sjoerg // expect the function to have.
11767330f729Sjoerg if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
11777330f729Sjoerg Specialization, Info)
11787330f729Sjoerg == Sema::TDK_Success) {
11797330f729Sjoerg R.addDecl(Specialization);
11807330f729Sjoerg Found = true;
11817330f729Sjoerg }
11827330f729Sjoerg }
11837330f729Sjoerg
11847330f729Sjoerg return Found;
11857330f729Sjoerg }
11867330f729Sjoerg
11877330f729Sjoerg // Performs C++ unqualified lookup into the given file context.
11887330f729Sjoerg static bool
CppNamespaceLookup(Sema & S,LookupResult & R,ASTContext & Context,DeclContext * NS,UnqualUsingDirectiveSet & UDirs)11897330f729Sjoerg CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
11907330f729Sjoerg DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
11917330f729Sjoerg
11927330f729Sjoerg assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
11937330f729Sjoerg
11947330f729Sjoerg // Perform direct name lookup into the LookupCtx.
11957330f729Sjoerg bool Found = LookupDirect(S, R, NS);
11967330f729Sjoerg
11977330f729Sjoerg // Perform direct name lookup into the namespaces nominated by the
11987330f729Sjoerg // using directives whose common ancestor is this namespace.
11997330f729Sjoerg for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
12007330f729Sjoerg if (LookupDirect(S, R, UUE.getNominatedNamespace()))
12017330f729Sjoerg Found = true;
12027330f729Sjoerg
12037330f729Sjoerg R.resolveKind();
12047330f729Sjoerg
12057330f729Sjoerg return Found;
12067330f729Sjoerg }
12077330f729Sjoerg
isNamespaceOrTranslationUnitScope(Scope * S)12087330f729Sjoerg static bool isNamespaceOrTranslationUnitScope(Scope *S) {
12097330f729Sjoerg if (DeclContext *Ctx = S->getEntity())
12107330f729Sjoerg return Ctx->isFileContext();
12117330f729Sjoerg return false;
12127330f729Sjoerg }
12137330f729Sjoerg
1214*e038c9c4Sjoerg /// Find the outer declaration context from this scope. This indicates the
1215*e038c9c4Sjoerg /// context that we should search up to (exclusive) before considering the
1216*e038c9c4Sjoerg /// parent of the specified scope.
findOuterContext(Scope * S)1217*e038c9c4Sjoerg static DeclContext *findOuterContext(Scope *S) {
1218*e038c9c4Sjoerg for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1219*e038c9c4Sjoerg if (DeclContext *DC = OuterS->getLookupEntity())
1220*e038c9c4Sjoerg return DC;
1221*e038c9c4Sjoerg return nullptr;
12227330f729Sjoerg }
12237330f729Sjoerg
12247330f729Sjoerg namespace {
12257330f729Sjoerg /// An RAII object to specify that we want to find block scope extern
12267330f729Sjoerg /// declarations.
12277330f729Sjoerg struct FindLocalExternScope {
FindLocalExternScope__anon8d9d45fa0211::FindLocalExternScope12287330f729Sjoerg FindLocalExternScope(LookupResult &R)
12297330f729Sjoerg : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
12307330f729Sjoerg Decl::IDNS_LocalExtern) {
12317330f729Sjoerg R.setFindLocalExtern(R.getIdentifierNamespace() &
12327330f729Sjoerg (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
12337330f729Sjoerg }
restore__anon8d9d45fa0211::FindLocalExternScope12347330f729Sjoerg void restore() {
12357330f729Sjoerg R.setFindLocalExtern(OldFindLocalExtern);
12367330f729Sjoerg }
~FindLocalExternScope__anon8d9d45fa0211::FindLocalExternScope12377330f729Sjoerg ~FindLocalExternScope() {
12387330f729Sjoerg restore();
12397330f729Sjoerg }
12407330f729Sjoerg LookupResult &R;
12417330f729Sjoerg bool OldFindLocalExtern;
12427330f729Sjoerg };
12437330f729Sjoerg } // end anonymous namespace
12447330f729Sjoerg
CppLookupName(LookupResult & R,Scope * S)12457330f729Sjoerg bool Sema::CppLookupName(LookupResult &R, Scope *S) {
12467330f729Sjoerg assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
12477330f729Sjoerg
12487330f729Sjoerg DeclarationName Name = R.getLookupName();
12497330f729Sjoerg Sema::LookupNameKind NameKind = R.getLookupKind();
12507330f729Sjoerg
12517330f729Sjoerg // If this is the name of an implicitly-declared special member function,
12527330f729Sjoerg // go through the scope stack to implicitly declare
12537330f729Sjoerg if (isImplicitlyDeclaredMemberFunctionName(Name)) {
12547330f729Sjoerg for (Scope *PreS = S; PreS; PreS = PreS->getParent())
12557330f729Sjoerg if (DeclContext *DC = PreS->getEntity())
12567330f729Sjoerg DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
12577330f729Sjoerg }
12587330f729Sjoerg
12597330f729Sjoerg // Implicitly declare member functions with the name we're looking for, if in
12607330f729Sjoerg // fact we are in a scope where it matters.
12617330f729Sjoerg
12627330f729Sjoerg Scope *Initial = S;
12637330f729Sjoerg IdentifierResolver::iterator
12647330f729Sjoerg I = IdResolver.begin(Name),
12657330f729Sjoerg IEnd = IdResolver.end();
12667330f729Sjoerg
12677330f729Sjoerg // First we lookup local scope.
12687330f729Sjoerg // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
12697330f729Sjoerg // ...During unqualified name lookup (3.4.1), the names appear as if
12707330f729Sjoerg // they were declared in the nearest enclosing namespace which contains
12717330f729Sjoerg // both the using-directive and the nominated namespace.
12727330f729Sjoerg // [Note: in this context, "contains" means "contains directly or
12737330f729Sjoerg // indirectly".
12747330f729Sjoerg //
12757330f729Sjoerg // For example:
12767330f729Sjoerg // namespace A { int i; }
12777330f729Sjoerg // void foo() {
12787330f729Sjoerg // int i;
12797330f729Sjoerg // {
12807330f729Sjoerg // using namespace A;
12817330f729Sjoerg // ++i; // finds local 'i', A::i appears at global scope
12827330f729Sjoerg // }
12837330f729Sjoerg // }
12847330f729Sjoerg //
12857330f729Sjoerg UnqualUsingDirectiveSet UDirs(*this);
12867330f729Sjoerg bool VisitedUsingDirectives = false;
12877330f729Sjoerg bool LeftStartingScope = false;
12887330f729Sjoerg
12897330f729Sjoerg // When performing a scope lookup, we want to find local extern decls.
12907330f729Sjoerg FindLocalExternScope FindLocals(R);
12917330f729Sjoerg
12927330f729Sjoerg for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
12937330f729Sjoerg bool SearchNamespaceScope = true;
12947330f729Sjoerg // Check whether the IdResolver has anything in this scope.
12957330f729Sjoerg for (; I != IEnd && S->isDeclScope(*I); ++I) {
12967330f729Sjoerg if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
12977330f729Sjoerg if (NameKind == LookupRedeclarationWithLinkage &&
12987330f729Sjoerg !(*I)->isTemplateParameter()) {
12997330f729Sjoerg // If it's a template parameter, we still find it, so we can diagnose
13007330f729Sjoerg // the invalid redeclaration.
13017330f729Sjoerg
13027330f729Sjoerg // Determine whether this (or a previous) declaration is
13037330f729Sjoerg // out-of-scope.
13047330f729Sjoerg if (!LeftStartingScope && !Initial->isDeclScope(*I))
13057330f729Sjoerg LeftStartingScope = true;
13067330f729Sjoerg
13077330f729Sjoerg // If we found something outside of our starting scope that
13087330f729Sjoerg // does not have linkage, skip it.
13097330f729Sjoerg if (LeftStartingScope && !((*I)->hasLinkage())) {
13107330f729Sjoerg R.setShadowed();
13117330f729Sjoerg continue;
13127330f729Sjoerg }
13137330f729Sjoerg } else {
13147330f729Sjoerg // We found something in this scope, we should not look at the
13157330f729Sjoerg // namespace scope
13167330f729Sjoerg SearchNamespaceScope = false;
13177330f729Sjoerg }
13187330f729Sjoerg R.addDecl(ND);
13197330f729Sjoerg }
13207330f729Sjoerg }
13217330f729Sjoerg if (!SearchNamespaceScope) {
13227330f729Sjoerg R.resolveKind();
13237330f729Sjoerg if (S->isClassScope())
1324*e038c9c4Sjoerg if (CXXRecordDecl *Record =
1325*e038c9c4Sjoerg dyn_cast_or_null<CXXRecordDecl>(S->getEntity()))
13267330f729Sjoerg R.setNamingClass(Record);
13277330f729Sjoerg return true;
13287330f729Sjoerg }
13297330f729Sjoerg
13307330f729Sjoerg if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
13317330f729Sjoerg // C++11 [class.friend]p11:
13327330f729Sjoerg // If a friend declaration appears in a local class and the name
13337330f729Sjoerg // specified is an unqualified name, a prior declaration is
13347330f729Sjoerg // looked up without considering scopes that are outside the
13357330f729Sjoerg // innermost enclosing non-class scope.
13367330f729Sjoerg return false;
13377330f729Sjoerg }
13387330f729Sjoerg
1339*e038c9c4Sjoerg if (DeclContext *Ctx = S->getLookupEntity()) {
1340*e038c9c4Sjoerg DeclContext *OuterCtx = findOuterContext(S);
13417330f729Sjoerg for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
13427330f729Sjoerg // We do not directly look into transparent contexts, since
13437330f729Sjoerg // those entities will be found in the nearest enclosing
13447330f729Sjoerg // non-transparent context.
13457330f729Sjoerg if (Ctx->isTransparentContext())
13467330f729Sjoerg continue;
13477330f729Sjoerg
13487330f729Sjoerg // We do not look directly into function or method contexts,
13497330f729Sjoerg // since all of the local variables and parameters of the
13507330f729Sjoerg // function/method are present within the Scope.
13517330f729Sjoerg if (Ctx->isFunctionOrMethod()) {
13527330f729Sjoerg // If we have an Objective-C instance method, look for ivars
13537330f729Sjoerg // in the corresponding interface.
13547330f729Sjoerg if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
13557330f729Sjoerg if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
13567330f729Sjoerg if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
13577330f729Sjoerg ObjCInterfaceDecl *ClassDeclared;
13587330f729Sjoerg if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
13597330f729Sjoerg Name.getAsIdentifierInfo(),
13607330f729Sjoerg ClassDeclared)) {
13617330f729Sjoerg if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
13627330f729Sjoerg R.addDecl(ND);
13637330f729Sjoerg R.resolveKind();
13647330f729Sjoerg return true;
13657330f729Sjoerg }
13667330f729Sjoerg }
13677330f729Sjoerg }
13687330f729Sjoerg }
13697330f729Sjoerg
13707330f729Sjoerg continue;
13717330f729Sjoerg }
13727330f729Sjoerg
13737330f729Sjoerg // If this is a file context, we need to perform unqualified name
13747330f729Sjoerg // lookup considering using directives.
13757330f729Sjoerg if (Ctx->isFileContext()) {
13767330f729Sjoerg // If we haven't handled using directives yet, do so now.
13777330f729Sjoerg if (!VisitedUsingDirectives) {
13787330f729Sjoerg // Add using directives from this context up to the top level.
13797330f729Sjoerg for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
13807330f729Sjoerg if (UCtx->isTransparentContext())
13817330f729Sjoerg continue;
13827330f729Sjoerg
13837330f729Sjoerg UDirs.visit(UCtx, UCtx);
13847330f729Sjoerg }
13857330f729Sjoerg
13867330f729Sjoerg // Find the innermost file scope, so we can add using directives
13877330f729Sjoerg // from local scopes.
13887330f729Sjoerg Scope *InnermostFileScope = S;
13897330f729Sjoerg while (InnermostFileScope &&
13907330f729Sjoerg !isNamespaceOrTranslationUnitScope(InnermostFileScope))
13917330f729Sjoerg InnermostFileScope = InnermostFileScope->getParent();
13927330f729Sjoerg UDirs.visitScopeChain(Initial, InnermostFileScope);
13937330f729Sjoerg
13947330f729Sjoerg UDirs.done();
13957330f729Sjoerg
13967330f729Sjoerg VisitedUsingDirectives = true;
13977330f729Sjoerg }
13987330f729Sjoerg
13997330f729Sjoerg if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
14007330f729Sjoerg R.resolveKind();
14017330f729Sjoerg return true;
14027330f729Sjoerg }
14037330f729Sjoerg
14047330f729Sjoerg continue;
14057330f729Sjoerg }
14067330f729Sjoerg
14077330f729Sjoerg // Perform qualified name lookup into this context.
14087330f729Sjoerg // FIXME: In some cases, we know that every name that could be found by
14097330f729Sjoerg // this qualified name lookup will also be on the identifier chain. For
14107330f729Sjoerg // example, inside a class without any base classes, we never need to
14117330f729Sjoerg // perform qualified lookup because all of the members are on top of the
14127330f729Sjoerg // identifier chain.
14137330f729Sjoerg if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
14147330f729Sjoerg return true;
14157330f729Sjoerg }
14167330f729Sjoerg }
14177330f729Sjoerg }
14187330f729Sjoerg
14197330f729Sjoerg // Stop if we ran out of scopes.
14207330f729Sjoerg // FIXME: This really, really shouldn't be happening.
14217330f729Sjoerg if (!S) return false;
14227330f729Sjoerg
14237330f729Sjoerg // If we are looking for members, no need to look into global/namespace scope.
14247330f729Sjoerg if (NameKind == LookupMemberName)
14257330f729Sjoerg return false;
14267330f729Sjoerg
14277330f729Sjoerg // Collect UsingDirectiveDecls in all scopes, and recursively all
14287330f729Sjoerg // nominated namespaces by those using-directives.
14297330f729Sjoerg //
14307330f729Sjoerg // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
14317330f729Sjoerg // don't build it for each lookup!
14327330f729Sjoerg if (!VisitedUsingDirectives) {
14337330f729Sjoerg UDirs.visitScopeChain(Initial, S);
14347330f729Sjoerg UDirs.done();
14357330f729Sjoerg }
14367330f729Sjoerg
14377330f729Sjoerg // If we're not performing redeclaration lookup, do not look for local
14387330f729Sjoerg // extern declarations outside of a function scope.
14397330f729Sjoerg if (!R.isForRedeclaration())
14407330f729Sjoerg FindLocals.restore();
14417330f729Sjoerg
14427330f729Sjoerg // Lookup namespace scope, and global scope.
14437330f729Sjoerg // Unqualified name lookup in C++ requires looking into scopes
14447330f729Sjoerg // that aren't strictly lexical, and therefore we walk through the
14457330f729Sjoerg // context as well as walking through the scopes.
14467330f729Sjoerg for (; S; S = S->getParent()) {
14477330f729Sjoerg // Check whether the IdResolver has anything in this scope.
14487330f729Sjoerg bool Found = false;
14497330f729Sjoerg for (; I != IEnd && S->isDeclScope(*I); ++I) {
14507330f729Sjoerg if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
14517330f729Sjoerg // We found something. Look for anything else in our scope
14527330f729Sjoerg // with this same name and in an acceptable identifier
14537330f729Sjoerg // namespace, so that we can construct an overload set if we
14547330f729Sjoerg // need to.
14557330f729Sjoerg Found = true;
14567330f729Sjoerg R.addDecl(ND);
14577330f729Sjoerg }
14587330f729Sjoerg }
14597330f729Sjoerg
14607330f729Sjoerg if (Found && S->isTemplateParamScope()) {
14617330f729Sjoerg R.resolveKind();
14627330f729Sjoerg return true;
14637330f729Sjoerg }
14647330f729Sjoerg
1465*e038c9c4Sjoerg DeclContext *Ctx = S->getLookupEntity();
14667330f729Sjoerg if (Ctx) {
1467*e038c9c4Sjoerg DeclContext *OuterCtx = findOuterContext(S);
14687330f729Sjoerg for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
14697330f729Sjoerg // We do not directly look into transparent contexts, since
14707330f729Sjoerg // those entities will be found in the nearest enclosing
14717330f729Sjoerg // non-transparent context.
14727330f729Sjoerg if (Ctx->isTransparentContext())
14737330f729Sjoerg continue;
14747330f729Sjoerg
14757330f729Sjoerg // If we have a context, and it's not a context stashed in the
14767330f729Sjoerg // template parameter scope for an out-of-line definition, also
14777330f729Sjoerg // look into that context.
14787330f729Sjoerg if (!(Found && S->isTemplateParamScope())) {
14797330f729Sjoerg assert(Ctx->isFileContext() &&
14807330f729Sjoerg "We should have been looking only at file context here already.");
14817330f729Sjoerg
14827330f729Sjoerg // Look into context considering using-directives.
14837330f729Sjoerg if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
14847330f729Sjoerg Found = true;
14857330f729Sjoerg }
14867330f729Sjoerg
14877330f729Sjoerg if (Found) {
14887330f729Sjoerg R.resolveKind();
14897330f729Sjoerg return true;
14907330f729Sjoerg }
14917330f729Sjoerg
14927330f729Sjoerg if (R.isForRedeclaration() && !Ctx->isTransparentContext())
14937330f729Sjoerg return false;
14947330f729Sjoerg }
14957330f729Sjoerg }
14967330f729Sjoerg
14977330f729Sjoerg if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
14987330f729Sjoerg return false;
14997330f729Sjoerg }
15007330f729Sjoerg
15017330f729Sjoerg return !R.empty();
15027330f729Sjoerg }
15037330f729Sjoerg
makeMergedDefinitionVisible(NamedDecl * ND)15047330f729Sjoerg void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
15057330f729Sjoerg if (auto *M = getCurrentModule())
15067330f729Sjoerg Context.mergeDefinitionIntoModule(ND, M);
15077330f729Sjoerg else
15087330f729Sjoerg // We're not building a module; just make the definition visible.
15097330f729Sjoerg ND->setVisibleDespiteOwningModule();
15107330f729Sjoerg
15117330f729Sjoerg // If ND is a template declaration, make the template parameters
15127330f729Sjoerg // visible too. They're not (necessarily) within a mergeable DeclContext.
15137330f729Sjoerg if (auto *TD = dyn_cast<TemplateDecl>(ND))
15147330f729Sjoerg for (auto *Param : *TD->getTemplateParameters())
15157330f729Sjoerg makeMergedDefinitionVisible(Param);
15167330f729Sjoerg }
15177330f729Sjoerg
15187330f729Sjoerg /// Find the module in which the given declaration was defined.
getDefiningModule(Sema & S,Decl * Entity)15197330f729Sjoerg static Module *getDefiningModule(Sema &S, Decl *Entity) {
15207330f729Sjoerg if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
15217330f729Sjoerg // If this function was instantiated from a template, the defining module is
15227330f729Sjoerg // the module containing the pattern.
15237330f729Sjoerg if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
15247330f729Sjoerg Entity = Pattern;
15257330f729Sjoerg } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
15267330f729Sjoerg if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
15277330f729Sjoerg Entity = Pattern;
15287330f729Sjoerg } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
15297330f729Sjoerg if (auto *Pattern = ED->getTemplateInstantiationPattern())
15307330f729Sjoerg Entity = Pattern;
15317330f729Sjoerg } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
15327330f729Sjoerg if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
15337330f729Sjoerg Entity = Pattern;
15347330f729Sjoerg }
15357330f729Sjoerg
15367330f729Sjoerg // Walk up to the containing context. That might also have been instantiated
15377330f729Sjoerg // from a template.
15387330f729Sjoerg DeclContext *Context = Entity->getLexicalDeclContext();
15397330f729Sjoerg if (Context->isFileContext())
15407330f729Sjoerg return S.getOwningModule(Entity);
15417330f729Sjoerg return getDefiningModule(S, cast<Decl>(Context));
15427330f729Sjoerg }
15437330f729Sjoerg
getLookupModules()15447330f729Sjoerg llvm::DenseSet<Module*> &Sema::getLookupModules() {
15457330f729Sjoerg unsigned N = CodeSynthesisContexts.size();
15467330f729Sjoerg for (unsigned I = CodeSynthesisContextLookupModules.size();
15477330f729Sjoerg I != N; ++I) {
1548*e038c9c4Sjoerg Module *M = CodeSynthesisContexts[I].Entity ?
1549*e038c9c4Sjoerg getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1550*e038c9c4Sjoerg nullptr;
15517330f729Sjoerg if (M && !LookupModulesCache.insert(M).second)
15527330f729Sjoerg M = nullptr;
15537330f729Sjoerg CodeSynthesisContextLookupModules.push_back(M);
15547330f729Sjoerg }
15557330f729Sjoerg return LookupModulesCache;
15567330f729Sjoerg }
15577330f729Sjoerg
15587330f729Sjoerg /// Determine whether the module M is part of the current module from the
15597330f729Sjoerg /// perspective of a module-private visibility check.
isInCurrentModule(const Module * M,const LangOptions & LangOpts)15607330f729Sjoerg static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
15617330f729Sjoerg // If M is the global module fragment of a module that we've not yet finished
15627330f729Sjoerg // parsing, then it must be part of the current module.
15637330f729Sjoerg return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
15647330f729Sjoerg (M->Kind == Module::GlobalModuleFragment && !M->Parent);
15657330f729Sjoerg }
15667330f729Sjoerg
hasVisibleMergedDefinition(NamedDecl * Def)15677330f729Sjoerg bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
15687330f729Sjoerg for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
15697330f729Sjoerg if (isModuleVisible(Merged))
15707330f729Sjoerg return true;
15717330f729Sjoerg return false;
15727330f729Sjoerg }
15737330f729Sjoerg
hasMergedDefinitionInCurrentModule(NamedDecl * Def)15747330f729Sjoerg bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
15757330f729Sjoerg for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
15767330f729Sjoerg if (isInCurrentModule(Merged, getLangOpts()))
15777330f729Sjoerg return true;
15787330f729Sjoerg return false;
15797330f729Sjoerg }
15807330f729Sjoerg
15817330f729Sjoerg template<typename ParmDecl>
15827330f729Sjoerg static bool
hasVisibleDefaultArgument(Sema & S,const ParmDecl * D,llvm::SmallVectorImpl<Module * > * Modules)15837330f729Sjoerg hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
15847330f729Sjoerg llvm::SmallVectorImpl<Module *> *Modules) {
15857330f729Sjoerg if (!D->hasDefaultArgument())
15867330f729Sjoerg return false;
15877330f729Sjoerg
15887330f729Sjoerg while (D) {
15897330f729Sjoerg auto &DefaultArg = D->getDefaultArgStorage();
15907330f729Sjoerg if (!DefaultArg.isInherited() && S.isVisible(D))
15917330f729Sjoerg return true;
15927330f729Sjoerg
15937330f729Sjoerg if (!DefaultArg.isInherited() && Modules) {
15947330f729Sjoerg auto *NonConstD = const_cast<ParmDecl*>(D);
15957330f729Sjoerg Modules->push_back(S.getOwningModule(NonConstD));
15967330f729Sjoerg }
15977330f729Sjoerg
15987330f729Sjoerg // If there was a previous default argument, maybe its parameter is visible.
15997330f729Sjoerg D = DefaultArg.getInheritedFrom();
16007330f729Sjoerg }
16017330f729Sjoerg return false;
16027330f729Sjoerg }
16037330f729Sjoerg
hasVisibleDefaultArgument(const NamedDecl * D,llvm::SmallVectorImpl<Module * > * Modules)16047330f729Sjoerg bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
16057330f729Sjoerg llvm::SmallVectorImpl<Module *> *Modules) {
16067330f729Sjoerg if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
16077330f729Sjoerg return ::hasVisibleDefaultArgument(*this, P, Modules);
16087330f729Sjoerg if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
16097330f729Sjoerg return ::hasVisibleDefaultArgument(*this, P, Modules);
16107330f729Sjoerg return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
16117330f729Sjoerg Modules);
16127330f729Sjoerg }
16137330f729Sjoerg
16147330f729Sjoerg template<typename Filter>
hasVisibleDeclarationImpl(Sema & S,const NamedDecl * D,llvm::SmallVectorImpl<Module * > * Modules,Filter F)16157330f729Sjoerg static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
16167330f729Sjoerg llvm::SmallVectorImpl<Module *> *Modules,
16177330f729Sjoerg Filter F) {
16187330f729Sjoerg bool HasFilteredRedecls = false;
16197330f729Sjoerg
16207330f729Sjoerg for (auto *Redecl : D->redecls()) {
16217330f729Sjoerg auto *R = cast<NamedDecl>(Redecl);
16227330f729Sjoerg if (!F(R))
16237330f729Sjoerg continue;
16247330f729Sjoerg
16257330f729Sjoerg if (S.isVisible(R))
16267330f729Sjoerg return true;
16277330f729Sjoerg
16287330f729Sjoerg HasFilteredRedecls = true;
16297330f729Sjoerg
16307330f729Sjoerg if (Modules)
16317330f729Sjoerg Modules->push_back(R->getOwningModule());
16327330f729Sjoerg }
16337330f729Sjoerg
16347330f729Sjoerg // Only return false if there is at least one redecl that is not filtered out.
16357330f729Sjoerg if (HasFilteredRedecls)
16367330f729Sjoerg return false;
16377330f729Sjoerg
16387330f729Sjoerg return true;
16397330f729Sjoerg }
16407330f729Sjoerg
hasVisibleExplicitSpecialization(const NamedDecl * D,llvm::SmallVectorImpl<Module * > * Modules)16417330f729Sjoerg bool Sema::hasVisibleExplicitSpecialization(
16427330f729Sjoerg const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
16437330f729Sjoerg return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
16447330f729Sjoerg if (auto *RD = dyn_cast<CXXRecordDecl>(D))
16457330f729Sjoerg return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
16467330f729Sjoerg if (auto *FD = dyn_cast<FunctionDecl>(D))
16477330f729Sjoerg return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
16487330f729Sjoerg if (auto *VD = dyn_cast<VarDecl>(D))
16497330f729Sjoerg return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
16507330f729Sjoerg llvm_unreachable("unknown explicit specialization kind");
16517330f729Sjoerg });
16527330f729Sjoerg }
16537330f729Sjoerg
hasVisibleMemberSpecialization(const NamedDecl * D,llvm::SmallVectorImpl<Module * > * Modules)16547330f729Sjoerg bool Sema::hasVisibleMemberSpecialization(
16557330f729Sjoerg const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
16567330f729Sjoerg assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
16577330f729Sjoerg "not a member specialization");
16587330f729Sjoerg return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
16597330f729Sjoerg // If the specialization is declared at namespace scope, then it's a member
16607330f729Sjoerg // specialization declaration. If it's lexically inside the class
16617330f729Sjoerg // definition then it was instantiated.
16627330f729Sjoerg //
16637330f729Sjoerg // FIXME: This is a hack. There should be a better way to determine this.
16647330f729Sjoerg // FIXME: What about MS-style explicit specializations declared within a
16657330f729Sjoerg // class definition?
16667330f729Sjoerg return D->getLexicalDeclContext()->isFileContext();
16677330f729Sjoerg });
16687330f729Sjoerg }
16697330f729Sjoerg
16707330f729Sjoerg /// Determine whether a declaration is visible to name lookup.
16717330f729Sjoerg ///
16727330f729Sjoerg /// This routine determines whether the declaration D is visible in the current
16737330f729Sjoerg /// lookup context, taking into account the current template instantiation
16747330f729Sjoerg /// stack. During template instantiation, a declaration is visible if it is
16757330f729Sjoerg /// visible from a module containing any entity on the template instantiation
16767330f729Sjoerg /// path (by instantiating a template, you allow it to see the declarations that
16777330f729Sjoerg /// your module can see, including those later on in your module).
isVisibleSlow(Sema & SemaRef,NamedDecl * D)16787330f729Sjoerg bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1679*e038c9c4Sjoerg assert(!D->isUnconditionallyVisible() &&
1680*e038c9c4Sjoerg "should not call this: not in slow case");
16817330f729Sjoerg
16827330f729Sjoerg Module *DeclModule = SemaRef.getOwningModule(D);
16837330f729Sjoerg assert(DeclModule && "hidden decl has no owning module");
16847330f729Sjoerg
16857330f729Sjoerg // If the owning module is visible, the decl is visible.
16867330f729Sjoerg if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
16877330f729Sjoerg return true;
16887330f729Sjoerg
16897330f729Sjoerg // Determine whether a decl context is a file context for the purpose of
16907330f729Sjoerg // visibility. This looks through some (export and linkage spec) transparent
16917330f729Sjoerg // contexts, but not others (enums).
16927330f729Sjoerg auto IsEffectivelyFileContext = [](const DeclContext *DC) {
16937330f729Sjoerg return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
16947330f729Sjoerg isa<ExportDecl>(DC);
16957330f729Sjoerg };
16967330f729Sjoerg
16977330f729Sjoerg // If this declaration is not at namespace scope
16987330f729Sjoerg // then it is visible if its lexical parent has a visible definition.
16997330f729Sjoerg DeclContext *DC = D->getLexicalDeclContext();
17007330f729Sjoerg if (DC && !IsEffectivelyFileContext(DC)) {
17017330f729Sjoerg // For a parameter, check whether our current template declaration's
17027330f729Sjoerg // lexical context is visible, not whether there's some other visible
17037330f729Sjoerg // definition of it, because parameters aren't "within" the definition.
17047330f729Sjoerg //
17057330f729Sjoerg // In C++ we need to check for a visible definition due to ODR merging,
17067330f729Sjoerg // and in C we must not because each declaration of a function gets its own
17077330f729Sjoerg // set of declarations for tags in prototype scope.
17087330f729Sjoerg bool VisibleWithinParent;
17097330f729Sjoerg if (D->isTemplateParameter()) {
17107330f729Sjoerg bool SearchDefinitions = true;
17117330f729Sjoerg if (const auto *DCD = dyn_cast<Decl>(DC)) {
17127330f729Sjoerg if (const auto *TD = DCD->getDescribedTemplate()) {
17137330f729Sjoerg TemplateParameterList *TPL = TD->getTemplateParameters();
17147330f729Sjoerg auto Index = getDepthAndIndex(D).second;
17157330f729Sjoerg SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
17167330f729Sjoerg }
17177330f729Sjoerg }
17187330f729Sjoerg if (SearchDefinitions)
17197330f729Sjoerg VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
17207330f729Sjoerg else
17217330f729Sjoerg VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
17227330f729Sjoerg } else if (isa<ParmVarDecl>(D) ||
17237330f729Sjoerg (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
17247330f729Sjoerg VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
17257330f729Sjoerg else if (D->isModulePrivate()) {
17267330f729Sjoerg // A module-private declaration is only visible if an enclosing lexical
17277330f729Sjoerg // parent was merged with another definition in the current module.
17287330f729Sjoerg VisibleWithinParent = false;
17297330f729Sjoerg do {
17307330f729Sjoerg if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
17317330f729Sjoerg VisibleWithinParent = true;
17327330f729Sjoerg break;
17337330f729Sjoerg }
17347330f729Sjoerg DC = DC->getLexicalParent();
17357330f729Sjoerg } while (!IsEffectivelyFileContext(DC));
17367330f729Sjoerg } else {
17377330f729Sjoerg VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
17387330f729Sjoerg }
17397330f729Sjoerg
17407330f729Sjoerg if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
17417330f729Sjoerg // FIXME: Do something better in this case.
17427330f729Sjoerg !SemaRef.getLangOpts().ModulesLocalVisibility) {
17437330f729Sjoerg // Cache the fact that this declaration is implicitly visible because
17447330f729Sjoerg // its parent has a visible definition.
17457330f729Sjoerg D->setVisibleDespiteOwningModule();
17467330f729Sjoerg }
17477330f729Sjoerg return VisibleWithinParent;
17487330f729Sjoerg }
17497330f729Sjoerg
17507330f729Sjoerg return false;
17517330f729Sjoerg }
17527330f729Sjoerg
isModuleVisible(const Module * M,bool ModulePrivate)17537330f729Sjoerg bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
17547330f729Sjoerg // The module might be ordinarily visible. For a module-private query, that
17557330f729Sjoerg // means it is part of the current module. For any other query, that means it
17567330f729Sjoerg // is in our visible module set.
17577330f729Sjoerg if (ModulePrivate) {
17587330f729Sjoerg if (isInCurrentModule(M, getLangOpts()))
17597330f729Sjoerg return true;
17607330f729Sjoerg } else {
17617330f729Sjoerg if (VisibleModules.isVisible(M))
17627330f729Sjoerg return true;
17637330f729Sjoerg }
17647330f729Sjoerg
17657330f729Sjoerg // Otherwise, it might be visible by virtue of the query being within a
17667330f729Sjoerg // template instantiation or similar that is permitted to look inside M.
17677330f729Sjoerg
17687330f729Sjoerg // Find the extra places where we need to look.
17697330f729Sjoerg const auto &LookupModules = getLookupModules();
17707330f729Sjoerg if (LookupModules.empty())
17717330f729Sjoerg return false;
17727330f729Sjoerg
17737330f729Sjoerg // If our lookup set contains the module, it's visible.
17747330f729Sjoerg if (LookupModules.count(M))
17757330f729Sjoerg return true;
17767330f729Sjoerg
17777330f729Sjoerg // For a module-private query, that's everywhere we get to look.
17787330f729Sjoerg if (ModulePrivate)
17797330f729Sjoerg return false;
17807330f729Sjoerg
17817330f729Sjoerg // Check whether M is transitively exported to an import of the lookup set.
17827330f729Sjoerg return llvm::any_of(LookupModules, [&](const Module *LookupM) {
17837330f729Sjoerg return LookupM->isModuleVisible(M);
17847330f729Sjoerg });
17857330f729Sjoerg }
17867330f729Sjoerg
isVisibleSlow(const NamedDecl * D)17877330f729Sjoerg bool Sema::isVisibleSlow(const NamedDecl *D) {
17887330f729Sjoerg return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
17897330f729Sjoerg }
17907330f729Sjoerg
shouldLinkPossiblyHiddenDecl(LookupResult & R,const NamedDecl * New)17917330f729Sjoerg bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
17927330f729Sjoerg // FIXME: If there are both visible and hidden declarations, we need to take
17937330f729Sjoerg // into account whether redeclaration is possible. Example:
17947330f729Sjoerg //
17957330f729Sjoerg // Non-imported module:
17967330f729Sjoerg // int f(T); // #1
17977330f729Sjoerg // Some TU:
17987330f729Sjoerg // static int f(U); // #2, not a redeclaration of #1
17997330f729Sjoerg // int f(T); // #3, finds both, should link with #1 if T != U, but
18007330f729Sjoerg // // with #2 if T == U; neither should be ambiguous.
18017330f729Sjoerg for (auto *D : R) {
18027330f729Sjoerg if (isVisible(D))
18037330f729Sjoerg return true;
18047330f729Sjoerg assert(D->isExternallyDeclarable() &&
18057330f729Sjoerg "should not have hidden, non-externally-declarable result here");
18067330f729Sjoerg }
18077330f729Sjoerg
18087330f729Sjoerg // This function is called once "New" is essentially complete, but before a
18097330f729Sjoerg // previous declaration is attached. We can't query the linkage of "New" in
18107330f729Sjoerg // general, because attaching the previous declaration can change the
18117330f729Sjoerg // linkage of New to match the previous declaration.
18127330f729Sjoerg //
18137330f729Sjoerg // However, because we've just determined that there is no *visible* prior
18147330f729Sjoerg // declaration, we can compute the linkage here. There are two possibilities:
18157330f729Sjoerg //
18167330f729Sjoerg // * This is not a redeclaration; it's safe to compute the linkage now.
18177330f729Sjoerg //
18187330f729Sjoerg // * This is a redeclaration of a prior declaration that is externally
18197330f729Sjoerg // redeclarable. In that case, the linkage of the declaration is not
18207330f729Sjoerg // changed by attaching the prior declaration, because both are externally
18217330f729Sjoerg // declarable (and thus ExternalLinkage or VisibleNoLinkage).
18227330f729Sjoerg //
18237330f729Sjoerg // FIXME: This is subtle and fragile.
18247330f729Sjoerg return New->isExternallyDeclarable();
18257330f729Sjoerg }
18267330f729Sjoerg
18277330f729Sjoerg /// Retrieve the visible declaration corresponding to D, if any.
18287330f729Sjoerg ///
18297330f729Sjoerg /// This routine determines whether the declaration D is visible in the current
18307330f729Sjoerg /// module, with the current imports. If not, it checks whether any
18317330f729Sjoerg /// redeclaration of D is visible, and if so, returns that declaration.
18327330f729Sjoerg ///
18337330f729Sjoerg /// \returns D, or a visible previous declaration of D, whichever is more recent
18347330f729Sjoerg /// and visible. If no declaration of D is visible, returns null.
findAcceptableDecl(Sema & SemaRef,NamedDecl * D,unsigned IDNS)18357330f729Sjoerg static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
18367330f729Sjoerg unsigned IDNS) {
18377330f729Sjoerg assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
18387330f729Sjoerg
18397330f729Sjoerg for (auto RD : D->redecls()) {
18407330f729Sjoerg // Don't bother with extra checks if we already know this one isn't visible.
18417330f729Sjoerg if (RD == D)
18427330f729Sjoerg continue;
18437330f729Sjoerg
18447330f729Sjoerg auto ND = cast<NamedDecl>(RD);
18457330f729Sjoerg // FIXME: This is wrong in the case where the previous declaration is not
18467330f729Sjoerg // visible in the same scope as D. This needs to be done much more
18477330f729Sjoerg // carefully.
18487330f729Sjoerg if (ND->isInIdentifierNamespace(IDNS) &&
18497330f729Sjoerg LookupResult::isVisible(SemaRef, ND))
18507330f729Sjoerg return ND;
18517330f729Sjoerg }
18527330f729Sjoerg
18537330f729Sjoerg return nullptr;
18547330f729Sjoerg }
18557330f729Sjoerg
hasVisibleDeclarationSlow(const NamedDecl * D,llvm::SmallVectorImpl<Module * > * Modules)18567330f729Sjoerg bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
18577330f729Sjoerg llvm::SmallVectorImpl<Module *> *Modules) {
18587330f729Sjoerg assert(!isVisible(D) && "not in slow case");
18597330f729Sjoerg return hasVisibleDeclarationImpl(*this, D, Modules,
18607330f729Sjoerg [](const NamedDecl *) { return true; });
18617330f729Sjoerg }
18627330f729Sjoerg
getAcceptableDeclSlow(NamedDecl * D) const18637330f729Sjoerg NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
18647330f729Sjoerg if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
18657330f729Sjoerg // Namespaces are a bit of a special case: we expect there to be a lot of
18667330f729Sjoerg // redeclarations of some namespaces, all declarations of a namespace are
18677330f729Sjoerg // essentially interchangeable, all declarations are found by name lookup
18687330f729Sjoerg // if any is, and namespaces are never looked up during template
18697330f729Sjoerg // instantiation. So we benefit from caching the check in this case, and
18707330f729Sjoerg // it is correct to do so.
18717330f729Sjoerg auto *Key = ND->getCanonicalDecl();
18727330f729Sjoerg if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
18737330f729Sjoerg return Acceptable;
18747330f729Sjoerg auto *Acceptable = isVisible(getSema(), Key)
18757330f729Sjoerg ? Key
18767330f729Sjoerg : findAcceptableDecl(getSema(), Key, IDNS);
18777330f729Sjoerg if (Acceptable)
18787330f729Sjoerg getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
18797330f729Sjoerg return Acceptable;
18807330f729Sjoerg }
18817330f729Sjoerg
18827330f729Sjoerg return findAcceptableDecl(getSema(), D, IDNS);
18837330f729Sjoerg }
18847330f729Sjoerg
18857330f729Sjoerg /// Perform unqualified name lookup starting from a given
18867330f729Sjoerg /// scope.
18877330f729Sjoerg ///
18887330f729Sjoerg /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
18897330f729Sjoerg /// used to find names within the current scope. For example, 'x' in
18907330f729Sjoerg /// @code
18917330f729Sjoerg /// int x;
18927330f729Sjoerg /// int f() {
18937330f729Sjoerg /// return x; // unqualified name look finds 'x' in the global scope
18947330f729Sjoerg /// }
18957330f729Sjoerg /// @endcode
18967330f729Sjoerg ///
18977330f729Sjoerg /// Different lookup criteria can find different names. For example, a
18987330f729Sjoerg /// particular scope can have both a struct and a function of the same
18997330f729Sjoerg /// name, and each can be found by certain lookup criteria. For more
19007330f729Sjoerg /// information about lookup criteria, see the documentation for the
19017330f729Sjoerg /// class LookupCriteria.
19027330f729Sjoerg ///
19037330f729Sjoerg /// @param S The scope from which unqualified name lookup will
19047330f729Sjoerg /// begin. If the lookup criteria permits, name lookup may also search
19057330f729Sjoerg /// in the parent scopes.
19067330f729Sjoerg ///
19077330f729Sjoerg /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
19087330f729Sjoerg /// look up and the lookup kind), and is updated with the results of lookup
19097330f729Sjoerg /// including zero or more declarations and possibly additional information
19107330f729Sjoerg /// used to diagnose ambiguities.
19117330f729Sjoerg ///
19127330f729Sjoerg /// @returns \c true if lookup succeeded and false otherwise.
LookupName(LookupResult & R,Scope * S,bool AllowBuiltinCreation)19137330f729Sjoerg bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
19147330f729Sjoerg DeclarationName Name = R.getLookupName();
19157330f729Sjoerg if (!Name) return false;
19167330f729Sjoerg
19177330f729Sjoerg LookupNameKind NameKind = R.getLookupKind();
19187330f729Sjoerg
19197330f729Sjoerg if (!getLangOpts().CPlusPlus) {
19207330f729Sjoerg // Unqualified name lookup in C/Objective-C is purely lexical, so
19217330f729Sjoerg // search in the declarations attached to the name.
19227330f729Sjoerg if (NameKind == Sema::LookupRedeclarationWithLinkage) {
19237330f729Sjoerg // Find the nearest non-transparent declaration scope.
19247330f729Sjoerg while (!(S->getFlags() & Scope::DeclScope) ||
19257330f729Sjoerg (S->getEntity() && S->getEntity()->isTransparentContext()))
19267330f729Sjoerg S = S->getParent();
19277330f729Sjoerg }
19287330f729Sjoerg
19297330f729Sjoerg // When performing a scope lookup, we want to find local extern decls.
19307330f729Sjoerg FindLocalExternScope FindLocals(R);
19317330f729Sjoerg
19327330f729Sjoerg // Scan up the scope chain looking for a decl that matches this
19337330f729Sjoerg // identifier that is in the appropriate namespace. This search
19347330f729Sjoerg // should not take long, as shadowing of names is uncommon, and
19357330f729Sjoerg // deep shadowing is extremely uncommon.
19367330f729Sjoerg bool LeftStartingScope = false;
19377330f729Sjoerg
19387330f729Sjoerg for (IdentifierResolver::iterator I = IdResolver.begin(Name),
19397330f729Sjoerg IEnd = IdResolver.end();
19407330f729Sjoerg I != IEnd; ++I)
19417330f729Sjoerg if (NamedDecl *D = R.getAcceptableDecl(*I)) {
19427330f729Sjoerg if (NameKind == LookupRedeclarationWithLinkage) {
19437330f729Sjoerg // Determine whether this (or a previous) declaration is
19447330f729Sjoerg // out-of-scope.
19457330f729Sjoerg if (!LeftStartingScope && !S->isDeclScope(*I))
19467330f729Sjoerg LeftStartingScope = true;
19477330f729Sjoerg
19487330f729Sjoerg // If we found something outside of our starting scope that
19497330f729Sjoerg // does not have linkage, skip it.
19507330f729Sjoerg if (LeftStartingScope && !((*I)->hasLinkage())) {
19517330f729Sjoerg R.setShadowed();
19527330f729Sjoerg continue;
19537330f729Sjoerg }
19547330f729Sjoerg }
19557330f729Sjoerg else if (NameKind == LookupObjCImplicitSelfParam &&
19567330f729Sjoerg !isa<ImplicitParamDecl>(*I))
19577330f729Sjoerg continue;
19587330f729Sjoerg
19597330f729Sjoerg R.addDecl(D);
19607330f729Sjoerg
19617330f729Sjoerg // Check whether there are any other declarations with the same name
19627330f729Sjoerg // and in the same scope.
19637330f729Sjoerg if (I != IEnd) {
19647330f729Sjoerg // Find the scope in which this declaration was declared (if it
19657330f729Sjoerg // actually exists in a Scope).
19667330f729Sjoerg while (S && !S->isDeclScope(D))
19677330f729Sjoerg S = S->getParent();
19687330f729Sjoerg
19697330f729Sjoerg // If the scope containing the declaration is the translation unit,
19707330f729Sjoerg // then we'll need to perform our checks based on the matching
19717330f729Sjoerg // DeclContexts rather than matching scopes.
19727330f729Sjoerg if (S && isNamespaceOrTranslationUnitScope(S))
19737330f729Sjoerg S = nullptr;
19747330f729Sjoerg
19757330f729Sjoerg // Compute the DeclContext, if we need it.
19767330f729Sjoerg DeclContext *DC = nullptr;
19777330f729Sjoerg if (!S)
19787330f729Sjoerg DC = (*I)->getDeclContext()->getRedeclContext();
19797330f729Sjoerg
19807330f729Sjoerg IdentifierResolver::iterator LastI = I;
19817330f729Sjoerg for (++LastI; LastI != IEnd; ++LastI) {
19827330f729Sjoerg if (S) {
19837330f729Sjoerg // Match based on scope.
19847330f729Sjoerg if (!S->isDeclScope(*LastI))
19857330f729Sjoerg break;
19867330f729Sjoerg } else {
19877330f729Sjoerg // Match based on DeclContext.
19887330f729Sjoerg DeclContext *LastDC
19897330f729Sjoerg = (*LastI)->getDeclContext()->getRedeclContext();
19907330f729Sjoerg if (!LastDC->Equals(DC))
19917330f729Sjoerg break;
19927330f729Sjoerg }
19937330f729Sjoerg
19947330f729Sjoerg // If the declaration is in the right namespace and visible, add it.
19957330f729Sjoerg if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
19967330f729Sjoerg R.addDecl(LastD);
19977330f729Sjoerg }
19987330f729Sjoerg
19997330f729Sjoerg R.resolveKind();
20007330f729Sjoerg }
20017330f729Sjoerg
20027330f729Sjoerg return true;
20037330f729Sjoerg }
20047330f729Sjoerg } else {
20057330f729Sjoerg // Perform C++ unqualified name lookup.
20067330f729Sjoerg if (CppLookupName(R, S))
20077330f729Sjoerg return true;
20087330f729Sjoerg }
20097330f729Sjoerg
20107330f729Sjoerg // If we didn't find a use of this identifier, and if the identifier
20117330f729Sjoerg // corresponds to a compiler builtin, create the decl object for the builtin
20127330f729Sjoerg // now, injecting it into translation unit scope, and return it.
20137330f729Sjoerg if (AllowBuiltinCreation && LookupBuiltin(R))
20147330f729Sjoerg return true;
20157330f729Sjoerg
20167330f729Sjoerg // If we didn't find a use of this identifier, the ExternalSource
20177330f729Sjoerg // may be able to handle the situation.
20187330f729Sjoerg // Note: some lookup failures are expected!
20197330f729Sjoerg // See e.g. R.isForRedeclaration().
20207330f729Sjoerg return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
20217330f729Sjoerg }
20227330f729Sjoerg
20237330f729Sjoerg /// Perform qualified name lookup in the namespaces nominated by
20247330f729Sjoerg /// using directives by the given context.
20257330f729Sjoerg ///
20267330f729Sjoerg /// C++98 [namespace.qual]p2:
20277330f729Sjoerg /// Given X::m (where X is a user-declared namespace), or given \::m
20287330f729Sjoerg /// (where X is the global namespace), let S be the set of all
20297330f729Sjoerg /// declarations of m in X and in the transitive closure of all
20307330f729Sjoerg /// namespaces nominated by using-directives in X and its used
20317330f729Sjoerg /// namespaces, except that using-directives are ignored in any
20327330f729Sjoerg /// namespace, including X, directly containing one or more
20337330f729Sjoerg /// declarations of m. No namespace is searched more than once in
20347330f729Sjoerg /// the lookup of a name. If S is the empty set, the program is
20357330f729Sjoerg /// ill-formed. Otherwise, if S has exactly one member, or if the
20367330f729Sjoerg /// context of the reference is a using-declaration
20377330f729Sjoerg /// (namespace.udecl), S is the required set of declarations of
20387330f729Sjoerg /// m. Otherwise if the use of m is not one that allows a unique
20397330f729Sjoerg /// declaration to be chosen from S, the program is ill-formed.
20407330f729Sjoerg ///
20417330f729Sjoerg /// C++98 [namespace.qual]p5:
20427330f729Sjoerg /// During the lookup of a qualified namespace member name, if the
20437330f729Sjoerg /// lookup finds more than one declaration of the member, and if one
20447330f729Sjoerg /// declaration introduces a class name or enumeration name and the
20457330f729Sjoerg /// other declarations either introduce the same object, the same
20467330f729Sjoerg /// enumerator or a set of functions, the non-type name hides the
20477330f729Sjoerg /// class or enumeration name if and only if the declarations are
20487330f729Sjoerg /// from the same namespace; otherwise (the declarations are from
20497330f729Sjoerg /// different namespaces), the program is ill-formed.
LookupQualifiedNameInUsingDirectives(Sema & S,LookupResult & R,DeclContext * StartDC)20507330f729Sjoerg static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
20517330f729Sjoerg DeclContext *StartDC) {
20527330f729Sjoerg assert(StartDC->isFileContext() && "start context is not a file context");
20537330f729Sjoerg
20547330f729Sjoerg // We have not yet looked into these namespaces, much less added
20557330f729Sjoerg // their "using-children" to the queue.
20567330f729Sjoerg SmallVector<NamespaceDecl*, 8> Queue;
20577330f729Sjoerg
20587330f729Sjoerg // We have at least added all these contexts to the queue.
20597330f729Sjoerg llvm::SmallPtrSet<DeclContext*, 8> Visited;
20607330f729Sjoerg Visited.insert(StartDC);
20617330f729Sjoerg
20627330f729Sjoerg // We have already looked into the initial namespace; seed the queue
20637330f729Sjoerg // with its using-children.
20647330f729Sjoerg for (auto *I : StartDC->using_directives()) {
20657330f729Sjoerg NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
20667330f729Sjoerg if (S.isVisible(I) && Visited.insert(ND).second)
20677330f729Sjoerg Queue.push_back(ND);
20687330f729Sjoerg }
20697330f729Sjoerg
20707330f729Sjoerg // The easiest way to implement the restriction in [namespace.qual]p5
20717330f729Sjoerg // is to check whether any of the individual results found a tag
20727330f729Sjoerg // and, if so, to declare an ambiguity if the final result is not
20737330f729Sjoerg // a tag.
20747330f729Sjoerg bool FoundTag = false;
20757330f729Sjoerg bool FoundNonTag = false;
20767330f729Sjoerg
20777330f729Sjoerg LookupResult LocalR(LookupResult::Temporary, R);
20787330f729Sjoerg
20797330f729Sjoerg bool Found = false;
20807330f729Sjoerg while (!Queue.empty()) {
20817330f729Sjoerg NamespaceDecl *ND = Queue.pop_back_val();
20827330f729Sjoerg
20837330f729Sjoerg // We go through some convolutions here to avoid copying results
20847330f729Sjoerg // between LookupResults.
20857330f729Sjoerg bool UseLocal = !R.empty();
20867330f729Sjoerg LookupResult &DirectR = UseLocal ? LocalR : R;
20877330f729Sjoerg bool FoundDirect = LookupDirect(S, DirectR, ND);
20887330f729Sjoerg
20897330f729Sjoerg if (FoundDirect) {
20907330f729Sjoerg // First do any local hiding.
20917330f729Sjoerg DirectR.resolveKind();
20927330f729Sjoerg
20937330f729Sjoerg // If the local result is a tag, remember that.
20947330f729Sjoerg if (DirectR.isSingleTagDecl())
20957330f729Sjoerg FoundTag = true;
20967330f729Sjoerg else
20977330f729Sjoerg FoundNonTag = true;
20987330f729Sjoerg
20997330f729Sjoerg // Append the local results to the total results if necessary.
21007330f729Sjoerg if (UseLocal) {
21017330f729Sjoerg R.addAllDecls(LocalR);
21027330f729Sjoerg LocalR.clear();
21037330f729Sjoerg }
21047330f729Sjoerg }
21057330f729Sjoerg
21067330f729Sjoerg // If we find names in this namespace, ignore its using directives.
21077330f729Sjoerg if (FoundDirect) {
21087330f729Sjoerg Found = true;
21097330f729Sjoerg continue;
21107330f729Sjoerg }
21117330f729Sjoerg
21127330f729Sjoerg for (auto I : ND->using_directives()) {
21137330f729Sjoerg NamespaceDecl *Nom = I->getNominatedNamespace();
21147330f729Sjoerg if (S.isVisible(I) && Visited.insert(Nom).second)
21157330f729Sjoerg Queue.push_back(Nom);
21167330f729Sjoerg }
21177330f729Sjoerg }
21187330f729Sjoerg
21197330f729Sjoerg if (Found) {
21207330f729Sjoerg if (FoundTag && FoundNonTag)
21217330f729Sjoerg R.setAmbiguousQualifiedTagHiding();
21227330f729Sjoerg else
21237330f729Sjoerg R.resolveKind();
21247330f729Sjoerg }
21257330f729Sjoerg
21267330f729Sjoerg return Found;
21277330f729Sjoerg }
21287330f729Sjoerg
21297330f729Sjoerg /// Perform qualified name lookup into a given context.
21307330f729Sjoerg ///
21317330f729Sjoerg /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
21327330f729Sjoerg /// names when the context of those names is explicit specified, e.g.,
21337330f729Sjoerg /// "std::vector" or "x->member", or as part of unqualified name lookup.
21347330f729Sjoerg ///
21357330f729Sjoerg /// Different lookup criteria can find different names. For example, a
21367330f729Sjoerg /// particular scope can have both a struct and a function of the same
21377330f729Sjoerg /// name, and each can be found by certain lookup criteria. For more
21387330f729Sjoerg /// information about lookup criteria, see the documentation for the
21397330f729Sjoerg /// class LookupCriteria.
21407330f729Sjoerg ///
21417330f729Sjoerg /// \param R captures both the lookup criteria and any lookup results found.
21427330f729Sjoerg ///
21437330f729Sjoerg /// \param LookupCtx The context in which qualified name lookup will
21447330f729Sjoerg /// search. If the lookup criteria permits, name lookup may also search
21457330f729Sjoerg /// in the parent contexts or (for C++ classes) base classes.
21467330f729Sjoerg ///
21477330f729Sjoerg /// \param InUnqualifiedLookup true if this is qualified name lookup that
21487330f729Sjoerg /// occurs as part of unqualified name lookup.
21497330f729Sjoerg ///
21507330f729Sjoerg /// \returns true if lookup succeeded, false if it failed.
LookupQualifiedName(LookupResult & R,DeclContext * LookupCtx,bool InUnqualifiedLookup)21517330f729Sjoerg bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
21527330f729Sjoerg bool InUnqualifiedLookup) {
21537330f729Sjoerg assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
21547330f729Sjoerg
21557330f729Sjoerg if (!R.getLookupName())
21567330f729Sjoerg return false;
21577330f729Sjoerg
21587330f729Sjoerg // Make sure that the declaration context is complete.
21597330f729Sjoerg assert((!isa<TagDecl>(LookupCtx) ||
21607330f729Sjoerg LookupCtx->isDependentContext() ||
21617330f729Sjoerg cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
21627330f729Sjoerg cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
21637330f729Sjoerg "Declaration context must already be complete!");
21647330f729Sjoerg
21657330f729Sjoerg struct QualifiedLookupInScope {
21667330f729Sjoerg bool oldVal;
21677330f729Sjoerg DeclContext *Context;
21687330f729Sjoerg // Set flag in DeclContext informing debugger that we're looking for qualified name
21697330f729Sjoerg QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
21707330f729Sjoerg oldVal = ctx->setUseQualifiedLookup();
21717330f729Sjoerg }
21727330f729Sjoerg ~QualifiedLookupInScope() {
21737330f729Sjoerg Context->setUseQualifiedLookup(oldVal);
21747330f729Sjoerg }
21757330f729Sjoerg } QL(LookupCtx);
21767330f729Sjoerg
21777330f729Sjoerg if (LookupDirect(*this, R, LookupCtx)) {
21787330f729Sjoerg R.resolveKind();
21797330f729Sjoerg if (isa<CXXRecordDecl>(LookupCtx))
21807330f729Sjoerg R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
21817330f729Sjoerg return true;
21827330f729Sjoerg }
21837330f729Sjoerg
21847330f729Sjoerg // Don't descend into implied contexts for redeclarations.
21857330f729Sjoerg // C++98 [namespace.qual]p6:
21867330f729Sjoerg // In a declaration for a namespace member in which the
21877330f729Sjoerg // declarator-id is a qualified-id, given that the qualified-id
21887330f729Sjoerg // for the namespace member has the form
21897330f729Sjoerg // nested-name-specifier unqualified-id
21907330f729Sjoerg // the unqualified-id shall name a member of the namespace
21917330f729Sjoerg // designated by the nested-name-specifier.
21927330f729Sjoerg // See also [class.mfct]p5 and [class.static.data]p2.
21937330f729Sjoerg if (R.isForRedeclaration())
21947330f729Sjoerg return false;
21957330f729Sjoerg
21967330f729Sjoerg // If this is a namespace, look it up in the implied namespaces.
21977330f729Sjoerg if (LookupCtx->isFileContext())
21987330f729Sjoerg return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
21997330f729Sjoerg
22007330f729Sjoerg // If this isn't a C++ class, we aren't allowed to look into base
22017330f729Sjoerg // classes, we're done.
22027330f729Sjoerg CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
22037330f729Sjoerg if (!LookupRec || !LookupRec->getDefinition())
22047330f729Sjoerg return false;
22057330f729Sjoerg
2206*e038c9c4Sjoerg // We're done for lookups that can never succeed for C++ classes.
2207*e038c9c4Sjoerg if (R.getLookupKind() == LookupOperatorName ||
2208*e038c9c4Sjoerg R.getLookupKind() == LookupNamespaceName ||
2209*e038c9c4Sjoerg R.getLookupKind() == LookupObjCProtocolName ||
2210*e038c9c4Sjoerg R.getLookupKind() == LookupLabel)
2211*e038c9c4Sjoerg return false;
2212*e038c9c4Sjoerg
22137330f729Sjoerg // If we're performing qualified name lookup into a dependent class,
22147330f729Sjoerg // then we are actually looking into a current instantiation. If we have any
22157330f729Sjoerg // dependent base classes, then we either have to delay lookup until
22167330f729Sjoerg // template instantiation time (at which point all bases will be available)
22177330f729Sjoerg // or we have to fail.
22187330f729Sjoerg if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
22197330f729Sjoerg LookupRec->hasAnyDependentBases()) {
22207330f729Sjoerg R.setNotFoundInCurrentInstantiation();
22217330f729Sjoerg return false;
22227330f729Sjoerg }
22237330f729Sjoerg
22247330f729Sjoerg // Perform lookup into our base classes.
22257330f729Sjoerg
22267330f729Sjoerg DeclarationName Name = R.getLookupName();
2227*e038c9c4Sjoerg unsigned IDNS = R.getIdentifierNamespace();
2228*e038c9c4Sjoerg
2229*e038c9c4Sjoerg // Look for this member in our base classes.
2230*e038c9c4Sjoerg auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2231*e038c9c4Sjoerg CXXBasePath &Path) -> bool {
2232*e038c9c4Sjoerg CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2233*e038c9c4Sjoerg // Drop leading non-matching lookup results from the declaration list so
2234*e038c9c4Sjoerg // we don't need to consider them again below.
2235*e038c9c4Sjoerg for (Path.Decls = BaseRecord->lookup(Name).begin();
2236*e038c9c4Sjoerg Path.Decls != Path.Decls.end(); ++Path.Decls) {
2237*e038c9c4Sjoerg if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2238*e038c9c4Sjoerg return true;
2239*e038c9c4Sjoerg }
2240*e038c9c4Sjoerg return false;
2241*e038c9c4Sjoerg };
2242*e038c9c4Sjoerg
2243*e038c9c4Sjoerg CXXBasePaths Paths;
2244*e038c9c4Sjoerg Paths.setOrigin(LookupRec);
2245*e038c9c4Sjoerg if (!LookupRec->lookupInBases(BaseCallback, Paths))
22467330f729Sjoerg return false;
22477330f729Sjoerg
22487330f729Sjoerg R.setNamingClass(LookupRec);
22497330f729Sjoerg
22507330f729Sjoerg // C++ [class.member.lookup]p2:
22517330f729Sjoerg // [...] If the resulting set of declarations are not all from
22527330f729Sjoerg // sub-objects of the same type, or the set has a nonstatic member
22537330f729Sjoerg // and includes members from distinct sub-objects, there is an
22547330f729Sjoerg // ambiguity and the program is ill-formed. Otherwise that set is
22557330f729Sjoerg // the result of the lookup.
22567330f729Sjoerg QualType SubobjectType;
22577330f729Sjoerg int SubobjectNumber = 0;
22587330f729Sjoerg AccessSpecifier SubobjectAccess = AS_none;
22597330f729Sjoerg
2260*e038c9c4Sjoerg // Check whether the given lookup result contains only static members.
2261*e038c9c4Sjoerg auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2262*e038c9c4Sjoerg for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2263*e038c9c4Sjoerg if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2264*e038c9c4Sjoerg return false;
2265*e038c9c4Sjoerg return true;
2266*e038c9c4Sjoerg };
2267*e038c9c4Sjoerg
2268*e038c9c4Sjoerg bool TemplateNameLookup = R.isTemplateNameLookup();
2269*e038c9c4Sjoerg
2270*e038c9c4Sjoerg // Determine whether two sets of members contain the same members, as
2271*e038c9c4Sjoerg // required by C++ [class.member.lookup]p6.
2272*e038c9c4Sjoerg auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2273*e038c9c4Sjoerg DeclContext::lookup_iterator B) {
2274*e038c9c4Sjoerg using Iterator = DeclContextLookupResult::iterator;
2275*e038c9c4Sjoerg using Result = const void *;
2276*e038c9c4Sjoerg
2277*e038c9c4Sjoerg auto Next = [&](Iterator &It, Iterator End) -> Result {
2278*e038c9c4Sjoerg while (It != End) {
2279*e038c9c4Sjoerg NamedDecl *ND = *It++;
2280*e038c9c4Sjoerg if (!ND->isInIdentifierNamespace(IDNS))
2281*e038c9c4Sjoerg continue;
2282*e038c9c4Sjoerg
2283*e038c9c4Sjoerg // C++ [temp.local]p3:
2284*e038c9c4Sjoerg // A lookup that finds an injected-class-name (10.2) can result in
2285*e038c9c4Sjoerg // an ambiguity in certain cases (for example, if it is found in
2286*e038c9c4Sjoerg // more than one base class). If all of the injected-class-names
2287*e038c9c4Sjoerg // that are found refer to specializations of the same class
2288*e038c9c4Sjoerg // template, and if the name is used as a template-name, the
2289*e038c9c4Sjoerg // reference refers to the class template itself and not a
2290*e038c9c4Sjoerg // specialization thereof, and is not ambiguous.
2291*e038c9c4Sjoerg if (TemplateNameLookup)
2292*e038c9c4Sjoerg if (auto *TD = getAsTemplateNameDecl(ND))
2293*e038c9c4Sjoerg ND = TD;
2294*e038c9c4Sjoerg
2295*e038c9c4Sjoerg // C++ [class.member.lookup]p3:
2296*e038c9c4Sjoerg // type declarations (including injected-class-names) are replaced by
2297*e038c9c4Sjoerg // the types they designate
2298*e038c9c4Sjoerg if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2299*e038c9c4Sjoerg QualType T = Context.getTypeDeclType(TD);
2300*e038c9c4Sjoerg return T.getCanonicalType().getAsOpaquePtr();
2301*e038c9c4Sjoerg }
2302*e038c9c4Sjoerg
2303*e038c9c4Sjoerg return ND->getUnderlyingDecl()->getCanonicalDecl();
2304*e038c9c4Sjoerg }
2305*e038c9c4Sjoerg return nullptr;
2306*e038c9c4Sjoerg };
2307*e038c9c4Sjoerg
2308*e038c9c4Sjoerg // We'll often find the declarations are in the same order. Handle this
2309*e038c9c4Sjoerg // case (and the special case of only one declaration) efficiently.
2310*e038c9c4Sjoerg Iterator AIt = A, BIt = B, AEnd, BEnd;
2311*e038c9c4Sjoerg while (true) {
2312*e038c9c4Sjoerg Result AResult = Next(AIt, AEnd);
2313*e038c9c4Sjoerg Result BResult = Next(BIt, BEnd);
2314*e038c9c4Sjoerg if (!AResult && !BResult)
2315*e038c9c4Sjoerg return true;
2316*e038c9c4Sjoerg if (!AResult || !BResult)
2317*e038c9c4Sjoerg return false;
2318*e038c9c4Sjoerg if (AResult != BResult) {
2319*e038c9c4Sjoerg // Found a mismatch; carefully check both lists, accounting for the
2320*e038c9c4Sjoerg // possibility of declarations appearing more than once.
2321*e038c9c4Sjoerg llvm::SmallDenseMap<Result, bool, 32> AResults;
2322*e038c9c4Sjoerg for (; AResult; AResult = Next(AIt, AEnd))
2323*e038c9c4Sjoerg AResults.insert({AResult, /*FoundInB*/false});
2324*e038c9c4Sjoerg unsigned Found = 0;
2325*e038c9c4Sjoerg for (; BResult; BResult = Next(BIt, BEnd)) {
2326*e038c9c4Sjoerg auto It = AResults.find(BResult);
2327*e038c9c4Sjoerg if (It == AResults.end())
2328*e038c9c4Sjoerg return false;
2329*e038c9c4Sjoerg if (!It->second) {
2330*e038c9c4Sjoerg It->second = true;
2331*e038c9c4Sjoerg ++Found;
2332*e038c9c4Sjoerg }
2333*e038c9c4Sjoerg }
2334*e038c9c4Sjoerg return AResults.size() == Found;
2335*e038c9c4Sjoerg }
2336*e038c9c4Sjoerg }
2337*e038c9c4Sjoerg };
2338*e038c9c4Sjoerg
23397330f729Sjoerg for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
23407330f729Sjoerg Path != PathEnd; ++Path) {
23417330f729Sjoerg const CXXBasePathElement &PathElement = Path->back();
23427330f729Sjoerg
23437330f729Sjoerg // Pick the best (i.e. most permissive i.e. numerically lowest) access
23447330f729Sjoerg // across all paths.
23457330f729Sjoerg SubobjectAccess = std::min(SubobjectAccess, Path->Access);
23467330f729Sjoerg
23477330f729Sjoerg // Determine whether we're looking at a distinct sub-object or not.
23487330f729Sjoerg if (SubobjectType.isNull()) {
23497330f729Sjoerg // This is the first subobject we've looked at. Record its type.
23507330f729Sjoerg SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
23517330f729Sjoerg SubobjectNumber = PathElement.SubobjectNumber;
23527330f729Sjoerg continue;
23537330f729Sjoerg }
23547330f729Sjoerg
2355*e038c9c4Sjoerg if (SubobjectType !=
2356*e038c9c4Sjoerg Context.getCanonicalType(PathElement.Base->getType())) {
23577330f729Sjoerg // We found members of the given name in two subobjects of
23587330f729Sjoerg // different types. If the declaration sets aren't the same, this
23597330f729Sjoerg // lookup is ambiguous.
2360*e038c9c4Sjoerg //
2361*e038c9c4Sjoerg // FIXME: The language rule says that this applies irrespective of
2362*e038c9c4Sjoerg // whether the sets contain only static members.
2363*e038c9c4Sjoerg if (HasOnlyStaticMembers(Path->Decls) &&
2364*e038c9c4Sjoerg HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
23657330f729Sjoerg continue;
23667330f729Sjoerg
23677330f729Sjoerg R.setAmbiguousBaseSubobjectTypes(Paths);
23687330f729Sjoerg return true;
23697330f729Sjoerg }
23707330f729Sjoerg
2371*e038c9c4Sjoerg // FIXME: This language rule no longer exists. Checking for ambiguous base
2372*e038c9c4Sjoerg // subobjects should be done as part of formation of a class member access
2373*e038c9c4Sjoerg // expression (when converting the object parameter to the member's type).
23747330f729Sjoerg if (SubobjectNumber != PathElement.SubobjectNumber) {
23757330f729Sjoerg // We have a different subobject of the same type.
23767330f729Sjoerg
23777330f729Sjoerg // C++ [class.member.lookup]p5:
23787330f729Sjoerg // A static member, a nested type or an enumerator defined in
23797330f729Sjoerg // a base class T can unambiguously be found even if an object
23807330f729Sjoerg // has more than one base class subobject of type T.
2381*e038c9c4Sjoerg if (HasOnlyStaticMembers(Path->Decls))
23827330f729Sjoerg continue;
23837330f729Sjoerg
23847330f729Sjoerg // We have found a nonstatic member name in multiple, distinct
23857330f729Sjoerg // subobjects. Name lookup is ambiguous.
23867330f729Sjoerg R.setAmbiguousBaseSubobjects(Paths);
23877330f729Sjoerg return true;
23887330f729Sjoerg }
23897330f729Sjoerg }
23907330f729Sjoerg
23917330f729Sjoerg // Lookup in a base class succeeded; return these results.
23927330f729Sjoerg
2393*e038c9c4Sjoerg for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2394*e038c9c4Sjoerg I != E; ++I) {
23957330f729Sjoerg AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2396*e038c9c4Sjoerg (*I)->getAccess());
2397*e038c9c4Sjoerg if (NamedDecl *ND = R.getAcceptableDecl(*I))
2398*e038c9c4Sjoerg R.addDecl(ND, AS);
23997330f729Sjoerg }
24007330f729Sjoerg R.resolveKind();
24017330f729Sjoerg return true;
24027330f729Sjoerg }
24037330f729Sjoerg
24047330f729Sjoerg /// Performs qualified name lookup or special type of lookup for
24057330f729Sjoerg /// "__super::" scope specifier.
24067330f729Sjoerg ///
24077330f729Sjoerg /// This routine is a convenience overload meant to be called from contexts
24087330f729Sjoerg /// that need to perform a qualified name lookup with an optional C++ scope
24097330f729Sjoerg /// specifier that might require special kind of lookup.
24107330f729Sjoerg ///
24117330f729Sjoerg /// \param R captures both the lookup criteria and any lookup results found.
24127330f729Sjoerg ///
24137330f729Sjoerg /// \param LookupCtx The context in which qualified name lookup will
24147330f729Sjoerg /// search.
24157330f729Sjoerg ///
24167330f729Sjoerg /// \param SS An optional C++ scope-specifier.
24177330f729Sjoerg ///
24187330f729Sjoerg /// \returns true if lookup succeeded, false if it failed.
LookupQualifiedName(LookupResult & R,DeclContext * LookupCtx,CXXScopeSpec & SS)24197330f729Sjoerg bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
24207330f729Sjoerg CXXScopeSpec &SS) {
24217330f729Sjoerg auto *NNS = SS.getScopeRep();
24227330f729Sjoerg if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
24237330f729Sjoerg return LookupInSuper(R, NNS->getAsRecordDecl());
24247330f729Sjoerg else
24257330f729Sjoerg
24267330f729Sjoerg return LookupQualifiedName(R, LookupCtx);
24277330f729Sjoerg }
24287330f729Sjoerg
24297330f729Sjoerg /// Performs name lookup for a name that was parsed in the
24307330f729Sjoerg /// source code, and may contain a C++ scope specifier.
24317330f729Sjoerg ///
24327330f729Sjoerg /// This routine is a convenience routine meant to be called from
24337330f729Sjoerg /// contexts that receive a name and an optional C++ scope specifier
24347330f729Sjoerg /// (e.g., "N::M::x"). It will then perform either qualified or
24357330f729Sjoerg /// unqualified name lookup (with LookupQualifiedName or LookupName,
24367330f729Sjoerg /// respectively) on the given name and return those results. It will
24377330f729Sjoerg /// perform a special type of lookup for "__super::" scope specifier.
24387330f729Sjoerg ///
24397330f729Sjoerg /// @param S The scope from which unqualified name lookup will
24407330f729Sjoerg /// begin.
24417330f729Sjoerg ///
24427330f729Sjoerg /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
24437330f729Sjoerg ///
24447330f729Sjoerg /// @param EnteringContext Indicates whether we are going to enter the
24457330f729Sjoerg /// context of the scope-specifier SS (if present).
24467330f729Sjoerg ///
24477330f729Sjoerg /// @returns True if any decls were found (but possibly ambiguous)
LookupParsedName(LookupResult & R,Scope * S,CXXScopeSpec * SS,bool AllowBuiltinCreation,bool EnteringContext)24487330f729Sjoerg bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
24497330f729Sjoerg bool AllowBuiltinCreation, bool EnteringContext) {
24507330f729Sjoerg if (SS && SS->isInvalid()) {
24517330f729Sjoerg // When the scope specifier is invalid, don't even look for
24527330f729Sjoerg // anything.
24537330f729Sjoerg return false;
24547330f729Sjoerg }
24557330f729Sjoerg
24567330f729Sjoerg if (SS && SS->isSet()) {
24577330f729Sjoerg NestedNameSpecifier *NNS = SS->getScopeRep();
24587330f729Sjoerg if (NNS->getKind() == NestedNameSpecifier::Super)
24597330f729Sjoerg return LookupInSuper(R, NNS->getAsRecordDecl());
24607330f729Sjoerg
24617330f729Sjoerg if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
24627330f729Sjoerg // We have resolved the scope specifier to a particular declaration
24637330f729Sjoerg // contex, and will perform name lookup in that context.
24647330f729Sjoerg if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
24657330f729Sjoerg return false;
24667330f729Sjoerg
24677330f729Sjoerg R.setContextRange(SS->getRange());
24687330f729Sjoerg return LookupQualifiedName(R, DC);
24697330f729Sjoerg }
24707330f729Sjoerg
24717330f729Sjoerg // We could not resolve the scope specified to a specific declaration
24727330f729Sjoerg // context, which means that SS refers to an unknown specialization.
24737330f729Sjoerg // Name lookup can't find anything in this case.
24747330f729Sjoerg R.setNotFoundInCurrentInstantiation();
24757330f729Sjoerg R.setContextRange(SS->getRange());
24767330f729Sjoerg return false;
24777330f729Sjoerg }
24787330f729Sjoerg
24797330f729Sjoerg // Perform unqualified name lookup starting in the given scope.
24807330f729Sjoerg return LookupName(R, S, AllowBuiltinCreation);
24817330f729Sjoerg }
24827330f729Sjoerg
24837330f729Sjoerg /// Perform qualified name lookup into all base classes of the given
24847330f729Sjoerg /// class.
24857330f729Sjoerg ///
24867330f729Sjoerg /// \param R captures both the lookup criteria and any lookup results found.
24877330f729Sjoerg ///
24887330f729Sjoerg /// \param Class The context in which qualified name lookup will
24897330f729Sjoerg /// search. Name lookup will search in all base classes merging the results.
24907330f729Sjoerg ///
24917330f729Sjoerg /// @returns True if any decls were found (but possibly ambiguous)
LookupInSuper(LookupResult & R,CXXRecordDecl * Class)24927330f729Sjoerg bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
24937330f729Sjoerg // The access-control rules we use here are essentially the rules for
24947330f729Sjoerg // doing a lookup in Class that just magically skipped the direct
24957330f729Sjoerg // members of Class itself. That is, the naming class is Class, and the
24967330f729Sjoerg // access includes the access of the base.
24977330f729Sjoerg for (const auto &BaseSpec : Class->bases()) {
24987330f729Sjoerg CXXRecordDecl *RD = cast<CXXRecordDecl>(
24997330f729Sjoerg BaseSpec.getType()->castAs<RecordType>()->getDecl());
25007330f729Sjoerg LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
25017330f729Sjoerg Result.setBaseObjectType(Context.getRecordType(Class));
25027330f729Sjoerg LookupQualifiedName(Result, RD);
25037330f729Sjoerg
25047330f729Sjoerg // Copy the lookup results into the target, merging the base's access into
25057330f729Sjoerg // the path access.
25067330f729Sjoerg for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
25077330f729Sjoerg R.addDecl(I.getDecl(),
25087330f729Sjoerg CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
25097330f729Sjoerg I.getAccess()));
25107330f729Sjoerg }
25117330f729Sjoerg
25127330f729Sjoerg Result.suppressDiagnostics();
25137330f729Sjoerg }
25147330f729Sjoerg
25157330f729Sjoerg R.resolveKind();
25167330f729Sjoerg R.setNamingClass(Class);
25177330f729Sjoerg
25187330f729Sjoerg return !R.empty();
25197330f729Sjoerg }
25207330f729Sjoerg
25217330f729Sjoerg /// Produce a diagnostic describing the ambiguity that resulted
25227330f729Sjoerg /// from name lookup.
25237330f729Sjoerg ///
25247330f729Sjoerg /// \param Result The result of the ambiguous lookup to be diagnosed.
DiagnoseAmbiguousLookup(LookupResult & Result)25257330f729Sjoerg void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
25267330f729Sjoerg assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
25277330f729Sjoerg
25287330f729Sjoerg DeclarationName Name = Result.getLookupName();
25297330f729Sjoerg SourceLocation NameLoc = Result.getNameLoc();
25307330f729Sjoerg SourceRange LookupRange = Result.getContextRange();
25317330f729Sjoerg
25327330f729Sjoerg switch (Result.getAmbiguityKind()) {
25337330f729Sjoerg case LookupResult::AmbiguousBaseSubobjects: {
25347330f729Sjoerg CXXBasePaths *Paths = Result.getBasePaths();
25357330f729Sjoerg QualType SubobjectType = Paths->front().back().Base->getType();
25367330f729Sjoerg Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
25377330f729Sjoerg << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
25387330f729Sjoerg << LookupRange;
25397330f729Sjoerg
2540*e038c9c4Sjoerg DeclContext::lookup_iterator Found = Paths->front().Decls;
25417330f729Sjoerg while (isa<CXXMethodDecl>(*Found) &&
25427330f729Sjoerg cast<CXXMethodDecl>(*Found)->isStatic())
25437330f729Sjoerg ++Found;
25447330f729Sjoerg
25457330f729Sjoerg Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
25467330f729Sjoerg break;
25477330f729Sjoerg }
25487330f729Sjoerg
25497330f729Sjoerg case LookupResult::AmbiguousBaseSubobjectTypes: {
25507330f729Sjoerg Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
25517330f729Sjoerg << Name << LookupRange;
25527330f729Sjoerg
25537330f729Sjoerg CXXBasePaths *Paths = Result.getBasePaths();
2554*e038c9c4Sjoerg std::set<const NamedDecl *> DeclsPrinted;
25557330f729Sjoerg for (CXXBasePaths::paths_iterator Path = Paths->begin(),
25567330f729Sjoerg PathEnd = Paths->end();
25577330f729Sjoerg Path != PathEnd; ++Path) {
2558*e038c9c4Sjoerg const NamedDecl *D = *Path->Decls;
2559*e038c9c4Sjoerg if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2560*e038c9c4Sjoerg continue;
2561*e038c9c4Sjoerg if (DeclsPrinted.insert(D).second) {
2562*e038c9c4Sjoerg if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2563*e038c9c4Sjoerg Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2564*e038c9c4Sjoerg << TD->getUnderlyingType();
2565*e038c9c4Sjoerg else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2566*e038c9c4Sjoerg Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2567*e038c9c4Sjoerg << Context.getTypeDeclType(TD);
2568*e038c9c4Sjoerg else
25697330f729Sjoerg Diag(D->getLocation(), diag::note_ambiguous_member_found);
25707330f729Sjoerg }
2571*e038c9c4Sjoerg }
25727330f729Sjoerg break;
25737330f729Sjoerg }
25747330f729Sjoerg
25757330f729Sjoerg case LookupResult::AmbiguousTagHiding: {
25767330f729Sjoerg Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
25777330f729Sjoerg
25787330f729Sjoerg llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
25797330f729Sjoerg
25807330f729Sjoerg for (auto *D : Result)
25817330f729Sjoerg if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
25827330f729Sjoerg TagDecls.insert(TD);
25837330f729Sjoerg Diag(TD->getLocation(), diag::note_hidden_tag);
25847330f729Sjoerg }
25857330f729Sjoerg
25867330f729Sjoerg for (auto *D : Result)
25877330f729Sjoerg if (!isa<TagDecl>(D))
25887330f729Sjoerg Diag(D->getLocation(), diag::note_hiding_object);
25897330f729Sjoerg
25907330f729Sjoerg // For recovery purposes, go ahead and implement the hiding.
25917330f729Sjoerg LookupResult::Filter F = Result.makeFilter();
25927330f729Sjoerg while (F.hasNext()) {
25937330f729Sjoerg if (TagDecls.count(F.next()))
25947330f729Sjoerg F.erase();
25957330f729Sjoerg }
25967330f729Sjoerg F.done();
25977330f729Sjoerg break;
25987330f729Sjoerg }
25997330f729Sjoerg
26007330f729Sjoerg case LookupResult::AmbiguousReference: {
26017330f729Sjoerg Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
26027330f729Sjoerg
26037330f729Sjoerg for (auto *D : Result)
26047330f729Sjoerg Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
26057330f729Sjoerg break;
26067330f729Sjoerg }
26077330f729Sjoerg }
26087330f729Sjoerg }
26097330f729Sjoerg
26107330f729Sjoerg namespace {
26117330f729Sjoerg struct AssociatedLookup {
AssociatedLookup__anon8d9d45fa0c11::AssociatedLookup26127330f729Sjoerg AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
26137330f729Sjoerg Sema::AssociatedNamespaceSet &Namespaces,
26147330f729Sjoerg Sema::AssociatedClassSet &Classes)
26157330f729Sjoerg : S(S), Namespaces(Namespaces), Classes(Classes),
26167330f729Sjoerg InstantiationLoc(InstantiationLoc) {
26177330f729Sjoerg }
26187330f729Sjoerg
addClassTransitive__anon8d9d45fa0c11::AssociatedLookup26197330f729Sjoerg bool addClassTransitive(CXXRecordDecl *RD) {
26207330f729Sjoerg Classes.insert(RD);
26217330f729Sjoerg return ClassesTransitive.insert(RD);
26227330f729Sjoerg }
26237330f729Sjoerg
26247330f729Sjoerg Sema &S;
26257330f729Sjoerg Sema::AssociatedNamespaceSet &Namespaces;
26267330f729Sjoerg Sema::AssociatedClassSet &Classes;
26277330f729Sjoerg SourceLocation InstantiationLoc;
26287330f729Sjoerg
26297330f729Sjoerg private:
26307330f729Sjoerg Sema::AssociatedClassSet ClassesTransitive;
26317330f729Sjoerg };
26327330f729Sjoerg } // end anonymous namespace
26337330f729Sjoerg
26347330f729Sjoerg static void
26357330f729Sjoerg addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
26367330f729Sjoerg
26377330f729Sjoerg // Given the declaration context \param Ctx of a class, class template or
26387330f729Sjoerg // enumeration, add the associated namespaces to \param Namespaces as described
26397330f729Sjoerg // in [basic.lookup.argdep]p2.
CollectEnclosingNamespace(Sema::AssociatedNamespaceSet & Namespaces,DeclContext * Ctx)26407330f729Sjoerg static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
26417330f729Sjoerg DeclContext *Ctx) {
26427330f729Sjoerg // The exact wording has been changed in C++14 as a result of
26437330f729Sjoerg // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
26447330f729Sjoerg // to all language versions since it is possible to return a local type
26457330f729Sjoerg // from a lambda in C++11.
26467330f729Sjoerg //
26477330f729Sjoerg // C++14 [basic.lookup.argdep]p2:
26487330f729Sjoerg // If T is a class type [...]. Its associated namespaces are the innermost
26497330f729Sjoerg // enclosing namespaces of its associated classes. [...]
26507330f729Sjoerg //
26517330f729Sjoerg // If T is an enumeration type, its associated namespace is the innermost
26527330f729Sjoerg // enclosing namespace of its declaration. [...]
26537330f729Sjoerg
26547330f729Sjoerg // We additionally skip inline namespaces. The innermost non-inline namespace
26557330f729Sjoerg // contains all names of all its nested inline namespaces anyway, so we can
26567330f729Sjoerg // replace the entire inline namespace tree with its root.
26577330f729Sjoerg while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
26587330f729Sjoerg Ctx = Ctx->getParent();
26597330f729Sjoerg
26607330f729Sjoerg Namespaces.insert(Ctx->getPrimaryContext());
26617330f729Sjoerg }
26627330f729Sjoerg
26637330f729Sjoerg // Add the associated classes and namespaces for argument-dependent
26647330f729Sjoerg // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
26657330f729Sjoerg static void
addAssociatedClassesAndNamespaces(AssociatedLookup & Result,const TemplateArgument & Arg)26667330f729Sjoerg addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
26677330f729Sjoerg const TemplateArgument &Arg) {
26687330f729Sjoerg // C++ [basic.lookup.argdep]p2, last bullet:
26697330f729Sjoerg // -- [...] ;
26707330f729Sjoerg switch (Arg.getKind()) {
26717330f729Sjoerg case TemplateArgument::Null:
26727330f729Sjoerg break;
26737330f729Sjoerg
26747330f729Sjoerg case TemplateArgument::Type:
26757330f729Sjoerg // [...] the namespaces and classes associated with the types of the
26767330f729Sjoerg // template arguments provided for template type parameters (excluding
26777330f729Sjoerg // template template parameters)
26787330f729Sjoerg addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
26797330f729Sjoerg break;
26807330f729Sjoerg
26817330f729Sjoerg case TemplateArgument::Template:
26827330f729Sjoerg case TemplateArgument::TemplateExpansion: {
26837330f729Sjoerg // [...] the namespaces in which any template template arguments are
26847330f729Sjoerg // defined; and the classes in which any member templates used as
26857330f729Sjoerg // template template arguments are defined.
26867330f729Sjoerg TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
26877330f729Sjoerg if (ClassTemplateDecl *ClassTemplate
26887330f729Sjoerg = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
26897330f729Sjoerg DeclContext *Ctx = ClassTemplate->getDeclContext();
26907330f729Sjoerg if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
26917330f729Sjoerg Result.Classes.insert(EnclosingClass);
26927330f729Sjoerg // Add the associated namespace for this class.
26937330f729Sjoerg CollectEnclosingNamespace(Result.Namespaces, Ctx);
26947330f729Sjoerg }
26957330f729Sjoerg break;
26967330f729Sjoerg }
26977330f729Sjoerg
26987330f729Sjoerg case TemplateArgument::Declaration:
26997330f729Sjoerg case TemplateArgument::Integral:
27007330f729Sjoerg case TemplateArgument::Expression:
27017330f729Sjoerg case TemplateArgument::NullPtr:
27027330f729Sjoerg // [Note: non-type template arguments do not contribute to the set of
27037330f729Sjoerg // associated namespaces. ]
27047330f729Sjoerg break;
27057330f729Sjoerg
27067330f729Sjoerg case TemplateArgument::Pack:
27077330f729Sjoerg for (const auto &P : Arg.pack_elements())
27087330f729Sjoerg addAssociatedClassesAndNamespaces(Result, P);
27097330f729Sjoerg break;
27107330f729Sjoerg }
27117330f729Sjoerg }
27127330f729Sjoerg
27137330f729Sjoerg // Add the associated classes and namespaces for argument-dependent lookup
27147330f729Sjoerg // with an argument of class type (C++ [basic.lookup.argdep]p2).
27157330f729Sjoerg static void
addAssociatedClassesAndNamespaces(AssociatedLookup & Result,CXXRecordDecl * Class)27167330f729Sjoerg addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
27177330f729Sjoerg CXXRecordDecl *Class) {
27187330f729Sjoerg
27197330f729Sjoerg // Just silently ignore anything whose name is __va_list_tag.
27207330f729Sjoerg if (Class->getDeclName() == Result.S.VAListTagName)
27217330f729Sjoerg return;
27227330f729Sjoerg
27237330f729Sjoerg // C++ [basic.lookup.argdep]p2:
27247330f729Sjoerg // [...]
27257330f729Sjoerg // -- If T is a class type (including unions), its associated
27267330f729Sjoerg // classes are: the class itself; the class of which it is a
27277330f729Sjoerg // member, if any; and its direct and indirect base classes.
27287330f729Sjoerg // Its associated namespaces are the innermost enclosing
27297330f729Sjoerg // namespaces of its associated classes.
27307330f729Sjoerg
27317330f729Sjoerg // Add the class of which it is a member, if any.
27327330f729Sjoerg DeclContext *Ctx = Class->getDeclContext();
27337330f729Sjoerg if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
27347330f729Sjoerg Result.Classes.insert(EnclosingClass);
27357330f729Sjoerg
27367330f729Sjoerg // Add the associated namespace for this class.
27377330f729Sjoerg CollectEnclosingNamespace(Result.Namespaces, Ctx);
27387330f729Sjoerg
27397330f729Sjoerg // -- If T is a template-id, its associated namespaces and classes are
27407330f729Sjoerg // the namespace in which the template is defined; for member
27417330f729Sjoerg // templates, the member template's class; the namespaces and classes
27427330f729Sjoerg // associated with the types of the template arguments provided for
27437330f729Sjoerg // template type parameters (excluding template template parameters); the
27447330f729Sjoerg // namespaces in which any template template arguments are defined; and
27457330f729Sjoerg // the classes in which any member templates used as template template
27467330f729Sjoerg // arguments are defined. [Note: non-type template arguments do not
27477330f729Sjoerg // contribute to the set of associated namespaces. ]
27487330f729Sjoerg if (ClassTemplateSpecializationDecl *Spec
27497330f729Sjoerg = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
27507330f729Sjoerg DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
27517330f729Sjoerg if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
27527330f729Sjoerg Result.Classes.insert(EnclosingClass);
27537330f729Sjoerg // Add the associated namespace for this class.
27547330f729Sjoerg CollectEnclosingNamespace(Result.Namespaces, Ctx);
27557330f729Sjoerg
27567330f729Sjoerg const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
27577330f729Sjoerg for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
27587330f729Sjoerg addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
27597330f729Sjoerg }
27607330f729Sjoerg
27617330f729Sjoerg // Add the class itself. If we've already transitively visited this class,
27627330f729Sjoerg // we don't need to visit base classes.
27637330f729Sjoerg if (!Result.addClassTransitive(Class))
27647330f729Sjoerg return;
27657330f729Sjoerg
27667330f729Sjoerg // Only recurse into base classes for complete types.
27677330f729Sjoerg if (!Result.S.isCompleteType(Result.InstantiationLoc,
27687330f729Sjoerg Result.S.Context.getRecordType(Class)))
27697330f729Sjoerg return;
27707330f729Sjoerg
27717330f729Sjoerg // Add direct and indirect base classes along with their associated
27727330f729Sjoerg // namespaces.
27737330f729Sjoerg SmallVector<CXXRecordDecl *, 32> Bases;
27747330f729Sjoerg Bases.push_back(Class);
27757330f729Sjoerg while (!Bases.empty()) {
27767330f729Sjoerg // Pop this class off the stack.
27777330f729Sjoerg Class = Bases.pop_back_val();
27787330f729Sjoerg
27797330f729Sjoerg // Visit the base classes.
27807330f729Sjoerg for (const auto &Base : Class->bases()) {
27817330f729Sjoerg const RecordType *BaseType = Base.getType()->getAs<RecordType>();
27827330f729Sjoerg // In dependent contexts, we do ADL twice, and the first time around,
27837330f729Sjoerg // the base type might be a dependent TemplateSpecializationType, or a
27847330f729Sjoerg // TemplateTypeParmType. If that happens, simply ignore it.
27857330f729Sjoerg // FIXME: If we want to support export, we probably need to add the
27867330f729Sjoerg // namespace of the template in a TemplateSpecializationType, or even
27877330f729Sjoerg // the classes and namespaces of known non-dependent arguments.
27887330f729Sjoerg if (!BaseType)
27897330f729Sjoerg continue;
27907330f729Sjoerg CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
27917330f729Sjoerg if (Result.addClassTransitive(BaseDecl)) {
27927330f729Sjoerg // Find the associated namespace for this base class.
27937330f729Sjoerg DeclContext *BaseCtx = BaseDecl->getDeclContext();
27947330f729Sjoerg CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
27957330f729Sjoerg
27967330f729Sjoerg // Make sure we visit the bases of this base class.
27977330f729Sjoerg if (BaseDecl->bases_begin() != BaseDecl->bases_end())
27987330f729Sjoerg Bases.push_back(BaseDecl);
27997330f729Sjoerg }
28007330f729Sjoerg }
28017330f729Sjoerg }
28027330f729Sjoerg }
28037330f729Sjoerg
28047330f729Sjoerg // Add the associated classes and namespaces for
28057330f729Sjoerg // argument-dependent lookup with an argument of type T
28067330f729Sjoerg // (C++ [basic.lookup.koenig]p2).
28077330f729Sjoerg static void
addAssociatedClassesAndNamespaces(AssociatedLookup & Result,QualType Ty)28087330f729Sjoerg addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
28097330f729Sjoerg // C++ [basic.lookup.koenig]p2:
28107330f729Sjoerg //
28117330f729Sjoerg // For each argument type T in the function call, there is a set
28127330f729Sjoerg // of zero or more associated namespaces and a set of zero or more
28137330f729Sjoerg // associated classes to be considered. The sets of namespaces and
28147330f729Sjoerg // classes is determined entirely by the types of the function
28157330f729Sjoerg // arguments (and the namespace of any template template
28167330f729Sjoerg // argument). Typedef names and using-declarations used to specify
28177330f729Sjoerg // the types do not contribute to this set. The sets of namespaces
28187330f729Sjoerg // and classes are determined in the following way:
28197330f729Sjoerg
28207330f729Sjoerg SmallVector<const Type *, 16> Queue;
28217330f729Sjoerg const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
28227330f729Sjoerg
28237330f729Sjoerg while (true) {
28247330f729Sjoerg switch (T->getTypeClass()) {
28257330f729Sjoerg
28267330f729Sjoerg #define TYPE(Class, Base)
28277330f729Sjoerg #define DEPENDENT_TYPE(Class, Base) case Type::Class:
28287330f729Sjoerg #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
28297330f729Sjoerg #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
28307330f729Sjoerg #define ABSTRACT_TYPE(Class, Base)
28317330f729Sjoerg #include "clang/AST/TypeNodes.inc"
28327330f729Sjoerg // T is canonical. We can also ignore dependent types because
28337330f729Sjoerg // we don't need to do ADL at the definition point, but if we
28347330f729Sjoerg // wanted to implement template export (or if we find some other
28357330f729Sjoerg // use for associated classes and namespaces...) this would be
28367330f729Sjoerg // wrong.
28377330f729Sjoerg break;
28387330f729Sjoerg
28397330f729Sjoerg // -- If T is a pointer to U or an array of U, its associated
28407330f729Sjoerg // namespaces and classes are those associated with U.
28417330f729Sjoerg case Type::Pointer:
28427330f729Sjoerg T = cast<PointerType>(T)->getPointeeType().getTypePtr();
28437330f729Sjoerg continue;
28447330f729Sjoerg case Type::ConstantArray:
28457330f729Sjoerg case Type::IncompleteArray:
28467330f729Sjoerg case Type::VariableArray:
28477330f729Sjoerg T = cast<ArrayType>(T)->getElementType().getTypePtr();
28487330f729Sjoerg continue;
28497330f729Sjoerg
28507330f729Sjoerg // -- If T is a fundamental type, its associated sets of
28517330f729Sjoerg // namespaces and classes are both empty.
28527330f729Sjoerg case Type::Builtin:
28537330f729Sjoerg break;
28547330f729Sjoerg
28557330f729Sjoerg // -- If T is a class type (including unions), its associated
28567330f729Sjoerg // classes are: the class itself; the class of which it is
28577330f729Sjoerg // a member, if any; and its direct and indirect base classes.
28587330f729Sjoerg // Its associated namespaces are the innermost enclosing
28597330f729Sjoerg // namespaces of its associated classes.
28607330f729Sjoerg case Type::Record: {
28617330f729Sjoerg CXXRecordDecl *Class =
28627330f729Sjoerg cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
28637330f729Sjoerg addAssociatedClassesAndNamespaces(Result, Class);
28647330f729Sjoerg break;
28657330f729Sjoerg }
28667330f729Sjoerg
28677330f729Sjoerg // -- If T is an enumeration type, its associated namespace
28687330f729Sjoerg // is the innermost enclosing namespace of its declaration.
28697330f729Sjoerg // If it is a class member, its associated class is the
28707330f729Sjoerg // member’s class; else it has no associated class.
28717330f729Sjoerg case Type::Enum: {
28727330f729Sjoerg EnumDecl *Enum = cast<EnumType>(T)->getDecl();
28737330f729Sjoerg
28747330f729Sjoerg DeclContext *Ctx = Enum->getDeclContext();
28757330f729Sjoerg if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
28767330f729Sjoerg Result.Classes.insert(EnclosingClass);
28777330f729Sjoerg
28787330f729Sjoerg // Add the associated namespace for this enumeration.
28797330f729Sjoerg CollectEnclosingNamespace(Result.Namespaces, Ctx);
28807330f729Sjoerg
28817330f729Sjoerg break;
28827330f729Sjoerg }
28837330f729Sjoerg
28847330f729Sjoerg // -- If T is a function type, its associated namespaces and
28857330f729Sjoerg // classes are those associated with the function parameter
28867330f729Sjoerg // types and those associated with the return type.
28877330f729Sjoerg case Type::FunctionProto: {
28887330f729Sjoerg const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
28897330f729Sjoerg for (const auto &Arg : Proto->param_types())
28907330f729Sjoerg Queue.push_back(Arg.getTypePtr());
28917330f729Sjoerg // fallthrough
28927330f729Sjoerg LLVM_FALLTHROUGH;
28937330f729Sjoerg }
28947330f729Sjoerg case Type::FunctionNoProto: {
28957330f729Sjoerg const FunctionType *FnType = cast<FunctionType>(T);
28967330f729Sjoerg T = FnType->getReturnType().getTypePtr();
28977330f729Sjoerg continue;
28987330f729Sjoerg }
28997330f729Sjoerg
29007330f729Sjoerg // -- If T is a pointer to a member function of a class X, its
29017330f729Sjoerg // associated namespaces and classes are those associated
29027330f729Sjoerg // with the function parameter types and return type,
29037330f729Sjoerg // together with those associated with X.
29047330f729Sjoerg //
29057330f729Sjoerg // -- If T is a pointer to a data member of class X, its
29067330f729Sjoerg // associated namespaces and classes are those associated
29077330f729Sjoerg // with the member type together with those associated with
29087330f729Sjoerg // X.
29097330f729Sjoerg case Type::MemberPointer: {
29107330f729Sjoerg const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
29117330f729Sjoerg
29127330f729Sjoerg // Queue up the class type into which this points.
29137330f729Sjoerg Queue.push_back(MemberPtr->getClass());
29147330f729Sjoerg
29157330f729Sjoerg // And directly continue with the pointee type.
29167330f729Sjoerg T = MemberPtr->getPointeeType().getTypePtr();
29177330f729Sjoerg continue;
29187330f729Sjoerg }
29197330f729Sjoerg
29207330f729Sjoerg // As an extension, treat this like a normal pointer.
29217330f729Sjoerg case Type::BlockPointer:
29227330f729Sjoerg T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
29237330f729Sjoerg continue;
29247330f729Sjoerg
29257330f729Sjoerg // References aren't covered by the standard, but that's such an
29267330f729Sjoerg // obvious defect that we cover them anyway.
29277330f729Sjoerg case Type::LValueReference:
29287330f729Sjoerg case Type::RValueReference:
29297330f729Sjoerg T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
29307330f729Sjoerg continue;
29317330f729Sjoerg
29327330f729Sjoerg // These are fundamental types.
29337330f729Sjoerg case Type::Vector:
29347330f729Sjoerg case Type::ExtVector:
2935*e038c9c4Sjoerg case Type::ConstantMatrix:
29367330f729Sjoerg case Type::Complex:
2937*e038c9c4Sjoerg case Type::ExtInt:
29387330f729Sjoerg break;
29397330f729Sjoerg
29407330f729Sjoerg // Non-deduced auto types only get here for error cases.
29417330f729Sjoerg case Type::Auto:
29427330f729Sjoerg case Type::DeducedTemplateSpecialization:
29437330f729Sjoerg break;
29447330f729Sjoerg
29457330f729Sjoerg // If T is an Objective-C object or interface type, or a pointer to an
29467330f729Sjoerg // object or interface type, the associated namespace is the global
29477330f729Sjoerg // namespace.
29487330f729Sjoerg case Type::ObjCObject:
29497330f729Sjoerg case Type::ObjCInterface:
29507330f729Sjoerg case Type::ObjCObjectPointer:
29517330f729Sjoerg Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
29527330f729Sjoerg break;
29537330f729Sjoerg
29547330f729Sjoerg // Atomic types are just wrappers; use the associations of the
29557330f729Sjoerg // contained type.
29567330f729Sjoerg case Type::Atomic:
29577330f729Sjoerg T = cast<AtomicType>(T)->getValueType().getTypePtr();
29587330f729Sjoerg continue;
29597330f729Sjoerg case Type::Pipe:
29607330f729Sjoerg T = cast<PipeType>(T)->getElementType().getTypePtr();
29617330f729Sjoerg continue;
29627330f729Sjoerg }
29637330f729Sjoerg
29647330f729Sjoerg if (Queue.empty())
29657330f729Sjoerg break;
29667330f729Sjoerg T = Queue.pop_back_val();
29677330f729Sjoerg }
29687330f729Sjoerg }
29697330f729Sjoerg
29707330f729Sjoerg /// Find the associated classes and namespaces for
29717330f729Sjoerg /// argument-dependent lookup for a call with the given set of
29727330f729Sjoerg /// arguments.
29737330f729Sjoerg ///
29747330f729Sjoerg /// This routine computes the sets of associated classes and associated
29757330f729Sjoerg /// namespaces searched by argument-dependent lookup
29767330f729Sjoerg /// (C++ [basic.lookup.argdep]) for a given set of arguments.
FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,ArrayRef<Expr * > Args,AssociatedNamespaceSet & AssociatedNamespaces,AssociatedClassSet & AssociatedClasses)29777330f729Sjoerg void Sema::FindAssociatedClassesAndNamespaces(
29787330f729Sjoerg SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
29797330f729Sjoerg AssociatedNamespaceSet &AssociatedNamespaces,
29807330f729Sjoerg AssociatedClassSet &AssociatedClasses) {
29817330f729Sjoerg AssociatedNamespaces.clear();
29827330f729Sjoerg AssociatedClasses.clear();
29837330f729Sjoerg
29847330f729Sjoerg AssociatedLookup Result(*this, InstantiationLoc,
29857330f729Sjoerg AssociatedNamespaces, AssociatedClasses);
29867330f729Sjoerg
29877330f729Sjoerg // C++ [basic.lookup.koenig]p2:
29887330f729Sjoerg // For each argument type T in the function call, there is a set
29897330f729Sjoerg // of zero or more associated namespaces and a set of zero or more
29907330f729Sjoerg // associated classes to be considered. The sets of namespaces and
29917330f729Sjoerg // classes is determined entirely by the types of the function
29927330f729Sjoerg // arguments (and the namespace of any template template
29937330f729Sjoerg // argument).
29947330f729Sjoerg for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
29957330f729Sjoerg Expr *Arg = Args[ArgIdx];
29967330f729Sjoerg
29977330f729Sjoerg if (Arg->getType() != Context.OverloadTy) {
29987330f729Sjoerg addAssociatedClassesAndNamespaces(Result, Arg->getType());
29997330f729Sjoerg continue;
30007330f729Sjoerg }
30017330f729Sjoerg
30027330f729Sjoerg // [...] In addition, if the argument is the name or address of a
30037330f729Sjoerg // set of overloaded functions and/or function templates, its
30047330f729Sjoerg // associated classes and namespaces are the union of those
30057330f729Sjoerg // associated with each of the members of the set: the namespace
30067330f729Sjoerg // in which the function or function template is defined and the
30077330f729Sjoerg // classes and namespaces associated with its (non-dependent)
30087330f729Sjoerg // parameter types and return type.
30097330f729Sjoerg OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
30107330f729Sjoerg
30117330f729Sjoerg for (const NamedDecl *D : OE->decls()) {
30127330f729Sjoerg // Look through any using declarations to find the underlying function.
30137330f729Sjoerg const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
30147330f729Sjoerg
30157330f729Sjoerg // Add the classes and namespaces associated with the parameter
30167330f729Sjoerg // types and return type of this function.
30177330f729Sjoerg addAssociatedClassesAndNamespaces(Result, FDecl->getType());
30187330f729Sjoerg }
30197330f729Sjoerg }
30207330f729Sjoerg }
30217330f729Sjoerg
LookupSingleName(Scope * S,DeclarationName Name,SourceLocation Loc,LookupNameKind NameKind,RedeclarationKind Redecl)30227330f729Sjoerg NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
30237330f729Sjoerg SourceLocation Loc,
30247330f729Sjoerg LookupNameKind NameKind,
30257330f729Sjoerg RedeclarationKind Redecl) {
30267330f729Sjoerg LookupResult R(*this, Name, Loc, NameKind, Redecl);
30277330f729Sjoerg LookupName(R, S);
30287330f729Sjoerg return R.getAsSingle<NamedDecl>();
30297330f729Sjoerg }
30307330f729Sjoerg
30317330f729Sjoerg /// Find the protocol with the given name, if any.
LookupProtocol(IdentifierInfo * II,SourceLocation IdLoc,RedeclarationKind Redecl)30327330f729Sjoerg ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
30337330f729Sjoerg SourceLocation IdLoc,
30347330f729Sjoerg RedeclarationKind Redecl) {
30357330f729Sjoerg Decl *D = LookupSingleName(TUScope, II, IdLoc,
30367330f729Sjoerg LookupObjCProtocolName, Redecl);
30377330f729Sjoerg return cast_or_null<ObjCProtocolDecl>(D);
30387330f729Sjoerg }
30397330f729Sjoerg
LookupOverloadedOperatorName(OverloadedOperatorKind Op,Scope * S,UnresolvedSetImpl & Functions)30407330f729Sjoerg void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
30417330f729Sjoerg UnresolvedSetImpl &Functions) {
30427330f729Sjoerg // C++ [over.match.oper]p3:
30437330f729Sjoerg // -- The set of non-member candidates is the result of the
30447330f729Sjoerg // unqualified lookup of operator@ in the context of the
30457330f729Sjoerg // expression according to the usual rules for name lookup in
30467330f729Sjoerg // unqualified function calls (3.4.2) except that all member
30477330f729Sjoerg // functions are ignored.
30487330f729Sjoerg DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
30497330f729Sjoerg LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
30507330f729Sjoerg LookupName(Operators, S);
30517330f729Sjoerg
30527330f729Sjoerg assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
30537330f729Sjoerg Functions.append(Operators.begin(), Operators.end());
30547330f729Sjoerg }
30557330f729Sjoerg
LookupSpecialMember(CXXRecordDecl * RD,CXXSpecialMember SM,bool ConstArg,bool VolatileArg,bool RValueThis,bool ConstThis,bool VolatileThis)30567330f729Sjoerg Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
30577330f729Sjoerg CXXSpecialMember SM,
30587330f729Sjoerg bool ConstArg,
30597330f729Sjoerg bool VolatileArg,
30607330f729Sjoerg bool RValueThis,
30617330f729Sjoerg bool ConstThis,
30627330f729Sjoerg bool VolatileThis) {
30637330f729Sjoerg assert(CanDeclareSpecialMemberFunction(RD) &&
30647330f729Sjoerg "doing special member lookup into record that isn't fully complete");
30657330f729Sjoerg RD = RD->getDefinition();
30667330f729Sjoerg if (RValueThis || ConstThis || VolatileThis)
30677330f729Sjoerg assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
30687330f729Sjoerg "constructors and destructors always have unqualified lvalue this");
30697330f729Sjoerg if (ConstArg || VolatileArg)
30707330f729Sjoerg assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
30717330f729Sjoerg "parameter-less special members can't have qualified arguments");
30727330f729Sjoerg
30737330f729Sjoerg // FIXME: Get the caller to pass in a location for the lookup.
30747330f729Sjoerg SourceLocation LookupLoc = RD->getLocation();
30757330f729Sjoerg
30767330f729Sjoerg llvm::FoldingSetNodeID ID;
30777330f729Sjoerg ID.AddPointer(RD);
30787330f729Sjoerg ID.AddInteger(SM);
30797330f729Sjoerg ID.AddInteger(ConstArg);
30807330f729Sjoerg ID.AddInteger(VolatileArg);
30817330f729Sjoerg ID.AddInteger(RValueThis);
30827330f729Sjoerg ID.AddInteger(ConstThis);
30837330f729Sjoerg ID.AddInteger(VolatileThis);
30847330f729Sjoerg
30857330f729Sjoerg void *InsertPoint;
30867330f729Sjoerg SpecialMemberOverloadResultEntry *Result =
30877330f729Sjoerg SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
30887330f729Sjoerg
30897330f729Sjoerg // This was already cached
30907330f729Sjoerg if (Result)
30917330f729Sjoerg return *Result;
30927330f729Sjoerg
30937330f729Sjoerg Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
30947330f729Sjoerg Result = new (Result) SpecialMemberOverloadResultEntry(ID);
30957330f729Sjoerg SpecialMemberCache.InsertNode(Result, InsertPoint);
30967330f729Sjoerg
30977330f729Sjoerg if (SM == CXXDestructor) {
30987330f729Sjoerg if (RD->needsImplicitDestructor()) {
30997330f729Sjoerg runWithSufficientStackSpace(RD->getLocation(), [&] {
31007330f729Sjoerg DeclareImplicitDestructor(RD);
31017330f729Sjoerg });
31027330f729Sjoerg }
31037330f729Sjoerg CXXDestructorDecl *DD = RD->getDestructor();
31047330f729Sjoerg Result->setMethod(DD);
3105*e038c9c4Sjoerg Result->setKind(DD && !DD->isDeleted()
3106*e038c9c4Sjoerg ? SpecialMemberOverloadResult::Success
3107*e038c9c4Sjoerg : SpecialMemberOverloadResult::NoMemberOrDeleted);
31087330f729Sjoerg return *Result;
31097330f729Sjoerg }
31107330f729Sjoerg
31117330f729Sjoerg // Prepare for overload resolution. Here we construct a synthetic argument
31127330f729Sjoerg // if necessary and make sure that implicit functions are declared.
31137330f729Sjoerg CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
31147330f729Sjoerg DeclarationName Name;
31157330f729Sjoerg Expr *Arg = nullptr;
31167330f729Sjoerg unsigned NumArgs;
31177330f729Sjoerg
31187330f729Sjoerg QualType ArgType = CanTy;
31197330f729Sjoerg ExprValueKind VK = VK_LValue;
31207330f729Sjoerg
31217330f729Sjoerg if (SM == CXXDefaultConstructor) {
31227330f729Sjoerg Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
31237330f729Sjoerg NumArgs = 0;
31247330f729Sjoerg if (RD->needsImplicitDefaultConstructor()) {
31257330f729Sjoerg runWithSufficientStackSpace(RD->getLocation(), [&] {
31267330f729Sjoerg DeclareImplicitDefaultConstructor(RD);
31277330f729Sjoerg });
31287330f729Sjoerg }
31297330f729Sjoerg } else {
31307330f729Sjoerg if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
31317330f729Sjoerg Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
31327330f729Sjoerg if (RD->needsImplicitCopyConstructor()) {
31337330f729Sjoerg runWithSufficientStackSpace(RD->getLocation(), [&] {
31347330f729Sjoerg DeclareImplicitCopyConstructor(RD);
31357330f729Sjoerg });
31367330f729Sjoerg }
31377330f729Sjoerg if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
31387330f729Sjoerg runWithSufficientStackSpace(RD->getLocation(), [&] {
31397330f729Sjoerg DeclareImplicitMoveConstructor(RD);
31407330f729Sjoerg });
31417330f729Sjoerg }
31427330f729Sjoerg } else {
31437330f729Sjoerg Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
31447330f729Sjoerg if (RD->needsImplicitCopyAssignment()) {
31457330f729Sjoerg runWithSufficientStackSpace(RD->getLocation(), [&] {
31467330f729Sjoerg DeclareImplicitCopyAssignment(RD);
31477330f729Sjoerg });
31487330f729Sjoerg }
31497330f729Sjoerg if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
31507330f729Sjoerg runWithSufficientStackSpace(RD->getLocation(), [&] {
31517330f729Sjoerg DeclareImplicitMoveAssignment(RD);
31527330f729Sjoerg });
31537330f729Sjoerg }
31547330f729Sjoerg }
31557330f729Sjoerg
31567330f729Sjoerg if (ConstArg)
31577330f729Sjoerg ArgType.addConst();
31587330f729Sjoerg if (VolatileArg)
31597330f729Sjoerg ArgType.addVolatile();
31607330f729Sjoerg
31617330f729Sjoerg // This isn't /really/ specified by the standard, but it's implied
31627330f729Sjoerg // we should be working from an RValue in the case of move to ensure
31637330f729Sjoerg // that we prefer to bind to rvalue references, and an LValue in the
31647330f729Sjoerg // case of copy to ensure we don't bind to rvalue references.
31657330f729Sjoerg // Possibly an XValue is actually correct in the case of move, but
31667330f729Sjoerg // there is no semantic difference for class types in this restricted
31677330f729Sjoerg // case.
31687330f729Sjoerg if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
31697330f729Sjoerg VK = VK_LValue;
31707330f729Sjoerg else
31717330f729Sjoerg VK = VK_RValue;
31727330f729Sjoerg }
31737330f729Sjoerg
31747330f729Sjoerg OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
31757330f729Sjoerg
31767330f729Sjoerg if (SM != CXXDefaultConstructor) {
31777330f729Sjoerg NumArgs = 1;
31787330f729Sjoerg Arg = &FakeArg;
31797330f729Sjoerg }
31807330f729Sjoerg
31817330f729Sjoerg // Create the object argument
31827330f729Sjoerg QualType ThisTy = CanTy;
31837330f729Sjoerg if (ConstThis)
31847330f729Sjoerg ThisTy.addConst();
31857330f729Sjoerg if (VolatileThis)
31867330f729Sjoerg ThisTy.addVolatile();
31877330f729Sjoerg Expr::Classification Classification =
31887330f729Sjoerg OpaqueValueExpr(LookupLoc, ThisTy,
31897330f729Sjoerg RValueThis ? VK_RValue : VK_LValue).Classify(Context);
31907330f729Sjoerg
31917330f729Sjoerg // Now we perform lookup on the name we computed earlier and do overload
31927330f729Sjoerg // resolution. Lookup is only performed directly into the class since there
31937330f729Sjoerg // will always be a (possibly implicit) declaration to shadow any others.
31947330f729Sjoerg OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
31957330f729Sjoerg DeclContext::lookup_result R = RD->lookup(Name);
31967330f729Sjoerg
31977330f729Sjoerg if (R.empty()) {
31987330f729Sjoerg // We might have no default constructor because we have a lambda's closure
31997330f729Sjoerg // type, rather than because there's some other declared constructor.
32007330f729Sjoerg // Every class has a copy/move constructor, copy/move assignment, and
32017330f729Sjoerg // destructor.
32027330f729Sjoerg assert(SM == CXXDefaultConstructor &&
32037330f729Sjoerg "lookup for a constructor or assignment operator was empty");
32047330f729Sjoerg Result->setMethod(nullptr);
32057330f729Sjoerg Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
32067330f729Sjoerg return *Result;
32077330f729Sjoerg }
32087330f729Sjoerg
32097330f729Sjoerg // Copy the candidates as our processing of them may load new declarations
32107330f729Sjoerg // from an external source and invalidate lookup_result.
32117330f729Sjoerg SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
32127330f729Sjoerg
32137330f729Sjoerg for (NamedDecl *CandDecl : Candidates) {
32147330f729Sjoerg if (CandDecl->isInvalidDecl())
32157330f729Sjoerg continue;
32167330f729Sjoerg
32177330f729Sjoerg DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
32187330f729Sjoerg auto CtorInfo = getConstructorInfo(Cand);
32197330f729Sjoerg if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
32207330f729Sjoerg if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
32217330f729Sjoerg AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
32227330f729Sjoerg llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
32237330f729Sjoerg else if (CtorInfo)
32247330f729Sjoerg AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
32257330f729Sjoerg llvm::makeArrayRef(&Arg, NumArgs), OCS,
32267330f729Sjoerg /*SuppressUserConversions*/ true);
32277330f729Sjoerg else
32287330f729Sjoerg AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
32297330f729Sjoerg /*SuppressUserConversions*/ true);
32307330f729Sjoerg } else if (FunctionTemplateDecl *Tmpl =
32317330f729Sjoerg dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
32327330f729Sjoerg if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
32337330f729Sjoerg AddMethodTemplateCandidate(
32347330f729Sjoerg Tmpl, Cand, RD, nullptr, ThisTy, Classification,
32357330f729Sjoerg llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
32367330f729Sjoerg else if (CtorInfo)
32377330f729Sjoerg AddTemplateOverloadCandidate(
32387330f729Sjoerg CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
32397330f729Sjoerg llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
32407330f729Sjoerg else
32417330f729Sjoerg AddTemplateOverloadCandidate(
32427330f729Sjoerg Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
32437330f729Sjoerg } else {
32447330f729Sjoerg assert(isa<UsingDecl>(Cand.getDecl()) &&
32457330f729Sjoerg "illegal Kind of operator = Decl");
32467330f729Sjoerg }
32477330f729Sjoerg }
32487330f729Sjoerg
32497330f729Sjoerg OverloadCandidateSet::iterator Best;
32507330f729Sjoerg switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
32517330f729Sjoerg case OR_Success:
32527330f729Sjoerg Result->setMethod(cast<CXXMethodDecl>(Best->Function));
32537330f729Sjoerg Result->setKind(SpecialMemberOverloadResult::Success);
32547330f729Sjoerg break;
32557330f729Sjoerg
32567330f729Sjoerg case OR_Deleted:
32577330f729Sjoerg Result->setMethod(cast<CXXMethodDecl>(Best->Function));
32587330f729Sjoerg Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
32597330f729Sjoerg break;
32607330f729Sjoerg
32617330f729Sjoerg case OR_Ambiguous:
32627330f729Sjoerg Result->setMethod(nullptr);
32637330f729Sjoerg Result->setKind(SpecialMemberOverloadResult::Ambiguous);
32647330f729Sjoerg break;
32657330f729Sjoerg
32667330f729Sjoerg case OR_No_Viable_Function:
32677330f729Sjoerg Result->setMethod(nullptr);
32687330f729Sjoerg Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
32697330f729Sjoerg break;
32707330f729Sjoerg }
32717330f729Sjoerg
32727330f729Sjoerg return *Result;
32737330f729Sjoerg }
32747330f729Sjoerg
32757330f729Sjoerg /// Look up the default constructor for the given class.
LookupDefaultConstructor(CXXRecordDecl * Class)32767330f729Sjoerg CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
32777330f729Sjoerg SpecialMemberOverloadResult Result =
32787330f729Sjoerg LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
32797330f729Sjoerg false, false);
32807330f729Sjoerg
32817330f729Sjoerg return cast_or_null<CXXConstructorDecl>(Result.getMethod());
32827330f729Sjoerg }
32837330f729Sjoerg
32847330f729Sjoerg /// Look up the copying constructor for the given class.
LookupCopyingConstructor(CXXRecordDecl * Class,unsigned Quals)32857330f729Sjoerg CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
32867330f729Sjoerg unsigned Quals) {
32877330f729Sjoerg assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
32887330f729Sjoerg "non-const, non-volatile qualifiers for copy ctor arg");
32897330f729Sjoerg SpecialMemberOverloadResult Result =
32907330f729Sjoerg LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
32917330f729Sjoerg Quals & Qualifiers::Volatile, false, false, false);
32927330f729Sjoerg
32937330f729Sjoerg return cast_or_null<CXXConstructorDecl>(Result.getMethod());
32947330f729Sjoerg }
32957330f729Sjoerg
32967330f729Sjoerg /// Look up the moving constructor for the given class.
LookupMovingConstructor(CXXRecordDecl * Class,unsigned Quals)32977330f729Sjoerg CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
32987330f729Sjoerg unsigned Quals) {
32997330f729Sjoerg SpecialMemberOverloadResult Result =
33007330f729Sjoerg LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
33017330f729Sjoerg Quals & Qualifiers::Volatile, false, false, false);
33027330f729Sjoerg
33037330f729Sjoerg return cast_or_null<CXXConstructorDecl>(Result.getMethod());
33047330f729Sjoerg }
33057330f729Sjoerg
33067330f729Sjoerg /// Look up the constructors for the given class.
LookupConstructors(CXXRecordDecl * Class)33077330f729Sjoerg DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
33087330f729Sjoerg // If the implicit constructors have not yet been declared, do so now.
33097330f729Sjoerg if (CanDeclareSpecialMemberFunction(Class)) {
33107330f729Sjoerg runWithSufficientStackSpace(Class->getLocation(), [&] {
33117330f729Sjoerg if (Class->needsImplicitDefaultConstructor())
33127330f729Sjoerg DeclareImplicitDefaultConstructor(Class);
33137330f729Sjoerg if (Class->needsImplicitCopyConstructor())
33147330f729Sjoerg DeclareImplicitCopyConstructor(Class);
33157330f729Sjoerg if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
33167330f729Sjoerg DeclareImplicitMoveConstructor(Class);
33177330f729Sjoerg });
33187330f729Sjoerg }
33197330f729Sjoerg
33207330f729Sjoerg CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
33217330f729Sjoerg DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
33227330f729Sjoerg return Class->lookup(Name);
33237330f729Sjoerg }
33247330f729Sjoerg
33257330f729Sjoerg /// Look up the copying assignment operator for the given class.
LookupCopyingAssignment(CXXRecordDecl * Class,unsigned Quals,bool RValueThis,unsigned ThisQuals)33267330f729Sjoerg CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
33277330f729Sjoerg unsigned Quals, bool RValueThis,
33287330f729Sjoerg unsigned ThisQuals) {
33297330f729Sjoerg assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
33307330f729Sjoerg "non-const, non-volatile qualifiers for copy assignment arg");
33317330f729Sjoerg assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
33327330f729Sjoerg "non-const, non-volatile qualifiers for copy assignment this");
33337330f729Sjoerg SpecialMemberOverloadResult Result =
33347330f729Sjoerg LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
33357330f729Sjoerg Quals & Qualifiers::Volatile, RValueThis,
33367330f729Sjoerg ThisQuals & Qualifiers::Const,
33377330f729Sjoerg ThisQuals & Qualifiers::Volatile);
33387330f729Sjoerg
33397330f729Sjoerg return Result.getMethod();
33407330f729Sjoerg }
33417330f729Sjoerg
33427330f729Sjoerg /// Look up the moving assignment operator for the given class.
LookupMovingAssignment(CXXRecordDecl * Class,unsigned Quals,bool RValueThis,unsigned ThisQuals)33437330f729Sjoerg CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
33447330f729Sjoerg unsigned Quals,
33457330f729Sjoerg bool RValueThis,
33467330f729Sjoerg unsigned ThisQuals) {
33477330f729Sjoerg assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
33487330f729Sjoerg "non-const, non-volatile qualifiers for copy assignment this");
33497330f729Sjoerg SpecialMemberOverloadResult Result =
33507330f729Sjoerg LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
33517330f729Sjoerg Quals & Qualifiers::Volatile, RValueThis,
33527330f729Sjoerg ThisQuals & Qualifiers::Const,
33537330f729Sjoerg ThisQuals & Qualifiers::Volatile);
33547330f729Sjoerg
33557330f729Sjoerg return Result.getMethod();
33567330f729Sjoerg }
33577330f729Sjoerg
33587330f729Sjoerg /// Look for the destructor of the given class.
33597330f729Sjoerg ///
33607330f729Sjoerg /// During semantic analysis, this routine should be used in lieu of
33617330f729Sjoerg /// CXXRecordDecl::getDestructor().
33627330f729Sjoerg ///
33637330f729Sjoerg /// \returns The destructor for this class.
LookupDestructor(CXXRecordDecl * Class)33647330f729Sjoerg CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
33657330f729Sjoerg return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
33667330f729Sjoerg false, false, false,
33677330f729Sjoerg false, false).getMethod());
33687330f729Sjoerg }
33697330f729Sjoerg
33707330f729Sjoerg /// LookupLiteralOperator - Determine which literal operator should be used for
33717330f729Sjoerg /// a user-defined literal, per C++11 [lex.ext].
33727330f729Sjoerg ///
33737330f729Sjoerg /// Normal overload resolution is not used to select which literal operator to
33747330f729Sjoerg /// call for a user-defined literal. Look up the provided literal operator name,
33757330f729Sjoerg /// and filter the results to the appropriate set for the given argument types.
33767330f729Sjoerg Sema::LiteralOperatorLookupResult
LookupLiteralOperator(Scope * S,LookupResult & R,ArrayRef<QualType> ArgTys,bool AllowRaw,bool AllowTemplate,bool AllowStringTemplatePack,bool DiagnoseMissing,StringLiteral * StringLit)33777330f729Sjoerg Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3378*e038c9c4Sjoerg ArrayRef<QualType> ArgTys, bool AllowRaw,
3379*e038c9c4Sjoerg bool AllowTemplate, bool AllowStringTemplatePack,
3380*e038c9c4Sjoerg bool DiagnoseMissing, StringLiteral *StringLit) {
33817330f729Sjoerg LookupName(R, S);
33827330f729Sjoerg assert(R.getResultKind() != LookupResult::Ambiguous &&
33837330f729Sjoerg "literal operator lookup can't be ambiguous");
33847330f729Sjoerg
33857330f729Sjoerg // Filter the lookup results appropriately.
33867330f729Sjoerg LookupResult::Filter F = R.makeFilter();
33877330f729Sjoerg
3388*e038c9c4Sjoerg bool AllowCooked = true;
33897330f729Sjoerg bool FoundRaw = false;
33907330f729Sjoerg bool FoundTemplate = false;
3391*e038c9c4Sjoerg bool FoundStringTemplatePack = false;
3392*e038c9c4Sjoerg bool FoundCooked = false;
33937330f729Sjoerg
33947330f729Sjoerg while (F.hasNext()) {
33957330f729Sjoerg Decl *D = F.next();
33967330f729Sjoerg if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
33977330f729Sjoerg D = USD->getTargetDecl();
33987330f729Sjoerg
33997330f729Sjoerg // If the declaration we found is invalid, skip it.
34007330f729Sjoerg if (D->isInvalidDecl()) {
34017330f729Sjoerg F.erase();
34027330f729Sjoerg continue;
34037330f729Sjoerg }
34047330f729Sjoerg
34057330f729Sjoerg bool IsRaw = false;
34067330f729Sjoerg bool IsTemplate = false;
3407*e038c9c4Sjoerg bool IsStringTemplatePack = false;
3408*e038c9c4Sjoerg bool IsCooked = false;
34097330f729Sjoerg
34107330f729Sjoerg if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
34117330f729Sjoerg if (FD->getNumParams() == 1 &&
34127330f729Sjoerg FD->getParamDecl(0)->getType()->getAs<PointerType>())
34137330f729Sjoerg IsRaw = true;
34147330f729Sjoerg else if (FD->getNumParams() == ArgTys.size()) {
3415*e038c9c4Sjoerg IsCooked = true;
34167330f729Sjoerg for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
34177330f729Sjoerg QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
34187330f729Sjoerg if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3419*e038c9c4Sjoerg IsCooked = false;
34207330f729Sjoerg break;
34217330f729Sjoerg }
34227330f729Sjoerg }
34237330f729Sjoerg }
34247330f729Sjoerg }
34257330f729Sjoerg if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
34267330f729Sjoerg TemplateParameterList *Params = FD->getTemplateParameters();
3427*e038c9c4Sjoerg if (Params->size() == 1) {
34287330f729Sjoerg IsTemplate = true;
3429*e038c9c4Sjoerg if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3430*e038c9c4Sjoerg // Implied but not stated: user-defined integer and floating literals
3431*e038c9c4Sjoerg // only ever use numeric literal operator templates, not templates
3432*e038c9c4Sjoerg // taking a parameter of class type.
3433*e038c9c4Sjoerg F.erase();
3434*e038c9c4Sjoerg continue;
34357330f729Sjoerg }
34367330f729Sjoerg
3437*e038c9c4Sjoerg // A string literal template is only considered if the string literal
3438*e038c9c4Sjoerg // is a well-formed template argument for the template parameter.
3439*e038c9c4Sjoerg if (StringLit) {
3440*e038c9c4Sjoerg SFINAETrap Trap(*this);
3441*e038c9c4Sjoerg SmallVector<TemplateArgument, 1> Checked;
3442*e038c9c4Sjoerg TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3443*e038c9c4Sjoerg if (CheckTemplateArgument(Params->getParam(0), Arg, FD,
3444*e038c9c4Sjoerg R.getNameLoc(), R.getNameLoc(), 0,
3445*e038c9c4Sjoerg Checked) ||
3446*e038c9c4Sjoerg Trap.hasErrorOccurred())
3447*e038c9c4Sjoerg IsTemplate = false;
3448*e038c9c4Sjoerg }
3449*e038c9c4Sjoerg } else {
3450*e038c9c4Sjoerg IsStringTemplatePack = true;
3451*e038c9c4Sjoerg }
3452*e038c9c4Sjoerg }
3453*e038c9c4Sjoerg
3454*e038c9c4Sjoerg if (AllowTemplate && StringLit && IsTemplate) {
3455*e038c9c4Sjoerg FoundTemplate = true;
34567330f729Sjoerg AllowRaw = false;
3457*e038c9c4Sjoerg AllowCooked = false;
3458*e038c9c4Sjoerg AllowStringTemplatePack = false;
3459*e038c9c4Sjoerg if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3460*e038c9c4Sjoerg F.restart();
3461*e038c9c4Sjoerg FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3462*e038c9c4Sjoerg }
3463*e038c9c4Sjoerg } else if (AllowCooked && IsCooked) {
3464*e038c9c4Sjoerg FoundCooked = true;
3465*e038c9c4Sjoerg AllowRaw = false;
3466*e038c9c4Sjoerg AllowTemplate = StringLit;
3467*e038c9c4Sjoerg AllowStringTemplatePack = false;
3468*e038c9c4Sjoerg if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
34697330f729Sjoerg // Go through again and remove the raw and template decls we've
34707330f729Sjoerg // already found.
34717330f729Sjoerg F.restart();
3472*e038c9c4Sjoerg FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
34737330f729Sjoerg }
34747330f729Sjoerg } else if (AllowRaw && IsRaw) {
34757330f729Sjoerg FoundRaw = true;
34767330f729Sjoerg } else if (AllowTemplate && IsTemplate) {
34777330f729Sjoerg FoundTemplate = true;
3478*e038c9c4Sjoerg } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3479*e038c9c4Sjoerg FoundStringTemplatePack = true;
34807330f729Sjoerg } else {
34817330f729Sjoerg F.erase();
34827330f729Sjoerg }
34837330f729Sjoerg }
34847330f729Sjoerg
34857330f729Sjoerg F.done();
34867330f729Sjoerg
3487*e038c9c4Sjoerg // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3488*e038c9c4Sjoerg // form for string literal operator templates.
3489*e038c9c4Sjoerg if (StringLit && FoundTemplate)
3490*e038c9c4Sjoerg return LOLR_Template;
3491*e038c9c4Sjoerg
34927330f729Sjoerg // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
34937330f729Sjoerg // parameter type, that is used in preference to a raw literal operator
34947330f729Sjoerg // or literal operator template.
3495*e038c9c4Sjoerg if (FoundCooked)
34967330f729Sjoerg return LOLR_Cooked;
34977330f729Sjoerg
34987330f729Sjoerg // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
34997330f729Sjoerg // operator template, but not both.
35007330f729Sjoerg if (FoundRaw && FoundTemplate) {
35017330f729Sjoerg Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
35027330f729Sjoerg for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
35037330f729Sjoerg NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
35047330f729Sjoerg return LOLR_Error;
35057330f729Sjoerg }
35067330f729Sjoerg
35077330f729Sjoerg if (FoundRaw)
35087330f729Sjoerg return LOLR_Raw;
35097330f729Sjoerg
35107330f729Sjoerg if (FoundTemplate)
35117330f729Sjoerg return LOLR_Template;
35127330f729Sjoerg
3513*e038c9c4Sjoerg if (FoundStringTemplatePack)
3514*e038c9c4Sjoerg return LOLR_StringTemplatePack;
35157330f729Sjoerg
35167330f729Sjoerg // Didn't find anything we could use.
35177330f729Sjoerg if (DiagnoseMissing) {
35187330f729Sjoerg Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
35197330f729Sjoerg << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
35207330f729Sjoerg << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3521*e038c9c4Sjoerg << (AllowTemplate || AllowStringTemplatePack);
35227330f729Sjoerg return LOLR_Error;
35237330f729Sjoerg }
35247330f729Sjoerg
35257330f729Sjoerg return LOLR_ErrorNoDiagnostic;
35267330f729Sjoerg }
35277330f729Sjoerg
insert(NamedDecl * New)35287330f729Sjoerg void ADLResult::insert(NamedDecl *New) {
35297330f729Sjoerg NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
35307330f729Sjoerg
35317330f729Sjoerg // If we haven't yet seen a decl for this key, or the last decl
35327330f729Sjoerg // was exactly this one, we're done.
35337330f729Sjoerg if (Old == nullptr || Old == New) {
35347330f729Sjoerg Old = New;
35357330f729Sjoerg return;
35367330f729Sjoerg }
35377330f729Sjoerg
35387330f729Sjoerg // Otherwise, decide which is a more recent redeclaration.
35397330f729Sjoerg FunctionDecl *OldFD = Old->getAsFunction();
35407330f729Sjoerg FunctionDecl *NewFD = New->getAsFunction();
35417330f729Sjoerg
35427330f729Sjoerg FunctionDecl *Cursor = NewFD;
35437330f729Sjoerg while (true) {
35447330f729Sjoerg Cursor = Cursor->getPreviousDecl();
35457330f729Sjoerg
35467330f729Sjoerg // If we got to the end without finding OldFD, OldFD is the newer
35477330f729Sjoerg // declaration; leave things as they are.
35487330f729Sjoerg if (!Cursor) return;
35497330f729Sjoerg
35507330f729Sjoerg // If we do find OldFD, then NewFD is newer.
35517330f729Sjoerg if (Cursor == OldFD) break;
35527330f729Sjoerg
35537330f729Sjoerg // Otherwise, keep looking.
35547330f729Sjoerg }
35557330f729Sjoerg
35567330f729Sjoerg Old = New;
35577330f729Sjoerg }
35587330f729Sjoerg
ArgumentDependentLookup(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,ADLResult & Result)35597330f729Sjoerg void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
35607330f729Sjoerg ArrayRef<Expr *> Args, ADLResult &Result) {
35617330f729Sjoerg // Find all of the associated namespaces and classes based on the
35627330f729Sjoerg // arguments we have.
35637330f729Sjoerg AssociatedNamespaceSet AssociatedNamespaces;
35647330f729Sjoerg AssociatedClassSet AssociatedClasses;
35657330f729Sjoerg FindAssociatedClassesAndNamespaces(Loc, Args,
35667330f729Sjoerg AssociatedNamespaces,
35677330f729Sjoerg AssociatedClasses);
35687330f729Sjoerg
35697330f729Sjoerg // C++ [basic.lookup.argdep]p3:
35707330f729Sjoerg // Let X be the lookup set produced by unqualified lookup (3.4.1)
35717330f729Sjoerg // and let Y be the lookup set produced by argument dependent
35727330f729Sjoerg // lookup (defined as follows). If X contains [...] then Y is
35737330f729Sjoerg // empty. Otherwise Y is the set of declarations found in the
35747330f729Sjoerg // namespaces associated with the argument types as described
35757330f729Sjoerg // below. The set of declarations found by the lookup of the name
35767330f729Sjoerg // is the union of X and Y.
35777330f729Sjoerg //
35787330f729Sjoerg // Here, we compute Y and add its members to the overloaded
35797330f729Sjoerg // candidate set.
35807330f729Sjoerg for (auto *NS : AssociatedNamespaces) {
35817330f729Sjoerg // When considering an associated namespace, the lookup is the
35827330f729Sjoerg // same as the lookup performed when the associated namespace is
35837330f729Sjoerg // used as a qualifier (3.4.3.2) except that:
35847330f729Sjoerg //
35857330f729Sjoerg // -- Any using-directives in the associated namespace are
35867330f729Sjoerg // ignored.
35877330f729Sjoerg //
35887330f729Sjoerg // -- Any namespace-scope friend functions declared in
35897330f729Sjoerg // associated classes are visible within their respective
35907330f729Sjoerg // namespaces even if they are not visible during an ordinary
35917330f729Sjoerg // lookup (11.4).
35927330f729Sjoerg DeclContext::lookup_result R = NS->lookup(Name);
35937330f729Sjoerg for (auto *D : R) {
35947330f729Sjoerg auto *Underlying = D;
35957330f729Sjoerg if (auto *USD = dyn_cast<UsingShadowDecl>(D))
35967330f729Sjoerg Underlying = USD->getTargetDecl();
35977330f729Sjoerg
35987330f729Sjoerg if (!isa<FunctionDecl>(Underlying) &&
35997330f729Sjoerg !isa<FunctionTemplateDecl>(Underlying))
36007330f729Sjoerg continue;
36017330f729Sjoerg
36027330f729Sjoerg // The declaration is visible to argument-dependent lookup if either
36037330f729Sjoerg // it's ordinarily visible or declared as a friend in an associated
36047330f729Sjoerg // class.
36057330f729Sjoerg bool Visible = false;
36067330f729Sjoerg for (D = D->getMostRecentDecl(); D;
36077330f729Sjoerg D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
36087330f729Sjoerg if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
36097330f729Sjoerg if (isVisible(D)) {
36107330f729Sjoerg Visible = true;
36117330f729Sjoerg break;
36127330f729Sjoerg }
36137330f729Sjoerg } else if (D->getFriendObjectKind()) {
36147330f729Sjoerg auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
36157330f729Sjoerg if (AssociatedClasses.count(RD) && isVisible(D)) {
36167330f729Sjoerg Visible = true;
36177330f729Sjoerg break;
36187330f729Sjoerg }
36197330f729Sjoerg }
36207330f729Sjoerg }
36217330f729Sjoerg
36227330f729Sjoerg // FIXME: Preserve D as the FoundDecl.
36237330f729Sjoerg if (Visible)
36247330f729Sjoerg Result.insert(Underlying);
36257330f729Sjoerg }
36267330f729Sjoerg }
36277330f729Sjoerg }
36287330f729Sjoerg
36297330f729Sjoerg //----------------------------------------------------------------------------
36307330f729Sjoerg // Search for all visible declarations.
36317330f729Sjoerg //----------------------------------------------------------------------------
~VisibleDeclConsumer()36327330f729Sjoerg VisibleDeclConsumer::~VisibleDeclConsumer() { }
36337330f729Sjoerg
includeHiddenDecls() const36347330f729Sjoerg bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
36357330f729Sjoerg
36367330f729Sjoerg namespace {
36377330f729Sjoerg
36387330f729Sjoerg class ShadowContextRAII;
36397330f729Sjoerg
36407330f729Sjoerg class VisibleDeclsRecord {
36417330f729Sjoerg public:
36427330f729Sjoerg /// An entry in the shadow map, which is optimized to store a
36437330f729Sjoerg /// single declaration (the common case) but can also store a list
36447330f729Sjoerg /// of declarations.
36457330f729Sjoerg typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
36467330f729Sjoerg
36477330f729Sjoerg private:
36487330f729Sjoerg /// A mapping from declaration names to the declarations that have
36497330f729Sjoerg /// this name within a particular scope.
36507330f729Sjoerg typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
36517330f729Sjoerg
36527330f729Sjoerg /// A list of shadow maps, which is used to model name hiding.
36537330f729Sjoerg std::list<ShadowMap> ShadowMaps;
36547330f729Sjoerg
36557330f729Sjoerg /// The declaration contexts we have already visited.
36567330f729Sjoerg llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
36577330f729Sjoerg
36587330f729Sjoerg friend class ShadowContextRAII;
36597330f729Sjoerg
36607330f729Sjoerg public:
36617330f729Sjoerg /// Determine whether we have already visited this context
36627330f729Sjoerg /// (and, if not, note that we are going to visit that context now).
visitedContext(DeclContext * Ctx)36637330f729Sjoerg bool visitedContext(DeclContext *Ctx) {
36647330f729Sjoerg return !VisitedContexts.insert(Ctx).second;
36657330f729Sjoerg }
36667330f729Sjoerg
alreadyVisitedContext(DeclContext * Ctx)36677330f729Sjoerg bool alreadyVisitedContext(DeclContext *Ctx) {
36687330f729Sjoerg return VisitedContexts.count(Ctx);
36697330f729Sjoerg }
36707330f729Sjoerg
36717330f729Sjoerg /// Determine whether the given declaration is hidden in the
36727330f729Sjoerg /// current scope.
36737330f729Sjoerg ///
36747330f729Sjoerg /// \returns the declaration that hides the given declaration, or
36757330f729Sjoerg /// NULL if no such declaration exists.
36767330f729Sjoerg NamedDecl *checkHidden(NamedDecl *ND);
36777330f729Sjoerg
36787330f729Sjoerg /// Add a declaration to the current shadow map.
add(NamedDecl * ND)36797330f729Sjoerg void add(NamedDecl *ND) {
36807330f729Sjoerg ShadowMaps.back()[ND->getDeclName()].push_back(ND);
36817330f729Sjoerg }
36827330f729Sjoerg };
36837330f729Sjoerg
36847330f729Sjoerg /// RAII object that records when we've entered a shadow context.
36857330f729Sjoerg class ShadowContextRAII {
36867330f729Sjoerg VisibleDeclsRecord &Visible;
36877330f729Sjoerg
36887330f729Sjoerg typedef VisibleDeclsRecord::ShadowMap ShadowMap;
36897330f729Sjoerg
36907330f729Sjoerg public:
ShadowContextRAII(VisibleDeclsRecord & Visible)36917330f729Sjoerg ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
36927330f729Sjoerg Visible.ShadowMaps.emplace_back();
36937330f729Sjoerg }
36947330f729Sjoerg
~ShadowContextRAII()36957330f729Sjoerg ~ShadowContextRAII() {
36967330f729Sjoerg Visible.ShadowMaps.pop_back();
36977330f729Sjoerg }
36987330f729Sjoerg };
36997330f729Sjoerg
37007330f729Sjoerg } // end anonymous namespace
37017330f729Sjoerg
checkHidden(NamedDecl * ND)37027330f729Sjoerg NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
37037330f729Sjoerg unsigned IDNS = ND->getIdentifierNamespace();
37047330f729Sjoerg std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
37057330f729Sjoerg for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
37067330f729Sjoerg SM != SMEnd; ++SM) {
37077330f729Sjoerg ShadowMap::iterator Pos = SM->find(ND->getDeclName());
37087330f729Sjoerg if (Pos == SM->end())
37097330f729Sjoerg continue;
37107330f729Sjoerg
37117330f729Sjoerg for (auto *D : Pos->second) {
37127330f729Sjoerg // A tag declaration does not hide a non-tag declaration.
37137330f729Sjoerg if (D->hasTagIdentifierNamespace() &&
37147330f729Sjoerg (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
37157330f729Sjoerg Decl::IDNS_ObjCProtocol)))
37167330f729Sjoerg continue;
37177330f729Sjoerg
37187330f729Sjoerg // Protocols are in distinct namespaces from everything else.
37197330f729Sjoerg if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
37207330f729Sjoerg || (IDNS & Decl::IDNS_ObjCProtocol)) &&
37217330f729Sjoerg D->getIdentifierNamespace() != IDNS)
37227330f729Sjoerg continue;
37237330f729Sjoerg
37247330f729Sjoerg // Functions and function templates in the same scope overload
37257330f729Sjoerg // rather than hide. FIXME: Look for hiding based on function
37267330f729Sjoerg // signatures!
37277330f729Sjoerg if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
37287330f729Sjoerg ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
37297330f729Sjoerg SM == ShadowMaps.rbegin())
37307330f729Sjoerg continue;
37317330f729Sjoerg
37327330f729Sjoerg // A shadow declaration that's created by a resolved using declaration
37337330f729Sjoerg // is not hidden by the same using declaration.
37347330f729Sjoerg if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
37357330f729Sjoerg cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
37367330f729Sjoerg continue;
37377330f729Sjoerg
37387330f729Sjoerg // We've found a declaration that hides this one.
37397330f729Sjoerg return D;
37407330f729Sjoerg }
37417330f729Sjoerg }
37427330f729Sjoerg
37437330f729Sjoerg return nullptr;
37447330f729Sjoerg }
37457330f729Sjoerg
37467330f729Sjoerg namespace {
37477330f729Sjoerg class LookupVisibleHelper {
37487330f729Sjoerg public:
LookupVisibleHelper(VisibleDeclConsumer & Consumer,bool IncludeDependentBases,bool LoadExternal)37497330f729Sjoerg LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
37507330f729Sjoerg bool LoadExternal)
37517330f729Sjoerg : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
37527330f729Sjoerg LoadExternal(LoadExternal) {}
37537330f729Sjoerg
lookupVisibleDecls(Sema & SemaRef,Scope * S,Sema::LookupNameKind Kind,bool IncludeGlobalScope)37547330f729Sjoerg void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
37557330f729Sjoerg bool IncludeGlobalScope) {
37567330f729Sjoerg // Determine the set of using directives available during
37577330f729Sjoerg // unqualified name lookup.
37587330f729Sjoerg Scope *Initial = S;
37597330f729Sjoerg UnqualUsingDirectiveSet UDirs(SemaRef);
37607330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus) {
37617330f729Sjoerg // Find the first namespace or translation-unit scope.
37627330f729Sjoerg while (S && !isNamespaceOrTranslationUnitScope(S))
37637330f729Sjoerg S = S->getParent();
37647330f729Sjoerg
37657330f729Sjoerg UDirs.visitScopeChain(Initial, S);
37667330f729Sjoerg }
37677330f729Sjoerg UDirs.done();
37687330f729Sjoerg
37697330f729Sjoerg // Look for visible declarations.
37707330f729Sjoerg LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
37717330f729Sjoerg Result.setAllowHidden(Consumer.includeHiddenDecls());
37727330f729Sjoerg if (!IncludeGlobalScope)
37737330f729Sjoerg Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
37747330f729Sjoerg ShadowContextRAII Shadow(Visited);
37757330f729Sjoerg lookupInScope(Initial, Result, UDirs);
37767330f729Sjoerg }
37777330f729Sjoerg
lookupVisibleDecls(Sema & SemaRef,DeclContext * Ctx,Sema::LookupNameKind Kind,bool IncludeGlobalScope)37787330f729Sjoerg void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
37797330f729Sjoerg Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
37807330f729Sjoerg LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
37817330f729Sjoerg Result.setAllowHidden(Consumer.includeHiddenDecls());
37827330f729Sjoerg if (!IncludeGlobalScope)
37837330f729Sjoerg Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
37847330f729Sjoerg
37857330f729Sjoerg ShadowContextRAII Shadow(Visited);
37867330f729Sjoerg lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
37877330f729Sjoerg /*InBaseClass=*/false);
37887330f729Sjoerg }
37897330f729Sjoerg
37907330f729Sjoerg private:
lookupInDeclContext(DeclContext * Ctx,LookupResult & Result,bool QualifiedNameLookup,bool InBaseClass)37917330f729Sjoerg void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
37927330f729Sjoerg bool QualifiedNameLookup, bool InBaseClass) {
37937330f729Sjoerg if (!Ctx)
37947330f729Sjoerg return;
37957330f729Sjoerg
37967330f729Sjoerg // Make sure we don't visit the same context twice.
37977330f729Sjoerg if (Visited.visitedContext(Ctx->getPrimaryContext()))
37987330f729Sjoerg return;
37997330f729Sjoerg
38007330f729Sjoerg Consumer.EnteredContext(Ctx);
38017330f729Sjoerg
38027330f729Sjoerg // Outside C++, lookup results for the TU live on identifiers.
38037330f729Sjoerg if (isa<TranslationUnitDecl>(Ctx) &&
38047330f729Sjoerg !Result.getSema().getLangOpts().CPlusPlus) {
38057330f729Sjoerg auto &S = Result.getSema();
38067330f729Sjoerg auto &Idents = S.Context.Idents;
38077330f729Sjoerg
38087330f729Sjoerg // Ensure all external identifiers are in the identifier table.
38097330f729Sjoerg if (LoadExternal)
38107330f729Sjoerg if (IdentifierInfoLookup *External =
38117330f729Sjoerg Idents.getExternalIdentifierLookup()) {
38127330f729Sjoerg std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
38137330f729Sjoerg for (StringRef Name = Iter->Next(); !Name.empty();
38147330f729Sjoerg Name = Iter->Next())
38157330f729Sjoerg Idents.get(Name);
38167330f729Sjoerg }
38177330f729Sjoerg
38187330f729Sjoerg // Walk all lookup results in the TU for each identifier.
38197330f729Sjoerg for (const auto &Ident : Idents) {
38207330f729Sjoerg for (auto I = S.IdResolver.begin(Ident.getValue()),
38217330f729Sjoerg E = S.IdResolver.end();
38227330f729Sjoerg I != E; ++I) {
38237330f729Sjoerg if (S.IdResolver.isDeclInScope(*I, Ctx)) {
38247330f729Sjoerg if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
38257330f729Sjoerg Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
38267330f729Sjoerg Visited.add(ND);
38277330f729Sjoerg }
38287330f729Sjoerg }
38297330f729Sjoerg }
38307330f729Sjoerg }
38317330f729Sjoerg
38327330f729Sjoerg return;
38337330f729Sjoerg }
38347330f729Sjoerg
38357330f729Sjoerg if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
38367330f729Sjoerg Result.getSema().ForceDeclarationOfImplicitMembers(Class);
38377330f729Sjoerg
38387330f729Sjoerg // We sometimes skip loading namespace-level results (they tend to be huge).
38397330f729Sjoerg bool Load = LoadExternal ||
38407330f729Sjoerg !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
38417330f729Sjoerg // Enumerate all of the results in this context.
38427330f729Sjoerg for (DeclContextLookupResult R :
38437330f729Sjoerg Load ? Ctx->lookups()
38447330f729Sjoerg : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
38457330f729Sjoerg for (auto *D : R) {
38467330f729Sjoerg if (auto *ND = Result.getAcceptableDecl(D)) {
38477330f729Sjoerg Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
38487330f729Sjoerg Visited.add(ND);
38497330f729Sjoerg }
38507330f729Sjoerg }
38517330f729Sjoerg }
38527330f729Sjoerg
38537330f729Sjoerg // Traverse using directives for qualified name lookup.
38547330f729Sjoerg if (QualifiedNameLookup) {
38557330f729Sjoerg ShadowContextRAII Shadow(Visited);
38567330f729Sjoerg for (auto I : Ctx->using_directives()) {
38577330f729Sjoerg if (!Result.getSema().isVisible(I))
38587330f729Sjoerg continue;
38597330f729Sjoerg lookupInDeclContext(I->getNominatedNamespace(), Result,
38607330f729Sjoerg QualifiedNameLookup, InBaseClass);
38617330f729Sjoerg }
38627330f729Sjoerg }
38637330f729Sjoerg
38647330f729Sjoerg // Traverse the contexts of inherited C++ classes.
38657330f729Sjoerg if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
38667330f729Sjoerg if (!Record->hasDefinition())
38677330f729Sjoerg return;
38687330f729Sjoerg
38697330f729Sjoerg for (const auto &B : Record->bases()) {
38707330f729Sjoerg QualType BaseType = B.getType();
38717330f729Sjoerg
38727330f729Sjoerg RecordDecl *RD;
38737330f729Sjoerg if (BaseType->isDependentType()) {
38747330f729Sjoerg if (!IncludeDependentBases) {
38757330f729Sjoerg // Don't look into dependent bases, because name lookup can't look
38767330f729Sjoerg // there anyway.
38777330f729Sjoerg continue;
38787330f729Sjoerg }
38797330f729Sjoerg const auto *TST = BaseType->getAs<TemplateSpecializationType>();
38807330f729Sjoerg if (!TST)
38817330f729Sjoerg continue;
38827330f729Sjoerg TemplateName TN = TST->getTemplateName();
38837330f729Sjoerg const auto *TD =
38847330f729Sjoerg dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
38857330f729Sjoerg if (!TD)
38867330f729Sjoerg continue;
38877330f729Sjoerg RD = TD->getTemplatedDecl();
38887330f729Sjoerg } else {
38897330f729Sjoerg const auto *Record = BaseType->getAs<RecordType>();
38907330f729Sjoerg if (!Record)
38917330f729Sjoerg continue;
38927330f729Sjoerg RD = Record->getDecl();
38937330f729Sjoerg }
38947330f729Sjoerg
38957330f729Sjoerg // FIXME: It would be nice to be able to determine whether referencing
38967330f729Sjoerg // a particular member would be ambiguous. For example, given
38977330f729Sjoerg //
38987330f729Sjoerg // struct A { int member; };
38997330f729Sjoerg // struct B { int member; };
39007330f729Sjoerg // struct C : A, B { };
39017330f729Sjoerg //
39027330f729Sjoerg // void f(C *c) { c->### }
39037330f729Sjoerg //
39047330f729Sjoerg // accessing 'member' would result in an ambiguity. However, we
39057330f729Sjoerg // could be smart enough to qualify the member with the base
39067330f729Sjoerg // class, e.g.,
39077330f729Sjoerg //
39087330f729Sjoerg // c->B::member
39097330f729Sjoerg //
39107330f729Sjoerg // or
39117330f729Sjoerg //
39127330f729Sjoerg // c->A::member
39137330f729Sjoerg
39147330f729Sjoerg // Find results in this base class (and its bases).
39157330f729Sjoerg ShadowContextRAII Shadow(Visited);
39167330f729Sjoerg lookupInDeclContext(RD, Result, QualifiedNameLookup,
39177330f729Sjoerg /*InBaseClass=*/true);
39187330f729Sjoerg }
39197330f729Sjoerg }
39207330f729Sjoerg
39217330f729Sjoerg // Traverse the contexts of Objective-C classes.
39227330f729Sjoerg if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
39237330f729Sjoerg // Traverse categories.
39247330f729Sjoerg for (auto *Cat : IFace->visible_categories()) {
39257330f729Sjoerg ShadowContextRAII Shadow(Visited);
39267330f729Sjoerg lookupInDeclContext(Cat, Result, QualifiedNameLookup,
39277330f729Sjoerg /*InBaseClass=*/false);
39287330f729Sjoerg }
39297330f729Sjoerg
39307330f729Sjoerg // Traverse protocols.
39317330f729Sjoerg for (auto *I : IFace->all_referenced_protocols()) {
39327330f729Sjoerg ShadowContextRAII Shadow(Visited);
39337330f729Sjoerg lookupInDeclContext(I, Result, QualifiedNameLookup,
39347330f729Sjoerg /*InBaseClass=*/false);
39357330f729Sjoerg }
39367330f729Sjoerg
39377330f729Sjoerg // Traverse the superclass.
39387330f729Sjoerg if (IFace->getSuperClass()) {
39397330f729Sjoerg ShadowContextRAII Shadow(Visited);
39407330f729Sjoerg lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
39417330f729Sjoerg /*InBaseClass=*/true);
39427330f729Sjoerg }
39437330f729Sjoerg
39447330f729Sjoerg // If there is an implementation, traverse it. We do this to find
39457330f729Sjoerg // synthesized ivars.
39467330f729Sjoerg if (IFace->getImplementation()) {
39477330f729Sjoerg ShadowContextRAII Shadow(Visited);
39487330f729Sjoerg lookupInDeclContext(IFace->getImplementation(), Result,
39497330f729Sjoerg QualifiedNameLookup, InBaseClass);
39507330f729Sjoerg }
39517330f729Sjoerg } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
39527330f729Sjoerg for (auto *I : Protocol->protocols()) {
39537330f729Sjoerg ShadowContextRAII Shadow(Visited);
39547330f729Sjoerg lookupInDeclContext(I, Result, QualifiedNameLookup,
39557330f729Sjoerg /*InBaseClass=*/false);
39567330f729Sjoerg }
39577330f729Sjoerg } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
39587330f729Sjoerg for (auto *I : Category->protocols()) {
39597330f729Sjoerg ShadowContextRAII Shadow(Visited);
39607330f729Sjoerg lookupInDeclContext(I, Result, QualifiedNameLookup,
39617330f729Sjoerg /*InBaseClass=*/false);
39627330f729Sjoerg }
39637330f729Sjoerg
39647330f729Sjoerg // If there is an implementation, traverse it.
39657330f729Sjoerg if (Category->getImplementation()) {
39667330f729Sjoerg ShadowContextRAII Shadow(Visited);
39677330f729Sjoerg lookupInDeclContext(Category->getImplementation(), Result,
39687330f729Sjoerg QualifiedNameLookup, /*InBaseClass=*/true);
39697330f729Sjoerg }
39707330f729Sjoerg }
39717330f729Sjoerg }
39727330f729Sjoerg
lookupInScope(Scope * S,LookupResult & Result,UnqualUsingDirectiveSet & UDirs)39737330f729Sjoerg void lookupInScope(Scope *S, LookupResult &Result,
39747330f729Sjoerg UnqualUsingDirectiveSet &UDirs) {
39757330f729Sjoerg // No clients run in this mode and it's not supported. Please add tests and
39767330f729Sjoerg // remove the assertion if you start relying on it.
39777330f729Sjoerg assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
39787330f729Sjoerg
39797330f729Sjoerg if (!S)
39807330f729Sjoerg return;
39817330f729Sjoerg
39827330f729Sjoerg if (!S->getEntity() ||
39837330f729Sjoerg (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
39847330f729Sjoerg (S->getEntity())->isFunctionOrMethod()) {
39857330f729Sjoerg FindLocalExternScope FindLocals(Result);
39867330f729Sjoerg // Walk through the declarations in this Scope. The consumer might add new
39877330f729Sjoerg // decls to the scope as part of deserialization, so make a copy first.
39887330f729Sjoerg SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
39897330f729Sjoerg for (Decl *D : ScopeDecls) {
39907330f729Sjoerg if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
39917330f729Sjoerg if ((ND = Result.getAcceptableDecl(ND))) {
39927330f729Sjoerg Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
39937330f729Sjoerg Visited.add(ND);
39947330f729Sjoerg }
39957330f729Sjoerg }
39967330f729Sjoerg }
39977330f729Sjoerg
3998*e038c9c4Sjoerg DeclContext *Entity = S->getLookupEntity();
3999*e038c9c4Sjoerg if (Entity) {
40007330f729Sjoerg // Look into this scope's declaration context, along with any of its
40017330f729Sjoerg // parent lookup contexts (e.g., enclosing classes), up to the point
40027330f729Sjoerg // where we hit the context stored in the next outer scope.
4003*e038c9c4Sjoerg DeclContext *OuterCtx = findOuterContext(S);
40047330f729Sjoerg
40057330f729Sjoerg for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
40067330f729Sjoerg Ctx = Ctx->getLookupParent()) {
40077330f729Sjoerg if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
40087330f729Sjoerg if (Method->isInstanceMethod()) {
40097330f729Sjoerg // For instance methods, look for ivars in the method's interface.
40107330f729Sjoerg LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
40117330f729Sjoerg Result.getNameLoc(),
40127330f729Sjoerg Sema::LookupMemberName);
40137330f729Sjoerg if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
40147330f729Sjoerg lookupInDeclContext(IFace, IvarResult,
40157330f729Sjoerg /*QualifiedNameLookup=*/false,
40167330f729Sjoerg /*InBaseClass=*/false);
40177330f729Sjoerg }
40187330f729Sjoerg }
40197330f729Sjoerg
40207330f729Sjoerg // We've already performed all of the name lookup that we need
40217330f729Sjoerg // to for Objective-C methods; the next context will be the
40227330f729Sjoerg // outer scope.
40237330f729Sjoerg break;
40247330f729Sjoerg }
40257330f729Sjoerg
40267330f729Sjoerg if (Ctx->isFunctionOrMethod())
40277330f729Sjoerg continue;
40287330f729Sjoerg
40297330f729Sjoerg lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
40307330f729Sjoerg /*InBaseClass=*/false);
40317330f729Sjoerg }
40327330f729Sjoerg } else if (!S->getParent()) {
40337330f729Sjoerg // Look into the translation unit scope. We walk through the translation
40347330f729Sjoerg // unit's declaration context, because the Scope itself won't have all of
40357330f729Sjoerg // the declarations if we loaded a precompiled header.
40367330f729Sjoerg // FIXME: We would like the translation unit's Scope object to point to
40377330f729Sjoerg // the translation unit, so we don't need this special "if" branch.
40387330f729Sjoerg // However, doing so would force the normal C++ name-lookup code to look
40397330f729Sjoerg // into the translation unit decl when the IdentifierInfo chains would
40407330f729Sjoerg // suffice. Once we fix that problem (which is part of a more general
40417330f729Sjoerg // "don't look in DeclContexts unless we have to" optimization), we can
40427330f729Sjoerg // eliminate this.
40437330f729Sjoerg Entity = Result.getSema().Context.getTranslationUnitDecl();
40447330f729Sjoerg lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
40457330f729Sjoerg /*InBaseClass=*/false);
40467330f729Sjoerg }
40477330f729Sjoerg
40487330f729Sjoerg if (Entity) {
40497330f729Sjoerg // Lookup visible declarations in any namespaces found by using
40507330f729Sjoerg // directives.
40517330f729Sjoerg for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
40527330f729Sjoerg lookupInDeclContext(
40537330f729Sjoerg const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
40547330f729Sjoerg /*QualifiedNameLookup=*/false,
40557330f729Sjoerg /*InBaseClass=*/false);
40567330f729Sjoerg }
40577330f729Sjoerg
40587330f729Sjoerg // Lookup names in the parent scope.
40597330f729Sjoerg ShadowContextRAII Shadow(Visited);
40607330f729Sjoerg lookupInScope(S->getParent(), Result, UDirs);
40617330f729Sjoerg }
40627330f729Sjoerg
40637330f729Sjoerg private:
40647330f729Sjoerg VisibleDeclsRecord Visited;
40657330f729Sjoerg VisibleDeclConsumer &Consumer;
40667330f729Sjoerg bool IncludeDependentBases;
40677330f729Sjoerg bool LoadExternal;
40687330f729Sjoerg };
40697330f729Sjoerg } // namespace
40707330f729Sjoerg
LookupVisibleDecls(Scope * S,LookupNameKind Kind,VisibleDeclConsumer & Consumer,bool IncludeGlobalScope,bool LoadExternal)40717330f729Sjoerg void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
40727330f729Sjoerg VisibleDeclConsumer &Consumer,
40737330f729Sjoerg bool IncludeGlobalScope, bool LoadExternal) {
40747330f729Sjoerg LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
40757330f729Sjoerg LoadExternal);
40767330f729Sjoerg H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
40777330f729Sjoerg }
40787330f729Sjoerg
LookupVisibleDecls(DeclContext * Ctx,LookupNameKind Kind,VisibleDeclConsumer & Consumer,bool IncludeGlobalScope,bool IncludeDependentBases,bool LoadExternal)40797330f729Sjoerg void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
40807330f729Sjoerg VisibleDeclConsumer &Consumer,
40817330f729Sjoerg bool IncludeGlobalScope,
40827330f729Sjoerg bool IncludeDependentBases, bool LoadExternal) {
40837330f729Sjoerg LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
40847330f729Sjoerg H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
40857330f729Sjoerg }
40867330f729Sjoerg
40877330f729Sjoerg /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
40887330f729Sjoerg /// If GnuLabelLoc is a valid source location, then this is a definition
40897330f729Sjoerg /// of an __label__ label name, otherwise it is a normal label definition
40907330f729Sjoerg /// or use.
LookupOrCreateLabel(IdentifierInfo * II,SourceLocation Loc,SourceLocation GnuLabelLoc)40917330f729Sjoerg LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
40927330f729Sjoerg SourceLocation GnuLabelLoc) {
40937330f729Sjoerg // Do a lookup to see if we have a label with this name already.
40947330f729Sjoerg NamedDecl *Res = nullptr;
40957330f729Sjoerg
40967330f729Sjoerg if (GnuLabelLoc.isValid()) {
40977330f729Sjoerg // Local label definitions always shadow existing labels.
40987330f729Sjoerg Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
40997330f729Sjoerg Scope *S = CurScope;
41007330f729Sjoerg PushOnScopeChains(Res, S, true);
41017330f729Sjoerg return cast<LabelDecl>(Res);
41027330f729Sjoerg }
41037330f729Sjoerg
41047330f729Sjoerg // Not a GNU local label.
41057330f729Sjoerg Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
41067330f729Sjoerg // If we found a label, check to see if it is in the same context as us.
41077330f729Sjoerg // When in a Block, we don't want to reuse a label in an enclosing function.
41087330f729Sjoerg if (Res && Res->getDeclContext() != CurContext)
41097330f729Sjoerg Res = nullptr;
41107330f729Sjoerg if (!Res) {
41117330f729Sjoerg // If not forward referenced or defined already, create the backing decl.
41127330f729Sjoerg Res = LabelDecl::Create(Context, CurContext, Loc, II);
41137330f729Sjoerg Scope *S = CurScope->getFnParent();
41147330f729Sjoerg assert(S && "Not in a function?");
41157330f729Sjoerg PushOnScopeChains(Res, S, true);
41167330f729Sjoerg }
41177330f729Sjoerg return cast<LabelDecl>(Res);
41187330f729Sjoerg }
41197330f729Sjoerg
41207330f729Sjoerg //===----------------------------------------------------------------------===//
41217330f729Sjoerg // Typo correction
41227330f729Sjoerg //===----------------------------------------------------------------------===//
41237330f729Sjoerg
isCandidateViable(CorrectionCandidateCallback & CCC,TypoCorrection & Candidate)41247330f729Sjoerg static bool isCandidateViable(CorrectionCandidateCallback &CCC,
41257330f729Sjoerg TypoCorrection &Candidate) {
41267330f729Sjoerg Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
41277330f729Sjoerg return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
41287330f729Sjoerg }
41297330f729Sjoerg
41307330f729Sjoerg static void LookupPotentialTypoResult(Sema &SemaRef,
41317330f729Sjoerg LookupResult &Res,
41327330f729Sjoerg IdentifierInfo *Name,
41337330f729Sjoerg Scope *S, CXXScopeSpec *SS,
41347330f729Sjoerg DeclContext *MemberContext,
41357330f729Sjoerg bool EnteringContext,
41367330f729Sjoerg bool isObjCIvarLookup,
41377330f729Sjoerg bool FindHidden);
41387330f729Sjoerg
41397330f729Sjoerg /// Check whether the declarations found for a typo correction are
41407330f729Sjoerg /// visible. Set the correction's RequiresImport flag to true if none of the
41417330f729Sjoerg /// declarations are visible, false otherwise.
checkCorrectionVisibility(Sema & SemaRef,TypoCorrection & TC)41427330f729Sjoerg static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
41437330f729Sjoerg TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
41447330f729Sjoerg
41457330f729Sjoerg for (/**/; DI != DE; ++DI)
41467330f729Sjoerg if (!LookupResult::isVisible(SemaRef, *DI))
41477330f729Sjoerg break;
41487330f729Sjoerg // No filtering needed if all decls are visible.
41497330f729Sjoerg if (DI == DE) {
41507330f729Sjoerg TC.setRequiresImport(false);
41517330f729Sjoerg return;
41527330f729Sjoerg }
41537330f729Sjoerg
41547330f729Sjoerg llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
41557330f729Sjoerg bool AnyVisibleDecls = !NewDecls.empty();
41567330f729Sjoerg
41577330f729Sjoerg for (/**/; DI != DE; ++DI) {
41587330f729Sjoerg if (LookupResult::isVisible(SemaRef, *DI)) {
41597330f729Sjoerg if (!AnyVisibleDecls) {
41607330f729Sjoerg // Found a visible decl, discard all hidden ones.
41617330f729Sjoerg AnyVisibleDecls = true;
41627330f729Sjoerg NewDecls.clear();
41637330f729Sjoerg }
41647330f729Sjoerg NewDecls.push_back(*DI);
41657330f729Sjoerg } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
41667330f729Sjoerg NewDecls.push_back(*DI);
41677330f729Sjoerg }
41687330f729Sjoerg
41697330f729Sjoerg if (NewDecls.empty())
41707330f729Sjoerg TC = TypoCorrection();
41717330f729Sjoerg else {
41727330f729Sjoerg TC.setCorrectionDecls(NewDecls);
41737330f729Sjoerg TC.setRequiresImport(!AnyVisibleDecls);
41747330f729Sjoerg }
41757330f729Sjoerg }
41767330f729Sjoerg
41777330f729Sjoerg // Fill the supplied vector with the IdentifierInfo pointers for each piece of
41787330f729Sjoerg // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
41797330f729Sjoerg // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
getNestedNameSpecifierIdentifiers(NestedNameSpecifier * NNS,SmallVectorImpl<const IdentifierInfo * > & Identifiers)41807330f729Sjoerg static void getNestedNameSpecifierIdentifiers(
41817330f729Sjoerg NestedNameSpecifier *NNS,
41827330f729Sjoerg SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
41837330f729Sjoerg if (NestedNameSpecifier *Prefix = NNS->getPrefix())
41847330f729Sjoerg getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
41857330f729Sjoerg else
41867330f729Sjoerg Identifiers.clear();
41877330f729Sjoerg
41887330f729Sjoerg const IdentifierInfo *II = nullptr;
41897330f729Sjoerg
41907330f729Sjoerg switch (NNS->getKind()) {
41917330f729Sjoerg case NestedNameSpecifier::Identifier:
41927330f729Sjoerg II = NNS->getAsIdentifier();
41937330f729Sjoerg break;
41947330f729Sjoerg
41957330f729Sjoerg case NestedNameSpecifier::Namespace:
41967330f729Sjoerg if (NNS->getAsNamespace()->isAnonymousNamespace())
41977330f729Sjoerg return;
41987330f729Sjoerg II = NNS->getAsNamespace()->getIdentifier();
41997330f729Sjoerg break;
42007330f729Sjoerg
42017330f729Sjoerg case NestedNameSpecifier::NamespaceAlias:
42027330f729Sjoerg II = NNS->getAsNamespaceAlias()->getIdentifier();
42037330f729Sjoerg break;
42047330f729Sjoerg
42057330f729Sjoerg case NestedNameSpecifier::TypeSpecWithTemplate:
42067330f729Sjoerg case NestedNameSpecifier::TypeSpec:
42077330f729Sjoerg II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
42087330f729Sjoerg break;
42097330f729Sjoerg
42107330f729Sjoerg case NestedNameSpecifier::Global:
42117330f729Sjoerg case NestedNameSpecifier::Super:
42127330f729Sjoerg return;
42137330f729Sjoerg }
42147330f729Sjoerg
42157330f729Sjoerg if (II)
42167330f729Sjoerg Identifiers.push_back(II);
42177330f729Sjoerg }
42187330f729Sjoerg
FoundDecl(NamedDecl * ND,NamedDecl * Hiding,DeclContext * Ctx,bool InBaseClass)42197330f729Sjoerg void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
42207330f729Sjoerg DeclContext *Ctx, bool InBaseClass) {
42217330f729Sjoerg // Don't consider hidden names for typo correction.
42227330f729Sjoerg if (Hiding)
42237330f729Sjoerg return;
42247330f729Sjoerg
42257330f729Sjoerg // Only consider entities with identifiers for names, ignoring
42267330f729Sjoerg // special names (constructors, overloaded operators, selectors,
42277330f729Sjoerg // etc.).
42287330f729Sjoerg IdentifierInfo *Name = ND->getIdentifier();
42297330f729Sjoerg if (!Name)
42307330f729Sjoerg return;
42317330f729Sjoerg
42327330f729Sjoerg // Only consider visible declarations and declarations from modules with
42337330f729Sjoerg // names that exactly match.
42347330f729Sjoerg if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
42357330f729Sjoerg return;
42367330f729Sjoerg
42377330f729Sjoerg FoundName(Name->getName());
42387330f729Sjoerg }
42397330f729Sjoerg
FoundName(StringRef Name)42407330f729Sjoerg void TypoCorrectionConsumer::FoundName(StringRef Name) {
42417330f729Sjoerg // Compute the edit distance between the typo and the name of this
42427330f729Sjoerg // entity, and add the identifier to the list of results.
42437330f729Sjoerg addName(Name, nullptr);
42447330f729Sjoerg }
42457330f729Sjoerg
addKeywordResult(StringRef Keyword)42467330f729Sjoerg void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
42477330f729Sjoerg // Compute the edit distance between the typo and this keyword,
42487330f729Sjoerg // and add the keyword to the list of results.
42497330f729Sjoerg addName(Keyword, nullptr, nullptr, true);
42507330f729Sjoerg }
42517330f729Sjoerg
addName(StringRef Name,NamedDecl * ND,NestedNameSpecifier * NNS,bool isKeyword)42527330f729Sjoerg void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
42537330f729Sjoerg NestedNameSpecifier *NNS, bool isKeyword) {
42547330f729Sjoerg // Use a simple length-based heuristic to determine the minimum possible
42557330f729Sjoerg // edit distance. If the minimum isn't good enough, bail out early.
42567330f729Sjoerg StringRef TypoStr = Typo->getName();
42577330f729Sjoerg unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
42587330f729Sjoerg if (MinED && TypoStr.size() / MinED < 3)
42597330f729Sjoerg return;
42607330f729Sjoerg
42617330f729Sjoerg // Compute an upper bound on the allowable edit distance, so that the
42627330f729Sjoerg // edit-distance algorithm can short-circuit.
42637330f729Sjoerg unsigned UpperBound = (TypoStr.size() + 2) / 3;
42647330f729Sjoerg unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
42657330f729Sjoerg if (ED > UpperBound) return;
42667330f729Sjoerg
42677330f729Sjoerg TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
42687330f729Sjoerg if (isKeyword) TC.makeKeyword();
42697330f729Sjoerg TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
42707330f729Sjoerg addCorrection(TC);
42717330f729Sjoerg }
42727330f729Sjoerg
42737330f729Sjoerg static const unsigned MaxTypoDistanceResultSets = 5;
42747330f729Sjoerg
addCorrection(TypoCorrection Correction)42757330f729Sjoerg void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
42767330f729Sjoerg StringRef TypoStr = Typo->getName();
42777330f729Sjoerg StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
42787330f729Sjoerg
42797330f729Sjoerg // For very short typos, ignore potential corrections that have a different
42807330f729Sjoerg // base identifier from the typo or which have a normalized edit distance
42817330f729Sjoerg // longer than the typo itself.
42827330f729Sjoerg if (TypoStr.size() < 3 &&
42837330f729Sjoerg (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
42847330f729Sjoerg return;
42857330f729Sjoerg
42867330f729Sjoerg // If the correction is resolved but is not viable, ignore it.
42877330f729Sjoerg if (Correction.isResolved()) {
42887330f729Sjoerg checkCorrectionVisibility(SemaRef, Correction);
42897330f729Sjoerg if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
42907330f729Sjoerg return;
42917330f729Sjoerg }
42927330f729Sjoerg
42937330f729Sjoerg TypoResultList &CList =
42947330f729Sjoerg CorrectionResults[Correction.getEditDistance(false)][Name];
42957330f729Sjoerg
42967330f729Sjoerg if (!CList.empty() && !CList.back().isResolved())
42977330f729Sjoerg CList.pop_back();
42987330f729Sjoerg if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
42997330f729Sjoerg std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
43007330f729Sjoerg for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
43017330f729Sjoerg RI != RIEnd; ++RI) {
43027330f729Sjoerg // If the Correction refers to a decl already in the result list,
43037330f729Sjoerg // replace the existing result if the string representation of Correction
43047330f729Sjoerg // comes before the current result alphabetically, then stop as there is
43057330f729Sjoerg // nothing more to be done to add Correction to the candidate set.
43067330f729Sjoerg if (RI->getCorrectionDecl() == NewND) {
43077330f729Sjoerg if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
43087330f729Sjoerg *RI = Correction;
43097330f729Sjoerg return;
43107330f729Sjoerg }
43117330f729Sjoerg }
43127330f729Sjoerg }
43137330f729Sjoerg if (CList.empty() || Correction.isResolved())
43147330f729Sjoerg CList.push_back(Correction);
43157330f729Sjoerg
43167330f729Sjoerg while (CorrectionResults.size() > MaxTypoDistanceResultSets)
43177330f729Sjoerg CorrectionResults.erase(std::prev(CorrectionResults.end()));
43187330f729Sjoerg }
43197330f729Sjoerg
addNamespaces(const llvm::MapVector<NamespaceDecl *,bool> & KnownNamespaces)43207330f729Sjoerg void TypoCorrectionConsumer::addNamespaces(
43217330f729Sjoerg const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
43227330f729Sjoerg SearchNamespaces = true;
43237330f729Sjoerg
43247330f729Sjoerg for (auto KNPair : KnownNamespaces)
43257330f729Sjoerg Namespaces.addNameSpecifier(KNPair.first);
43267330f729Sjoerg
43277330f729Sjoerg bool SSIsTemplate = false;
43287330f729Sjoerg if (NestedNameSpecifier *NNS =
43297330f729Sjoerg (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
43307330f729Sjoerg if (const Type *T = NNS->getAsType())
43317330f729Sjoerg SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
43327330f729Sjoerg }
43337330f729Sjoerg // Do not transform this into an iterator-based loop. The loop body can
43347330f729Sjoerg // trigger the creation of further types (through lazy deserialization) and
43357330f729Sjoerg // invalid iterators into this list.
43367330f729Sjoerg auto &Types = SemaRef.getASTContext().getTypes();
43377330f729Sjoerg for (unsigned I = 0; I != Types.size(); ++I) {
43387330f729Sjoerg const auto *TI = Types[I];
43397330f729Sjoerg if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
43407330f729Sjoerg CD = CD->getCanonicalDecl();
43417330f729Sjoerg if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
43427330f729Sjoerg !CD->isUnion() && CD->getIdentifier() &&
43437330f729Sjoerg (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
43447330f729Sjoerg (CD->isBeingDefined() || CD->isCompleteDefinition()))
43457330f729Sjoerg Namespaces.addNameSpecifier(CD);
43467330f729Sjoerg }
43477330f729Sjoerg }
43487330f729Sjoerg }
43497330f729Sjoerg
getNextCorrection()43507330f729Sjoerg const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
43517330f729Sjoerg if (++CurrentTCIndex < ValidatedCorrections.size())
43527330f729Sjoerg return ValidatedCorrections[CurrentTCIndex];
43537330f729Sjoerg
43547330f729Sjoerg CurrentTCIndex = ValidatedCorrections.size();
43557330f729Sjoerg while (!CorrectionResults.empty()) {
43567330f729Sjoerg auto DI = CorrectionResults.begin();
43577330f729Sjoerg if (DI->second.empty()) {
43587330f729Sjoerg CorrectionResults.erase(DI);
43597330f729Sjoerg continue;
43607330f729Sjoerg }
43617330f729Sjoerg
43627330f729Sjoerg auto RI = DI->second.begin();
43637330f729Sjoerg if (RI->second.empty()) {
43647330f729Sjoerg DI->second.erase(RI);
43657330f729Sjoerg performQualifiedLookups();
43667330f729Sjoerg continue;
43677330f729Sjoerg }
43687330f729Sjoerg
43697330f729Sjoerg TypoCorrection TC = RI->second.pop_back_val();
43707330f729Sjoerg if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
43717330f729Sjoerg ValidatedCorrections.push_back(TC);
43727330f729Sjoerg return ValidatedCorrections[CurrentTCIndex];
43737330f729Sjoerg }
43747330f729Sjoerg }
43757330f729Sjoerg return ValidatedCorrections[0]; // The empty correction.
43767330f729Sjoerg }
43777330f729Sjoerg
resolveCorrection(TypoCorrection & Candidate)43787330f729Sjoerg bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
43797330f729Sjoerg IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
43807330f729Sjoerg DeclContext *TempMemberContext = MemberContext;
43817330f729Sjoerg CXXScopeSpec *TempSS = SS.get();
43827330f729Sjoerg retry_lookup:
43837330f729Sjoerg LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
43847330f729Sjoerg EnteringContext,
43857330f729Sjoerg CorrectionValidator->IsObjCIvarLookup,
43867330f729Sjoerg Name == Typo && !Candidate.WillReplaceSpecifier());
43877330f729Sjoerg switch (Result.getResultKind()) {
43887330f729Sjoerg case LookupResult::NotFound:
43897330f729Sjoerg case LookupResult::NotFoundInCurrentInstantiation:
43907330f729Sjoerg case LookupResult::FoundUnresolvedValue:
43917330f729Sjoerg if (TempSS) {
43927330f729Sjoerg // Immediately retry the lookup without the given CXXScopeSpec
43937330f729Sjoerg TempSS = nullptr;
43947330f729Sjoerg Candidate.WillReplaceSpecifier(true);
43957330f729Sjoerg goto retry_lookup;
43967330f729Sjoerg }
43977330f729Sjoerg if (TempMemberContext) {
43987330f729Sjoerg if (SS && !TempSS)
43997330f729Sjoerg TempSS = SS.get();
44007330f729Sjoerg TempMemberContext = nullptr;
44017330f729Sjoerg goto retry_lookup;
44027330f729Sjoerg }
44037330f729Sjoerg if (SearchNamespaces)
44047330f729Sjoerg QualifiedResults.push_back(Candidate);
44057330f729Sjoerg break;
44067330f729Sjoerg
44077330f729Sjoerg case LookupResult::Ambiguous:
44087330f729Sjoerg // We don't deal with ambiguities.
44097330f729Sjoerg break;
44107330f729Sjoerg
44117330f729Sjoerg case LookupResult::Found:
44127330f729Sjoerg case LookupResult::FoundOverloaded:
44137330f729Sjoerg // Store all of the Decls for overloaded symbols
44147330f729Sjoerg for (auto *TRD : Result)
44157330f729Sjoerg Candidate.addCorrectionDecl(TRD);
44167330f729Sjoerg checkCorrectionVisibility(SemaRef, Candidate);
44177330f729Sjoerg if (!isCandidateViable(*CorrectionValidator, Candidate)) {
44187330f729Sjoerg if (SearchNamespaces)
44197330f729Sjoerg QualifiedResults.push_back(Candidate);
44207330f729Sjoerg break;
44217330f729Sjoerg }
44227330f729Sjoerg Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
44237330f729Sjoerg return true;
44247330f729Sjoerg }
44257330f729Sjoerg return false;
44267330f729Sjoerg }
44277330f729Sjoerg
performQualifiedLookups()44287330f729Sjoerg void TypoCorrectionConsumer::performQualifiedLookups() {
44297330f729Sjoerg unsigned TypoLen = Typo->getName().size();
44307330f729Sjoerg for (const TypoCorrection &QR : QualifiedResults) {
44317330f729Sjoerg for (const auto &NSI : Namespaces) {
44327330f729Sjoerg DeclContext *Ctx = NSI.DeclCtx;
44337330f729Sjoerg const Type *NSType = NSI.NameSpecifier->getAsType();
44347330f729Sjoerg
44357330f729Sjoerg // If the current NestedNameSpecifier refers to a class and the
44367330f729Sjoerg // current correction candidate is the name of that class, then skip
44377330f729Sjoerg // it as it is unlikely a qualified version of the class' constructor
44387330f729Sjoerg // is an appropriate correction.
44397330f729Sjoerg if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
44407330f729Sjoerg nullptr) {
44417330f729Sjoerg if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
44427330f729Sjoerg continue;
44437330f729Sjoerg }
44447330f729Sjoerg
44457330f729Sjoerg TypoCorrection TC(QR);
44467330f729Sjoerg TC.ClearCorrectionDecls();
44477330f729Sjoerg TC.setCorrectionSpecifier(NSI.NameSpecifier);
44487330f729Sjoerg TC.setQualifierDistance(NSI.EditDistance);
44497330f729Sjoerg TC.setCallbackDistance(0); // Reset the callback distance
44507330f729Sjoerg
44517330f729Sjoerg // If the current correction candidate and namespace combination are
44527330f729Sjoerg // too far away from the original typo based on the normalized edit
44537330f729Sjoerg // distance, then skip performing a qualified name lookup.
44547330f729Sjoerg unsigned TmpED = TC.getEditDistance(true);
44557330f729Sjoerg if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
44567330f729Sjoerg TypoLen / TmpED < 3)
44577330f729Sjoerg continue;
44587330f729Sjoerg
44597330f729Sjoerg Result.clear();
44607330f729Sjoerg Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
44617330f729Sjoerg if (!SemaRef.LookupQualifiedName(Result, Ctx))
44627330f729Sjoerg continue;
44637330f729Sjoerg
44647330f729Sjoerg // Any corrections added below will be validated in subsequent
44657330f729Sjoerg // iterations of the main while() loop over the Consumer's contents.
44667330f729Sjoerg switch (Result.getResultKind()) {
44677330f729Sjoerg case LookupResult::Found:
44687330f729Sjoerg case LookupResult::FoundOverloaded: {
44697330f729Sjoerg if (SS && SS->isValid()) {
44707330f729Sjoerg std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
44717330f729Sjoerg std::string OldQualified;
44727330f729Sjoerg llvm::raw_string_ostream OldOStream(OldQualified);
44737330f729Sjoerg SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
44747330f729Sjoerg OldOStream << Typo->getName();
44757330f729Sjoerg // If correction candidate would be an identical written qualified
44767330f729Sjoerg // identifier, then the existing CXXScopeSpec probably included a
44777330f729Sjoerg // typedef that didn't get accounted for properly.
44787330f729Sjoerg if (OldOStream.str() == NewQualified)
44797330f729Sjoerg break;
44807330f729Sjoerg }
44817330f729Sjoerg for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
44827330f729Sjoerg TRD != TRDEnd; ++TRD) {
44837330f729Sjoerg if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
44847330f729Sjoerg NSType ? NSType->getAsCXXRecordDecl()
44857330f729Sjoerg : nullptr,
44867330f729Sjoerg TRD.getPair()) == Sema::AR_accessible)
44877330f729Sjoerg TC.addCorrectionDecl(*TRD);
44887330f729Sjoerg }
44897330f729Sjoerg if (TC.isResolved()) {
44907330f729Sjoerg TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
44917330f729Sjoerg addCorrection(TC);
44927330f729Sjoerg }
44937330f729Sjoerg break;
44947330f729Sjoerg }
44957330f729Sjoerg case LookupResult::NotFound:
44967330f729Sjoerg case LookupResult::NotFoundInCurrentInstantiation:
44977330f729Sjoerg case LookupResult::Ambiguous:
44987330f729Sjoerg case LookupResult::FoundUnresolvedValue:
44997330f729Sjoerg break;
45007330f729Sjoerg }
45017330f729Sjoerg }
45027330f729Sjoerg }
45037330f729Sjoerg QualifiedResults.clear();
45047330f729Sjoerg }
45057330f729Sjoerg
NamespaceSpecifierSet(ASTContext & Context,DeclContext * CurContext,CXXScopeSpec * CurScopeSpec)45067330f729Sjoerg TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
45077330f729Sjoerg ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
45087330f729Sjoerg : Context(Context), CurContextChain(buildContextChain(CurContext)) {
45097330f729Sjoerg if (NestedNameSpecifier *NNS =
45107330f729Sjoerg CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
45117330f729Sjoerg llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
45127330f729Sjoerg NNS->print(SpecifierOStream, Context.getPrintingPolicy());
45137330f729Sjoerg
45147330f729Sjoerg getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
45157330f729Sjoerg }
45167330f729Sjoerg // Build the list of identifiers that would be used for an absolute
45177330f729Sjoerg // (from the global context) NestedNameSpecifier referring to the current
45187330f729Sjoerg // context.
45197330f729Sjoerg for (DeclContext *C : llvm::reverse(CurContextChain)) {
45207330f729Sjoerg if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
45217330f729Sjoerg CurContextIdentifiers.push_back(ND->getIdentifier());
45227330f729Sjoerg }
45237330f729Sjoerg
45247330f729Sjoerg // Add the global context as a NestedNameSpecifier
45257330f729Sjoerg SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
45267330f729Sjoerg NestedNameSpecifier::GlobalSpecifier(Context), 1};
45277330f729Sjoerg DistanceMap[1].push_back(SI);
45287330f729Sjoerg }
45297330f729Sjoerg
buildContextChain(DeclContext * Start)45307330f729Sjoerg auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
45317330f729Sjoerg DeclContext *Start) -> DeclContextList {
45327330f729Sjoerg assert(Start && "Building a context chain from a null context");
45337330f729Sjoerg DeclContextList Chain;
45347330f729Sjoerg for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
45357330f729Sjoerg DC = DC->getLookupParent()) {
45367330f729Sjoerg NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
45377330f729Sjoerg if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
45387330f729Sjoerg !(ND && ND->isAnonymousNamespace()))
45397330f729Sjoerg Chain.push_back(DC->getPrimaryContext());
45407330f729Sjoerg }
45417330f729Sjoerg return Chain;
45427330f729Sjoerg }
45437330f729Sjoerg
45447330f729Sjoerg unsigned
buildNestedNameSpecifier(DeclContextList & DeclChain,NestedNameSpecifier * & NNS)45457330f729Sjoerg TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
45467330f729Sjoerg DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
45477330f729Sjoerg unsigned NumSpecifiers = 0;
45487330f729Sjoerg for (DeclContext *C : llvm::reverse(DeclChain)) {
45497330f729Sjoerg if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
45507330f729Sjoerg NNS = NestedNameSpecifier::Create(Context, NNS, ND);
45517330f729Sjoerg ++NumSpecifiers;
45527330f729Sjoerg } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
45537330f729Sjoerg NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
45547330f729Sjoerg RD->getTypeForDecl());
45557330f729Sjoerg ++NumSpecifiers;
45567330f729Sjoerg }
45577330f729Sjoerg }
45587330f729Sjoerg return NumSpecifiers;
45597330f729Sjoerg }
45607330f729Sjoerg
addNameSpecifier(DeclContext * Ctx)45617330f729Sjoerg void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
45627330f729Sjoerg DeclContext *Ctx) {
45637330f729Sjoerg NestedNameSpecifier *NNS = nullptr;
45647330f729Sjoerg unsigned NumSpecifiers = 0;
45657330f729Sjoerg DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
45667330f729Sjoerg DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
45677330f729Sjoerg
45687330f729Sjoerg // Eliminate common elements from the two DeclContext chains.
45697330f729Sjoerg for (DeclContext *C : llvm::reverse(CurContextChain)) {
45707330f729Sjoerg if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
45717330f729Sjoerg break;
45727330f729Sjoerg NamespaceDeclChain.pop_back();
45737330f729Sjoerg }
45747330f729Sjoerg
45757330f729Sjoerg // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
45767330f729Sjoerg NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
45777330f729Sjoerg
45787330f729Sjoerg // Add an explicit leading '::' specifier if needed.
45797330f729Sjoerg if (NamespaceDeclChain.empty()) {
45807330f729Sjoerg // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
45817330f729Sjoerg NNS = NestedNameSpecifier::GlobalSpecifier(Context);
45827330f729Sjoerg NumSpecifiers =
45837330f729Sjoerg buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
45847330f729Sjoerg } else if (NamedDecl *ND =
45857330f729Sjoerg dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
45867330f729Sjoerg IdentifierInfo *Name = ND->getIdentifier();
45877330f729Sjoerg bool SameNameSpecifier = false;
45887330f729Sjoerg if (std::find(CurNameSpecifierIdentifiers.begin(),
45897330f729Sjoerg CurNameSpecifierIdentifiers.end(),
45907330f729Sjoerg Name) != CurNameSpecifierIdentifiers.end()) {
45917330f729Sjoerg std::string NewNameSpecifier;
45927330f729Sjoerg llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
45937330f729Sjoerg SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
45947330f729Sjoerg getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
45957330f729Sjoerg NNS->print(SpecifierOStream, Context.getPrintingPolicy());
45967330f729Sjoerg SpecifierOStream.flush();
45977330f729Sjoerg SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
45987330f729Sjoerg }
45997330f729Sjoerg if (SameNameSpecifier || llvm::find(CurContextIdentifiers, Name) !=
46007330f729Sjoerg CurContextIdentifiers.end()) {
46017330f729Sjoerg // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
46027330f729Sjoerg NNS = NestedNameSpecifier::GlobalSpecifier(Context);
46037330f729Sjoerg NumSpecifiers =
46047330f729Sjoerg buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
46057330f729Sjoerg }
46067330f729Sjoerg }
46077330f729Sjoerg
46087330f729Sjoerg // If the built NestedNameSpecifier would be replacing an existing
46097330f729Sjoerg // NestedNameSpecifier, use the number of component identifiers that
46107330f729Sjoerg // would need to be changed as the edit distance instead of the number
46117330f729Sjoerg // of components in the built NestedNameSpecifier.
46127330f729Sjoerg if (NNS && !CurNameSpecifierIdentifiers.empty()) {
46137330f729Sjoerg SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
46147330f729Sjoerg getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
46157330f729Sjoerg NumSpecifiers = llvm::ComputeEditDistance(
46167330f729Sjoerg llvm::makeArrayRef(CurNameSpecifierIdentifiers),
46177330f729Sjoerg llvm::makeArrayRef(NewNameSpecifierIdentifiers));
46187330f729Sjoerg }
46197330f729Sjoerg
46207330f729Sjoerg SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
46217330f729Sjoerg DistanceMap[NumSpecifiers].push_back(SI);
46227330f729Sjoerg }
46237330f729Sjoerg
46247330f729Sjoerg /// Perform name lookup for a possible result for typo correction.
LookupPotentialTypoResult(Sema & SemaRef,LookupResult & Res,IdentifierInfo * Name,Scope * S,CXXScopeSpec * SS,DeclContext * MemberContext,bool EnteringContext,bool isObjCIvarLookup,bool FindHidden)46257330f729Sjoerg static void LookupPotentialTypoResult(Sema &SemaRef,
46267330f729Sjoerg LookupResult &Res,
46277330f729Sjoerg IdentifierInfo *Name,
46287330f729Sjoerg Scope *S, CXXScopeSpec *SS,
46297330f729Sjoerg DeclContext *MemberContext,
46307330f729Sjoerg bool EnteringContext,
46317330f729Sjoerg bool isObjCIvarLookup,
46327330f729Sjoerg bool FindHidden) {
46337330f729Sjoerg Res.suppressDiagnostics();
46347330f729Sjoerg Res.clear();
46357330f729Sjoerg Res.setLookupName(Name);
46367330f729Sjoerg Res.setAllowHidden(FindHidden);
46377330f729Sjoerg if (MemberContext) {
46387330f729Sjoerg if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
46397330f729Sjoerg if (isObjCIvarLookup) {
46407330f729Sjoerg if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
46417330f729Sjoerg Res.addDecl(Ivar);
46427330f729Sjoerg Res.resolveKind();
46437330f729Sjoerg return;
46447330f729Sjoerg }
46457330f729Sjoerg }
46467330f729Sjoerg
46477330f729Sjoerg if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
46487330f729Sjoerg Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
46497330f729Sjoerg Res.addDecl(Prop);
46507330f729Sjoerg Res.resolveKind();
46517330f729Sjoerg return;
46527330f729Sjoerg }
46537330f729Sjoerg }
46547330f729Sjoerg
46557330f729Sjoerg SemaRef.LookupQualifiedName(Res, MemberContext);
46567330f729Sjoerg return;
46577330f729Sjoerg }
46587330f729Sjoerg
46597330f729Sjoerg SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
46607330f729Sjoerg EnteringContext);
46617330f729Sjoerg
46627330f729Sjoerg // Fake ivar lookup; this should really be part of
46637330f729Sjoerg // LookupParsedName.
46647330f729Sjoerg if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
46657330f729Sjoerg if (Method->isInstanceMethod() && Method->getClassInterface() &&
46667330f729Sjoerg (Res.empty() ||
46677330f729Sjoerg (Res.isSingleResult() &&
46687330f729Sjoerg Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
46697330f729Sjoerg if (ObjCIvarDecl *IV
46707330f729Sjoerg = Method->getClassInterface()->lookupInstanceVariable(Name)) {
46717330f729Sjoerg Res.addDecl(IV);
46727330f729Sjoerg Res.resolveKind();
46737330f729Sjoerg }
46747330f729Sjoerg }
46757330f729Sjoerg }
46767330f729Sjoerg }
46777330f729Sjoerg
46787330f729Sjoerg /// Add keywords to the consumer as possible typo corrections.
AddKeywordsToConsumer(Sema & SemaRef,TypoCorrectionConsumer & Consumer,Scope * S,CorrectionCandidateCallback & CCC,bool AfterNestedNameSpecifier)46797330f729Sjoerg static void AddKeywordsToConsumer(Sema &SemaRef,
46807330f729Sjoerg TypoCorrectionConsumer &Consumer,
46817330f729Sjoerg Scope *S, CorrectionCandidateCallback &CCC,
46827330f729Sjoerg bool AfterNestedNameSpecifier) {
46837330f729Sjoerg if (AfterNestedNameSpecifier) {
46847330f729Sjoerg // For 'X::', we know exactly which keywords can appear next.
46857330f729Sjoerg Consumer.addKeywordResult("template");
46867330f729Sjoerg if (CCC.WantExpressionKeywords)
46877330f729Sjoerg Consumer.addKeywordResult("operator");
46887330f729Sjoerg return;
46897330f729Sjoerg }
46907330f729Sjoerg
46917330f729Sjoerg if (CCC.WantObjCSuper)
46927330f729Sjoerg Consumer.addKeywordResult("super");
46937330f729Sjoerg
46947330f729Sjoerg if (CCC.WantTypeSpecifiers) {
46957330f729Sjoerg // Add type-specifier keywords to the set of results.
46967330f729Sjoerg static const char *const CTypeSpecs[] = {
46977330f729Sjoerg "char", "const", "double", "enum", "float", "int", "long", "short",
46987330f729Sjoerg "signed", "struct", "union", "unsigned", "void", "volatile",
46997330f729Sjoerg "_Complex", "_Imaginary",
47007330f729Sjoerg // storage-specifiers as well
47017330f729Sjoerg "extern", "inline", "static", "typedef"
47027330f729Sjoerg };
47037330f729Sjoerg
47047330f729Sjoerg const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
47057330f729Sjoerg for (unsigned I = 0; I != NumCTypeSpecs; ++I)
47067330f729Sjoerg Consumer.addKeywordResult(CTypeSpecs[I]);
47077330f729Sjoerg
47087330f729Sjoerg if (SemaRef.getLangOpts().C99)
47097330f729Sjoerg Consumer.addKeywordResult("restrict");
47107330f729Sjoerg if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
47117330f729Sjoerg Consumer.addKeywordResult("bool");
47127330f729Sjoerg else if (SemaRef.getLangOpts().C99)
47137330f729Sjoerg Consumer.addKeywordResult("_Bool");
47147330f729Sjoerg
47157330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus) {
47167330f729Sjoerg Consumer.addKeywordResult("class");
47177330f729Sjoerg Consumer.addKeywordResult("typename");
47187330f729Sjoerg Consumer.addKeywordResult("wchar_t");
47197330f729Sjoerg
47207330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus11) {
47217330f729Sjoerg Consumer.addKeywordResult("char16_t");
47227330f729Sjoerg Consumer.addKeywordResult("char32_t");
47237330f729Sjoerg Consumer.addKeywordResult("constexpr");
47247330f729Sjoerg Consumer.addKeywordResult("decltype");
47257330f729Sjoerg Consumer.addKeywordResult("thread_local");
47267330f729Sjoerg }
47277330f729Sjoerg }
47287330f729Sjoerg
47297330f729Sjoerg if (SemaRef.getLangOpts().GNUKeywords)
47307330f729Sjoerg Consumer.addKeywordResult("typeof");
47317330f729Sjoerg } else if (CCC.WantFunctionLikeCasts) {
47327330f729Sjoerg static const char *const CastableTypeSpecs[] = {
47337330f729Sjoerg "char", "double", "float", "int", "long", "short",
47347330f729Sjoerg "signed", "unsigned", "void"
47357330f729Sjoerg };
47367330f729Sjoerg for (auto *kw : CastableTypeSpecs)
47377330f729Sjoerg Consumer.addKeywordResult(kw);
47387330f729Sjoerg }
47397330f729Sjoerg
47407330f729Sjoerg if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
47417330f729Sjoerg Consumer.addKeywordResult("const_cast");
47427330f729Sjoerg Consumer.addKeywordResult("dynamic_cast");
47437330f729Sjoerg Consumer.addKeywordResult("reinterpret_cast");
47447330f729Sjoerg Consumer.addKeywordResult("static_cast");
47457330f729Sjoerg }
47467330f729Sjoerg
47477330f729Sjoerg if (CCC.WantExpressionKeywords) {
47487330f729Sjoerg Consumer.addKeywordResult("sizeof");
47497330f729Sjoerg if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
47507330f729Sjoerg Consumer.addKeywordResult("false");
47517330f729Sjoerg Consumer.addKeywordResult("true");
47527330f729Sjoerg }
47537330f729Sjoerg
47547330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus) {
47557330f729Sjoerg static const char *const CXXExprs[] = {
47567330f729Sjoerg "delete", "new", "operator", "throw", "typeid"
47577330f729Sjoerg };
47587330f729Sjoerg const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
47597330f729Sjoerg for (unsigned I = 0; I != NumCXXExprs; ++I)
47607330f729Sjoerg Consumer.addKeywordResult(CXXExprs[I]);
47617330f729Sjoerg
47627330f729Sjoerg if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
47637330f729Sjoerg cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
47647330f729Sjoerg Consumer.addKeywordResult("this");
47657330f729Sjoerg
47667330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus11) {
47677330f729Sjoerg Consumer.addKeywordResult("alignof");
47687330f729Sjoerg Consumer.addKeywordResult("nullptr");
47697330f729Sjoerg }
47707330f729Sjoerg }
47717330f729Sjoerg
47727330f729Sjoerg if (SemaRef.getLangOpts().C11) {
47737330f729Sjoerg // FIXME: We should not suggest _Alignof if the alignof macro
47747330f729Sjoerg // is present.
47757330f729Sjoerg Consumer.addKeywordResult("_Alignof");
47767330f729Sjoerg }
47777330f729Sjoerg }
47787330f729Sjoerg
47797330f729Sjoerg if (CCC.WantRemainingKeywords) {
47807330f729Sjoerg if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
47817330f729Sjoerg // Statements.
47827330f729Sjoerg static const char *const CStmts[] = {
47837330f729Sjoerg "do", "else", "for", "goto", "if", "return", "switch", "while" };
47847330f729Sjoerg const unsigned NumCStmts = llvm::array_lengthof(CStmts);
47857330f729Sjoerg for (unsigned I = 0; I != NumCStmts; ++I)
47867330f729Sjoerg Consumer.addKeywordResult(CStmts[I]);
47877330f729Sjoerg
47887330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus) {
47897330f729Sjoerg Consumer.addKeywordResult("catch");
47907330f729Sjoerg Consumer.addKeywordResult("try");
47917330f729Sjoerg }
47927330f729Sjoerg
47937330f729Sjoerg if (S && S->getBreakParent())
47947330f729Sjoerg Consumer.addKeywordResult("break");
47957330f729Sjoerg
47967330f729Sjoerg if (S && S->getContinueParent())
47977330f729Sjoerg Consumer.addKeywordResult("continue");
47987330f729Sjoerg
47997330f729Sjoerg if (SemaRef.getCurFunction() &&
48007330f729Sjoerg !SemaRef.getCurFunction()->SwitchStack.empty()) {
48017330f729Sjoerg Consumer.addKeywordResult("case");
48027330f729Sjoerg Consumer.addKeywordResult("default");
48037330f729Sjoerg }
48047330f729Sjoerg } else {
48057330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus) {
48067330f729Sjoerg Consumer.addKeywordResult("namespace");
48077330f729Sjoerg Consumer.addKeywordResult("template");
48087330f729Sjoerg }
48097330f729Sjoerg
48107330f729Sjoerg if (S && S->isClassScope()) {
48117330f729Sjoerg Consumer.addKeywordResult("explicit");
48127330f729Sjoerg Consumer.addKeywordResult("friend");
48137330f729Sjoerg Consumer.addKeywordResult("mutable");
48147330f729Sjoerg Consumer.addKeywordResult("private");
48157330f729Sjoerg Consumer.addKeywordResult("protected");
48167330f729Sjoerg Consumer.addKeywordResult("public");
48177330f729Sjoerg Consumer.addKeywordResult("virtual");
48187330f729Sjoerg }
48197330f729Sjoerg }
48207330f729Sjoerg
48217330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus) {
48227330f729Sjoerg Consumer.addKeywordResult("using");
48237330f729Sjoerg
48247330f729Sjoerg if (SemaRef.getLangOpts().CPlusPlus11)
48257330f729Sjoerg Consumer.addKeywordResult("static_assert");
48267330f729Sjoerg }
48277330f729Sjoerg }
48287330f729Sjoerg }
48297330f729Sjoerg
makeTypoCorrectionConsumer(const DeclarationNameInfo & TypoName,Sema::LookupNameKind LookupKind,Scope * S,CXXScopeSpec * SS,CorrectionCandidateCallback & CCC,DeclContext * MemberContext,bool EnteringContext,const ObjCObjectPointerType * OPT,bool ErrorRecovery)48307330f729Sjoerg std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
48317330f729Sjoerg const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
48327330f729Sjoerg Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
48337330f729Sjoerg DeclContext *MemberContext, bool EnteringContext,
48347330f729Sjoerg const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
48357330f729Sjoerg
48367330f729Sjoerg if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
48377330f729Sjoerg DisableTypoCorrection)
48387330f729Sjoerg return nullptr;
48397330f729Sjoerg
48407330f729Sjoerg // In Microsoft mode, don't perform typo correction in a template member
48417330f729Sjoerg // function dependent context because it interferes with the "lookup into
48427330f729Sjoerg // dependent bases of class templates" feature.
48437330f729Sjoerg if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
48447330f729Sjoerg isa<CXXMethodDecl>(CurContext))
48457330f729Sjoerg return nullptr;
48467330f729Sjoerg
48477330f729Sjoerg // We only attempt to correct typos for identifiers.
48487330f729Sjoerg IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
48497330f729Sjoerg if (!Typo)
48507330f729Sjoerg return nullptr;
48517330f729Sjoerg
48527330f729Sjoerg // If the scope specifier itself was invalid, don't try to correct
48537330f729Sjoerg // typos.
48547330f729Sjoerg if (SS && SS->isInvalid())
48557330f729Sjoerg return nullptr;
48567330f729Sjoerg
48577330f729Sjoerg // Never try to correct typos during any kind of code synthesis.
48587330f729Sjoerg if (!CodeSynthesisContexts.empty())
48597330f729Sjoerg return nullptr;
48607330f729Sjoerg
48617330f729Sjoerg // Don't try to correct 'super'.
48627330f729Sjoerg if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
48637330f729Sjoerg return nullptr;
48647330f729Sjoerg
48657330f729Sjoerg // Abort if typo correction already failed for this specific typo.
48667330f729Sjoerg IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
48677330f729Sjoerg if (locs != TypoCorrectionFailures.end() &&
48687330f729Sjoerg locs->second.count(TypoName.getLoc()))
48697330f729Sjoerg return nullptr;
48707330f729Sjoerg
48717330f729Sjoerg // Don't try to correct the identifier "vector" when in AltiVec mode.
48727330f729Sjoerg // TODO: Figure out why typo correction misbehaves in this case, fix it, and
48737330f729Sjoerg // remove this workaround.
48747330f729Sjoerg if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
48757330f729Sjoerg return nullptr;
48767330f729Sjoerg
48777330f729Sjoerg // Provide a stop gap for files that are just seriously broken. Trying
48787330f729Sjoerg // to correct all typos can turn into a HUGE performance penalty, causing
48797330f729Sjoerg // some files to take minutes to get rejected by the parser.
48807330f729Sjoerg unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
48817330f729Sjoerg if (Limit && TyposCorrected >= Limit)
48827330f729Sjoerg return nullptr;
48837330f729Sjoerg ++TyposCorrected;
48847330f729Sjoerg
48857330f729Sjoerg // If we're handling a missing symbol error, using modules, and the
48867330f729Sjoerg // special search all modules option is used, look for a missing import.
48877330f729Sjoerg if (ErrorRecovery && getLangOpts().Modules &&
48887330f729Sjoerg getLangOpts().ModulesSearchAll) {
48897330f729Sjoerg // The following has the side effect of loading the missing module.
48907330f729Sjoerg getModuleLoader().lookupMissingImports(Typo->getName(),
48917330f729Sjoerg TypoName.getBeginLoc());
48927330f729Sjoerg }
48937330f729Sjoerg
48947330f729Sjoerg // Extend the lifetime of the callback. We delayed this until here
48957330f729Sjoerg // to avoid allocations in the hot path (which is where no typo correction
48967330f729Sjoerg // occurs). Note that CorrectionCandidateCallback is polymorphic and
48977330f729Sjoerg // initially stack-allocated.
48987330f729Sjoerg std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
48997330f729Sjoerg auto Consumer = std::make_unique<TypoCorrectionConsumer>(
49007330f729Sjoerg *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
49017330f729Sjoerg EnteringContext);
49027330f729Sjoerg
49037330f729Sjoerg // Perform name lookup to find visible, similarly-named entities.
49047330f729Sjoerg bool IsUnqualifiedLookup = false;
49057330f729Sjoerg DeclContext *QualifiedDC = MemberContext;
49067330f729Sjoerg if (MemberContext) {
49077330f729Sjoerg LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
49087330f729Sjoerg
49097330f729Sjoerg // Look in qualified interfaces.
49107330f729Sjoerg if (OPT) {
49117330f729Sjoerg for (auto *I : OPT->quals())
49127330f729Sjoerg LookupVisibleDecls(I, LookupKind, *Consumer);
49137330f729Sjoerg }
49147330f729Sjoerg } else if (SS && SS->isSet()) {
49157330f729Sjoerg QualifiedDC = computeDeclContext(*SS, EnteringContext);
49167330f729Sjoerg if (!QualifiedDC)
49177330f729Sjoerg return nullptr;
49187330f729Sjoerg
49197330f729Sjoerg LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
49207330f729Sjoerg } else {
49217330f729Sjoerg IsUnqualifiedLookup = true;
49227330f729Sjoerg }
49237330f729Sjoerg
49247330f729Sjoerg // Determine whether we are going to search in the various namespaces for
49257330f729Sjoerg // corrections.
49267330f729Sjoerg bool SearchNamespaces
49277330f729Sjoerg = getLangOpts().CPlusPlus &&
49287330f729Sjoerg (IsUnqualifiedLookup || (SS && SS->isSet()));
49297330f729Sjoerg
49307330f729Sjoerg if (IsUnqualifiedLookup || SearchNamespaces) {
49317330f729Sjoerg // For unqualified lookup, look through all of the names that we have
49327330f729Sjoerg // seen in this translation unit.
49337330f729Sjoerg // FIXME: Re-add the ability to skip very unlikely potential corrections.
49347330f729Sjoerg for (const auto &I : Context.Idents)
49357330f729Sjoerg Consumer->FoundName(I.getKey());
49367330f729Sjoerg
49377330f729Sjoerg // Walk through identifiers in external identifier sources.
49387330f729Sjoerg // FIXME: Re-add the ability to skip very unlikely potential corrections.
49397330f729Sjoerg if (IdentifierInfoLookup *External
49407330f729Sjoerg = Context.Idents.getExternalIdentifierLookup()) {
49417330f729Sjoerg std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
49427330f729Sjoerg do {
49437330f729Sjoerg StringRef Name = Iter->Next();
49447330f729Sjoerg if (Name.empty())
49457330f729Sjoerg break;
49467330f729Sjoerg
49477330f729Sjoerg Consumer->FoundName(Name);
49487330f729Sjoerg } while (true);
49497330f729Sjoerg }
49507330f729Sjoerg }
49517330f729Sjoerg
49527330f729Sjoerg AddKeywordsToConsumer(*this, *Consumer, S,
49537330f729Sjoerg *Consumer->getCorrectionValidator(),
49547330f729Sjoerg SS && SS->isNotEmpty());
49557330f729Sjoerg
49567330f729Sjoerg // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
49577330f729Sjoerg // to search those namespaces.
49587330f729Sjoerg if (SearchNamespaces) {
49597330f729Sjoerg // Load any externally-known namespaces.
49607330f729Sjoerg if (ExternalSource && !LoadedExternalKnownNamespaces) {
49617330f729Sjoerg SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
49627330f729Sjoerg LoadedExternalKnownNamespaces = true;
49637330f729Sjoerg ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
49647330f729Sjoerg for (auto *N : ExternalKnownNamespaces)
49657330f729Sjoerg KnownNamespaces[N] = true;
49667330f729Sjoerg }
49677330f729Sjoerg
49687330f729Sjoerg Consumer->addNamespaces(KnownNamespaces);
49697330f729Sjoerg }
49707330f729Sjoerg
49717330f729Sjoerg return Consumer;
49727330f729Sjoerg }
49737330f729Sjoerg
49747330f729Sjoerg /// Try to "correct" a typo in the source code by finding
49757330f729Sjoerg /// visible declarations whose names are similar to the name that was
49767330f729Sjoerg /// present in the source code.
49777330f729Sjoerg ///
49787330f729Sjoerg /// \param TypoName the \c DeclarationNameInfo structure that contains
49797330f729Sjoerg /// the name that was present in the source code along with its location.
49807330f729Sjoerg ///
49817330f729Sjoerg /// \param LookupKind the name-lookup criteria used to search for the name.
49827330f729Sjoerg ///
49837330f729Sjoerg /// \param S the scope in which name lookup occurs.
49847330f729Sjoerg ///
49857330f729Sjoerg /// \param SS the nested-name-specifier that precedes the name we're
49867330f729Sjoerg /// looking for, if present.
49877330f729Sjoerg ///
49887330f729Sjoerg /// \param CCC A CorrectionCandidateCallback object that provides further
49897330f729Sjoerg /// validation of typo correction candidates. It also provides flags for
49907330f729Sjoerg /// determining the set of keywords permitted.
49917330f729Sjoerg ///
49927330f729Sjoerg /// \param MemberContext if non-NULL, the context in which to look for
49937330f729Sjoerg /// a member access expression.
49947330f729Sjoerg ///
49957330f729Sjoerg /// \param EnteringContext whether we're entering the context described by
49967330f729Sjoerg /// the nested-name-specifier SS.
49977330f729Sjoerg ///
49987330f729Sjoerg /// \param OPT when non-NULL, the search for visible declarations will
49997330f729Sjoerg /// also walk the protocols in the qualified interfaces of \p OPT.
50007330f729Sjoerg ///
50017330f729Sjoerg /// \returns a \c TypoCorrection containing the corrected name if the typo
50027330f729Sjoerg /// along with information such as the \c NamedDecl where the corrected name
50037330f729Sjoerg /// was declared, and any additional \c NestedNameSpecifier needed to access
50047330f729Sjoerg /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
CorrectTypo(const DeclarationNameInfo & TypoName,Sema::LookupNameKind LookupKind,Scope * S,CXXScopeSpec * SS,CorrectionCandidateCallback & CCC,CorrectTypoKind Mode,DeclContext * MemberContext,bool EnteringContext,const ObjCObjectPointerType * OPT,bool RecordFailure)50057330f729Sjoerg TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
50067330f729Sjoerg Sema::LookupNameKind LookupKind,
50077330f729Sjoerg Scope *S, CXXScopeSpec *SS,
50087330f729Sjoerg CorrectionCandidateCallback &CCC,
50097330f729Sjoerg CorrectTypoKind Mode,
50107330f729Sjoerg DeclContext *MemberContext,
50117330f729Sjoerg bool EnteringContext,
50127330f729Sjoerg const ObjCObjectPointerType *OPT,
50137330f729Sjoerg bool RecordFailure) {
50147330f729Sjoerg // Always let the ExternalSource have the first chance at correction, even
50157330f729Sjoerg // if we would otherwise have given up.
50167330f729Sjoerg if (ExternalSource) {
50177330f729Sjoerg if (TypoCorrection Correction =
50187330f729Sjoerg ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
50197330f729Sjoerg MemberContext, EnteringContext, OPT))
50207330f729Sjoerg return Correction;
50217330f729Sjoerg }
50227330f729Sjoerg
50237330f729Sjoerg // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
50247330f729Sjoerg // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
50257330f729Sjoerg // some instances of CTC_Unknown, while WantRemainingKeywords is true
50267330f729Sjoerg // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
50277330f729Sjoerg bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
50287330f729Sjoerg
50297330f729Sjoerg IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
50307330f729Sjoerg auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
50317330f729Sjoerg MemberContext, EnteringContext,
50327330f729Sjoerg OPT, Mode == CTK_ErrorRecovery);
50337330f729Sjoerg
50347330f729Sjoerg if (!Consumer)
50357330f729Sjoerg return TypoCorrection();
50367330f729Sjoerg
50377330f729Sjoerg // If we haven't found anything, we're done.
50387330f729Sjoerg if (Consumer->empty())
50397330f729Sjoerg return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
50407330f729Sjoerg
50417330f729Sjoerg // Make sure the best edit distance (prior to adding any namespace qualifiers)
50427330f729Sjoerg // is not more that about a third of the length of the typo's identifier.
50437330f729Sjoerg unsigned ED = Consumer->getBestEditDistance(true);
50447330f729Sjoerg unsigned TypoLen = Typo->getName().size();
50457330f729Sjoerg if (ED > 0 && TypoLen / ED < 3)
50467330f729Sjoerg return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
50477330f729Sjoerg
50487330f729Sjoerg TypoCorrection BestTC = Consumer->getNextCorrection();
50497330f729Sjoerg TypoCorrection SecondBestTC = Consumer->getNextCorrection();
50507330f729Sjoerg if (!BestTC)
50517330f729Sjoerg return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
50527330f729Sjoerg
50537330f729Sjoerg ED = BestTC.getEditDistance();
50547330f729Sjoerg
50557330f729Sjoerg if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
50567330f729Sjoerg // If this was an unqualified lookup and we believe the callback
50577330f729Sjoerg // object wouldn't have filtered out possible corrections, note
50587330f729Sjoerg // that no correction was found.
50597330f729Sjoerg return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
50607330f729Sjoerg }
50617330f729Sjoerg
50627330f729Sjoerg // If only a single name remains, return that result.
50637330f729Sjoerg if (!SecondBestTC ||
50647330f729Sjoerg SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
50657330f729Sjoerg const TypoCorrection &Result = BestTC;
50667330f729Sjoerg
50677330f729Sjoerg // Don't correct to a keyword that's the same as the typo; the keyword
50687330f729Sjoerg // wasn't actually in scope.
50697330f729Sjoerg if (ED == 0 && Result.isKeyword())
50707330f729Sjoerg return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
50717330f729Sjoerg
50727330f729Sjoerg TypoCorrection TC = Result;
50737330f729Sjoerg TC.setCorrectionRange(SS, TypoName);
50747330f729Sjoerg checkCorrectionVisibility(*this, TC);
50757330f729Sjoerg return TC;
50767330f729Sjoerg } else if (SecondBestTC && ObjCMessageReceiver) {
50777330f729Sjoerg // Prefer 'super' when we're completing in a message-receiver
50787330f729Sjoerg // context.
50797330f729Sjoerg
50807330f729Sjoerg if (BestTC.getCorrection().getAsString() != "super") {
50817330f729Sjoerg if (SecondBestTC.getCorrection().getAsString() == "super")
50827330f729Sjoerg BestTC = SecondBestTC;
50837330f729Sjoerg else if ((*Consumer)["super"].front().isKeyword())
50847330f729Sjoerg BestTC = (*Consumer)["super"].front();
50857330f729Sjoerg }
50867330f729Sjoerg // Don't correct to a keyword that's the same as the typo; the keyword
50877330f729Sjoerg // wasn't actually in scope.
50887330f729Sjoerg if (BestTC.getEditDistance() == 0 ||
50897330f729Sjoerg BestTC.getCorrection().getAsString() != "super")
50907330f729Sjoerg return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
50917330f729Sjoerg
50927330f729Sjoerg BestTC.setCorrectionRange(SS, TypoName);
50937330f729Sjoerg return BestTC;
50947330f729Sjoerg }
50957330f729Sjoerg
50967330f729Sjoerg // Record the failure's location if needed and return an empty correction. If
50977330f729Sjoerg // this was an unqualified lookup and we believe the callback object did not
50987330f729Sjoerg // filter out possible corrections, also cache the failure for the typo.
50997330f729Sjoerg return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
51007330f729Sjoerg }
51017330f729Sjoerg
51027330f729Sjoerg /// Try to "correct" a typo in the source code by finding
51037330f729Sjoerg /// visible declarations whose names are similar to the name that was
51047330f729Sjoerg /// present in the source code.
51057330f729Sjoerg ///
51067330f729Sjoerg /// \param TypoName the \c DeclarationNameInfo structure that contains
51077330f729Sjoerg /// the name that was present in the source code along with its location.
51087330f729Sjoerg ///
51097330f729Sjoerg /// \param LookupKind the name-lookup criteria used to search for the name.
51107330f729Sjoerg ///
51117330f729Sjoerg /// \param S the scope in which name lookup occurs.
51127330f729Sjoerg ///
51137330f729Sjoerg /// \param SS the nested-name-specifier that precedes the name we're
51147330f729Sjoerg /// looking for, if present.
51157330f729Sjoerg ///
51167330f729Sjoerg /// \param CCC A CorrectionCandidateCallback object that provides further
51177330f729Sjoerg /// validation of typo correction candidates. It also provides flags for
51187330f729Sjoerg /// determining the set of keywords permitted.
51197330f729Sjoerg ///
51207330f729Sjoerg /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
51217330f729Sjoerg /// diagnostics when the actual typo correction is attempted.
51227330f729Sjoerg ///
51237330f729Sjoerg /// \param TRC A TypoRecoveryCallback functor that will be used to build an
51247330f729Sjoerg /// Expr from a typo correction candidate.
51257330f729Sjoerg ///
51267330f729Sjoerg /// \param MemberContext if non-NULL, the context in which to look for
51277330f729Sjoerg /// a member access expression.
51287330f729Sjoerg ///
51297330f729Sjoerg /// \param EnteringContext whether we're entering the context described by
51307330f729Sjoerg /// the nested-name-specifier SS.
51317330f729Sjoerg ///
51327330f729Sjoerg /// \param OPT when non-NULL, the search for visible declarations will
51337330f729Sjoerg /// also walk the protocols in the qualified interfaces of \p OPT.
51347330f729Sjoerg ///
51357330f729Sjoerg /// \returns a new \c TypoExpr that will later be replaced in the AST with an
51367330f729Sjoerg /// Expr representing the result of performing typo correction, or nullptr if
51377330f729Sjoerg /// typo correction is not possible. If nullptr is returned, no diagnostics will
51387330f729Sjoerg /// be emitted and it is the responsibility of the caller to emit any that are
51397330f729Sjoerg /// needed.
CorrectTypoDelayed(const DeclarationNameInfo & TypoName,Sema::LookupNameKind LookupKind,Scope * S,CXXScopeSpec * SS,CorrectionCandidateCallback & CCC,TypoDiagnosticGenerator TDG,TypoRecoveryCallback TRC,CorrectTypoKind Mode,DeclContext * MemberContext,bool EnteringContext,const ObjCObjectPointerType * OPT)51407330f729Sjoerg TypoExpr *Sema::CorrectTypoDelayed(
51417330f729Sjoerg const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
51427330f729Sjoerg Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
51437330f729Sjoerg TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
51447330f729Sjoerg DeclContext *MemberContext, bool EnteringContext,
51457330f729Sjoerg const ObjCObjectPointerType *OPT) {
51467330f729Sjoerg auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
51477330f729Sjoerg MemberContext, EnteringContext,
51487330f729Sjoerg OPT, Mode == CTK_ErrorRecovery);
51497330f729Sjoerg
51507330f729Sjoerg // Give the external sema source a chance to correct the typo.
51517330f729Sjoerg TypoCorrection ExternalTypo;
51527330f729Sjoerg if (ExternalSource && Consumer) {
51537330f729Sjoerg ExternalTypo = ExternalSource->CorrectTypo(
51547330f729Sjoerg TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
51557330f729Sjoerg MemberContext, EnteringContext, OPT);
51567330f729Sjoerg if (ExternalTypo)
51577330f729Sjoerg Consumer->addCorrection(ExternalTypo);
51587330f729Sjoerg }
51597330f729Sjoerg
51607330f729Sjoerg if (!Consumer || Consumer->empty())
51617330f729Sjoerg return nullptr;
51627330f729Sjoerg
51637330f729Sjoerg // Make sure the best edit distance (prior to adding any namespace qualifiers)
51647330f729Sjoerg // is not more that about a third of the length of the typo's identifier.
51657330f729Sjoerg unsigned ED = Consumer->getBestEditDistance(true);
51667330f729Sjoerg IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
51677330f729Sjoerg if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
51687330f729Sjoerg return nullptr;
51697330f729Sjoerg ExprEvalContexts.back().NumTypos++;
5170*e038c9c4Sjoerg return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5171*e038c9c4Sjoerg TypoName.getLoc());
51727330f729Sjoerg }
51737330f729Sjoerg
addCorrectionDecl(NamedDecl * CDecl)51747330f729Sjoerg void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
51757330f729Sjoerg if (!CDecl) return;
51767330f729Sjoerg
51777330f729Sjoerg if (isKeyword())
51787330f729Sjoerg CorrectionDecls.clear();
51797330f729Sjoerg
51807330f729Sjoerg CorrectionDecls.push_back(CDecl);
51817330f729Sjoerg
51827330f729Sjoerg if (!CorrectionName)
51837330f729Sjoerg CorrectionName = CDecl->getDeclName();
51847330f729Sjoerg }
51857330f729Sjoerg
getAsString(const LangOptions & LO) const51867330f729Sjoerg std::string TypoCorrection::getAsString(const LangOptions &LO) const {
51877330f729Sjoerg if (CorrectionNameSpec) {
51887330f729Sjoerg std::string tmpBuffer;
51897330f729Sjoerg llvm::raw_string_ostream PrefixOStream(tmpBuffer);
51907330f729Sjoerg CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
51917330f729Sjoerg PrefixOStream << CorrectionName;
51927330f729Sjoerg return PrefixOStream.str();
51937330f729Sjoerg }
51947330f729Sjoerg
51957330f729Sjoerg return CorrectionName.getAsString();
51967330f729Sjoerg }
51977330f729Sjoerg
ValidateCandidate(const TypoCorrection & candidate)51987330f729Sjoerg bool CorrectionCandidateCallback::ValidateCandidate(
51997330f729Sjoerg const TypoCorrection &candidate) {
52007330f729Sjoerg if (!candidate.isResolved())
52017330f729Sjoerg return true;
52027330f729Sjoerg
52037330f729Sjoerg if (candidate.isKeyword())
52047330f729Sjoerg return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
52057330f729Sjoerg WantRemainingKeywords || WantObjCSuper;
52067330f729Sjoerg
52077330f729Sjoerg bool HasNonType = false;
52087330f729Sjoerg bool HasStaticMethod = false;
52097330f729Sjoerg bool HasNonStaticMethod = false;
52107330f729Sjoerg for (Decl *D : candidate) {
52117330f729Sjoerg if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
52127330f729Sjoerg D = FTD->getTemplatedDecl();
52137330f729Sjoerg if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
52147330f729Sjoerg if (Method->isStatic())
52157330f729Sjoerg HasStaticMethod = true;
52167330f729Sjoerg else
52177330f729Sjoerg HasNonStaticMethod = true;
52187330f729Sjoerg }
52197330f729Sjoerg if (!isa<TypeDecl>(D))
52207330f729Sjoerg HasNonType = true;
52217330f729Sjoerg }
52227330f729Sjoerg
52237330f729Sjoerg if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
52247330f729Sjoerg !candidate.getCorrectionSpecifier())
52257330f729Sjoerg return false;
52267330f729Sjoerg
52277330f729Sjoerg return WantTypeSpecifiers || HasNonType;
52287330f729Sjoerg }
52297330f729Sjoerg
FunctionCallFilterCCC(Sema & SemaRef,unsigned NumArgs,bool HasExplicitTemplateArgs,MemberExpr * ME)52307330f729Sjoerg FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
52317330f729Sjoerg bool HasExplicitTemplateArgs,
52327330f729Sjoerg MemberExpr *ME)
52337330f729Sjoerg : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
52347330f729Sjoerg CurContext(SemaRef.CurContext), MemberFn(ME) {
52357330f729Sjoerg WantTypeSpecifiers = false;
52367330f729Sjoerg WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
52377330f729Sjoerg !HasExplicitTemplateArgs && NumArgs == 1;
52387330f729Sjoerg WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
52397330f729Sjoerg WantRemainingKeywords = false;
52407330f729Sjoerg }
52417330f729Sjoerg
ValidateCandidate(const TypoCorrection & candidate)52427330f729Sjoerg bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
52437330f729Sjoerg if (!candidate.getCorrectionDecl())
52447330f729Sjoerg return candidate.isKeyword();
52457330f729Sjoerg
52467330f729Sjoerg for (auto *C : candidate) {
52477330f729Sjoerg FunctionDecl *FD = nullptr;
52487330f729Sjoerg NamedDecl *ND = C->getUnderlyingDecl();
52497330f729Sjoerg if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
52507330f729Sjoerg FD = FTD->getTemplatedDecl();
52517330f729Sjoerg if (!HasExplicitTemplateArgs && !FD) {
52527330f729Sjoerg if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
52537330f729Sjoerg // If the Decl is neither a function nor a template function,
52547330f729Sjoerg // determine if it is a pointer or reference to a function. If so,
52557330f729Sjoerg // check against the number of arguments expected for the pointee.
52567330f729Sjoerg QualType ValType = cast<ValueDecl>(ND)->getType();
52577330f729Sjoerg if (ValType.isNull())
52587330f729Sjoerg continue;
52597330f729Sjoerg if (ValType->isAnyPointerType() || ValType->isReferenceType())
52607330f729Sjoerg ValType = ValType->getPointeeType();
52617330f729Sjoerg if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
52627330f729Sjoerg if (FPT->getNumParams() == NumArgs)
52637330f729Sjoerg return true;
52647330f729Sjoerg }
52657330f729Sjoerg }
52667330f729Sjoerg
52677330f729Sjoerg // A typo for a function-style cast can look like a function call in C++.
52687330f729Sjoerg if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
52697330f729Sjoerg : isa<TypeDecl>(ND)) &&
52707330f729Sjoerg CurContext->getParentASTContext().getLangOpts().CPlusPlus)
52717330f729Sjoerg // Only a class or class template can take two or more arguments.
52727330f729Sjoerg return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
52737330f729Sjoerg
52747330f729Sjoerg // Skip the current candidate if it is not a FunctionDecl or does not accept
52757330f729Sjoerg // the current number of arguments.
52767330f729Sjoerg if (!FD || !(FD->getNumParams() >= NumArgs &&
52777330f729Sjoerg FD->getMinRequiredArguments() <= NumArgs))
52787330f729Sjoerg continue;
52797330f729Sjoerg
52807330f729Sjoerg // If the current candidate is a non-static C++ method, skip the candidate
52817330f729Sjoerg // unless the method being corrected--or the current DeclContext, if the
52827330f729Sjoerg // function being corrected is not a method--is a method in the same class
52837330f729Sjoerg // or a descendent class of the candidate's parent class.
52847330f729Sjoerg if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
52857330f729Sjoerg if (MemberFn || !MD->isStatic()) {
52867330f729Sjoerg CXXMethodDecl *CurMD =
52877330f729Sjoerg MemberFn
52887330f729Sjoerg ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
52897330f729Sjoerg : dyn_cast_or_null<CXXMethodDecl>(CurContext);
52907330f729Sjoerg CXXRecordDecl *CurRD =
52917330f729Sjoerg CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
52927330f729Sjoerg CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
52937330f729Sjoerg if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
52947330f729Sjoerg continue;
52957330f729Sjoerg }
52967330f729Sjoerg }
52977330f729Sjoerg return true;
52987330f729Sjoerg }
52997330f729Sjoerg return false;
53007330f729Sjoerg }
53017330f729Sjoerg
diagnoseTypo(const TypoCorrection & Correction,const PartialDiagnostic & TypoDiag,bool ErrorRecovery)53027330f729Sjoerg void Sema::diagnoseTypo(const TypoCorrection &Correction,
53037330f729Sjoerg const PartialDiagnostic &TypoDiag,
53047330f729Sjoerg bool ErrorRecovery) {
53057330f729Sjoerg diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
53067330f729Sjoerg ErrorRecovery);
53077330f729Sjoerg }
53087330f729Sjoerg
53097330f729Sjoerg /// Find which declaration we should import to provide the definition of
53107330f729Sjoerg /// the given declaration.
getDefinitionToImport(NamedDecl * D)53117330f729Sjoerg static NamedDecl *getDefinitionToImport(NamedDecl *D) {
53127330f729Sjoerg if (VarDecl *VD = dyn_cast<VarDecl>(D))
53137330f729Sjoerg return VD->getDefinition();
53147330f729Sjoerg if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
53157330f729Sjoerg return FD->getDefinition();
53167330f729Sjoerg if (TagDecl *TD = dyn_cast<TagDecl>(D))
53177330f729Sjoerg return TD->getDefinition();
53187330f729Sjoerg // The first definition for this ObjCInterfaceDecl might be in the TU
53197330f729Sjoerg // and not associated with any module. Use the one we know to be complete
53207330f729Sjoerg // and have just seen in a module.
53217330f729Sjoerg if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
53227330f729Sjoerg return ID;
53237330f729Sjoerg if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
53247330f729Sjoerg return PD->getDefinition();
53257330f729Sjoerg if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
53267330f729Sjoerg if (NamedDecl *TTD = TD->getTemplatedDecl())
53277330f729Sjoerg return getDefinitionToImport(TTD);
53287330f729Sjoerg return nullptr;
53297330f729Sjoerg }
53307330f729Sjoerg
diagnoseMissingImport(SourceLocation Loc,NamedDecl * Decl,MissingImportKind MIK,bool Recover)53317330f729Sjoerg void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
53327330f729Sjoerg MissingImportKind MIK, bool Recover) {
53337330f729Sjoerg // Suggest importing a module providing the definition of this entity, if
53347330f729Sjoerg // possible.
53357330f729Sjoerg NamedDecl *Def = getDefinitionToImport(Decl);
53367330f729Sjoerg if (!Def)
53377330f729Sjoerg Def = Decl;
53387330f729Sjoerg
53397330f729Sjoerg Module *Owner = getOwningModule(Def);
53407330f729Sjoerg assert(Owner && "definition of hidden declaration is not in a module");
53417330f729Sjoerg
53427330f729Sjoerg llvm::SmallVector<Module*, 8> OwningModules;
53437330f729Sjoerg OwningModules.push_back(Owner);
53447330f729Sjoerg auto Merged = Context.getModulesWithMergedDefinition(Def);
53457330f729Sjoerg OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
53467330f729Sjoerg
53477330f729Sjoerg diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
53487330f729Sjoerg Recover);
53497330f729Sjoerg }
53507330f729Sjoerg
53517330f729Sjoerg /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
53527330f729Sjoerg /// suggesting the addition of a #include of the specified file.
getHeaderNameForHeader(Preprocessor & PP,const FileEntry * E,llvm::StringRef IncludingFile)5353*e038c9c4Sjoerg static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E,
53547330f729Sjoerg llvm::StringRef IncludingFile) {
53557330f729Sjoerg bool IsSystem = false;
53567330f729Sjoerg auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
53577330f729Sjoerg E, IncludingFile, &IsSystem);
53587330f729Sjoerg return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
53597330f729Sjoerg }
53607330f729Sjoerg
diagnoseMissingImport(SourceLocation UseLoc,NamedDecl * Decl,SourceLocation DeclLoc,ArrayRef<Module * > Modules,MissingImportKind MIK,bool Recover)53617330f729Sjoerg void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
53627330f729Sjoerg SourceLocation DeclLoc,
53637330f729Sjoerg ArrayRef<Module *> Modules,
53647330f729Sjoerg MissingImportKind MIK, bool Recover) {
53657330f729Sjoerg assert(!Modules.empty());
53667330f729Sjoerg
53677330f729Sjoerg auto NotePrevious = [&] {
5368*e038c9c4Sjoerg // FIXME: Suppress the note backtrace even under
5369*e038c9c4Sjoerg // -fdiagnostics-show-note-include-stack. We don't care how this
5370*e038c9c4Sjoerg // declaration was previously reached.
5371*e038c9c4Sjoerg Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
53727330f729Sjoerg };
53737330f729Sjoerg
53747330f729Sjoerg // Weed out duplicates from module list.
53757330f729Sjoerg llvm::SmallVector<Module*, 8> UniqueModules;
53767330f729Sjoerg llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
53777330f729Sjoerg for (auto *M : Modules) {
53787330f729Sjoerg if (M->Kind == Module::GlobalModuleFragment)
53797330f729Sjoerg continue;
53807330f729Sjoerg if (UniqueModuleSet.insert(M).second)
53817330f729Sjoerg UniqueModules.push_back(M);
53827330f729Sjoerg }
53837330f729Sjoerg
5384*e038c9c4Sjoerg // Try to find a suitable header-name to #include.
5385*e038c9c4Sjoerg std::string HeaderName;
5386*e038c9c4Sjoerg if (const FileEntry *Header =
5387*e038c9c4Sjoerg PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
53887330f729Sjoerg if (const FileEntry *FE =
53897330f729Sjoerg SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5390*e038c9c4Sjoerg HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName());
5391*e038c9c4Sjoerg }
53927330f729Sjoerg
5393*e038c9c4Sjoerg // If we have a #include we should suggest, or if all definition locations
5394*e038c9c4Sjoerg // were in global module fragments, don't suggest an import.
5395*e038c9c4Sjoerg if (!HeaderName.empty() || UniqueModules.empty()) {
53967330f729Sjoerg // FIXME: Find a smart place to suggest inserting a #include, and add
53977330f729Sjoerg // a FixItHint there.
5398*e038c9c4Sjoerg Diag(UseLoc, diag::err_module_unimported_use_header)
5399*e038c9c4Sjoerg << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5400*e038c9c4Sjoerg // Produce a note showing where the entity was declared.
54017330f729Sjoerg NotePrevious();
54027330f729Sjoerg if (Recover)
54037330f729Sjoerg createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
54047330f729Sjoerg return;
54057330f729Sjoerg }
54067330f729Sjoerg
54077330f729Sjoerg Modules = UniqueModules;
54087330f729Sjoerg
54097330f729Sjoerg if (Modules.size() > 1) {
54107330f729Sjoerg std::string ModuleList;
54117330f729Sjoerg unsigned N = 0;
54127330f729Sjoerg for (Module *M : Modules) {
54137330f729Sjoerg ModuleList += "\n ";
54147330f729Sjoerg if (++N == 5 && N != Modules.size()) {
54157330f729Sjoerg ModuleList += "[...]";
54167330f729Sjoerg break;
54177330f729Sjoerg }
54187330f729Sjoerg ModuleList += M->getFullModuleName();
54197330f729Sjoerg }
54207330f729Sjoerg
54217330f729Sjoerg Diag(UseLoc, diag::err_module_unimported_use_multiple)
54227330f729Sjoerg << (int)MIK << Decl << ModuleList;
54237330f729Sjoerg } else {
54247330f729Sjoerg // FIXME: Add a FixItHint that imports the corresponding module.
54257330f729Sjoerg Diag(UseLoc, diag::err_module_unimported_use)
54267330f729Sjoerg << (int)MIK << Decl << Modules[0]->getFullModuleName();
54277330f729Sjoerg }
54287330f729Sjoerg
54297330f729Sjoerg NotePrevious();
54307330f729Sjoerg
54317330f729Sjoerg // Try to recover by implicitly importing this module.
54327330f729Sjoerg if (Recover)
54337330f729Sjoerg createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
54347330f729Sjoerg }
54357330f729Sjoerg
54367330f729Sjoerg /// Diagnose a successfully-corrected typo. Separated from the correction
54377330f729Sjoerg /// itself to allow external validation of the result, etc.
54387330f729Sjoerg ///
54397330f729Sjoerg /// \param Correction The result of performing typo correction.
54407330f729Sjoerg /// \param TypoDiag The diagnostic to produce. This will have the corrected
54417330f729Sjoerg /// string added to it (and usually also a fixit).
54427330f729Sjoerg /// \param PrevNote A note to use when indicating the location of the entity to
54437330f729Sjoerg /// which we are correcting. Will have the correction string added to it.
54447330f729Sjoerg /// \param ErrorRecovery If \c true (the default), the caller is going to
54457330f729Sjoerg /// recover from the typo as if the corrected string had been typed.
54467330f729Sjoerg /// In this case, \c PDiag must be an error, and we will attach a fixit
54477330f729Sjoerg /// to it.
diagnoseTypo(const TypoCorrection & Correction,const PartialDiagnostic & TypoDiag,const PartialDiagnostic & PrevNote,bool ErrorRecovery)54487330f729Sjoerg void Sema::diagnoseTypo(const TypoCorrection &Correction,
54497330f729Sjoerg const PartialDiagnostic &TypoDiag,
54507330f729Sjoerg const PartialDiagnostic &PrevNote,
54517330f729Sjoerg bool ErrorRecovery) {
54527330f729Sjoerg std::string CorrectedStr = Correction.getAsString(getLangOpts());
54537330f729Sjoerg std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
54547330f729Sjoerg FixItHint FixTypo = FixItHint::CreateReplacement(
54557330f729Sjoerg Correction.getCorrectionRange(), CorrectedStr);
54567330f729Sjoerg
54577330f729Sjoerg // Maybe we're just missing a module import.
54587330f729Sjoerg if (Correction.requiresImport()) {
54597330f729Sjoerg NamedDecl *Decl = Correction.getFoundDecl();
54607330f729Sjoerg assert(Decl && "import required but no declaration to import");
54617330f729Sjoerg
54627330f729Sjoerg diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
54637330f729Sjoerg MissingImportKind::Declaration, ErrorRecovery);
54647330f729Sjoerg return;
54657330f729Sjoerg }
54667330f729Sjoerg
54677330f729Sjoerg Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
54687330f729Sjoerg << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
54697330f729Sjoerg
54707330f729Sjoerg NamedDecl *ChosenDecl =
54717330f729Sjoerg Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
54727330f729Sjoerg if (PrevNote.getDiagID() && ChosenDecl)
54737330f729Sjoerg Diag(ChosenDecl->getLocation(), PrevNote)
54747330f729Sjoerg << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
54757330f729Sjoerg
54767330f729Sjoerg // Add any extra diagnostics.
54777330f729Sjoerg for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
54787330f729Sjoerg Diag(Correction.getCorrectionRange().getBegin(), PD);
54797330f729Sjoerg }
54807330f729Sjoerg
createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,TypoDiagnosticGenerator TDG,TypoRecoveryCallback TRC,SourceLocation TypoLoc)54817330f729Sjoerg TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
54827330f729Sjoerg TypoDiagnosticGenerator TDG,
5483*e038c9c4Sjoerg TypoRecoveryCallback TRC,
5484*e038c9c4Sjoerg SourceLocation TypoLoc) {
54857330f729Sjoerg assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5486*e038c9c4Sjoerg auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
54877330f729Sjoerg auto &State = DelayedTypos[TE];
54887330f729Sjoerg State.Consumer = std::move(TCC);
54897330f729Sjoerg State.DiagHandler = std::move(TDG);
54907330f729Sjoerg State.RecoveryHandler = std::move(TRC);
54917330f729Sjoerg if (TE)
54927330f729Sjoerg TypoExprs.push_back(TE);
54937330f729Sjoerg return TE;
54947330f729Sjoerg }
54957330f729Sjoerg
getTypoExprState(TypoExpr * TE) const54967330f729Sjoerg const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
54977330f729Sjoerg auto Entry = DelayedTypos.find(TE);
54987330f729Sjoerg assert(Entry != DelayedTypos.end() &&
54997330f729Sjoerg "Failed to get the state for a TypoExpr!");
55007330f729Sjoerg return Entry->second;
55017330f729Sjoerg }
55027330f729Sjoerg
clearDelayedTypo(TypoExpr * TE)55037330f729Sjoerg void Sema::clearDelayedTypo(TypoExpr *TE) {
55047330f729Sjoerg DelayedTypos.erase(TE);
55057330f729Sjoerg }
55067330f729Sjoerg
ActOnPragmaDump(Scope * S,SourceLocation IILoc,IdentifierInfo * II)55077330f729Sjoerg void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
55087330f729Sjoerg DeclarationNameInfo Name(II, IILoc);
55097330f729Sjoerg LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
55107330f729Sjoerg R.suppressDiagnostics();
55117330f729Sjoerg R.setHideTags(false);
55127330f729Sjoerg LookupName(R, S);
55137330f729Sjoerg R.dump();
55147330f729Sjoerg }
5515