1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements name lookup for C, C++, Objective-C, and
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclLookups.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/Basic/Builtins.h"
24 #include "clang/Basic/FileManager.h"
25 #include "clang/Basic/LangOptions.h"
26 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/ModuleLoader.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/Overload.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Sema.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "clang/Sema/TemplateDeduction.h"
37 #include "clang/Sema/TypoCorrection.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/TinyPtrVector.h"
41 #include "llvm/ADT/edit_distance.h"
42 #include "llvm/Support/ErrorHandling.h"
50 #include "OpenCLBuiltins.inc"
52 using namespace clang;
56 class UnqualUsingEntry {
57 const DeclContext *Nominated;
58 const DeclContext *CommonAncestor;
61 UnqualUsingEntry(const DeclContext *Nominated,
62 const DeclContext *CommonAncestor)
63 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
66 const DeclContext *getCommonAncestor() const {
67 return CommonAncestor;
70 const DeclContext *getNominatedNamespace() const {
74 // Sort by the pointer value of the common ancestor.
76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
80 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
84 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
85 return DC < E.getCommonAncestor();
90 /// A collection of using directives, as used by C++ unqualified
92 class UnqualUsingDirectiveSet {
95 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
98 llvm::SmallPtrSet<DeclContext*, 8> visited;
101 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
103 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
104 // C++ [namespace.udir]p1:
105 // During unqualified name lookup, the names appear as if they
106 // were declared in the nearest enclosing namespace which contains
107 // both the using-directive and the nominated namespace.
108 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
109 assert(InnermostFileDC && InnermostFileDC->isFileContext());
111 for (; S; S = S->getParent()) {
112 // C++ [namespace.udir]p1:
113 // A using-directive shall not appear in class scope, but may
114 // appear in namespace scope or in block scope.
115 DeclContext *Ctx = S->getEntity();
116 if (Ctx && Ctx->isFileContext()) {
118 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
119 for (auto *I : S->using_directives())
120 if (SemaRef.isVisible(I))
121 visit(I, InnermostFileDC);
126 // Visits a context and collect all of its using directives
127 // recursively. Treats all using directives as if they were
128 // declared in the context.
130 // A given context is only every visited once, so it is important
131 // that contexts be visited from the inside out in order to get
132 // the effective DCs right.
133 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
134 if (!visited.insert(DC).second)
137 addUsingDirectives(DC, EffectiveDC);
140 // Visits a using directive and collects all of its using
141 // directives recursively. Treats all using directives as if they
142 // were declared in the effective DC.
143 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
144 DeclContext *NS = UD->getNominatedNamespace();
145 if (!visited.insert(NS).second)
148 addUsingDirective(UD, EffectiveDC);
149 addUsingDirectives(NS, EffectiveDC);
152 // Adds all the using directives in a context (and those nominated
153 // by its using directives, transitively) as if they appeared in
154 // the given effective context.
155 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
156 SmallVector<DeclContext*, 4> queue;
158 for (auto UD : DC->using_directives()) {
159 DeclContext *NS = UD->getNominatedNamespace();
160 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
161 addUsingDirective(UD, EffectiveDC);
169 DC = queue.pop_back_val();
173 // Add a using directive as if it had been declared in the given
174 // context. This helps implement C++ [namespace.udir]p3:
175 // The using-directive is transitive: if a scope contains a
176 // using-directive that nominates a second namespace that itself
177 // contains using-directives, the effect is as if the
178 // using-directives from the second namespace also appeared in
180 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
181 // Find the common ancestor between the effective context and
182 // the nominated namespace.
183 DeclContext *Common = UD->getNominatedNamespace();
184 while (!Common->Encloses(EffectiveDC))
185 Common = Common->getParent();
186 Common = Common->getPrimaryContext();
188 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
191 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
193 typedef ListTy::const_iterator const_iterator;
195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
198 llvm::iterator_range<const_iterator>
199 getNamespacesFor(DeclContext *DC) const {
200 return llvm::make_range(std::equal_range(begin(), end(),
201 DC->getPrimaryContext(),
202 UnqualUsingEntry::Comparator()));
205 } // end anonymous namespace
207 // Retrieve the set of identifier namespaces that correspond to a
208 // specific kind of name lookup.
209 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
211 bool Redeclaration) {
214 case Sema::LookupObjCImplicitSelfParam:
215 case Sema::LookupOrdinaryName:
216 case Sema::LookupRedeclarationWithLinkage:
217 case Sema::LookupLocalFriendName:
218 IDNS = Decl::IDNS_Ordinary;
220 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
222 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
225 IDNS |= Decl::IDNS_LocalExtern;
228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup");
232 IDNS = Decl::IDNS_NonMemberOperator;
235 case Sema::LookupTagName:
237 IDNS = Decl::IDNS_Type;
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
247 IDNS = Decl::IDNS_Tag;
251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
261 case Sema::LookupNestedNameSpecifierName:
262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
265 case Sema::LookupNamespaceName:
266 IDNS = Decl::IDNS_Namespace;
269 case Sema::LookupUsingDeclName:
270 assert(Redeclaration && "should only be used for redecl lookup");
271 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
272 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
273 Decl::IDNS_LocalExtern;
276 case Sema::LookupObjCProtocolName:
277 IDNS = Decl::IDNS_ObjCProtocol;
280 case Sema::LookupOMPReductionName:
281 IDNS = Decl::IDNS_OMPReduction;
284 case Sema::LookupOMPMapperName:
285 IDNS = Decl::IDNS_OMPMapper;
288 case Sema::LookupAnyName:
289 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
290 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
297 void LookupResult::configure() {
298 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
299 isForRedeclaration());
301 // If we're looking for one of the allocation or deallocation
302 // operators, make sure that the implicitly-declared new and delete
303 // operators can be found.
304 switch (NameInfo.getName().getCXXOverloadedOperator()) {
308 case OO_Array_Delete:
309 getSema().DeclareGlobalNewDelete();
316 // Compiler builtins are always visible, regardless of where they end
317 // up being declared.
318 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
319 if (unsigned BuiltinID = Id->getBuiltinID()) {
320 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
326 bool LookupResult::sanity() const {
327 // This function is never called by NDEBUG builds.
328 assert(ResultKind != NotFound || Decls.size() == 0);
329 assert(ResultKind != Found || Decls.size() == 1);
330 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
331 (Decls.size() == 1 &&
332 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
333 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved());
334 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
335 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
336 Ambiguity == AmbiguousBaseSubobjectTypes)));
337 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
338 (Ambiguity == AmbiguousBaseSubobjectTypes ||
339 Ambiguity == AmbiguousBaseSubobjects)));
343 // Necessary because CXXBasePaths is not complete in Sema.h
344 void LookupResult::deletePaths(CXXBasePaths *Paths) {
348 /// Get a representative context for a declaration such that two declarations
349 /// will have the same context if they were found within the same scope.
350 static DeclContext *getContextForScopeMatching(Decl *D) {
351 // For function-local declarations, use that function as the context. This
352 // doesn't account for scopes within the function; the caller must deal with
354 DeclContext *DC = D->getLexicalDeclContext();
355 if (DC->isFunctionOrMethod())
358 // Otherwise, look at the semantic context of the declaration. The
359 // declaration must have been found there.
360 return D->getDeclContext()->getRedeclContext();
363 /// Determine whether \p D is a better lookup result than \p Existing,
364 /// given that they declare the same entity.
365 static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
366 NamedDecl *D, NamedDecl *Existing) {
367 // When looking up redeclarations of a using declaration, prefer a using
368 // shadow declaration over any other declaration of the same entity.
369 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
370 !isa<UsingShadowDecl>(Existing))
373 auto *DUnderlying = D->getUnderlyingDecl();
374 auto *EUnderlying = Existing->getUnderlyingDecl();
376 // If they have different underlying declarations, prefer a typedef over the
377 // original type (this happens when two type declarations denote the same
378 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
379 // might carry additional semantic information, such as an alignment override.
380 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
381 // declaration over a typedef.
382 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
383 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
384 bool HaveTag = isa<TagDecl>(EUnderlying);
385 bool WantTag = Kind == Sema::LookupTagName;
386 return HaveTag != WantTag;
389 // Pick the function with more default arguments.
390 // FIXME: In the presence of ambiguous default arguments, we should keep both,
391 // so we can diagnose the ambiguity if the default argument is needed.
392 // See C++ [over.match.best]p3.
393 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
394 auto *EFD = cast<FunctionDecl>(EUnderlying);
395 unsigned DMin = DFD->getMinRequiredArguments();
396 unsigned EMin = EFD->getMinRequiredArguments();
397 // If D has more default arguments, it is preferred.
400 // FIXME: When we track visibility for default function arguments, check
401 // that we pick the declaration with more visible default arguments.
404 // Pick the template with more default template arguments.
405 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
406 auto *ETD = cast<TemplateDecl>(EUnderlying);
407 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
408 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
409 // If D has more default arguments, it is preferred. Note that default
410 // arguments (and their visibility) is monotonically increasing across the
411 // redeclaration chain, so this is a quick proxy for "is more recent".
414 // If D has more *visible* default arguments, it is preferred. Note, an
415 // earlier default argument being visible does not imply that a later
416 // default argument is visible, so we can't just check the first one.
417 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
419 if (!S.hasVisibleDefaultArgument(
420 ETD->getTemplateParameters()->getParam(I)) &&
421 S.hasVisibleDefaultArgument(
422 DTD->getTemplateParameters()->getParam(I)))
427 // VarDecl can have incomplete array types, prefer the one with more complete
429 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
430 VarDecl *EVD = cast<VarDecl>(EUnderlying);
431 if (EVD->getType()->isIncompleteType() &&
432 !DVD->getType()->isIncompleteType()) {
433 // Prefer the decl with a more complete type if visible.
434 return S.isVisible(DVD);
436 return false; // Avoid picking up a newer decl, just because it was newer.
439 // For most kinds of declaration, it doesn't really matter which one we pick.
440 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
441 // If the existing declaration is hidden, prefer the new one. Otherwise,
442 // keep what we've got.
443 return !S.isVisible(Existing);
446 // Pick the newer declaration; it might have a more precise type.
447 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
448 Prev = Prev->getPreviousDecl())
449 if (Prev == EUnderlying)
454 /// Determine whether \p D can hide a tag declaration.
455 static bool canHideTag(NamedDecl *D) {
456 // C++ [basic.scope.declarative]p4:
457 // Given a set of declarations in a single declarative region [...]
458 // exactly one declaration shall declare a class name or enumeration name
459 // that is not a typedef name and the other declarations shall all refer to
460 // the same variable, non-static data member, or enumerator, or all refer
461 // to functions and function templates; in this case the class name or
462 // enumeration name is hidden.
463 // C++ [basic.scope.hiding]p2:
464 // A class name or enumeration name can be hidden by the name of a
465 // variable, data member, function, or enumerator declared in the same
467 // An UnresolvedUsingValueDecl always instantiates to one of these.
468 D = D->getUnderlyingDecl();
469 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
470 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
471 isa<UnresolvedUsingValueDecl>(D);
474 /// Resolves the result kind of this lookup.
475 void LookupResult::resolveKind() {
476 unsigned N = Decls.size();
478 // Fast case: no possible ambiguity.
480 assert(ResultKind == NotFound ||
481 ResultKind == NotFoundInCurrentInstantiation);
485 // If there's a single decl, we need to examine it to decide what
486 // kind of lookup this is.
488 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
489 if (isa<FunctionTemplateDecl>(D))
490 ResultKind = FoundOverloaded;
491 else if (isa<UnresolvedUsingValueDecl>(D))
492 ResultKind = FoundUnresolvedValue;
496 // Don't do any extra resolution if we've already resolved as ambiguous.
497 if (ResultKind == Ambiguous) return;
499 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
500 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
502 bool Ambiguous = false;
503 bool HasTag = false, HasFunction = false;
504 bool HasFunctionTemplate = false, HasUnresolved = false;
505 NamedDecl *HasNonFunction = nullptr;
507 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
509 unsigned UniqueTagIndex = 0;
513 NamedDecl *D = Decls[I]->getUnderlyingDecl();
514 D = cast<NamedDecl>(D->getCanonicalDecl());
516 // Ignore an invalid declaration unless it's the only one left.
517 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
518 Decls[I] = Decls[--N];
522 llvm::Optional<unsigned> ExistingI;
524 // Redeclarations of types via typedef can occur both within a scope
525 // and, through using declarations and directives, across scopes. There is
526 // no ambiguity if they all refer to the same type, so unique based on the
528 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
529 QualType T = getSema().Context.getTypeDeclType(TD);
530 auto UniqueResult = UniqueTypes.insert(
531 std::make_pair(getSema().Context.getCanonicalType(T), I));
532 if (!UniqueResult.second) {
533 // The type is not unique.
534 ExistingI = UniqueResult.first->second;
538 // For non-type declarations, check for a prior lookup result naming this
539 // canonical declaration.
541 auto UniqueResult = Unique.insert(std::make_pair(D, I));
542 if (!UniqueResult.second) {
543 // We've seen this entity before.
544 ExistingI = UniqueResult.first->second;
549 // This is not a unique lookup result. Pick one of the results and
550 // discard the other.
551 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
553 Decls[*ExistingI] = Decls[I];
554 Decls[I] = Decls[--N];
558 // Otherwise, do some decl type analysis and then continue.
560 if (isa<UnresolvedUsingValueDecl>(D)) {
561 HasUnresolved = true;
562 } else if (isa<TagDecl>(D)) {
567 } else if (isa<FunctionTemplateDecl>(D)) {
569 HasFunctionTemplate = true;
570 } else if (isa<FunctionDecl>(D)) {
573 if (HasNonFunction) {
574 // If we're about to create an ambiguity between two declarations that
575 // are equivalent, but one is an internal linkage declaration from one
576 // module and the other is an internal linkage declaration from another
577 // module, just skip it.
578 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
580 EquivalentNonFunctions.push_back(D);
581 Decls[I] = Decls[--N];
592 // C++ [basic.scope.hiding]p2:
593 // A class name or enumeration name can be hidden by the name of
594 // an object, function, or enumerator declared in the same
595 // scope. If a class or enumeration name and an object, function,
596 // or enumerator are declared in the same scope (in any order)
597 // with the same name, the class or enumeration name is hidden
598 // wherever the object, function, or enumerator name is visible.
599 // But it's still an error if there are distinct tag types found,
600 // even if they're not visible. (ref?)
601 if (N > 1 && HideTags && HasTag && !Ambiguous &&
602 (HasFunction || HasNonFunction || HasUnresolved)) {
603 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
604 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
605 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
606 getContextForScopeMatching(OtherDecl)) &&
607 canHideTag(OtherDecl))
608 Decls[UniqueTagIndex] = Decls[--N];
613 // FIXME: This diagnostic should really be delayed until we're done with
614 // the lookup result, in case the ambiguity is resolved by the caller.
615 if (!EquivalentNonFunctions.empty() && !Ambiguous)
616 getSema().diagnoseEquivalentInternalLinkageDeclarations(
617 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
621 if (HasNonFunction && (HasFunction || HasUnresolved))
625 setAmbiguous(LookupResult::AmbiguousReference);
626 else if (HasUnresolved)
627 ResultKind = LookupResult::FoundUnresolvedValue;
628 else if (N > 1 || HasFunctionTemplate)
629 ResultKind = LookupResult::FoundOverloaded;
631 ResultKind = LookupResult::Found;
634 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
635 CXXBasePaths::const_paths_iterator I, E;
636 for (I = P.begin(), E = P.end(); I != E; ++I)
637 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
638 DE = I->Decls.end(); DI != DE; ++DI)
642 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
643 Paths = new CXXBasePaths;
645 addDeclsFromBasePaths(*Paths);
647 setAmbiguous(AmbiguousBaseSubobjects);
650 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
651 Paths = new CXXBasePaths;
653 addDeclsFromBasePaths(*Paths);
655 setAmbiguous(AmbiguousBaseSubobjectTypes);
658 void LookupResult::print(raw_ostream &Out) {
659 Out << Decls.size() << " result(s)";
660 if (isAmbiguous()) Out << ", ambiguous";
661 if (Paths) Out << ", base paths present";
663 for (iterator I = begin(), E = end(); I != E; ++I) {
669 LLVM_DUMP_METHOD void LookupResult::dump() {
670 llvm::errs() << "lookup results for " << getLookupName().getAsString()
672 for (NamedDecl *D : *this)
676 /// When trying to resolve a function name, if the isOpenCLBuiltin function
677 /// defined in "OpenCLBuiltins.inc" returns a non-null <Index, Len>, then the
678 /// identifier is referencing an OpenCL builtin function. Thus, all its
679 /// prototypes are added to the LookUpResult.
681 /// \param S The Sema instance
682 /// \param LR The LookupResult instance
683 /// \param II The identifier being resolved
684 /// \param Index The list of prototypes starts at Index in OpenCLBuiltins[]
685 /// \param Len The list of prototypes has Len elements
686 static void InsertOCLBuiltinDeclarations(Sema &S, LookupResult &LR,
687 IdentifierInfo *II, unsigned Index,
690 for (unsigned i = 0; i < Len; ++i) {
691 const OpenCLBuiltinDecl &Decl = OpenCLBuiltins[Index - 1 + i];
692 ASTContext &Context = S.Context;
694 // Ignore this BIF if the version is incorrect.
695 if (Context.getLangOpts().OpenCLVersion < Decl.Version)
698 FunctionProtoType::ExtProtoInfo PI;
701 // Defined in "OpenCLBuiltins.inc"
702 QualType RT = OCL2Qual(Context, OpenCLSignature[Decl.ArgTableIndex]);
704 SmallVector<QualType, 5> ArgTypes;
705 for (unsigned I = 1; I < Decl.NumArgs; I++) {
706 QualType Ty = OCL2Qual(Context, OpenCLSignature[Decl.ArgTableIndex + I]);
707 ArgTypes.push_back(Ty);
710 QualType R = Context.getFunctionType(RT, ArgTypes, PI);
711 SourceLocation Loc = LR.getNameLoc();
713 // TODO: This part is taken from Sema::LazilyCreateBuiltin,
714 // maybe refactor it.
715 DeclContext *Parent = Context.getTranslationUnitDecl();
716 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, R,
717 /*TInfo=*/nullptr, SC_Extern,
718 false, R->isFunctionProtoType());
721 // Create Decl objects for each parameter, adding them to the
723 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
724 SmallVector<ParmVarDecl *, 16> Params;
725 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
727 ParmVarDecl::Create(Context, New, SourceLocation(),
728 SourceLocation(), nullptr, FT->getParamType(i),
729 /*TInfo=*/nullptr, SC_None, nullptr);
730 Parm->setScopeInfo(0, i);
731 Params.push_back(Parm);
733 New->setParams(Params);
736 New->addAttr(OverloadableAttr::CreateImplicit(Context));
738 if (strlen(Decl.Extension))
739 S.setOpenCLExtensionForDecl(New, Decl.Extension);
744 // If we added overloads, need to resolve the lookup result.
749 /// Lookup a builtin function, when name lookup would otherwise
751 static bool LookupBuiltin(Sema &S, LookupResult &R) {
752 Sema::LookupNameKind NameKind = R.getLookupKind();
754 // If we didn't find a use of this identifier, and if the identifier
755 // corresponds to a compiler builtin, create the decl object for the builtin
756 // now, injecting it into translation unit scope, and return it.
757 if (NameKind == Sema::LookupOrdinaryName ||
758 NameKind == Sema::LookupRedeclarationWithLinkage) {
759 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
761 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
762 if (II == S.getASTContext().getMakeIntegerSeqName()) {
763 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
765 } else if (II == S.getASTContext().getTypePackElementName()) {
766 R.addDecl(S.getASTContext().getTypePackElementDecl());
771 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
772 if (S.getLangOpts().OpenCL && S.getLangOpts().DeclareOpenCLBuiltins) {
773 auto Index = isOpenCLBuiltin(II->getName());
775 InsertOCLBuiltinDeclarations(S, R, II, Index.first, Index.second);
780 // If this is a builtin on this (or all) targets, create the decl.
781 if (unsigned BuiltinID = II->getBuiltinID()) {
782 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
783 // library functions like 'malloc'. Instead, we'll just error.
784 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
785 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
788 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
789 BuiltinID, S.TUScope,
790 R.isForRedeclaration(),
802 /// Determine whether we can declare a special member function within
803 /// the class at this point.
804 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
805 // We need to have a definition for the class.
806 if (!Class->getDefinition() || Class->isDependentContext())
809 // We can't be in the middle of defining the class.
810 return !Class->isBeingDefined();
813 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
814 if (!CanDeclareSpecialMemberFunction(Class))
817 // If the default constructor has not yet been declared, do so now.
818 if (Class->needsImplicitDefaultConstructor())
819 DeclareImplicitDefaultConstructor(Class);
821 // If the copy constructor has not yet been declared, do so now.
822 if (Class->needsImplicitCopyConstructor())
823 DeclareImplicitCopyConstructor(Class);
825 // If the copy assignment operator has not yet been declared, do so now.
826 if (Class->needsImplicitCopyAssignment())
827 DeclareImplicitCopyAssignment(Class);
829 if (getLangOpts().CPlusPlus11) {
830 // If the move constructor has not yet been declared, do so now.
831 if (Class->needsImplicitMoveConstructor())
832 DeclareImplicitMoveConstructor(Class);
834 // If the move assignment operator has not yet been declared, do so now.
835 if (Class->needsImplicitMoveAssignment())
836 DeclareImplicitMoveAssignment(Class);
839 // If the destructor has not yet been declared, do so now.
840 if (Class->needsImplicitDestructor())
841 DeclareImplicitDestructor(Class);
844 /// Determine whether this is the name of an implicitly-declared
845 /// special member function.
846 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
847 switch (Name.getNameKind()) {
848 case DeclarationName::CXXConstructorName:
849 case DeclarationName::CXXDestructorName:
852 case DeclarationName::CXXOperatorName:
853 return Name.getCXXOverloadedOperator() == OO_Equal;
862 /// If there are any implicit member functions with the given name
863 /// that need to be declared in the given declaration context, do so.
864 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
865 DeclarationName Name,
867 const DeclContext *DC) {
871 switch (Name.getNameKind()) {
872 case DeclarationName::CXXConstructorName:
873 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
874 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
875 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
876 if (Record->needsImplicitDefaultConstructor())
877 S.DeclareImplicitDefaultConstructor(Class);
878 if (Record->needsImplicitCopyConstructor())
879 S.DeclareImplicitCopyConstructor(Class);
880 if (S.getLangOpts().CPlusPlus11 &&
881 Record->needsImplicitMoveConstructor())
882 S.DeclareImplicitMoveConstructor(Class);
886 case DeclarationName::CXXDestructorName:
887 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
888 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
889 CanDeclareSpecialMemberFunction(Record))
890 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
893 case DeclarationName::CXXOperatorName:
894 if (Name.getCXXOverloadedOperator() != OO_Equal)
897 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
898 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
899 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
900 if (Record->needsImplicitCopyAssignment())
901 S.DeclareImplicitCopyAssignment(Class);
902 if (S.getLangOpts().CPlusPlus11 &&
903 Record->needsImplicitMoveAssignment())
904 S.DeclareImplicitMoveAssignment(Class);
909 case DeclarationName::CXXDeductionGuideName:
910 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
918 // Adds all qualifying matches for a name within a decl context to the
919 // given lookup result. Returns true if any matches were found.
920 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
923 // Lazily declare C++ special member functions.
924 if (S.getLangOpts().CPlusPlus)
925 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
928 // Perform lookup into this declaration context.
929 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
930 for (NamedDecl *D : DR) {
931 if ((D = R.getAcceptableDecl(D))) {
937 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
940 if (R.getLookupName().getNameKind()
941 != DeclarationName::CXXConversionFunctionName ||
942 R.getLookupName().getCXXNameType()->isDependentType() ||
943 !isa<CXXRecordDecl>(DC))
947 // A specialization of a conversion function template is not found by
948 // name lookup. Instead, any conversion function templates visible in the
949 // context of the use are considered. [...]
950 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
951 if (!Record->isCompleteDefinition())
954 // For conversion operators, 'operator auto' should only match
955 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
956 // as a candidate for template substitution.
957 auto *ContainedDeducedType =
958 R.getLookupName().getCXXNameType()->getContainedDeducedType();
959 if (R.getLookupName().getNameKind() ==
960 DeclarationName::CXXConversionFunctionName &&
961 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
964 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
965 UEnd = Record->conversion_end(); U != UEnd; ++U) {
966 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
970 // When we're performing lookup for the purposes of redeclaration, just
971 // add the conversion function template. When we deduce template
972 // arguments for specializations, we'll end up unifying the return
973 // type of the new declaration with the type of the function template.
974 if (R.isForRedeclaration()) {
975 R.addDecl(ConvTemplate);
981 // [...] For each such operator, if argument deduction succeeds
982 // (14.9.2.3), the resulting specialization is used as if found by
985 // When referencing a conversion function for any purpose other than
986 // a redeclaration (such that we'll be building an expression with the
987 // result), perform template argument deduction and place the
988 // specialization into the result set. We do this to avoid forcing all
989 // callers to perform special deduction for conversion functions.
990 TemplateDeductionInfo Info(R.getNameLoc());
991 FunctionDecl *Specialization = nullptr;
993 const FunctionProtoType *ConvProto
994 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
995 assert(ConvProto && "Nonsensical conversion function template type");
997 // Compute the type of the function that we would expect the conversion
998 // function to have, if it were to match the name given.
999 // FIXME: Calling convention!
1000 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
1001 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
1002 EPI.ExceptionSpec = EST_None;
1003 QualType ExpectedType
1004 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
1007 // Perform template argument deduction against the type that we would
1008 // expect the function to have.
1009 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
1010 Specialization, Info)
1011 == Sema::TDK_Success) {
1012 R.addDecl(Specialization);
1020 // Performs C++ unqualified lookup into the given file context.
1022 CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1023 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
1025 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1027 // Perform direct name lookup into the LookupCtx.
1028 bool Found = LookupDirect(S, R, NS);
1030 // Perform direct name lookup into the namespaces nominated by the
1031 // using directives whose common ancestor is this namespace.
1032 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1033 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
1041 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
1042 if (DeclContext *Ctx = S->getEntity())
1043 return Ctx->isFileContext();
1047 // Find the next outer declaration context from this scope. This
1048 // routine actually returns the semantic outer context, which may
1049 // differ from the lexical context (encoded directly in the Scope
1050 // stack) when we are parsing a member of a class template. In this
1051 // case, the second element of the pair will be true, to indicate that
1052 // name lookup should continue searching in this semantic context when
1053 // it leaves the current template parameter scope.
1054 static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
1055 DeclContext *DC = S->getEntity();
1056 DeclContext *Lexical = nullptr;
1057 for (Scope *OuterS = S->getParent(); OuterS;
1058 OuterS = OuterS->getParent()) {
1059 if (OuterS->getEntity()) {
1060 Lexical = OuterS->getEntity();
1065 // C++ [temp.local]p8:
1066 // In the definition of a member of a class template that appears
1067 // outside of the namespace containing the class template
1068 // definition, the name of a template-parameter hides the name of
1069 // a member of this namespace.
1076 // template<class T> class B {
1081 // template<class C> void N::B<C>::f(C) {
1082 // C b; // C is the template parameter, not N::C
1085 // In this example, the lexical context we return is the
1086 // TranslationUnit, while the semantic context is the namespace N.
1087 if (!Lexical || !DC || !S->getParent() ||
1088 !S->getParent()->isTemplateParamScope())
1089 return std::make_pair(Lexical, false);
1091 // Find the outermost template parameter scope.
1092 // For the example, this is the scope for the template parameters of
1093 // template<class C>.
1094 Scope *OutermostTemplateScope = S->getParent();
1095 while (OutermostTemplateScope->getParent() &&
1096 OutermostTemplateScope->getParent()->isTemplateParamScope())
1097 OutermostTemplateScope = OutermostTemplateScope->getParent();
1099 // Find the namespace context in which the original scope occurs. In
1100 // the example, this is namespace N.
1101 DeclContext *Semantic = DC;
1102 while (!Semantic->isFileContext())
1103 Semantic = Semantic->getParent();
1105 // Find the declaration context just outside of the template
1106 // parameter scope. This is the context in which the template is
1107 // being lexically declaration (a namespace context). In the
1108 // example, this is the global scope.
1109 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1110 Lexical->Encloses(Semantic))
1111 return std::make_pair(Semantic, true);
1113 return std::make_pair(Lexical, false);
1117 /// An RAII object to specify that we want to find block scope extern
1119 struct FindLocalExternScope {
1120 FindLocalExternScope(LookupResult &R)
1121 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1122 Decl::IDNS_LocalExtern) {
1123 R.setFindLocalExtern(R.getIdentifierNamespace() &
1124 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
1127 R.setFindLocalExtern(OldFindLocalExtern);
1129 ~FindLocalExternScope() {
1133 bool OldFindLocalExtern;
1135 } // end anonymous namespace
1137 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1138 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1140 DeclarationName Name = R.getLookupName();
1141 Sema::LookupNameKind NameKind = R.getLookupKind();
1143 // If this is the name of an implicitly-declared special member function,
1144 // go through the scope stack to implicitly declare
1145 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1146 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1147 if (DeclContext *DC = PreS->getEntity())
1148 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
1151 // Implicitly declare member functions with the name we're looking for, if in
1152 // fact we are in a scope where it matters.
1155 IdentifierResolver::iterator
1156 I = IdResolver.begin(Name),
1157 IEnd = IdResolver.end();
1159 // First we lookup local scope.
1160 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1161 // ...During unqualified name lookup (3.4.1), the names appear as if
1162 // they were declared in the nearest enclosing namespace which contains
1163 // both the using-directive and the nominated namespace.
1164 // [Note: in this context, "contains" means "contains directly or
1168 // namespace A { int i; }
1172 // using namespace A;
1173 // ++i; // finds local 'i', A::i appears at global scope
1177 UnqualUsingDirectiveSet UDirs(*this);
1178 bool VisitedUsingDirectives = false;
1179 bool LeftStartingScope = false;
1180 DeclContext *OutsideOfTemplateParamDC = nullptr;
1182 // When performing a scope lookup, we want to find local extern decls.
1183 FindLocalExternScope FindLocals(R);
1185 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1186 DeclContext *Ctx = S->getEntity();
1187 bool SearchNamespaceScope = true;
1188 // Check whether the IdResolver has anything in this scope.
1189 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1190 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1191 if (NameKind == LookupRedeclarationWithLinkage &&
1192 !(*I)->isTemplateParameter()) {
1193 // If it's a template parameter, we still find it, so we can diagnose
1194 // the invalid redeclaration.
1196 // Determine whether this (or a previous) declaration is
1198 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1199 LeftStartingScope = true;
1201 // If we found something outside of our starting scope that
1202 // does not have linkage, skip it.
1203 if (LeftStartingScope && !((*I)->hasLinkage())) {
1208 // We found something in this scope, we should not look at the
1210 SearchNamespaceScope = false;
1215 if (!SearchNamespaceScope) {
1217 if (S->isClassScope())
1218 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1219 R.setNamingClass(Record);
1223 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1224 // C++11 [class.friend]p11:
1225 // If a friend declaration appears in a local class and the name
1226 // specified is an unqualified name, a prior declaration is
1227 // looked up without considering scopes that are outside the
1228 // innermost enclosing non-class scope.
1232 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1233 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1234 // We've just searched the last template parameter scope and
1235 // found nothing, so look into the contexts between the
1236 // lexical and semantic declaration contexts returned by
1237 // findOuterContext(). This implements the name lookup behavior
1238 // of C++ [temp.local]p8.
1239 Ctx = OutsideOfTemplateParamDC;
1240 OutsideOfTemplateParamDC = nullptr;
1244 DeclContext *OuterCtx;
1245 bool SearchAfterTemplateScope;
1246 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1247 if (SearchAfterTemplateScope)
1248 OutsideOfTemplateParamDC = OuterCtx;
1250 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1251 // We do not directly look into transparent contexts, since
1252 // those entities will be found in the nearest enclosing
1253 // non-transparent context.
1254 if (Ctx->isTransparentContext())
1257 // We do not look directly into function or method contexts,
1258 // since all of the local variables and parameters of the
1259 // function/method are present within the Scope.
1260 if (Ctx->isFunctionOrMethod()) {
1261 // If we have an Objective-C instance method, look for ivars
1262 // in the corresponding interface.
1263 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1264 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1265 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1266 ObjCInterfaceDecl *ClassDeclared;
1267 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1268 Name.getAsIdentifierInfo(),
1270 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1282 // If this is a file context, we need to perform unqualified name
1283 // lookup considering using directives.
1284 if (Ctx->isFileContext()) {
1285 // If we haven't handled using directives yet, do so now.
1286 if (!VisitedUsingDirectives) {
1287 // Add using directives from this context up to the top level.
1288 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1289 if (UCtx->isTransparentContext())
1292 UDirs.visit(UCtx, UCtx);
1295 // Find the innermost file scope, so we can add using directives
1296 // from local scopes.
1297 Scope *InnermostFileScope = S;
1298 while (InnermostFileScope &&
1299 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1300 InnermostFileScope = InnermostFileScope->getParent();
1301 UDirs.visitScopeChain(Initial, InnermostFileScope);
1305 VisitedUsingDirectives = true;
1308 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1316 // Perform qualified name lookup into this context.
1317 // FIXME: In some cases, we know that every name that could be found by
1318 // this qualified name lookup will also be on the identifier chain. For
1319 // example, inside a class without any base classes, we never need to
1320 // perform qualified lookup because all of the members are on top of the
1321 // identifier chain.
1322 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1328 // Stop if we ran out of scopes.
1329 // FIXME: This really, really shouldn't be happening.
1330 if (!S) return false;
1332 // If we are looking for members, no need to look into global/namespace scope.
1333 if (NameKind == LookupMemberName)
1336 // Collect UsingDirectiveDecls in all scopes, and recursively all
1337 // nominated namespaces by those using-directives.
1339 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1340 // don't build it for each lookup!
1341 if (!VisitedUsingDirectives) {
1342 UDirs.visitScopeChain(Initial, S);
1346 // If we're not performing redeclaration lookup, do not look for local
1347 // extern declarations outside of a function scope.
1348 if (!R.isForRedeclaration())
1349 FindLocals.restore();
1351 // Lookup namespace scope, and global scope.
1352 // Unqualified name lookup in C++ requires looking into scopes
1353 // that aren't strictly lexical, and therefore we walk through the
1354 // context as well as walking through the scopes.
1355 for (; S; S = S->getParent()) {
1356 // Check whether the IdResolver has anything in this scope.
1358 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1359 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1360 // We found something. Look for anything else in our scope
1361 // with this same name and in an acceptable identifier
1362 // namespace, so that we can construct an overload set if we
1369 if (Found && S->isTemplateParamScope()) {
1374 DeclContext *Ctx = S->getEntity();
1375 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1376 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1377 // We've just searched the last template parameter scope and
1378 // found nothing, so look into the contexts between the
1379 // lexical and semantic declaration contexts returned by
1380 // findOuterContext(). This implements the name lookup behavior
1381 // of C++ [temp.local]p8.
1382 Ctx = OutsideOfTemplateParamDC;
1383 OutsideOfTemplateParamDC = nullptr;
1387 DeclContext *OuterCtx;
1388 bool SearchAfterTemplateScope;
1389 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1390 if (SearchAfterTemplateScope)
1391 OutsideOfTemplateParamDC = OuterCtx;
1393 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1394 // We do not directly look into transparent contexts, since
1395 // those entities will be found in the nearest enclosing
1396 // non-transparent context.
1397 if (Ctx->isTransparentContext())
1400 // If we have a context, and it's not a context stashed in the
1401 // template parameter scope for an out-of-line definition, also
1402 // look into that context.
1403 if (!(Found && S->isTemplateParamScope())) {
1404 assert(Ctx->isFileContext() &&
1405 "We should have been looking only at file context here already.");
1407 // Look into context considering using-directives.
1408 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1417 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1422 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1429 void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1430 if (auto *M = getCurrentModule())
1431 Context.mergeDefinitionIntoModule(ND, M);
1433 // We're not building a module; just make the definition visible.
1434 ND->setVisibleDespiteOwningModule();
1436 // If ND is a template declaration, make the template parameters
1437 // visible too. They're not (necessarily) within a mergeable DeclContext.
1438 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1439 for (auto *Param : *TD->getTemplateParameters())
1440 makeMergedDefinitionVisible(Param);
1443 /// Find the module in which the given declaration was defined.
1444 static Module *getDefiningModule(Sema &S, Decl *Entity) {
1445 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1446 // If this function was instantiated from a template, the defining module is
1447 // the module containing the pattern.
1448 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1450 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1451 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1453 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1454 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1456 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1457 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1461 // Walk up to the containing context. That might also have been instantiated
1463 DeclContext *Context = Entity->getLexicalDeclContext();
1464 if (Context->isFileContext())
1465 return S.getOwningModule(Entity);
1466 return getDefiningModule(S, cast<Decl>(Context));
1469 llvm::DenseSet<Module*> &Sema::getLookupModules() {
1470 unsigned N = CodeSynthesisContexts.size();
1471 for (unsigned I = CodeSynthesisContextLookupModules.size();
1473 Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity);
1474 if (M && !LookupModulesCache.insert(M).second)
1476 CodeSynthesisContextLookupModules.push_back(M);
1478 return LookupModulesCache;
1481 /// Determine whether the module M is part of the current module from the
1482 /// perspective of a module-private visibility check.
1483 static bool isInCurrentModule(const Module *M, const LangOptions &LangOpts) {
1484 // If M is the global module fragment of a module that we've not yet finished
1485 // parsing, then it must be part of the current module.
1486 return M->getTopLevelModuleName() == LangOpts.CurrentModule ||
1487 (M->Kind == Module::GlobalModuleFragment && !M->Parent);
1490 bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1491 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1492 if (isModuleVisible(Merged))
1497 bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
1498 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1499 if (isInCurrentModule(Merged, getLangOpts()))
1504 template<typename ParmDecl>
1506 hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1507 llvm::SmallVectorImpl<Module *> *Modules) {
1508 if (!D->hasDefaultArgument())
1512 auto &DefaultArg = D->getDefaultArgStorage();
1513 if (!DefaultArg.isInherited() && S.isVisible(D))
1516 if (!DefaultArg.isInherited() && Modules) {
1517 auto *NonConstD = const_cast<ParmDecl*>(D);
1518 Modules->push_back(S.getOwningModule(NonConstD));
1521 // If there was a previous default argument, maybe its parameter is visible.
1522 D = DefaultArg.getInheritedFrom();
1527 bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1528 llvm::SmallVectorImpl<Module *> *Modules) {
1529 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1530 return ::hasVisibleDefaultArgument(*this, P, Modules);
1531 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1532 return ::hasVisibleDefaultArgument(*this, P, Modules);
1533 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1537 template<typename Filter>
1538 static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1539 llvm::SmallVectorImpl<Module *> *Modules,
1541 bool HasFilteredRedecls = false;
1543 for (auto *Redecl : D->redecls()) {
1544 auto *R = cast<NamedDecl>(Redecl);
1551 HasFilteredRedecls = true;
1554 Modules->push_back(R->getOwningModule());
1557 // Only return false if there is at least one redecl that is not filtered out.
1558 if (HasFilteredRedecls)
1564 bool Sema::hasVisibleExplicitSpecialization(
1565 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1566 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1567 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1568 return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1569 if (auto *FD = dyn_cast<FunctionDecl>(D))
1570 return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1571 if (auto *VD = dyn_cast<VarDecl>(D))
1572 return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1573 llvm_unreachable("unknown explicit specialization kind");
1577 bool Sema::hasVisibleMemberSpecialization(
1578 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1579 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1580 "not a member specialization");
1581 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1582 // If the specialization is declared at namespace scope, then it's a member
1583 // specialization declaration. If it's lexically inside the class
1584 // definition then it was instantiated.
1586 // FIXME: This is a hack. There should be a better way to determine this.
1587 // FIXME: What about MS-style explicit specializations declared within a
1588 // class definition?
1589 return D->getLexicalDeclContext()->isFileContext();
1593 /// Determine whether a declaration is visible to name lookup.
1595 /// This routine determines whether the declaration D is visible in the current
1596 /// lookup context, taking into account the current template instantiation
1597 /// stack. During template instantiation, a declaration is visible if it is
1598 /// visible from a module containing any entity on the template instantiation
1599 /// path (by instantiating a template, you allow it to see the declarations that
1600 /// your module can see, including those later on in your module).
1601 bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1602 assert(D->isHidden() && "should not call this: not in slow case");
1604 Module *DeclModule = SemaRef.getOwningModule(D);
1605 assert(DeclModule && "hidden decl has no owning module");
1607 // If the owning module is visible, the decl is visible.
1608 if (SemaRef.isModuleVisible(DeclModule, D->isModulePrivate()))
1611 // Determine whether a decl context is a file context for the purpose of
1612 // visibility. This looks through some (export and linkage spec) transparent
1613 // contexts, but not others (enums).
1614 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1615 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1616 isa<ExportDecl>(DC);
1619 // If this declaration is not at namespace scope
1620 // then it is visible if its lexical parent has a visible definition.
1621 DeclContext *DC = D->getLexicalDeclContext();
1622 if (DC && !IsEffectivelyFileContext(DC)) {
1623 // For a parameter, check whether our current template declaration's
1624 // lexical context is visible, not whether there's some other visible
1625 // definition of it, because parameters aren't "within" the definition.
1627 // In C++ we need to check for a visible definition due to ODR merging,
1628 // and in C we must not because each declaration of a function gets its own
1629 // set of declarations for tags in prototype scope.
1630 bool VisibleWithinParent;
1631 if (D->isTemplateParameter()) {
1632 bool SearchDefinitions = true;
1633 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1634 if (const auto *TD = DCD->getDescribedTemplate()) {
1635 TemplateParameterList *TPL = TD->getTemplateParameters();
1636 auto Index = getDepthAndIndex(D).second;
1637 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1640 if (SearchDefinitions)
1641 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1643 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1644 } else if (isa<ParmVarDecl>(D) ||
1645 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1646 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1647 else if (D->isModulePrivate()) {
1648 // A module-private declaration is only visible if an enclosing lexical
1649 // parent was merged with another definition in the current module.
1650 VisibleWithinParent = false;
1652 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1653 VisibleWithinParent = true;
1656 DC = DC->getLexicalParent();
1657 } while (!IsEffectivelyFileContext(DC));
1659 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1662 if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1663 // FIXME: Do something better in this case.
1664 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1665 // Cache the fact that this declaration is implicitly visible because
1666 // its parent has a visible definition.
1667 D->setVisibleDespiteOwningModule();
1669 return VisibleWithinParent;
1675 bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1676 // The module might be ordinarily visible. For a module-private query, that
1677 // means it is part of the current module. For any other query, that means it
1678 // is in our visible module set.
1679 if (ModulePrivate) {
1680 if (isInCurrentModule(M, getLangOpts()))
1683 if (VisibleModules.isVisible(M))
1687 // Otherwise, it might be visible by virtue of the query being within a
1688 // template instantiation or similar that is permitted to look inside M.
1690 // Find the extra places where we need to look.
1691 const auto &LookupModules = getLookupModules();
1692 if (LookupModules.empty())
1695 // If our lookup set contains the module, it's visible.
1696 if (LookupModules.count(M))
1699 // For a module-private query, that's everywhere we get to look.
1703 // Check whether M is transitively exported to an import of the lookup set.
1704 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1705 return LookupM->isModuleVisible(M);
1709 bool Sema::isVisibleSlow(const NamedDecl *D) {
1710 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1713 bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1714 // FIXME: If there are both visible and hidden declarations, we need to take
1715 // into account whether redeclaration is possible. Example:
1717 // Non-imported module:
1720 // static int f(U); // #2, not a redeclaration of #1
1721 // int f(T); // #3, finds both, should link with #1 if T != U, but
1722 // // with #2 if T == U; neither should be ambiguous.
1726 assert(D->isExternallyDeclarable() &&
1727 "should not have hidden, non-externally-declarable result here");
1730 // This function is called once "New" is essentially complete, but before a
1731 // previous declaration is attached. We can't query the linkage of "New" in
1732 // general, because attaching the previous declaration can change the
1733 // linkage of New to match the previous declaration.
1735 // However, because we've just determined that there is no *visible* prior
1736 // declaration, we can compute the linkage here. There are two possibilities:
1738 // * This is not a redeclaration; it's safe to compute the linkage now.
1740 // * This is a redeclaration of a prior declaration that is externally
1741 // redeclarable. In that case, the linkage of the declaration is not
1742 // changed by attaching the prior declaration, because both are externally
1743 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
1745 // FIXME: This is subtle and fragile.
1746 return New->isExternallyDeclarable();
1749 /// Retrieve the visible declaration corresponding to D, if any.
1751 /// This routine determines whether the declaration D is visible in the current
1752 /// module, with the current imports. If not, it checks whether any
1753 /// redeclaration of D is visible, and if so, returns that declaration.
1755 /// \returns D, or a visible previous declaration of D, whichever is more recent
1756 /// and visible. If no declaration of D is visible, returns null.
1757 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
1759 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
1761 for (auto RD : D->redecls()) {
1762 // Don't bother with extra checks if we already know this one isn't visible.
1766 auto ND = cast<NamedDecl>(RD);
1767 // FIXME: This is wrong in the case where the previous declaration is not
1768 // visible in the same scope as D. This needs to be done much more
1770 if (ND->isInIdentifierNamespace(IDNS) &&
1771 LookupResult::isVisible(SemaRef, ND))
1778 bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1779 llvm::SmallVectorImpl<Module *> *Modules) {
1780 assert(!isVisible(D) && "not in slow case");
1781 return hasVisibleDeclarationImpl(*this, D, Modules,
1782 [](const NamedDecl *) { return true; });
1785 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1786 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1787 // Namespaces are a bit of a special case: we expect there to be a lot of
1788 // redeclarations of some namespaces, all declarations of a namespace are
1789 // essentially interchangeable, all declarations are found by name lookup
1790 // if any is, and namespaces are never looked up during template
1791 // instantiation. So we benefit from caching the check in this case, and
1792 // it is correct to do so.
1793 auto *Key = ND->getCanonicalDecl();
1794 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1796 auto *Acceptable = isVisible(getSema(), Key)
1798 : findAcceptableDecl(getSema(), Key, IDNS);
1800 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1804 return findAcceptableDecl(getSema(), D, IDNS);
1807 /// Perform unqualified name lookup starting from a given
1810 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1811 /// used to find names within the current scope. For example, 'x' in
1815 /// return x; // unqualified name look finds 'x' in the global scope
1819 /// Different lookup criteria can find different names. For example, a
1820 /// particular scope can have both a struct and a function of the same
1821 /// name, and each can be found by certain lookup criteria. For more
1822 /// information about lookup criteria, see the documentation for the
1823 /// class LookupCriteria.
1825 /// @param S The scope from which unqualified name lookup will
1826 /// begin. If the lookup criteria permits, name lookup may also search
1827 /// in the parent scopes.
1829 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1830 /// look up and the lookup kind), and is updated with the results of lookup
1831 /// including zero or more declarations and possibly additional information
1832 /// used to diagnose ambiguities.
1834 /// @returns \c true if lookup succeeded and false otherwise.
1835 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1836 DeclarationName Name = R.getLookupName();
1837 if (!Name) return false;
1839 LookupNameKind NameKind = R.getLookupKind();
1841 if (!getLangOpts().CPlusPlus) {
1842 // Unqualified name lookup in C/Objective-C is purely lexical, so
1843 // search in the declarations attached to the name.
1844 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1845 // Find the nearest non-transparent declaration scope.
1846 while (!(S->getFlags() & Scope::DeclScope) ||
1847 (S->getEntity() && S->getEntity()->isTransparentContext()))
1851 // When performing a scope lookup, we want to find local extern decls.
1852 FindLocalExternScope FindLocals(R);
1854 // Scan up the scope chain looking for a decl that matches this
1855 // identifier that is in the appropriate namespace. This search
1856 // should not take long, as shadowing of names is uncommon, and
1857 // deep shadowing is extremely uncommon.
1858 bool LeftStartingScope = false;
1860 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1861 IEnd = IdResolver.end();
1863 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
1864 if (NameKind == LookupRedeclarationWithLinkage) {
1865 // Determine whether this (or a previous) declaration is
1867 if (!LeftStartingScope && !S->isDeclScope(*I))
1868 LeftStartingScope = true;
1870 // If we found something outside of our starting scope that
1871 // does not have linkage, skip it.
1872 if (LeftStartingScope && !((*I)->hasLinkage())) {
1877 else if (NameKind == LookupObjCImplicitSelfParam &&
1878 !isa<ImplicitParamDecl>(*I))
1883 // Check whether there are any other declarations with the same name
1884 // and in the same scope.
1886 // Find the scope in which this declaration was declared (if it
1887 // actually exists in a Scope).
1888 while (S && !S->isDeclScope(D))
1891 // If the scope containing the declaration is the translation unit,
1892 // then we'll need to perform our checks based on the matching
1893 // DeclContexts rather than matching scopes.
1894 if (S && isNamespaceOrTranslationUnitScope(S))
1897 // Compute the DeclContext, if we need it.
1898 DeclContext *DC = nullptr;
1900 DC = (*I)->getDeclContext()->getRedeclContext();
1902 IdentifierResolver::iterator LastI = I;
1903 for (++LastI; LastI != IEnd; ++LastI) {
1905 // Match based on scope.
1906 if (!S->isDeclScope(*LastI))
1909 // Match based on DeclContext.
1911 = (*LastI)->getDeclContext()->getRedeclContext();
1912 if (!LastDC->Equals(DC))
1916 // If the declaration is in the right namespace and visible, add it.
1917 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1927 // Perform C++ unqualified name lookup.
1928 if (CppLookupName(R, S))
1932 // If we didn't find a use of this identifier, and if the identifier
1933 // corresponds to a compiler builtin, create the decl object for the builtin
1934 // now, injecting it into translation unit scope, and return it.
1935 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1938 // If we didn't find a use of this identifier, the ExternalSource
1939 // may be able to handle the situation.
1940 // Note: some lookup failures are expected!
1941 // See e.g. R.isForRedeclaration().
1942 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1945 /// Perform qualified name lookup in the namespaces nominated by
1946 /// using directives by the given context.
1948 /// C++98 [namespace.qual]p2:
1949 /// Given X::m (where X is a user-declared namespace), or given \::m
1950 /// (where X is the global namespace), let S be the set of all
1951 /// declarations of m in X and in the transitive closure of all
1952 /// namespaces nominated by using-directives in X and its used
1953 /// namespaces, except that using-directives are ignored in any
1954 /// namespace, including X, directly containing one or more
1955 /// declarations of m. No namespace is searched more than once in
1956 /// the lookup of a name. If S is the empty set, the program is
1957 /// ill-formed. Otherwise, if S has exactly one member, or if the
1958 /// context of the reference is a using-declaration
1959 /// (namespace.udecl), S is the required set of declarations of
1960 /// m. Otherwise if the use of m is not one that allows a unique
1961 /// declaration to be chosen from S, the program is ill-formed.
1963 /// C++98 [namespace.qual]p5:
1964 /// During the lookup of a qualified namespace member name, if the
1965 /// lookup finds more than one declaration of the member, and if one
1966 /// declaration introduces a class name or enumeration name and the
1967 /// other declarations either introduce the same object, the same
1968 /// enumerator or a set of functions, the non-type name hides the
1969 /// class or enumeration name if and only if the declarations are
1970 /// from the same namespace; otherwise (the declarations are from
1971 /// different namespaces), the program is ill-formed.
1972 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1973 DeclContext *StartDC) {
1974 assert(StartDC->isFileContext() && "start context is not a file context");
1976 // We have not yet looked into these namespaces, much less added
1977 // their "using-children" to the queue.
1978 SmallVector<NamespaceDecl*, 8> Queue;
1980 // We have at least added all these contexts to the queue.
1981 llvm::SmallPtrSet<DeclContext*, 8> Visited;
1982 Visited.insert(StartDC);
1984 // We have already looked into the initial namespace; seed the queue
1985 // with its using-children.
1986 for (auto *I : StartDC->using_directives()) {
1987 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
1988 if (S.isVisible(I) && Visited.insert(ND).second)
1989 Queue.push_back(ND);
1992 // The easiest way to implement the restriction in [namespace.qual]p5
1993 // is to check whether any of the individual results found a tag
1994 // and, if so, to declare an ambiguity if the final result is not
1996 bool FoundTag = false;
1997 bool FoundNonTag = false;
1999 LookupResult LocalR(LookupResult::Temporary, R);
2002 while (!Queue.empty()) {
2003 NamespaceDecl *ND = Queue.pop_back_val();
2005 // We go through some convolutions here to avoid copying results
2006 // between LookupResults.
2007 bool UseLocal = !R.empty();
2008 LookupResult &DirectR = UseLocal ? LocalR : R;
2009 bool FoundDirect = LookupDirect(S, DirectR, ND);
2012 // First do any local hiding.
2013 DirectR.resolveKind();
2015 // If the local result is a tag, remember that.
2016 if (DirectR.isSingleTagDecl())
2021 // Append the local results to the total results if necessary.
2023 R.addAllDecls(LocalR);
2028 // If we find names in this namespace, ignore its using directives.
2034 for (auto I : ND->using_directives()) {
2035 NamespaceDecl *Nom = I->getNominatedNamespace();
2036 if (S.isVisible(I) && Visited.insert(Nom).second)
2037 Queue.push_back(Nom);
2042 if (FoundTag && FoundNonTag)
2043 R.setAmbiguousQualifiedTagHiding();
2051 /// Callback that looks for any member of a class with the given name.
2052 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
2053 CXXBasePath &Path, DeclarationName Name) {
2054 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
2056 Path.Decls = BaseRecord->lookup(Name);
2057 return !Path.Decls.empty();
2060 /// Determine whether the given set of member declarations contains only
2061 /// static members, nested types, and enumerators.
2062 template<typename InputIterator>
2063 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
2064 Decl *D = (*First)->getUnderlyingDecl();
2065 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
2068 if (isa<CXXMethodDecl>(D)) {
2069 // Determine whether all of the methods are static.
2070 bool AllMethodsAreStatic = true;
2071 for(; First != Last; ++First) {
2072 D = (*First)->getUnderlyingDecl();
2074 if (!isa<CXXMethodDecl>(D)) {
2075 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
2079 if (!cast<CXXMethodDecl>(D)->isStatic()) {
2080 AllMethodsAreStatic = false;
2085 if (AllMethodsAreStatic)
2092 /// Perform qualified name lookup into a given context.
2094 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2095 /// names when the context of those names is explicit specified, e.g.,
2096 /// "std::vector" or "x->member", or as part of unqualified name lookup.
2098 /// Different lookup criteria can find different names. For example, a
2099 /// particular scope can have both a struct and a function of the same
2100 /// name, and each can be found by certain lookup criteria. For more
2101 /// information about lookup criteria, see the documentation for the
2102 /// class LookupCriteria.
2104 /// \param R captures both the lookup criteria and any lookup results found.
2106 /// \param LookupCtx The context in which qualified name lookup will
2107 /// search. If the lookup criteria permits, name lookup may also search
2108 /// in the parent contexts or (for C++ classes) base classes.
2110 /// \param InUnqualifiedLookup true if this is qualified name lookup that
2111 /// occurs as part of unqualified name lookup.
2113 /// \returns true if lookup succeeded, false if it failed.
2114 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2115 bool InUnqualifiedLookup) {
2116 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2118 if (!R.getLookupName())
2121 // Make sure that the declaration context is complete.
2122 assert((!isa<TagDecl>(LookupCtx) ||
2123 LookupCtx->isDependentContext() ||
2124 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2125 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2126 "Declaration context must already be complete!");
2128 struct QualifiedLookupInScope {
2130 DeclContext *Context;
2131 // Set flag in DeclContext informing debugger that we're looking for qualified name
2132 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2133 oldVal = ctx->setUseQualifiedLookup();
2135 ~QualifiedLookupInScope() {
2136 Context->setUseQualifiedLookup(oldVal);
2140 if (LookupDirect(*this, R, LookupCtx)) {
2142 if (isa<CXXRecordDecl>(LookupCtx))
2143 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2147 // Don't descend into implied contexts for redeclarations.
2148 // C++98 [namespace.qual]p6:
2149 // In a declaration for a namespace member in which the
2150 // declarator-id is a qualified-id, given that the qualified-id
2151 // for the namespace member has the form
2152 // nested-name-specifier unqualified-id
2153 // the unqualified-id shall name a member of the namespace
2154 // designated by the nested-name-specifier.
2155 // See also [class.mfct]p5 and [class.static.data]p2.
2156 if (R.isForRedeclaration())
2159 // If this is a namespace, look it up in the implied namespaces.
2160 if (LookupCtx->isFileContext())
2161 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2163 // If this isn't a C++ class, we aren't allowed to look into base
2164 // classes, we're done.
2165 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2166 if (!LookupRec || !LookupRec->getDefinition())
2169 // If we're performing qualified name lookup into a dependent class,
2170 // then we are actually looking into a current instantiation. If we have any
2171 // dependent base classes, then we either have to delay lookup until
2172 // template instantiation time (at which point all bases will be available)
2173 // or we have to fail.
2174 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2175 LookupRec->hasAnyDependentBases()) {
2176 R.setNotFoundInCurrentInstantiation();
2180 // Perform lookup into our base classes.
2182 Paths.setOrigin(LookupRec);
2184 // Look for this member in our base classes
2185 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2186 DeclarationName Name) = nullptr;
2187 switch (R.getLookupKind()) {
2188 case LookupObjCImplicitSelfParam:
2189 case LookupOrdinaryName:
2190 case LookupMemberName:
2191 case LookupRedeclarationWithLinkage:
2192 case LookupLocalFriendName:
2193 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2197 BaseCallback = &CXXRecordDecl::FindTagMember;
2201 BaseCallback = &LookupAnyMember;
2204 case LookupOMPReductionName:
2205 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2208 case LookupOMPMapperName:
2209 BaseCallback = &CXXRecordDecl::FindOMPMapperMember;
2212 case LookupUsingDeclName:
2213 // This lookup is for redeclarations only.
2215 case LookupOperatorName:
2216 case LookupNamespaceName:
2217 case LookupObjCProtocolName:
2219 // These lookups will never find a member in a C++ class (or base class).
2222 case LookupNestedNameSpecifierName:
2223 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2227 DeclarationName Name = R.getLookupName();
2228 if (!LookupRec->lookupInBases(
2229 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2230 return BaseCallback(Specifier, Path, Name);
2235 R.setNamingClass(LookupRec);
2237 // C++ [class.member.lookup]p2:
2238 // [...] If the resulting set of declarations are not all from
2239 // sub-objects of the same type, or the set has a nonstatic member
2240 // and includes members from distinct sub-objects, there is an
2241 // ambiguity and the program is ill-formed. Otherwise that set is
2242 // the result of the lookup.
2243 QualType SubobjectType;
2244 int SubobjectNumber = 0;
2245 AccessSpecifier SubobjectAccess = AS_none;
2247 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2248 Path != PathEnd; ++Path) {
2249 const CXXBasePathElement &PathElement = Path->back();
2251 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2252 // across all paths.
2253 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2255 // Determine whether we're looking at a distinct sub-object or not.
2256 if (SubobjectType.isNull()) {
2257 // This is the first subobject we've looked at. Record its type.
2258 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2259 SubobjectNumber = PathElement.SubobjectNumber;
2264 != Context.getCanonicalType(PathElement.Base->getType())) {
2265 // We found members of the given name in two subobjects of
2266 // different types. If the declaration sets aren't the same, this
2267 // lookup is ambiguous.
2268 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
2269 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
2270 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2271 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
2273 // Get the decl that we should use for deduplicating this lookup.
2274 auto GetRepresentativeDecl = [&](NamedDecl *D) -> Decl * {
2275 // C++ [temp.local]p3:
2276 // A lookup that finds an injected-class-name (10.2) can result in
2277 // an ambiguity in certain cases (for example, if it is found in
2278 // more than one base class). If all of the injected-class-names
2279 // that are found refer to specializations of the same class
2280 // template, and if the name is used as a template-name, the
2281 // reference refers to the class template itself and not a
2282 // specialization thereof, and is not ambiguous.
2283 if (R.isTemplateNameLookup())
2284 if (auto *TD = getAsTemplateNameDecl(D))
2286 return D->getUnderlyingDecl()->getCanonicalDecl();
2289 while (FirstD != FirstPath->Decls.end() &&
2290 CurrentD != Path->Decls.end()) {
2291 if (GetRepresentativeDecl(*FirstD) !=
2292 GetRepresentativeDecl(*CurrentD))
2299 if (FirstD == FirstPath->Decls.end() &&
2300 CurrentD == Path->Decls.end())
2304 R.setAmbiguousBaseSubobjectTypes(Paths);
2308 if (SubobjectNumber != PathElement.SubobjectNumber) {
2309 // We have a different subobject of the same type.
2311 // C++ [class.member.lookup]p5:
2312 // A static member, a nested type or an enumerator defined in
2313 // a base class T can unambiguously be found even if an object
2314 // has more than one base class subobject of type T.
2315 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
2318 // We have found a nonstatic member name in multiple, distinct
2319 // subobjects. Name lookup is ambiguous.
2320 R.setAmbiguousBaseSubobjects(Paths);
2325 // Lookup in a base class succeeded; return these results.
2327 for (auto *D : Paths.front().Decls) {
2328 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2336 /// Performs qualified name lookup or special type of lookup for
2337 /// "__super::" scope specifier.
2339 /// This routine is a convenience overload meant to be called from contexts
2340 /// that need to perform a qualified name lookup with an optional C++ scope
2341 /// specifier that might require special kind of lookup.
2343 /// \param R captures both the lookup criteria and any lookup results found.
2345 /// \param LookupCtx The context in which qualified name lookup will
2348 /// \param SS An optional C++ scope-specifier.
2350 /// \returns true if lookup succeeded, false if it failed.
2351 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2353 auto *NNS = SS.getScopeRep();
2354 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2355 return LookupInSuper(R, NNS->getAsRecordDecl());
2358 return LookupQualifiedName(R, LookupCtx);
2361 /// Performs name lookup for a name that was parsed in the
2362 /// source code, and may contain a C++ scope specifier.
2364 /// This routine is a convenience routine meant to be called from
2365 /// contexts that receive a name and an optional C++ scope specifier
2366 /// (e.g., "N::M::x"). It will then perform either qualified or
2367 /// unqualified name lookup (with LookupQualifiedName or LookupName,
2368 /// respectively) on the given name and return those results. It will
2369 /// perform a special type of lookup for "__super::" scope specifier.
2371 /// @param S The scope from which unqualified name lookup will
2374 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2376 /// @param EnteringContext Indicates whether we are going to enter the
2377 /// context of the scope-specifier SS (if present).
2379 /// @returns True if any decls were found (but possibly ambiguous)
2380 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2381 bool AllowBuiltinCreation, bool EnteringContext) {
2382 if (SS && SS->isInvalid()) {
2383 // When the scope specifier is invalid, don't even look for
2388 if (SS && SS->isSet()) {
2389 NestedNameSpecifier *NNS = SS->getScopeRep();
2390 if (NNS->getKind() == NestedNameSpecifier::Super)
2391 return LookupInSuper(R, NNS->getAsRecordDecl());
2393 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2394 // We have resolved the scope specifier to a particular declaration
2395 // contex, and will perform name lookup in that context.
2396 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2399 R.setContextRange(SS->getRange());
2400 return LookupQualifiedName(R, DC);
2403 // We could not resolve the scope specified to a specific declaration
2404 // context, which means that SS refers to an unknown specialization.
2405 // Name lookup can't find anything in this case.
2406 R.setNotFoundInCurrentInstantiation();
2407 R.setContextRange(SS->getRange());
2411 // Perform unqualified name lookup starting in the given scope.
2412 return LookupName(R, S, AllowBuiltinCreation);
2415 /// Perform qualified name lookup into all base classes of the given
2418 /// \param R captures both the lookup criteria and any lookup results found.
2420 /// \param Class The context in which qualified name lookup will
2421 /// search. Name lookup will search in all base classes merging the results.
2423 /// @returns True if any decls were found (but possibly ambiguous)
2424 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2425 // The access-control rules we use here are essentially the rules for
2426 // doing a lookup in Class that just magically skipped the direct
2427 // members of Class itself. That is, the naming class is Class, and the
2428 // access includes the access of the base.
2429 for (const auto &BaseSpec : Class->bases()) {
2430 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2431 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2432 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2433 Result.setBaseObjectType(Context.getRecordType(Class));
2434 LookupQualifiedName(Result, RD);
2436 // Copy the lookup results into the target, merging the base's access into
2438 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2439 R.addDecl(I.getDecl(),
2440 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2444 Result.suppressDiagnostics();
2448 R.setNamingClass(Class);
2453 /// Produce a diagnostic describing the ambiguity that resulted
2454 /// from name lookup.
2456 /// \param Result The result of the ambiguous lookup to be diagnosed.
2457 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2458 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2460 DeclarationName Name = Result.getLookupName();
2461 SourceLocation NameLoc = Result.getNameLoc();
2462 SourceRange LookupRange = Result.getContextRange();
2464 switch (Result.getAmbiguityKind()) {
2465 case LookupResult::AmbiguousBaseSubobjects: {
2466 CXXBasePaths *Paths = Result.getBasePaths();
2467 QualType SubobjectType = Paths->front().back().Base->getType();
2468 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2469 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2472 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
2473 while (isa<CXXMethodDecl>(*Found) &&
2474 cast<CXXMethodDecl>(*Found)->isStatic())
2477 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2481 case LookupResult::AmbiguousBaseSubobjectTypes: {
2482 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2483 << Name << LookupRange;
2485 CXXBasePaths *Paths = Result.getBasePaths();
2486 std::set<Decl *> DeclsPrinted;
2487 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2488 PathEnd = Paths->end();
2489 Path != PathEnd; ++Path) {
2490 Decl *D = Path->Decls.front();
2491 if (DeclsPrinted.insert(D).second)
2492 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2497 case LookupResult::AmbiguousTagHiding: {
2498 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2500 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2502 for (auto *D : Result)
2503 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2504 TagDecls.insert(TD);
2505 Diag(TD->getLocation(), diag::note_hidden_tag);
2508 for (auto *D : Result)
2509 if (!isa<TagDecl>(D))
2510 Diag(D->getLocation(), diag::note_hiding_object);
2512 // For recovery purposes, go ahead and implement the hiding.
2513 LookupResult::Filter F = Result.makeFilter();
2514 while (F.hasNext()) {
2515 if (TagDecls.count(F.next()))
2522 case LookupResult::AmbiguousReference: {
2523 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2525 for (auto *D : Result)
2526 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2533 struct AssociatedLookup {
2534 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2535 Sema::AssociatedNamespaceSet &Namespaces,
2536 Sema::AssociatedClassSet &Classes)
2537 : S(S), Namespaces(Namespaces), Classes(Classes),
2538 InstantiationLoc(InstantiationLoc) {
2541 bool addClassTransitive(CXXRecordDecl *RD) {
2543 return ClassesTransitive.insert(RD);
2547 Sema::AssociatedNamespaceSet &Namespaces;
2548 Sema::AssociatedClassSet &Classes;
2549 SourceLocation InstantiationLoc;
2552 Sema::AssociatedClassSet ClassesTransitive;
2554 } // end anonymous namespace
2557 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2559 // Given the declaration context \param Ctx of a class, class template or
2560 // enumeration, add the associated namespaces to \param Namespaces as described
2561 // in [basic.lookup.argdep]p2.
2562 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2564 // The exact wording has been changed in C++14 as a result of
2565 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2566 // to all language versions since it is possible to return a local type
2567 // from a lambda in C++11.
2569 // C++14 [basic.lookup.argdep]p2:
2570 // If T is a class type [...]. Its associated namespaces are the innermost
2571 // enclosing namespaces of its associated classes. [...]
2573 // If T is an enumeration type, its associated namespace is the innermost
2574 // enclosing namespace of its declaration. [...]
2576 // We additionally skip inline namespaces. The innermost non-inline namespace
2577 // contains all names of all its nested inline namespaces anyway, so we can
2578 // replace the entire inline namespace tree with its root.
2579 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2580 Ctx = Ctx->getParent();
2582 Namespaces.insert(Ctx->getPrimaryContext());
2585 // Add the associated classes and namespaces for argument-dependent
2586 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2588 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2589 const TemplateArgument &Arg) {
2590 // C++ [basic.lookup.argdep]p2, last bullet:
2592 switch (Arg.getKind()) {
2593 case TemplateArgument::Null:
2596 case TemplateArgument::Type:
2597 // [...] the namespaces and classes associated with the types of the
2598 // template arguments provided for template type parameters (excluding
2599 // template template parameters)
2600 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2603 case TemplateArgument::Template:
2604 case TemplateArgument::TemplateExpansion: {
2605 // [...] the namespaces in which any template template arguments are
2606 // defined; and the classes in which any member templates used as
2607 // template template arguments are defined.
2608 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2609 if (ClassTemplateDecl *ClassTemplate
2610 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2611 DeclContext *Ctx = ClassTemplate->getDeclContext();
2612 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2613 Result.Classes.insert(EnclosingClass);
2614 // Add the associated namespace for this class.
2615 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2620 case TemplateArgument::Declaration:
2621 case TemplateArgument::Integral:
2622 case TemplateArgument::Expression:
2623 case TemplateArgument::NullPtr:
2624 // [Note: non-type template arguments do not contribute to the set of
2625 // associated namespaces. ]
2628 case TemplateArgument::Pack:
2629 for (const auto &P : Arg.pack_elements())
2630 addAssociatedClassesAndNamespaces(Result, P);
2635 // Add the associated classes and namespaces for argument-dependent lookup
2636 // with an argument of class type (C++ [basic.lookup.argdep]p2).
2638 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2639 CXXRecordDecl *Class) {
2641 // Just silently ignore anything whose name is __va_list_tag.
2642 if (Class->getDeclName() == Result.S.VAListTagName)
2645 // C++ [basic.lookup.argdep]p2:
2647 // -- If T is a class type (including unions), its associated
2648 // classes are: the class itself; the class of which it is a
2649 // member, if any; and its direct and indirect base classes.
2650 // Its associated namespaces are the innermost enclosing
2651 // namespaces of its associated classes.
2653 // Add the class of which it is a member, if any.
2654 DeclContext *Ctx = Class->getDeclContext();
2655 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2656 Result.Classes.insert(EnclosingClass);
2658 // Add the associated namespace for this class.
2659 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2661 // -- If T is a template-id, its associated namespaces and classes are
2662 // the namespace in which the template is defined; for member
2663 // templates, the member template's class; the namespaces and classes
2664 // associated with the types of the template arguments provided for
2665 // template type parameters (excluding template template parameters); the
2666 // namespaces in which any template template arguments are defined; and
2667 // the classes in which any member templates used as template template
2668 // arguments are defined. [Note: non-type template arguments do not
2669 // contribute to the set of associated namespaces. ]
2670 if (ClassTemplateSpecializationDecl *Spec
2671 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2672 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2673 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2674 Result.Classes.insert(EnclosingClass);
2675 // Add the associated namespace for this class.
2676 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2678 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2679 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2680 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2683 // Add the class itself. If we've already transitively visited this class,
2684 // we don't need to visit base classes.
2685 if (!Result.addClassTransitive(Class))
2688 // Only recurse into base classes for complete types.
2689 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2690 Result.S.Context.getRecordType(Class)))
2693 // Add direct and indirect base classes along with their associated
2695 SmallVector<CXXRecordDecl *, 32> Bases;
2696 Bases.push_back(Class);
2697 while (!Bases.empty()) {
2698 // Pop this class off the stack.
2699 Class = Bases.pop_back_val();
2701 // Visit the base classes.
2702 for (const auto &Base : Class->bases()) {
2703 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2704 // In dependent contexts, we do ADL twice, and the first time around,
2705 // the base type might be a dependent TemplateSpecializationType, or a
2706 // TemplateTypeParmType. If that happens, simply ignore it.
2707 // FIXME: If we want to support export, we probably need to add the
2708 // namespace of the template in a TemplateSpecializationType, or even
2709 // the classes and namespaces of known non-dependent arguments.
2712 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2713 if (Result.addClassTransitive(BaseDecl)) {
2714 // Find the associated namespace for this base class.
2715 DeclContext *BaseCtx = BaseDecl->getDeclContext();
2716 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2718 // Make sure we visit the bases of this base class.
2719 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2720 Bases.push_back(BaseDecl);
2726 // Add the associated classes and namespaces for
2727 // argument-dependent lookup with an argument of type T
2728 // (C++ [basic.lookup.koenig]p2).
2730 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2731 // C++ [basic.lookup.koenig]p2:
2733 // For each argument type T in the function call, there is a set
2734 // of zero or more associated namespaces and a set of zero or more
2735 // associated classes to be considered. The sets of namespaces and
2736 // classes is determined entirely by the types of the function
2737 // arguments (and the namespace of any template template
2738 // argument). Typedef names and using-declarations used to specify
2739 // the types do not contribute to this set. The sets of namespaces
2740 // and classes are determined in the following way:
2742 SmallVector<const Type *, 16> Queue;
2743 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2746 switch (T->getTypeClass()) {
2748 #define TYPE(Class, Base)
2749 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2750 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2751 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2752 #define ABSTRACT_TYPE(Class, Base)
2753 #include "clang/AST/TypeNodes.def"
2754 // T is canonical. We can also ignore dependent types because
2755 // we don't need to do ADL at the definition point, but if we
2756 // wanted to implement template export (or if we find some other
2757 // use for associated classes and namespaces...) this would be
2761 // -- If T is a pointer to U or an array of U, its associated
2762 // namespaces and classes are those associated with U.
2764 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2766 case Type::ConstantArray:
2767 case Type::IncompleteArray:
2768 case Type::VariableArray:
2769 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2772 // -- If T is a fundamental type, its associated sets of
2773 // namespaces and classes are both empty.
2777 // -- If T is a class type (including unions), its associated
2778 // classes are: the class itself; the class of which it is
2779 // a member, if any; and its direct and indirect base classes.
2780 // Its associated namespaces are the innermost enclosing
2781 // namespaces of its associated classes.
2782 case Type::Record: {
2783 CXXRecordDecl *Class =
2784 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2785 addAssociatedClassesAndNamespaces(Result, Class);
2789 // -- If T is an enumeration type, its associated namespace
2790 // is the innermost enclosing namespace of its declaration.
2791 // If it is a class member, its associated class is the
2792 // member’s class; else it has no associated class.
2794 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2796 DeclContext *Ctx = Enum->getDeclContext();
2797 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2798 Result.Classes.insert(EnclosingClass);
2800 // Add the associated namespace for this enumeration.
2801 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2806 // -- If T is a function type, its associated namespaces and
2807 // classes are those associated with the function parameter
2808 // types and those associated with the return type.
2809 case Type::FunctionProto: {
2810 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2811 for (const auto &Arg : Proto->param_types())
2812 Queue.push_back(Arg.getTypePtr());
2816 case Type::FunctionNoProto: {
2817 const FunctionType *FnType = cast<FunctionType>(T);
2818 T = FnType->getReturnType().getTypePtr();
2822 // -- If T is a pointer to a member function of a class X, its
2823 // associated namespaces and classes are those associated
2824 // with the function parameter types and return type,
2825 // together with those associated with X.
2827 // -- If T is a pointer to a data member of class X, its
2828 // associated namespaces and classes are those associated
2829 // with the member type together with those associated with
2831 case Type::MemberPointer: {
2832 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2834 // Queue up the class type into which this points.
2835 Queue.push_back(MemberPtr->getClass());
2837 // And directly continue with the pointee type.
2838 T = MemberPtr->getPointeeType().getTypePtr();
2842 // As an extension, treat this like a normal pointer.
2843 case Type::BlockPointer:
2844 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2847 // References aren't covered by the standard, but that's such an
2848 // obvious defect that we cover them anyway.
2849 case Type::LValueReference:
2850 case Type::RValueReference:
2851 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2854 // These are fundamental types.
2856 case Type::ExtVector:
2860 // Non-deduced auto types only get here for error cases.
2862 case Type::DeducedTemplateSpecialization:
2865 // If T is an Objective-C object or interface type, or a pointer to an
2866 // object or interface type, the associated namespace is the global
2868 case Type::ObjCObject:
2869 case Type::ObjCInterface:
2870 case Type::ObjCObjectPointer:
2871 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2874 // Atomic types are just wrappers; use the associations of the
2877 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2880 T = cast<PipeType>(T)->getElementType().getTypePtr();
2886 T = Queue.pop_back_val();
2890 /// Find the associated classes and namespaces for
2891 /// argument-dependent lookup for a call with the given set of
2894 /// This routine computes the sets of associated classes and associated
2895 /// namespaces searched by argument-dependent lookup
2896 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
2897 void Sema::FindAssociatedClassesAndNamespaces(
2898 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2899 AssociatedNamespaceSet &AssociatedNamespaces,
2900 AssociatedClassSet &AssociatedClasses) {
2901 AssociatedNamespaces.clear();
2902 AssociatedClasses.clear();
2904 AssociatedLookup Result(*this, InstantiationLoc,
2905 AssociatedNamespaces, AssociatedClasses);
2907 // C++ [basic.lookup.koenig]p2:
2908 // For each argument type T in the function call, there is a set
2909 // of zero or more associated namespaces and a set of zero or more
2910 // associated classes to be considered. The sets of namespaces and
2911 // classes is determined entirely by the types of the function
2912 // arguments (and the namespace of any template template
2914 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2915 Expr *Arg = Args[ArgIdx];
2917 if (Arg->getType() != Context.OverloadTy) {
2918 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2922 // [...] In addition, if the argument is the name or address of a
2923 // set of overloaded functions and/or function templates, its
2924 // associated classes and namespaces are the union of those
2925 // associated with each of the members of the set: the namespace
2926 // in which the function or function template is defined and the
2927 // classes and namespaces associated with its (non-dependent)
2928 // parameter types and return type.
2929 OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
2931 for (const NamedDecl *D : OE->decls()) {
2932 // Look through any using declarations to find the underlying function.
2933 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
2935 // Add the classes and namespaces associated with the parameter
2936 // types and return type of this function.
2937 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2942 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2944 LookupNameKind NameKind,
2945 RedeclarationKind Redecl) {
2946 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2948 return R.getAsSingle<NamedDecl>();
2951 /// Find the protocol with the given name, if any.
2952 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2953 SourceLocation IdLoc,
2954 RedeclarationKind Redecl) {
2955 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2956 LookupObjCProtocolName, Redecl);
2957 return cast_or_null<ObjCProtocolDecl>(D);
2960 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2961 QualType T1, QualType T2,
2962 UnresolvedSetImpl &Functions) {
2963 // C++ [over.match.oper]p3:
2964 // -- The set of non-member candidates is the result of the
2965 // unqualified lookup of operator@ in the context of the
2966 // expression according to the usual rules for name lookup in
2967 // unqualified function calls (3.4.2) except that all member
2968 // functions are ignored.
2969 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2970 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2971 LookupName(Operators, S);
2973 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
2974 Functions.append(Operators.begin(), Operators.end());
2977 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
2978 CXXSpecialMember SM,
2983 bool VolatileThis) {
2984 assert(CanDeclareSpecialMemberFunction(RD) &&
2985 "doing special member lookup into record that isn't fully complete");
2986 RD = RD->getDefinition();
2987 if (RValueThis || ConstThis || VolatileThis)
2988 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
2989 "constructors and destructors always have unqualified lvalue this");
2990 if (ConstArg || VolatileArg)
2991 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
2992 "parameter-less special members can't have qualified arguments");
2994 // FIXME: Get the caller to pass in a location for the lookup.
2995 SourceLocation LookupLoc = RD->getLocation();
2997 llvm::FoldingSetNodeID ID;
3000 ID.AddInteger(ConstArg);
3001 ID.AddInteger(VolatileArg);
3002 ID.AddInteger(RValueThis);
3003 ID.AddInteger(ConstThis);
3004 ID.AddInteger(VolatileThis);
3007 SpecialMemberOverloadResultEntry *Result =
3008 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3010 // This was already cached
3014 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
3015 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
3016 SpecialMemberCache.InsertNode(Result, InsertPoint);
3018 if (SM == CXXDestructor) {
3019 if (RD->needsImplicitDestructor())
3020 DeclareImplicitDestructor(RD);
3021 CXXDestructorDecl *DD = RD->getDestructor();
3022 assert(DD && "record without a destructor");
3023 Result->setMethod(DD);
3024 Result->setKind(DD->isDeleted() ?
3025 SpecialMemberOverloadResult::NoMemberOrDeleted :
3026 SpecialMemberOverloadResult::Success);
3030 // Prepare for overload resolution. Here we construct a synthetic argument
3031 // if necessary and make sure that implicit functions are declared.
3032 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
3033 DeclarationName Name;
3034 Expr *Arg = nullptr;
3037 QualType ArgType = CanTy;
3038 ExprValueKind VK = VK_LValue;
3040 if (SM == CXXDefaultConstructor) {
3041 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3043 if (RD->needsImplicitDefaultConstructor())
3044 DeclareImplicitDefaultConstructor(RD);
3046 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
3047 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3048 if (RD->needsImplicitCopyConstructor())
3049 DeclareImplicitCopyConstructor(RD);
3050 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
3051 DeclareImplicitMoveConstructor(RD);
3053 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3054 if (RD->needsImplicitCopyAssignment())
3055 DeclareImplicitCopyAssignment(RD);
3056 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
3057 DeclareImplicitMoveAssignment(RD);
3063 ArgType.addVolatile();
3065 // This isn't /really/ specified by the standard, but it's implied
3066 // we should be working from an RValue in the case of move to ensure
3067 // that we prefer to bind to rvalue references, and an LValue in the
3068 // case of copy to ensure we don't bind to rvalue references.
3069 // Possibly an XValue is actually correct in the case of move, but
3070 // there is no semantic difference for class types in this restricted
3072 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
3078 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3080 if (SM != CXXDefaultConstructor) {
3085 // Create the object argument
3086 QualType ThisTy = CanTy;
3090 ThisTy.addVolatile();
3091 Expr::Classification Classification =
3092 OpaqueValueExpr(LookupLoc, ThisTy,
3093 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
3095 // Now we perform lookup on the name we computed earlier and do overload
3096 // resolution. Lookup is only performed directly into the class since there
3097 // will always be a (possibly implicit) declaration to shadow any others.
3098 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
3099 DeclContext::lookup_result R = RD->lookup(Name);
3102 // We might have no default constructor because we have a lambda's closure
3103 // type, rather than because there's some other declared constructor.
3104 // Every class has a copy/move constructor, copy/move assignment, and
3106 assert(SM == CXXDefaultConstructor &&
3107 "lookup for a constructor or assignment operator was empty");
3108 Result->setMethod(nullptr);
3109 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3113 // Copy the candidates as our processing of them may load new declarations
3114 // from an external source and invalidate lookup_result.
3115 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3117 for (NamedDecl *CandDecl : Candidates) {
3118 if (CandDecl->isInvalidDecl())
3121 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3122 auto CtorInfo = getConstructorInfo(Cand);
3123 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3124 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3125 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3126 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3128 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3129 llvm::makeArrayRef(&Arg, NumArgs), OCS,
3130 /*SuppressUserConversions*/ true);
3132 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3133 /*SuppressUserConversions*/ true);
3134 } else if (FunctionTemplateDecl *Tmpl =
3135 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3136 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3137 AddMethodTemplateCandidate(
3138 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
3139 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3141 AddTemplateOverloadCandidate(
3142 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3143 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3145 AddTemplateOverloadCandidate(
3146 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3148 assert(isa<UsingDecl>(Cand.getDecl()) &&
3149 "illegal Kind of operator = Decl");
3153 OverloadCandidateSet::iterator Best;
3154 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3156 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3157 Result->setKind(SpecialMemberOverloadResult::Success);
3161 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3162 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3166 Result->setMethod(nullptr);
3167 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3170 case OR_No_Viable_Function:
3171 Result->setMethod(nullptr);
3172 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3179 /// Look up the default constructor for the given class.
3180 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3181 SpecialMemberOverloadResult Result =
3182 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3185 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3188 /// Look up the copying constructor for the given class.
3189 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3191 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3192 "non-const, non-volatile qualifiers for copy ctor arg");
3193 SpecialMemberOverloadResult Result =
3194 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3195 Quals & Qualifiers::Volatile, false, false, false);
3197 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3200 /// Look up the moving constructor for the given class.
3201 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3203 SpecialMemberOverloadResult Result =
3204 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3205 Quals & Qualifiers::Volatile, false, false, false);
3207 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3210 /// Look up the constructors for the given class.
3211 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3212 // If the implicit constructors have not yet been declared, do so now.
3213 if (CanDeclareSpecialMemberFunction(Class)) {
3214 if (Class->needsImplicitDefaultConstructor())
3215 DeclareImplicitDefaultConstructor(Class);
3216 if (Class->needsImplicitCopyConstructor())
3217 DeclareImplicitCopyConstructor(Class);
3218 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3219 DeclareImplicitMoveConstructor(Class);
3222 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3223 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3224 return Class->lookup(Name);
3227 /// Look up the copying assignment operator for the given class.
3228 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3229 unsigned Quals, bool RValueThis,
3230 unsigned ThisQuals) {
3231 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3232 "non-const, non-volatile qualifiers for copy assignment arg");
3233 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3234 "non-const, non-volatile qualifiers for copy assignment this");
3235 SpecialMemberOverloadResult Result =
3236 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3237 Quals & Qualifiers::Volatile, RValueThis,
3238 ThisQuals & Qualifiers::Const,
3239 ThisQuals & Qualifiers::Volatile);
3241 return Result.getMethod();
3244 /// Look up the moving assignment operator for the given class.
3245 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3248 unsigned ThisQuals) {
3249 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3250 "non-const, non-volatile qualifiers for copy assignment this");
3251 SpecialMemberOverloadResult Result =
3252 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3253 Quals & Qualifiers::Volatile, RValueThis,
3254 ThisQuals & Qualifiers::Const,
3255 ThisQuals & Qualifiers::Volatile);
3257 return Result.getMethod();
3260 /// Look for the destructor of the given class.
3262 /// During semantic analysis, this routine should be used in lieu of
3263 /// CXXRecordDecl::getDestructor().
3265 /// \returns The destructor for this class.
3266 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3267 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3268 false, false, false,
3269 false, false).getMethod());
3272 /// LookupLiteralOperator - Determine which literal operator should be used for
3273 /// a user-defined literal, per C++11 [lex.ext].
3275 /// Normal overload resolution is not used to select which literal operator to
3276 /// call for a user-defined literal. Look up the provided literal operator name,
3277 /// and filter the results to the appropriate set for the given argument types.
3278 Sema::LiteralOperatorLookupResult
3279 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3280 ArrayRef<QualType> ArgTys,
3281 bool AllowRaw, bool AllowTemplate,
3282 bool AllowStringTemplate, bool DiagnoseMissing) {
3284 assert(R.getResultKind() != LookupResult::Ambiguous &&
3285 "literal operator lookup can't be ambiguous");
3287 // Filter the lookup results appropriately.
3288 LookupResult::Filter F = R.makeFilter();
3290 bool FoundRaw = false;
3291 bool FoundTemplate = false;
3292 bool FoundStringTemplate = false;
3293 bool FoundExactMatch = false;
3295 while (F.hasNext()) {
3297 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3298 D = USD->getTargetDecl();
3300 // If the declaration we found is invalid, skip it.
3301 if (D->isInvalidDecl()) {
3307 bool IsTemplate = false;
3308 bool IsStringTemplate = false;
3309 bool IsExactMatch = false;
3311 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3312 if (FD->getNumParams() == 1 &&
3313 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3315 else if (FD->getNumParams() == ArgTys.size()) {
3316 IsExactMatch = true;
3317 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3318 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3319 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3320 IsExactMatch = false;
3326 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3327 TemplateParameterList *Params = FD->getTemplateParameters();
3328 if (Params->size() == 1)
3331 IsStringTemplate = true;
3335 FoundExactMatch = true;
3337 AllowTemplate = false;
3338 AllowStringTemplate = false;
3339 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
3340 // Go through again and remove the raw and template decls we've
3343 FoundRaw = FoundTemplate = FoundStringTemplate = false;
3345 } else if (AllowRaw && IsRaw) {
3347 } else if (AllowTemplate && IsTemplate) {
3348 FoundTemplate = true;
3349 } else if (AllowStringTemplate && IsStringTemplate) {
3350 FoundStringTemplate = true;
3358 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3359 // parameter type, that is used in preference to a raw literal operator
3360 // or literal operator template.
3361 if (FoundExactMatch)
3364 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3365 // operator template, but not both.
3366 if (FoundRaw && FoundTemplate) {
3367 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3368 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3369 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
3377 return LOLR_Template;
3379 if (FoundStringTemplate)
3380 return LOLR_StringTemplate;
3382 // Didn't find anything we could use.
3383 if (DiagnoseMissing) {
3384 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3385 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3386 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3387 << (AllowTemplate || AllowStringTemplate);
3391 return LOLR_ErrorNoDiagnostic;
3394 void ADLResult::insert(NamedDecl *New) {
3395 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3397 // If we haven't yet seen a decl for this key, or the last decl
3398 // was exactly this one, we're done.
3399 if (Old == nullptr || Old == New) {
3404 // Otherwise, decide which is a more recent redeclaration.
3405 FunctionDecl *OldFD = Old->getAsFunction();
3406 FunctionDecl *NewFD = New->getAsFunction();
3408 FunctionDecl *Cursor = NewFD;
3410 Cursor = Cursor->getPreviousDecl();
3412 // If we got to the end without finding OldFD, OldFD is the newer
3413 // declaration; leave things as they are.
3414 if (!Cursor) return;
3416 // If we do find OldFD, then NewFD is newer.
3417 if (Cursor == OldFD) break;
3419 // Otherwise, keep looking.
3425 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3426 ArrayRef<Expr *> Args, ADLResult &Result) {
3427 // Find all of the associated namespaces and classes based on the
3428 // arguments we have.
3429 AssociatedNamespaceSet AssociatedNamespaces;
3430 AssociatedClassSet AssociatedClasses;
3431 FindAssociatedClassesAndNamespaces(Loc, Args,
3432 AssociatedNamespaces,
3435 // C++ [basic.lookup.argdep]p3:
3436 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3437 // and let Y be the lookup set produced by argument dependent
3438 // lookup (defined as follows). If X contains [...] then Y is
3439 // empty. Otherwise Y is the set of declarations found in the
3440 // namespaces associated with the argument types as described
3441 // below. The set of declarations found by the lookup of the name
3442 // is the union of X and Y.
3444 // Here, we compute Y and add its members to the overloaded
3446 for (auto *NS : AssociatedNamespaces) {
3447 // When considering an associated namespace, the lookup is the
3448 // same as the lookup performed when the associated namespace is
3449 // used as a qualifier (3.4.3.2) except that:
3451 // -- Any using-directives in the associated namespace are
3454 // -- Any namespace-scope friend functions declared in
3455 // associated classes are visible within their respective
3456 // namespaces even if they are not visible during an ordinary
3458 DeclContext::lookup_result R = NS->lookup(Name);
3460 auto *Underlying = D;
3461 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3462 Underlying = USD->getTargetDecl();
3464 if (!isa<FunctionDecl>(Underlying) &&
3465 !isa<FunctionTemplateDecl>(Underlying))
3468 // The declaration is visible to argument-dependent lookup if either
3469 // it's ordinarily visible or declared as a friend in an associated
3471 bool Visible = false;
3472 for (D = D->getMostRecentDecl(); D;
3473 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3474 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3479 } else if (D->getFriendObjectKind()) {
3480 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3481 if (AssociatedClasses.count(RD) && isVisible(D)) {
3488 // FIXME: Preserve D as the FoundDecl.
3490 Result.insert(Underlying);
3495 //----------------------------------------------------------------------------
3496 // Search for all visible declarations.
3497 //----------------------------------------------------------------------------
3498 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3500 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3504 class ShadowContextRAII;
3506 class VisibleDeclsRecord {
3508 /// An entry in the shadow map, which is optimized to store a
3509 /// single declaration (the common case) but can also store a list
3510 /// of declarations.
3511 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3514 /// A mapping from declaration names to the declarations that have
3515 /// this name within a particular scope.
3516 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3518 /// A list of shadow maps, which is used to model name hiding.
3519 std::list<ShadowMap> ShadowMaps;
3521 /// The declaration contexts we have already visited.
3522 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3524 friend class ShadowContextRAII;
3527 /// Determine whether we have already visited this context
3528 /// (and, if not, note that we are going to visit that context now).
3529 bool visitedContext(DeclContext *Ctx) {
3530 return !VisitedContexts.insert(Ctx).second;
3533 bool alreadyVisitedContext(DeclContext *Ctx) {
3534 return VisitedContexts.count(Ctx);
3537 /// Determine whether the given declaration is hidden in the
3540 /// \returns the declaration that hides the given declaration, or
3541 /// NULL if no such declaration exists.
3542 NamedDecl *checkHidden(NamedDecl *ND);
3544 /// Add a declaration to the current shadow map.
3545 void add(NamedDecl *ND) {
3546 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3550 /// RAII object that records when we've entered a shadow context.
3551 class ShadowContextRAII {
3552 VisibleDeclsRecord &Visible;
3554 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3557 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3558 Visible.ShadowMaps.emplace_back();
3561 ~ShadowContextRAII() {
3562 Visible.ShadowMaps.pop_back();
3566 } // end anonymous namespace
3568 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3569 unsigned IDNS = ND->getIdentifierNamespace();
3570 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3571 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3572 SM != SMEnd; ++SM) {
3573 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3574 if (Pos == SM->end())
3577 for (auto *D : Pos->second) {
3578 // A tag declaration does not hide a non-tag declaration.
3579 if (D->hasTagIdentifierNamespace() &&
3580 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3581 Decl::IDNS_ObjCProtocol)))
3584 // Protocols are in distinct namespaces from everything else.
3585 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3586 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3587 D->getIdentifierNamespace() != IDNS)
3590 // Functions and function templates in the same scope overload
3591 // rather than hide. FIXME: Look for hiding based on function
3593 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3594 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3595 SM == ShadowMaps.rbegin())
3598 // A shadow declaration that's created by a resolved using declaration
3599 // is not hidden by the same using declaration.
3600 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3601 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3604 // We've found a declaration that hides this one.
3612 static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3613 bool QualifiedNameLookup,
3615 VisibleDeclConsumer &Consumer,
3616 VisibleDeclsRecord &Visited,
3617 bool IncludeDependentBases,
3618 bool LoadExternal) {
3622 // Make sure we don't visit the same context twice.
3623 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3626 Consumer.EnteredContext(Ctx);
3628 // Outside C++, lookup results for the TU live on identifiers.
3629 if (isa<TranslationUnitDecl>(Ctx) &&
3630 !Result.getSema().getLangOpts().CPlusPlus) {
3631 auto &S = Result.getSema();
3632 auto &Idents = S.Context.Idents;
3634 // Ensure all external identifiers are in the identifier table.
3636 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3637 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3638 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3642 // Walk all lookup results in the TU for each identifier.
3643 for (const auto &Ident : Idents) {
3644 for (auto I = S.IdResolver.begin(Ident.getValue()),
3645 E = S.IdResolver.end();
3647 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3648 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3649 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3659 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3660 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3662 // We sometimes skip loading namespace-level results (they tend to be huge).
3663 bool Load = LoadExternal ||
3664 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
3665 // Enumerate all of the results in this context.
3666 for (DeclContextLookupResult R :
3667 Load ? Ctx->lookups()
3668 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
3670 if (auto *ND = Result.getAcceptableDecl(D)) {
3671 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3677 // Traverse using directives for qualified name lookup.
3678 if (QualifiedNameLookup) {
3679 ShadowContextRAII Shadow(Visited);
3680 for (auto I : Ctx->using_directives()) {
3681 if (!Result.getSema().isVisible(I))
3683 LookupVisibleDecls(I->getNominatedNamespace(), Result,
3684 QualifiedNameLookup, InBaseClass, Consumer, Visited,
3685 IncludeDependentBases, LoadExternal);
3689 // Traverse the contexts of inherited C++ classes.
3690 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3691 if (!Record->hasDefinition())
3694 for (const auto &B : Record->bases()) {
3695 QualType BaseType = B.getType();
3698 if (BaseType->isDependentType()) {
3699 if (!IncludeDependentBases) {
3700 // Don't look into dependent bases, because name lookup can't look
3704 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3707 TemplateName TN = TST->getTemplateName();
3709 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3712 RD = TD->getTemplatedDecl();
3714 const auto *Record = BaseType->getAs<RecordType>();
3717 RD = Record->getDecl();
3720 // FIXME: It would be nice to be able to determine whether referencing
3721 // a particular member would be ambiguous. For example, given
3723 // struct A { int member; };
3724 // struct B { int member; };
3725 // struct C : A, B { };
3727 // void f(C *c) { c->### }
3729 // accessing 'member' would result in an ambiguity. However, we
3730 // could be smart enough to qualify the member with the base
3739 // Find results in this base class (and its bases).
3740 ShadowContextRAII Shadow(Visited);
3741 LookupVisibleDecls(RD, Result, QualifiedNameLookup, /*InBaseClass=*/true,
3742 Consumer, Visited, IncludeDependentBases,
3747 // Traverse the contexts of Objective-C classes.
3748 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3749 // Traverse categories.
3750 for (auto *Cat : IFace->visible_categories()) {
3751 ShadowContextRAII Shadow(Visited);
3752 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer,
3753 Visited, IncludeDependentBases, LoadExternal);
3756 // Traverse protocols.
3757 for (auto *I : IFace->all_referenced_protocols()) {
3758 ShadowContextRAII Shadow(Visited);
3759 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3760 Visited, IncludeDependentBases, LoadExternal);
3763 // Traverse the superclass.
3764 if (IFace->getSuperClass()) {
3765 ShadowContextRAII Shadow(Visited);
3766 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
3767 true, Consumer, Visited, IncludeDependentBases,
3771 // If there is an implementation, traverse it. We do this to find
3772 // synthesized ivars.
3773 if (IFace->getImplementation()) {
3774 ShadowContextRAII Shadow(Visited);
3775 LookupVisibleDecls(IFace->getImplementation(), Result,
3776 QualifiedNameLookup, InBaseClass, Consumer, Visited,
3777 IncludeDependentBases, LoadExternal);
3779 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3780 for (auto *I : Protocol->protocols()) {
3781 ShadowContextRAII Shadow(Visited);
3782 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3783 Visited, IncludeDependentBases, LoadExternal);
3785 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3786 for (auto *I : Category->protocols()) {
3787 ShadowContextRAII Shadow(Visited);
3788 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3789 Visited, IncludeDependentBases, LoadExternal);
3792 // If there is an implementation, traverse it.
3793 if (Category->getImplementation()) {
3794 ShadowContextRAII Shadow(Visited);
3795 LookupVisibleDecls(Category->getImplementation(), Result,
3796 QualifiedNameLookup, true, Consumer, Visited,
3797 IncludeDependentBases, LoadExternal);
3802 static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3803 UnqualUsingDirectiveSet &UDirs,
3804 VisibleDeclConsumer &Consumer,
3805 VisibleDeclsRecord &Visited,
3806 bool LoadExternal) {
3810 if (!S->getEntity() ||
3812 !Visited.alreadyVisitedContext(S->getEntity())) ||
3813 (S->getEntity())->isFunctionOrMethod()) {
3814 FindLocalExternScope FindLocals(Result);
3815 // Walk through the declarations in this Scope. The consumer might add new
3816 // decls to the scope as part of deserialization, so make a copy first.
3817 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3818 for (Decl *D : ScopeDecls) {
3819 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3820 if ((ND = Result.getAcceptableDecl(ND))) {
3821 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
3827 // FIXME: C++ [temp.local]p8
3828 DeclContext *Entity = nullptr;
3829 if (S->getEntity()) {
3830 // Look into this scope's declaration context, along with any of its
3831 // parent lookup contexts (e.g., enclosing classes), up to the point
3832 // where we hit the context stored in the next outer scope.
3833 Entity = S->getEntity();
3834 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3836 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3837 Ctx = Ctx->getLookupParent()) {
3838 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3839 if (Method->isInstanceMethod()) {
3840 // For instance methods, look for ivars in the method's interface.
3841 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3842 Result.getNameLoc(), Sema::LookupMemberName);
3843 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3844 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3845 /*InBaseClass=*/false, Consumer, Visited,
3846 /*IncludeDependentBases=*/false, LoadExternal);
3850 // We've already performed all of the name lookup that we need
3851 // to for Objective-C methods; the next context will be the
3856 if (Ctx->isFunctionOrMethod())
3859 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3860 /*InBaseClass=*/false, Consumer, Visited,
3861 /*IncludeDependentBases=*/false, LoadExternal);
3863 } else if (!S->getParent()) {
3864 // Look into the translation unit scope. We walk through the translation
3865 // unit's declaration context, because the Scope itself won't have all of
3866 // the declarations if we loaded a precompiled header.
3867 // FIXME: We would like the translation unit's Scope object to point to the
3868 // translation unit, so we don't need this special "if" branch. However,
3869 // doing so would force the normal C++ name-lookup code to look into the
3870 // translation unit decl when the IdentifierInfo chains would suffice.
3871 // Once we fix that problem (which is part of a more general "don't look
3872 // in DeclContexts unless we have to" optimization), we can eliminate this.
3873 Entity = Result.getSema().Context.getTranslationUnitDecl();
3874 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3875 /*InBaseClass=*/false, Consumer, Visited,
3876 /*IncludeDependentBases=*/false, LoadExternal);
3880 // Lookup visible declarations in any namespaces found by using
3882 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3883 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
3884 Result, /*QualifiedNameLookup=*/false,
3885 /*InBaseClass=*/false, Consumer, Visited,
3886 /*IncludeDependentBases=*/false, LoadExternal);
3889 // Lookup names in the parent scope.
3890 ShadowContextRAII Shadow(Visited);
3891 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited,
3895 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3896 VisibleDeclConsumer &Consumer,
3897 bool IncludeGlobalScope, bool LoadExternal) {
3898 // Determine the set of using directives available during
3899 // unqualified name lookup.
3901 UnqualUsingDirectiveSet UDirs(*this);
3902 if (getLangOpts().CPlusPlus) {
3903 // Find the first namespace or translation-unit scope.
3904 while (S && !isNamespaceOrTranslationUnitScope(S))
3907 UDirs.visitScopeChain(Initial, S);
3911 // Look for visible declarations.
3912 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3913 Result.setAllowHidden(Consumer.includeHiddenDecls());
3914 VisibleDeclsRecord Visited;
3915 if (!IncludeGlobalScope)
3916 Visited.visitedContext(Context.getTranslationUnitDecl());
3917 ShadowContextRAII Shadow(Visited);
3918 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal);
3921 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3922 VisibleDeclConsumer &Consumer,
3923 bool IncludeGlobalScope,
3924 bool IncludeDependentBases, bool LoadExternal) {
3925 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3926 Result.setAllowHidden(Consumer.includeHiddenDecls());
3927 VisibleDeclsRecord Visited;
3928 if (!IncludeGlobalScope)
3929 Visited.visitedContext(Context.getTranslationUnitDecl());
3930 ShadowContextRAII Shadow(Visited);
3931 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3932 /*InBaseClass=*/false, Consumer, Visited,
3933 IncludeDependentBases, LoadExternal);
3936 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3937 /// If GnuLabelLoc is a valid source location, then this is a definition
3938 /// of an __label__ label name, otherwise it is a normal label definition
3940 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3941 SourceLocation GnuLabelLoc) {
3942 // Do a lookup to see if we have a label with this name already.
3943 NamedDecl *Res = nullptr;
3945 if (GnuLabelLoc.isValid()) {
3946 // Local label definitions always shadow existing labels.
3947 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3948 Scope *S = CurScope;
3949 PushOnScopeChains(Res, S, true);
3950 return cast<LabelDecl>(Res);
3953 // Not a GNU local label.
3954 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3955 // If we found a label, check to see if it is in the same context as us.
3956 // When in a Block, we don't want to reuse a label in an enclosing function.
3957 if (Res && Res->getDeclContext() != CurContext)
3960 // If not forward referenced or defined already, create the backing decl.
3961 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3962 Scope *S = CurScope->getFnParent();
3963 assert(S && "Not in a function?");
3964 PushOnScopeChains(Res, S, true);
3966 return cast<LabelDecl>(Res);
3969 //===----------------------------------------------------------------------===//
3971 //===----------------------------------------------------------------------===//
3973 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3974 TypoCorrection &Candidate) {
3975 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3976 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3979 static void LookupPotentialTypoResult(Sema &SemaRef,
3981 IdentifierInfo *Name,
3982 Scope *S, CXXScopeSpec *SS,
3983 DeclContext *MemberContext,
3984 bool EnteringContext,
3985 bool isObjCIvarLookup,
3988 /// Check whether the declarations found for a typo correction are
3989 /// visible. Set the correction's RequiresImport flag to true if none of the
3990 /// declarations are visible, false otherwise.
3991 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3992 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3994 for (/**/; DI != DE; ++DI)
3995 if (!LookupResult::isVisible(SemaRef, *DI))
3997 // No filtering needed if all decls are visible.
3999 TC.setRequiresImport(false);
4003 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4004 bool AnyVisibleDecls = !NewDecls.empty();
4006 for (/**/; DI != DE; ++DI) {
4007 if (LookupResult::isVisible(SemaRef, *DI)) {
4008 if (!AnyVisibleDecls) {
4009 // Found a visible decl, discard all hidden ones.
4010 AnyVisibleDecls = true;
4013 NewDecls.push_back(*DI);
4014 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4015 NewDecls.push_back(*DI);
4018 if (NewDecls.empty())
4019 TC = TypoCorrection();
4021 TC.setCorrectionDecls(NewDecls);
4022 TC.setRequiresImport(!AnyVisibleDecls);
4026 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4027 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4028 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4029 static void getNestedNameSpecifierIdentifiers(
4030 NestedNameSpecifier *NNS,
4031 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4032 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4033 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4035 Identifiers.clear();
4037 const IdentifierInfo *II = nullptr;
4039 switch (NNS->getKind()) {
4040 case NestedNameSpecifier::Identifier:
4041 II = NNS->getAsIdentifier();
4044 case NestedNameSpecifier::Namespace:
4045 if (NNS->getAsNamespace()->isAnonymousNamespace())
4047 II = NNS->getAsNamespace()->getIdentifier();
4050 case NestedNameSpecifier::NamespaceAlias:
4051 II = NNS->getAsNamespaceAlias()->getIdentifier();
4054 case NestedNameSpecifier::TypeSpecWithTemplate:
4055 case NestedNameSpecifier::TypeSpec:
4056 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4059 case NestedNameSpecifier::Global:
4060 case NestedNameSpecifier::Super:
4065 Identifiers.push_back(II);
4068 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4069 DeclContext *Ctx, bool InBaseClass) {
4070 // Don't consider hidden names for typo correction.
4074 // Only consider entities with identifiers for names, ignoring
4075 // special names (constructors, overloaded operators, selectors,
4077 IdentifierInfo *Name = ND->getIdentifier();
4081 // Only consider visible declarations and declarations from modules with
4082 // names that exactly match.
4083 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4086 FoundName(Name->getName());
4089 void TypoCorrectionConsumer::FoundName(StringRef Name) {
4090 // Compute the edit distance between the typo and the name of this
4091 // entity, and add the identifier to the list of results.
4092 addName(Name, nullptr);
4095 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4096 // Compute the edit distance between the typo and this keyword,
4097 // and add the keyword to the list of results.
4098 addName(Keyword, nullptr, nullptr, true);
4101 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4102 NestedNameSpecifier *NNS, bool isKeyword) {
4103 // Use a simple length-based heuristic to determine the minimum possible
4104 // edit distance. If the minimum isn't good enough, bail out early.
4105 StringRef TypoStr = Typo->getName();
4106 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4107 if (MinED && TypoStr.size() / MinED < 3)
4110 // Compute an upper bound on the allowable edit distance, so that the
4111 // edit-distance algorithm can short-circuit.
4112 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4113 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4114 if (ED > UpperBound) return;
4116 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4117 if (isKeyword) TC.makeKeyword();
4118 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4122 static const unsigned MaxTypoDistanceResultSets = 5;
4124 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4125 StringRef TypoStr = Typo->getName();
4126 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4128 // For very short typos, ignore potential corrections that have a different
4129 // base identifier from the typo or which have a normalized edit distance
4130 // longer than the typo itself.
4131 if (TypoStr.size() < 3 &&
4132 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4135 // If the correction is resolved but is not viable, ignore it.
4136 if (Correction.isResolved()) {
4137 checkCorrectionVisibility(SemaRef, Correction);
4138 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4142 TypoResultList &CList =
4143 CorrectionResults[Correction.getEditDistance(false)][Name];
4145 if (!CList.empty() && !CList.back().isResolved())
4147 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4148 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4149 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4150 RI != RIEnd; ++RI) {
4151 // If the Correction refers to a decl already in the result list,
4152 // replace the existing result if the string representation of Correction
4153 // comes before the current result alphabetically, then stop as there is
4154 // nothing more to be done to add Correction to the candidate set.
4155 if (RI->getCorrectionDecl() == NewND) {
4156 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4162 if (CList.empty() || Correction.isResolved())
4163 CList.push_back(Correction);
4165 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4166 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4169 void TypoCorrectionConsumer::addNamespaces(
4170 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4171 SearchNamespaces = true;
4173 for (auto KNPair : KnownNamespaces)
4174 Namespaces.addNameSpecifier(KNPair.first);
4176 bool SSIsTemplate = false;
4177 if (NestedNameSpecifier *NNS =
4178 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4179 if (const Type *T = NNS->getAsType())
4180 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4182 // Do not transform this into an iterator-based loop. The loop body can
4183 // trigger the creation of further types (through lazy deserialization) and
4184 // invalid iterators into this list.
4185 auto &Types = SemaRef.getASTContext().getTypes();
4186 for (unsigned I = 0; I != Types.size(); ++I) {
4187 const auto *TI = Types[I];
4188 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4189 CD = CD->getCanonicalDecl();
4190 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4191 !CD->isUnion() && CD->getIdentifier() &&
4192 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4193 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4194 Namespaces.addNameSpecifier(CD);
4199 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4200 if (++CurrentTCIndex < ValidatedCorrections.size())
4201 return ValidatedCorrections[CurrentTCIndex];
4203 CurrentTCIndex = ValidatedCorrections.size();
4204 while (!CorrectionResults.empty()) {
4205 auto DI = CorrectionResults.begin();
4206 if (DI->second.empty()) {
4207 CorrectionResults.erase(DI);
4211 auto RI = DI->second.begin();
4212 if (RI->second.empty()) {
4213 DI->second.erase(RI);
4214 performQualifiedLookups();
4218 TypoCorrection TC = RI->second.pop_back_val();
4219 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4220 ValidatedCorrections.push_back(TC);
4221 return ValidatedCorrections[CurrentTCIndex];
4224 return ValidatedCorrections[0]; // The empty correction.
4227 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4228 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4229 DeclContext *TempMemberContext = MemberContext;
4230 CXXScopeSpec *TempSS = SS.get();
4232 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4234 CorrectionValidator->IsObjCIvarLookup,
4235 Name == Typo && !Candidate.WillReplaceSpecifier());
4236 switch (Result.getResultKind()) {
4237 case LookupResult::NotFound:
4238 case LookupResult::NotFoundInCurrentInstantiation:
4239 case LookupResult::FoundUnresolvedValue:
4241 // Immediately retry the lookup without the given CXXScopeSpec
4243 Candidate.WillReplaceSpecifier(true);
4246 if (TempMemberContext) {
4249 TempMemberContext = nullptr;
4252 if (SearchNamespaces)
4253 QualifiedResults.push_back(Candidate);
4256 case LookupResult::Ambiguous:
4257 // We don't deal with ambiguities.
4260 case LookupResult::Found:
4261 case LookupResult::FoundOverloaded:
4262 // Store all of the Decls for overloaded symbols
4263 for (auto *TRD : Result)
4264 Candidate.addCorrectionDecl(TRD);
4265 checkCorrectionVisibility(SemaRef, Candidate);
4266 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4267 if (SearchNamespaces)
4268 QualifiedResults.push_back(Candidate);
4271 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4277 void TypoCorrectionConsumer::performQualifiedLookups() {
4278 unsigned TypoLen = Typo->getName().size();
4279 for (const TypoCorrection &QR : QualifiedResults) {
4280 for (const auto &NSI : Namespaces) {
4281 DeclContext *Ctx = NSI.DeclCtx;
4282 const Type *NSType = NSI.NameSpecifier->getAsType();
4284 // If the current NestedNameSpecifier refers to a class and the
4285 // current correction candidate is the name of that class, then skip
4286 // it as it is unlikely a qualified version of the class' constructor
4287 // is an appropriate correction.
4288 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4290 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4294 TypoCorrection TC(QR);
4295 TC.ClearCorrectionDecls();
4296 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4297 TC.setQualifierDistance(NSI.EditDistance);
4298 TC.setCallbackDistance(0); // Reset the callback distance
4300 // If the current correction candidate and namespace combination are
4301 // too far away from the original typo based on the normalized edit
4302 // distance, then skip performing a qualified name lookup.
4303 unsigned TmpED = TC.getEditDistance(true);
4304 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4305 TypoLen / TmpED < 3)
4309 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4310 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4313 // Any corrections added below will be validated in subsequent
4314 // iterations of the main while() loop over the Consumer's contents.
4315 switch (Result.getResultKind()) {
4316 case LookupResult::Found:
4317 case LookupResult::FoundOverloaded: {
4318 if (SS && SS->isValid()) {
4319 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4320 std::string OldQualified;
4321 llvm::raw_string_ostream OldOStream(OldQualified);
4322 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4323 OldOStream << Typo->getName();
4324 // If correction candidate would be an identical written qualified
4325 // identifier, then the existing CXXScopeSpec probably included a
4326 // typedef that didn't get accounted for properly.
4327 if (OldOStream.str() == NewQualified)
4330 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4331 TRD != TRDEnd; ++TRD) {
4332 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4333 NSType ? NSType->getAsCXXRecordDecl()
4335 TRD.getPair()) == Sema::AR_accessible)
4336 TC.addCorrectionDecl(*TRD);
4338 if (TC.isResolved()) {
4339 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4344 case LookupResult::NotFound:
4345 case LookupResult::NotFoundInCurrentInstantiation:
4346 case LookupResult::Ambiguous:
4347 case LookupResult::FoundUnresolvedValue:
4352 QualifiedResults.clear();
4355 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4356 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4357 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4358 if (NestedNameSpecifier *NNS =
4359 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4360 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4361 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4363 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4365 // Build the list of identifiers that would be used for an absolute
4366 // (from the global context) NestedNameSpecifier referring to the current
4368 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4369 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4370 CurContextIdentifiers.push_back(ND->getIdentifier());
4373 // Add the global context as a NestedNameSpecifier
4374 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4375 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4376 DistanceMap[1].push_back(SI);
4379 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4380 DeclContext *Start) -> DeclContextList {
4381 assert(Start && "Building a context chain from a null context");
4382 DeclContextList Chain;
4383 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4384 DC = DC->getLookupParent()) {
4385 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4386 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4387 !(ND && ND->isAnonymousNamespace()))
4388 Chain.push_back(DC->getPrimaryContext());
4394 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4395 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4396 unsigned NumSpecifiers = 0;
4397 for (DeclContext *C : llvm::reverse(DeclChain)) {
4398 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4399 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4401 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4402 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4403 RD->getTypeForDecl());
4407 return NumSpecifiers;
4410 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4412 NestedNameSpecifier *NNS = nullptr;
4413 unsigned NumSpecifiers = 0;
4414 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4415 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4417 // Eliminate common elements from the two DeclContext chains.
4418 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4419 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4421 NamespaceDeclChain.pop_back();
4424 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4425 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4427 // Add an explicit leading '::' specifier if needed.
4428 if (NamespaceDeclChain.empty()) {
4429 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4430 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4432 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4433 } else if (NamedDecl *ND =
4434 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4435 IdentifierInfo *Name = ND->getIdentifier();
4436 bool SameNameSpecifier = false;
4437 if (std::find(CurNameSpecifierIdentifiers.begin(),
4438 CurNameSpecifierIdentifiers.end(),
4439 Name) != CurNameSpecifierIdentifiers.end()) {
4440 std::string NewNameSpecifier;
4441 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4442 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4443 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4444 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4445 SpecifierOStream.flush();
4446 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4448 if (SameNameSpecifier || llvm::find(CurContextIdentifiers, Name) !=
4449 CurContextIdentifiers.end()) {
4450 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4451 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4453 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4457 // If the built NestedNameSpecifier would be replacing an existing
4458 // NestedNameSpecifier, use the number of component identifiers that
4459 // would need to be changed as the edit distance instead of the number
4460 // of components in the built NestedNameSpecifier.
4461 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4462 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4463 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4464 NumSpecifiers = llvm::ComputeEditDistance(
4465 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4466 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4469 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4470 DistanceMap[NumSpecifiers].push_back(SI);
4473 /// Perform name lookup for a possible result for typo correction.
4474 static void LookupPotentialTypoResult(Sema &SemaRef,
4476 IdentifierInfo *Name,
4477 Scope *S, CXXScopeSpec *SS,
4478 DeclContext *MemberContext,
4479 bool EnteringContext,
4480 bool isObjCIvarLookup,
4482 Res.suppressDiagnostics();
4484 Res.setLookupName(Name);
4485 Res.setAllowHidden(FindHidden);
4486 if (MemberContext) {
4487 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4488 if (isObjCIvarLookup) {
4489 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4496 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4497 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
4504 SemaRef.LookupQualifiedName(Res, MemberContext);
4508 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4511 // Fake ivar lookup; this should really be part of
4512 // LookupParsedName.
4513 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4514 if (Method->isInstanceMethod() && Method->getClassInterface() &&
4516 (Res.isSingleResult() &&
4517 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4518 if (ObjCIvarDecl *IV
4519 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4527 /// Add keywords to the consumer as possible typo corrections.
4528 static void AddKeywordsToConsumer(Sema &SemaRef,
4529 TypoCorrectionConsumer &Consumer,
4530 Scope *S, CorrectionCandidateCallback &CCC,
4531 bool AfterNestedNameSpecifier) {
4532 if (AfterNestedNameSpecifier) {
4533 // For 'X::', we know exactly which keywords can appear next.
4534 Consumer.addKeywordResult("template");
4535 if (CCC.WantExpressionKeywords)
4536 Consumer.addKeywordResult("operator");
4540 if (CCC.WantObjCSuper)
4541 Consumer.addKeywordResult("super");
4543 if (CCC.WantTypeSpecifiers) {
4544 // Add type-specifier keywords to the set of results.
4545 static const char *const CTypeSpecs[] = {
4546 "char", "const", "double", "enum", "float", "int", "long", "short",
4547 "signed", "struct", "union", "unsigned", "void", "volatile",
4548 "_Complex", "_Imaginary",
4549 // storage-specifiers as well
4550 "extern", "inline", "static", "typedef"
4553 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4554 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4555 Consumer.addKeywordResult(CTypeSpecs[I]);
4557 if (SemaRef.getLangOpts().C99)
4558 Consumer.addKeywordResult("restrict");
4559 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
4560 Consumer.addKeywordResult("bool");
4561 else if (SemaRef.getLangOpts().C99)
4562 Consumer.addKeywordResult("_Bool");
4564 if (SemaRef.getLangOpts().CPlusPlus) {
4565 Consumer.addKeywordResult("class");
4566 Consumer.addKeywordResult("typename");
4567 Consumer.addKeywordResult("wchar_t");
4569 if (SemaRef.getLangOpts().CPlusPlus11) {
4570 Consumer.addKeywordResult("char16_t");
4571 Consumer.addKeywordResult("char32_t");
4572 Consumer.addKeywordResult("constexpr");
4573 Consumer.addKeywordResult("decltype");
4574 Consumer.addKeywordResult("thread_local");
4578 if (SemaRef.getLangOpts().GNUKeywords)
4579 Consumer.addKeywordResult("typeof");
4580 } else if (CCC.WantFunctionLikeCasts) {
4581 static const char *const CastableTypeSpecs[] = {
4582 "char", "double", "float", "int", "long", "short",
4583 "signed", "unsigned", "void"
4585 for (auto *kw : CastableTypeSpecs)
4586 Consumer.addKeywordResult(kw);
4589 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
4590 Consumer.addKeywordResult("const_cast");
4591 Consumer.addKeywordResult("dynamic_cast");
4592 Consumer.addKeywordResult("reinterpret_cast");
4593 Consumer.addKeywordResult("static_cast");
4596 if (CCC.WantExpressionKeywords) {
4597 Consumer.addKeywordResult("sizeof");
4598 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
4599 Consumer.addKeywordResult("false");
4600 Consumer.addKeywordResult("true");
4603 if (SemaRef.getLangOpts().CPlusPlus) {
4604 static const char *const CXXExprs[] = {
4605 "delete", "new", "operator", "throw", "typeid"
4607 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4608 for (unsigned I = 0; I != NumCXXExprs; ++I)
4609 Consumer.addKeywordResult(CXXExprs[I]);
4611 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4612 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4613 Consumer.addKeywordResult("this");
4615 if (SemaRef.getLangOpts().CPlusPlus11) {
4616 Consumer.addKeywordResult("alignof");
4617 Consumer.addKeywordResult("nullptr");
4621 if (SemaRef.getLangOpts().C11) {
4622 // FIXME: We should not suggest _Alignof if the alignof macro
4624 Consumer.addKeywordResult("_Alignof");
4628 if (CCC.WantRemainingKeywords) {
4629 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4631 static const char *const CStmts[] = {
4632 "do", "else", "for", "goto", "if", "return", "switch", "while" };
4633 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4634 for (unsigned I = 0; I != NumCStmts; ++I)
4635 Consumer.addKeywordResult(CStmts[I]);
4637 if (SemaRef.getLangOpts().CPlusPlus) {
4638 Consumer.addKeywordResult("catch");
4639 Consumer.addKeywordResult("try");
4642 if (S && S->getBreakParent())
4643 Consumer.addKeywordResult("break");
4645 if (S && S->getContinueParent())
4646 Consumer.addKeywordResult("continue");
4648 if (SemaRef.getCurFunction() &&
4649 !SemaRef.getCurFunction()->SwitchStack.empty()) {
4650 Consumer.addKeywordResult("case");
4651 Consumer.addKeywordResult("default");
4654 if (SemaRef.getLangOpts().CPlusPlus) {
4655 Consumer.addKeywordResult("namespace");
4656 Consumer.addKeywordResult("template");
4659 if (S && S->isClassScope()) {
4660 Consumer.addKeywordResult("explicit");
4661 Consumer.addKeywordResult("friend");
4662 Consumer.addKeywordResult("mutable");
4663 Consumer.addKeywordResult("private");
4664 Consumer.addKeywordResult("protected");
4665 Consumer.addKeywordResult("public");
4666 Consumer.addKeywordResult("virtual");
4670 if (SemaRef.getLangOpts().CPlusPlus) {
4671 Consumer.addKeywordResult("using");
4673 if (SemaRef.getLangOpts().CPlusPlus11)
4674 Consumer.addKeywordResult("static_assert");
4679 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4680 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4681 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
4682 DeclContext *MemberContext, bool EnteringContext,
4683 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
4685 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4686 DisableTypoCorrection)
4689 // In Microsoft mode, don't perform typo correction in a template member
4690 // function dependent context because it interferes with the "lookup into
4691 // dependent bases of class templates" feature.
4692 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4693 isa<CXXMethodDecl>(CurContext))
4696 // We only attempt to correct typos for identifiers.
4697 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4701 // If the scope specifier itself was invalid, don't try to correct
4703 if (SS && SS->isInvalid())
4706 // Never try to correct typos during any kind of code synthesis.
4707 if (!CodeSynthesisContexts.empty())
4710 // Don't try to correct 'super'.
4711 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4714 // Abort if typo correction already failed for this specific typo.
4715 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4716 if (locs != TypoCorrectionFailures.end() &&
4717 locs->second.count(TypoName.getLoc()))
4720 // Don't try to correct the identifier "vector" when in AltiVec mode.
4721 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4722 // remove this workaround.
4723 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
4726 // Provide a stop gap for files that are just seriously broken. Trying
4727 // to correct all typos can turn into a HUGE performance penalty, causing
4728 // some files to take minutes to get rejected by the parser.
4729 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4730 if (Limit && TyposCorrected >= Limit)
4734 // If we're handling a missing symbol error, using modules, and the
4735 // special search all modules option is used, look for a missing import.
4736 if (ErrorRecovery && getLangOpts().Modules &&
4737 getLangOpts().ModulesSearchAll) {
4738 // The following has the side effect of loading the missing module.
4739 getModuleLoader().lookupMissingImports(Typo->getName(),
4740 TypoName.getBeginLoc());
4743 // Extend the lifetime of the callback. We delayed this until here
4744 // to avoid allocations in the hot path (which is where no typo correction
4745 // occurs). Note that CorrectionCandidateCallback is polymorphic and
4746 // initially stack-allocated.
4747 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
4748 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4749 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
4752 // Perform name lookup to find visible, similarly-named entities.
4753 bool IsUnqualifiedLookup = false;
4754 DeclContext *QualifiedDC = MemberContext;
4755 if (MemberContext) {
4756 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4758 // Look in qualified interfaces.
4760 for (auto *I : OPT->quals())
4761 LookupVisibleDecls(I, LookupKind, *Consumer);
4763 } else if (SS && SS->isSet()) {
4764 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4768 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4770 IsUnqualifiedLookup = true;
4773 // Determine whether we are going to search in the various namespaces for
4775 bool SearchNamespaces
4776 = getLangOpts().CPlusPlus &&
4777 (IsUnqualifiedLookup || (SS && SS->isSet()));
4779 if (IsUnqualifiedLookup || SearchNamespaces) {
4780 // For unqualified lookup, look through all of the names that we have
4781 // seen in this translation unit.
4782 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4783 for (const auto &I : Context.Idents)
4784 Consumer->FoundName(I.getKey());
4786 // Walk through identifiers in external identifier sources.
4787 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4788 if (IdentifierInfoLookup *External
4789 = Context.Idents.getExternalIdentifierLookup()) {
4790 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4792 StringRef Name = Iter->Next();
4796 Consumer->FoundName(Name);
4801 AddKeywordsToConsumer(*this, *Consumer, S,
4802 *Consumer->getCorrectionValidator(),
4803 SS && SS->isNotEmpty());
4805 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4806 // to search those namespaces.
4807 if (SearchNamespaces) {
4808 // Load any externally-known namespaces.
4809 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4810 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4811 LoadedExternalKnownNamespaces = true;
4812 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4813 for (auto *N : ExternalKnownNamespaces)
4814 KnownNamespaces[N] = true;
4817 Consumer->addNamespaces(KnownNamespaces);
4823 /// Try to "correct" a typo in the source code by finding
4824 /// visible declarations whose names are similar to the name that was
4825 /// present in the source code.
4827 /// \param TypoName the \c DeclarationNameInfo structure that contains
4828 /// the name that was present in the source code along with its location.
4830 /// \param LookupKind the name-lookup criteria used to search for the name.
4832 /// \param S the scope in which name lookup occurs.
4834 /// \param SS the nested-name-specifier that precedes the name we're
4835 /// looking for, if present.
4837 /// \param CCC A CorrectionCandidateCallback object that provides further
4838 /// validation of typo correction candidates. It also provides flags for
4839 /// determining the set of keywords permitted.
4841 /// \param MemberContext if non-NULL, the context in which to look for
4842 /// a member access expression.
4844 /// \param EnteringContext whether we're entering the context described by
4845 /// the nested-name-specifier SS.
4847 /// \param OPT when non-NULL, the search for visible declarations will
4848 /// also walk the protocols in the qualified interfaces of \p OPT.
4850 /// \returns a \c TypoCorrection containing the corrected name if the typo
4851 /// along with information such as the \c NamedDecl where the corrected name
4852 /// was declared, and any additional \c NestedNameSpecifier needed to access
4853 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4854 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4855 Sema::LookupNameKind LookupKind,
4856 Scope *S, CXXScopeSpec *SS,
4857 CorrectionCandidateCallback &CCC,
4858 CorrectTypoKind Mode,
4859 DeclContext *MemberContext,
4860 bool EnteringContext,
4861 const ObjCObjectPointerType *OPT,
4862 bool RecordFailure) {
4863 // Always let the ExternalSource have the first chance at correction, even
4864 // if we would otherwise have given up.
4865 if (ExternalSource) {
4866 if (TypoCorrection Correction =
4867 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
4868 MemberContext, EnteringContext, OPT))
4872 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4873 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4874 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4875 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4876 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
4878 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4879 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
4880 MemberContext, EnteringContext,
4881 OPT, Mode == CTK_ErrorRecovery);
4884 return TypoCorrection();
4886 // If we haven't found anything, we're done.
4887 if (Consumer->empty())
4888 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4890 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4891 // is not more that about a third of the length of the typo's identifier.
4892 unsigned ED = Consumer->getBestEditDistance(true);
4893 unsigned TypoLen = Typo->getName().size();
4894 if (ED > 0 && TypoLen / ED < 3)
4895 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4897 TypoCorrection BestTC = Consumer->getNextCorrection();
4898 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
4900 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4902 ED = BestTC.getEditDistance();
4904 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
4905 // If this was an unqualified lookup and we believe the callback
4906 // object wouldn't have filtered out possible corrections, note
4907 // that no correction was found.
4908 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4911 // If only a single name remains, return that result.
4912 if (!SecondBestTC ||
4913 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4914 const TypoCorrection &Result = BestTC;
4916 // Don't correct to a keyword that's the same as the typo; the keyword
4917 // wasn't actually in scope.
4918 if (ED == 0 && Result.isKeyword())
4919 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4921 TypoCorrection TC = Result;
4922 TC.setCorrectionRange(SS, TypoName);
4923 checkCorrectionVisibility(*this, TC);
4925 } else if (SecondBestTC && ObjCMessageReceiver) {
4926 // Prefer 'super' when we're completing in a message-receiver
4929 if (BestTC.getCorrection().getAsString() != "super") {
4930 if (SecondBestTC.getCorrection().getAsString() == "super")
4931 BestTC = SecondBestTC;
4932 else if ((*Consumer)["super"].front().isKeyword())
4933 BestTC = (*Consumer)["super"].front();
4935 // Don't correct to a keyword that's the same as the typo; the keyword
4936 // wasn't actually in scope.
4937 if (BestTC.getEditDistance() == 0 ||
4938 BestTC.getCorrection().getAsString() != "super")
4939 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4941 BestTC.setCorrectionRange(SS, TypoName);
4945 // Record the failure's location if needed and return an empty correction. If
4946 // this was an unqualified lookup and we believe the callback object did not
4947 // filter out possible corrections, also cache the failure for the typo.
4948 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
4951 /// Try to "correct" a typo in the source code by finding
4952 /// visible declarations whose names are similar to the name that was
4953 /// present in the source code.
4955 /// \param TypoName the \c DeclarationNameInfo structure that contains
4956 /// the name that was present in the source code along with its location.
4958 /// \param LookupKind the name-lookup criteria used to search for the name.
4960 /// \param S the scope in which name lookup occurs.
4962 /// \param SS the nested-name-specifier that precedes the name we're
4963 /// looking for, if present.
4965 /// \param CCC A CorrectionCandidateCallback object that provides further
4966 /// validation of typo correction candidates. It also provides flags for
4967 /// determining the set of keywords permitted.
4969 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4970 /// diagnostics when the actual typo correction is attempted.
4972 /// \param TRC A TypoRecoveryCallback functor that will be used to build an
4973 /// Expr from a typo correction candidate.
4975 /// \param MemberContext if non-NULL, the context in which to look for
4976 /// a member access expression.
4978 /// \param EnteringContext whether we're entering the context described by
4979 /// the nested-name-specifier SS.
4981 /// \param OPT when non-NULL, the search for visible declarations will
4982 /// also walk the protocols in the qualified interfaces of \p OPT.
4984 /// \returns a new \c TypoExpr that will later be replaced in the AST with an
4985 /// Expr representing the result of performing typo correction, or nullptr if
4986 /// typo correction is not possible. If nullptr is returned, no diagnostics will
4987 /// be emitted and it is the responsibility of the caller to emit any that are
4989 TypoExpr *Sema::CorrectTypoDelayed(
4990 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4991 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
4992 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4993 DeclContext *MemberContext, bool EnteringContext,
4994 const ObjCObjectPointerType *OPT) {
4995 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
4996 MemberContext, EnteringContext,
4997 OPT, Mode == CTK_ErrorRecovery);
4999 // Give the external sema source a chance to correct the typo.
5000 TypoCorrection ExternalTypo;
5001 if (ExternalSource && Consumer) {
5002 ExternalTypo = ExternalSource->CorrectTypo(
5003 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5004 MemberContext, EnteringContext, OPT);
5006 Consumer->addCorrection(ExternalTypo);
5009 if (!Consumer || Consumer->empty())
5012 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5013 // is not more that about a third of the length of the typo's identifier.
5014 unsigned ED = Consumer->getBestEditDistance(true);
5015 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5016 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5019 ExprEvalContexts.back().NumTypos++;
5020 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
5023 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5027 CorrectionDecls.clear();
5029 CorrectionDecls.push_back(CDecl);
5031 if (!CorrectionName)
5032 CorrectionName = CDecl->getDeclName();
5035 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5036 if (CorrectionNameSpec) {
5037 std::string tmpBuffer;
5038 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5039 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5040 PrefixOStream << CorrectionName;
5041 return PrefixOStream.str();
5044 return CorrectionName.getAsString();
5047 bool CorrectionCandidateCallback::ValidateCandidate(
5048 const TypoCorrection &candidate) {
5049 if (!candidate.isResolved())
5052 if (candidate.isKeyword())
5053 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5054 WantRemainingKeywords || WantObjCSuper;
5056 bool HasNonType = false;
5057 bool HasStaticMethod = false;
5058 bool HasNonStaticMethod = false;
5059 for (Decl *D : candidate) {
5060 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5061 D = FTD->getTemplatedDecl();
5062 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5063 if (Method->isStatic())
5064 HasStaticMethod = true;
5066 HasNonStaticMethod = true;
5068 if (!isa<TypeDecl>(D))
5072 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5073 !candidate.getCorrectionSpecifier())
5076 return WantTypeSpecifiers || HasNonType;
5079 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5080 bool HasExplicitTemplateArgs,
5082 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5083 CurContext(SemaRef.CurContext), MemberFn(ME) {
5084 WantTypeSpecifiers = false;
5085 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5086 !HasExplicitTemplateArgs && NumArgs == 1;
5087 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5088 WantRemainingKeywords = false;
5091 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5092 if (!candidate.getCorrectionDecl())
5093 return candidate.isKeyword();
5095 for (auto *C : candidate) {
5096 FunctionDecl *FD = nullptr;
5097 NamedDecl *ND = C->getUnderlyingDecl();
5098 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5099 FD = FTD->getTemplatedDecl();
5100 if (!HasExplicitTemplateArgs && !FD) {
5101 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5102 // If the Decl is neither a function nor a template function,
5103 // determine if it is a pointer or reference to a function. If so,
5104 // check against the number of arguments expected for the pointee.
5105 QualType ValType = cast<ValueDecl>(ND)->getType();
5106 if (ValType.isNull())
5108 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5109 ValType = ValType->getPointeeType();
5110 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5111 if (FPT->getNumParams() == NumArgs)
5116 // A typo for a function-style cast can look like a function call in C++.
5117 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5118 : isa<TypeDecl>(ND)) &&
5119 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5120 // Only a class or class template can take two or more arguments.
5121 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5123 // Skip the current candidate if it is not a FunctionDecl or does not accept
5124 // the current number of arguments.
5125 if (!FD || !(FD->getNumParams() >= NumArgs &&
5126 FD->getMinRequiredArguments() <= NumArgs))
5129 // If the current candidate is a non-static C++ method, skip the candidate
5130 // unless the method being corrected--or the current DeclContext, if the
5131 // function being corrected is not a method--is a method in the same class
5132 // or a descendent class of the candidate's parent class.
5133 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5134 if (MemberFn || !MD->isStatic()) {
5135 CXXMethodDecl *CurMD =
5137 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5138 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
5139 CXXRecordDecl *CurRD =
5140 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5141 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5142 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5151 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5152 const PartialDiagnostic &TypoDiag,
5153 bool ErrorRecovery) {
5154 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5158 /// Find which declaration we should import to provide the definition of
5159 /// the given declaration.
5160 static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5161 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5162 return VD->getDefinition();
5163 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5164 return FD->getDefinition();
5165 if (TagDecl *TD = dyn_cast<TagDecl>(D))
5166 return TD->getDefinition();
5167 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
5168 return ID->getDefinition();
5169 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
5170 return PD->getDefinition();
5171 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5172 if (NamedDecl *TTD = TD->getTemplatedDecl())
5173 return getDefinitionToImport(TTD);
5177 void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
5178 MissingImportKind MIK, bool Recover) {
5179 // Suggest importing a module providing the definition of this entity, if
5181 NamedDecl *Def = getDefinitionToImport(Decl);
5185 Module *Owner = getOwningModule(Def);
5186 assert(Owner && "definition of hidden declaration is not in a module");
5188 llvm::SmallVector<Module*, 8> OwningModules;
5189 OwningModules.push_back(Owner);
5190 auto Merged = Context.getModulesWithMergedDefinition(Def);
5191 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5193 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5197 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5198 /// suggesting the addition of a #include of the specified file.
5199 static std::string getIncludeStringForHeader(Preprocessor &PP,
5201 llvm::StringRef IncludingFile) {
5202 bool IsSystem = false;
5203 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5204 E, IncludingFile, &IsSystem);
5205 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5208 void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5209 SourceLocation DeclLoc,
5210 ArrayRef<Module *> Modules,
5211 MissingImportKind MIK, bool Recover) {
5212 assert(!Modules.empty());
5214 auto NotePrevious = [&] {
5217 case MissingImportKind::Declaration:
5218 DiagID = diag::note_previous_declaration;
5220 case MissingImportKind::Definition:
5221 DiagID = diag::note_previous_definition;
5223 case MissingImportKind::DefaultArgument:
5224 DiagID = diag::note_default_argument_declared_here;
5226 case MissingImportKind::ExplicitSpecialization:
5227 DiagID = diag::note_explicit_specialization_declared_here;
5229 case MissingImportKind::PartialSpecialization:
5230 DiagID = diag::note_partial_specialization_declared_here;
5233 Diag(DeclLoc, DiagID);
5236 // Weed out duplicates from module list.
5237 llvm::SmallVector<Module*, 8> UniqueModules;
5238 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5239 for (auto *M : Modules) {
5240 if (M->Kind == Module::GlobalModuleFragment)
5242 if (UniqueModuleSet.insert(M).second)
5243 UniqueModules.push_back(M);
5246 llvm::StringRef IncludingFile;
5247 if (const FileEntry *FE =
5248 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5249 IncludingFile = FE->tryGetRealPathName();
5251 if (UniqueModules.empty()) {
5252 // All candidates were global module fragments. Try to suggest a #include.
5253 const FileEntry *E =
5254 PP.getModuleHeaderToIncludeForDiagnostics(UseLoc, Modules[0], DeclLoc);
5255 // FIXME: Find a smart place to suggest inserting a #include, and add
5256 // a FixItHint there.
5257 Diag(UseLoc, diag::err_module_unimported_use_global_module_fragment)
5258 << (int)MIK << Decl << !!E
5259 << (E ? getIncludeStringForHeader(PP, E, IncludingFile) : "");
5260 // Produce a "previous" note if it will point to a header rather than some
5261 // random global module fragment.
5262 // FIXME: Suppress the note backtrace even under
5263 // -fdiagnostics-show-note-include-stack.
5267 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5271 Modules = UniqueModules;
5273 if (Modules.size() > 1) {
5274 std::string ModuleList;
5276 for (Module *M : Modules) {
5277 ModuleList += "\n ";
5278 if (++N == 5 && N != Modules.size()) {
5279 ModuleList += "[...]";
5282 ModuleList += M->getFullModuleName();
5285 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5286 << (int)MIK << Decl << ModuleList;
5287 } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
5288 UseLoc, Modules[0], DeclLoc)) {
5289 // The right way to make the declaration visible is to include a header;
5290 // suggest doing so.
5292 // FIXME: Find a smart place to suggest inserting a #include, and add
5293 // a FixItHint there.
5294 Diag(UseLoc, diag::err_module_unimported_use_header)
5295 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5296 << getIncludeStringForHeader(PP, E, IncludingFile);
5298 // FIXME: Add a FixItHint that imports the corresponding module.
5299 Diag(UseLoc, diag::err_module_unimported_use)
5300 << (int)MIK << Decl << Modules[0]->getFullModuleName();
5305 // Try to recover by implicitly importing this module.
5307 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5310 /// Diagnose a successfully-corrected typo. Separated from the correction
5311 /// itself to allow external validation of the result, etc.
5313 /// \param Correction The result of performing typo correction.
5314 /// \param TypoDiag The diagnostic to produce. This will have the corrected
5315 /// string added to it (and usually also a fixit).
5316 /// \param PrevNote A note to use when indicating the location of the entity to
5317 /// which we are correcting. Will have the correction string added to it.
5318 /// \param ErrorRecovery If \c true (the default), the caller is going to
5319 /// recover from the typo as if the corrected string had been typed.
5320 /// In this case, \c PDiag must be an error, and we will attach a fixit
5322 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5323 const PartialDiagnostic &TypoDiag,
5324 const PartialDiagnostic &PrevNote,
5325 bool ErrorRecovery) {
5326 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5327 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5328 FixItHint FixTypo = FixItHint::CreateReplacement(
5329 Correction.getCorrectionRange(), CorrectedStr);
5331 // Maybe we're just missing a module import.
5332 if (Correction.requiresImport()) {
5333 NamedDecl *Decl = Correction.getFoundDecl();
5334 assert(Decl && "import required but no declaration to import");
5336 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5337 MissingImportKind::Declaration, ErrorRecovery);
5341 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5342 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5344 NamedDecl *ChosenDecl =
5345 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5346 if (PrevNote.getDiagID() && ChosenDecl)
5347 Diag(ChosenDecl->getLocation(), PrevNote)
5348 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5350 // Add any extra diagnostics.
5351 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5352 Diag(Correction.getCorrectionRange().getBegin(), PD);
5355 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5356 TypoDiagnosticGenerator TDG,
5357 TypoRecoveryCallback TRC) {
5358 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5359 auto TE = new (Context) TypoExpr(Context.DependentTy);
5360 auto &State = DelayedTypos[TE];
5361 State.Consumer = std::move(TCC);
5362 State.DiagHandler = std::move(TDG);
5363 State.RecoveryHandler = std::move(TRC);
5367 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5368 auto Entry = DelayedTypos.find(TE);
5369 assert(Entry != DelayedTypos.end() &&
5370 "Failed to get the state for a TypoExpr!");
5371 return Entry->second;
5374 void Sema::clearDelayedTypo(TypoExpr *TE) {
5375 DelayedTypos.erase(TE);
5378 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5379 DeclarationNameInfo Name(II, IILoc);
5380 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5381 R.suppressDiagnostics();
5382 R.setHideTags(false);