[DFAJumpThreading] Remove incoming StartBlock from all phis when unfolding select...
[llvm-project.git] / clang / lib / Sema / SemaLookup.cpp
blob324a57095560b7962922147fa0c6a619686c00af
1 //===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements name lookup for C, C++, Objective-C, and
10 // Objective-C++.
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/RISCVIntrinsicManager.h"
33 #include "clang/Sema/Scope.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/Sema.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "clang/Sema/TypoCorrection.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/TinyPtrVector.h"
42 #include "llvm/ADT/edit_distance.h"
43 #include "llvm/Support/Casting.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include <algorithm>
46 #include <iterator>
47 #include <list>
48 #include <optional>
49 #include <set>
50 #include <utility>
51 #include <vector>
53 #include "OpenCLBuiltins.inc"
55 using namespace clang;
56 using namespace sema;
58 namespace {
59 class UnqualUsingEntry {
60 const DeclContext *Nominated;
61 const DeclContext *CommonAncestor;
63 public:
64 UnqualUsingEntry(const DeclContext *Nominated,
65 const DeclContext *CommonAncestor)
66 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
69 const DeclContext *getCommonAncestor() const {
70 return CommonAncestor;
73 const DeclContext *getNominatedNamespace() const {
74 return Nominated;
77 // Sort by the pointer value of the common ancestor.
78 struct Comparator {
79 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
80 return L.getCommonAncestor() < R.getCommonAncestor();
83 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
84 return E.getCommonAncestor() < DC;
87 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
88 return DC < E.getCommonAncestor();
93 /// A collection of using directives, as used by C++ unqualified
94 /// lookup.
95 class UnqualUsingDirectiveSet {
96 Sema &SemaRef;
98 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
100 ListTy list;
101 llvm::SmallPtrSet<DeclContext*, 8> visited;
103 public:
104 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
106 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
107 // C++ [namespace.udir]p1:
108 // During unqualified name lookup, the names appear as if they
109 // were declared in the nearest enclosing namespace which contains
110 // both the using-directive and the nominated namespace.
111 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
112 assert(InnermostFileDC && InnermostFileDC->isFileContext());
114 for (; S; S = S->getParent()) {
115 // C++ [namespace.udir]p1:
116 // A using-directive shall not appear in class scope, but may
117 // appear in namespace scope or in block scope.
118 DeclContext *Ctx = S->getEntity();
119 if (Ctx && Ctx->isFileContext()) {
120 visit(Ctx, Ctx);
121 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
122 for (auto *I : S->using_directives())
123 if (SemaRef.isVisible(I))
124 visit(I, InnermostFileDC);
129 // Visits a context and collect all of its using directives
130 // recursively. Treats all using directives as if they were
131 // declared in the context.
133 // A given context is only every visited once, so it is important
134 // that contexts be visited from the inside out in order to get
135 // the effective DCs right.
136 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
137 if (!visited.insert(DC).second)
138 return;
140 addUsingDirectives(DC, EffectiveDC);
143 // Visits a using directive and collects all of its using
144 // directives recursively. Treats all using directives as if they
145 // were declared in the effective DC.
146 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
147 DeclContext *NS = UD->getNominatedNamespace();
148 if (!visited.insert(NS).second)
149 return;
151 addUsingDirective(UD, EffectiveDC);
152 addUsingDirectives(NS, EffectiveDC);
155 // Adds all the using directives in a context (and those nominated
156 // by its using directives, transitively) as if they appeared in
157 // the given effective context.
158 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
159 SmallVector<DeclContext*, 4> queue;
160 while (true) {
161 for (auto *UD : DC->using_directives()) {
162 DeclContext *NS = UD->getNominatedNamespace();
163 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
164 addUsingDirective(UD, EffectiveDC);
165 queue.push_back(NS);
169 if (queue.empty())
170 return;
172 DC = queue.pop_back_val();
176 // Add a using directive as if it had been declared in the given
177 // context. This helps implement C++ [namespace.udir]p3:
178 // The using-directive is transitive: if a scope contains a
179 // using-directive that nominates a second namespace that itself
180 // contains using-directives, the effect is as if the
181 // using-directives from the second namespace also appeared in
182 // the first.
183 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
184 // Find the common ancestor between the effective context and
185 // the nominated namespace.
186 DeclContext *Common = UD->getNominatedNamespace();
187 while (!Common->Encloses(EffectiveDC))
188 Common = Common->getParent();
189 Common = Common->getPrimaryContext();
191 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
194 void done() { llvm::sort(list, UnqualUsingEntry::Comparator()); }
196 typedef ListTy::const_iterator const_iterator;
198 const_iterator begin() const { return list.begin(); }
199 const_iterator end() const { return list.end(); }
201 llvm::iterator_range<const_iterator>
202 getNamespacesFor(const DeclContext *DC) const {
203 return llvm::make_range(std::equal_range(begin(), end(),
204 DC->getPrimaryContext(),
205 UnqualUsingEntry::Comparator()));
208 } // end anonymous namespace
210 // Retrieve the set of identifier namespaces that correspond to a
211 // specific kind of name lookup.
212 static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
213 bool CPlusPlus,
214 bool Redeclaration) {
215 unsigned IDNS = 0;
216 switch (NameKind) {
217 case Sema::LookupObjCImplicitSelfParam:
218 case Sema::LookupOrdinaryName:
219 case Sema::LookupRedeclarationWithLinkage:
220 case Sema::LookupLocalFriendName:
221 case Sema::LookupDestructorName:
222 IDNS = Decl::IDNS_Ordinary;
223 if (CPlusPlus) {
224 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
225 if (Redeclaration)
226 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
228 if (Redeclaration)
229 IDNS |= Decl::IDNS_LocalExtern;
230 break;
232 case Sema::LookupOperatorName:
233 // Operator lookup is its own crazy thing; it is not the same
234 // as (e.g.) looking up an operator name for redeclaration.
235 assert(!Redeclaration && "cannot do redeclaration operator lookup");
236 IDNS = Decl::IDNS_NonMemberOperator;
237 break;
239 case Sema::LookupTagName:
240 if (CPlusPlus) {
241 IDNS = Decl::IDNS_Type;
243 // When looking for a redeclaration of a tag name, we add:
244 // 1) TagFriend to find undeclared friend decls
245 // 2) Namespace because they can't "overload" with tag decls.
246 // 3) Tag because it includes class templates, which can't
247 // "overload" with tag decls.
248 if (Redeclaration)
249 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
250 } else {
251 IDNS = Decl::IDNS_Tag;
253 break;
255 case Sema::LookupLabel:
256 IDNS = Decl::IDNS_Label;
257 break;
259 case Sema::LookupMemberName:
260 IDNS = Decl::IDNS_Member;
261 if (CPlusPlus)
262 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
263 break;
265 case Sema::LookupNestedNameSpecifierName:
266 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
267 break;
269 case Sema::LookupNamespaceName:
270 IDNS = Decl::IDNS_Namespace;
271 break;
273 case Sema::LookupUsingDeclName:
274 assert(Redeclaration && "should only be used for redecl lookup");
275 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
276 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
277 Decl::IDNS_LocalExtern;
278 break;
280 case Sema::LookupObjCProtocolName:
281 IDNS = Decl::IDNS_ObjCProtocol;
282 break;
284 case Sema::LookupOMPReductionName:
285 IDNS = Decl::IDNS_OMPReduction;
286 break;
288 case Sema::LookupOMPMapperName:
289 IDNS = Decl::IDNS_OMPMapper;
290 break;
292 case Sema::LookupAnyName:
293 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
294 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
295 | Decl::IDNS_Type;
296 break;
298 return IDNS;
301 void LookupResult::configure() {
302 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
303 isForRedeclaration());
305 // If we're looking for one of the allocation or deallocation
306 // operators, make sure that the implicitly-declared new and delete
307 // operators can be found.
308 switch (NameInfo.getName().getCXXOverloadedOperator()) {
309 case OO_New:
310 case OO_Delete:
311 case OO_Array_New:
312 case OO_Array_Delete:
313 getSema().DeclareGlobalNewDelete();
314 break;
316 default:
317 break;
320 // Compiler builtins are always visible, regardless of where they end
321 // up being declared.
322 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
323 if (unsigned BuiltinID = Id->getBuiltinID()) {
324 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
325 AllowHidden = true;
330 bool LookupResult::checkDebugAssumptions() const {
331 // This function is never called by NDEBUG builds.
332 assert(ResultKind != NotFound || Decls.size() == 0);
333 assert(ResultKind != Found || Decls.size() == 1);
334 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||
335 (Decls.size() == 1 &&
336 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())));
337 assert(ResultKind != FoundUnresolvedValue || checkUnresolved());
338 assert(ResultKind != Ambiguous || Decls.size() > 1 ||
339 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||
340 Ambiguity == AmbiguousBaseSubobjectTypes)));
341 assert((Paths != nullptr) == (ResultKind == Ambiguous &&
342 (Ambiguity == AmbiguousBaseSubobjectTypes ||
343 Ambiguity == AmbiguousBaseSubobjects)));
344 return true;
347 // Necessary because CXXBasePaths is not complete in Sema.h
348 void LookupResult::deletePaths(CXXBasePaths *Paths) {
349 delete Paths;
352 /// Get a representative context for a declaration such that two declarations
353 /// will have the same context if they were found within the same scope.
354 static const DeclContext *getContextForScopeMatching(const Decl *D) {
355 // For function-local declarations, use that function as the context. This
356 // doesn't account for scopes within the function; the caller must deal with
357 // those.
358 if (const DeclContext *DC = D->getLexicalDeclContext();
359 DC->isFunctionOrMethod())
360 return DC;
362 // Otherwise, look at the semantic context of the declaration. The
363 // declaration must have been found there.
364 return D->getDeclContext()->getRedeclContext();
367 /// Determine whether \p D is a better lookup result than \p Existing,
368 /// given that they declare the same entity.
369 static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
370 const NamedDecl *D,
371 const NamedDecl *Existing) {
372 // When looking up redeclarations of a using declaration, prefer a using
373 // shadow declaration over any other declaration of the same entity.
374 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
375 !isa<UsingShadowDecl>(Existing))
376 return true;
378 const auto *DUnderlying = D->getUnderlyingDecl();
379 const auto *EUnderlying = Existing->getUnderlyingDecl();
381 // If they have different underlying declarations, prefer a typedef over the
382 // original type (this happens when two type declarations denote the same
383 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
384 // might carry additional semantic information, such as an alignment override.
385 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
386 // declaration over a typedef. Also prefer a tag over a typedef for
387 // destructor name lookup because in some contexts we only accept a
388 // class-name in a destructor declaration.
389 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
390 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying));
391 bool HaveTag = isa<TagDecl>(EUnderlying);
392 bool WantTag =
393 Kind == Sema::LookupTagName || Kind == Sema::LookupDestructorName;
394 return HaveTag != WantTag;
397 // Pick the function with more default arguments.
398 // FIXME: In the presence of ambiguous default arguments, we should keep both,
399 // so we can diagnose the ambiguity if the default argument is needed.
400 // See C++ [over.match.best]p3.
401 if (const auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
402 const auto *EFD = cast<FunctionDecl>(EUnderlying);
403 unsigned DMin = DFD->getMinRequiredArguments();
404 unsigned EMin = EFD->getMinRequiredArguments();
405 // If D has more default arguments, it is preferred.
406 if (DMin != EMin)
407 return DMin < EMin;
408 // FIXME: When we track visibility for default function arguments, check
409 // that we pick the declaration with more visible default arguments.
412 // Pick the template with more default template arguments.
413 if (const auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
414 const auto *ETD = cast<TemplateDecl>(EUnderlying);
415 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
416 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
417 // If D has more default arguments, it is preferred. Note that default
418 // arguments (and their visibility) is monotonically increasing across the
419 // redeclaration chain, so this is a quick proxy for "is more recent".
420 if (DMin != EMin)
421 return DMin < EMin;
422 // If D has more *visible* default arguments, it is preferred. Note, an
423 // earlier default argument being visible does not imply that a later
424 // default argument is visible, so we can't just check the first one.
425 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
426 I != N; ++I) {
427 if (!S.hasVisibleDefaultArgument(
428 ETD->getTemplateParameters()->getParam(I)) &&
429 S.hasVisibleDefaultArgument(
430 DTD->getTemplateParameters()->getParam(I)))
431 return true;
435 // VarDecl can have incomplete array types, prefer the one with more complete
436 // array type.
437 if (const auto *DVD = dyn_cast<VarDecl>(DUnderlying)) {
438 const auto *EVD = cast<VarDecl>(EUnderlying);
439 if (EVD->getType()->isIncompleteType() &&
440 !DVD->getType()->isIncompleteType()) {
441 // Prefer the decl with a more complete type if visible.
442 return S.isVisible(DVD);
444 return false; // Avoid picking up a newer decl, just because it was newer.
447 // For most kinds of declaration, it doesn't really matter which one we pick.
448 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
449 // If the existing declaration is hidden, prefer the new one. Otherwise,
450 // keep what we've got.
451 return !S.isVisible(Existing);
454 // Pick the newer declaration; it might have a more precise type.
455 for (const Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
456 Prev = Prev->getPreviousDecl())
457 if (Prev == EUnderlying)
458 return true;
459 return false;
462 /// Determine whether \p D can hide a tag declaration.
463 static bool canHideTag(const NamedDecl *D) {
464 // C++ [basic.scope.declarative]p4:
465 // Given a set of declarations in a single declarative region [...]
466 // exactly one declaration shall declare a class name or enumeration name
467 // that is not a typedef name and the other declarations shall all refer to
468 // the same variable, non-static data member, or enumerator, or all refer
469 // to functions and function templates; in this case the class name or
470 // enumeration name is hidden.
471 // C++ [basic.scope.hiding]p2:
472 // A class name or enumeration name can be hidden by the name of a
473 // variable, data member, function, or enumerator declared in the same
474 // scope.
475 // An UnresolvedUsingValueDecl always instantiates to one of these.
476 D = D->getUnderlyingDecl();
477 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
478 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
479 isa<UnresolvedUsingValueDecl>(D);
482 /// Resolves the result kind of this lookup.
483 void LookupResult::resolveKind() {
484 unsigned N = Decls.size();
486 // Fast case: no possible ambiguity.
487 if (N == 0) {
488 assert(ResultKind == NotFound ||
489 ResultKind == NotFoundInCurrentInstantiation);
490 return;
493 // If there's a single decl, we need to examine it to decide what
494 // kind of lookup this is.
495 if (N == 1) {
496 const NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
497 if (isa<FunctionTemplateDecl>(D))
498 ResultKind = FoundOverloaded;
499 else if (isa<UnresolvedUsingValueDecl>(D))
500 ResultKind = FoundUnresolvedValue;
501 return;
504 // Don't do any extra resolution if we've already resolved as ambiguous.
505 if (ResultKind == Ambiguous) return;
507 llvm::SmallDenseMap<const NamedDecl *, unsigned, 16> Unique;
508 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
510 bool Ambiguous = false;
511 bool ReferenceToPlaceHolderVariable = false;
512 bool HasTag = false, HasFunction = false;
513 bool HasFunctionTemplate = false, HasUnresolved = false;
514 const NamedDecl *HasNonFunction = nullptr;
516 llvm::SmallVector<const NamedDecl *, 4> EquivalentNonFunctions;
517 llvm::BitVector RemovedDecls(N);
519 for (unsigned I = 0; I < N; I++) {
520 const NamedDecl *D = Decls[I]->getUnderlyingDecl();
521 D = cast<NamedDecl>(D->getCanonicalDecl());
523 // Ignore an invalid declaration unless it's the only one left.
524 // Also ignore HLSLBufferDecl which not have name conflict with other Decls.
525 if ((D->isInvalidDecl() || isa<HLSLBufferDecl>(D)) &&
526 N - RemovedDecls.count() > 1) {
527 RemovedDecls.set(I);
528 continue;
531 // C++ [basic.scope.hiding]p2:
532 // A class name or enumeration name can be hidden by the name of
533 // an object, function, or enumerator declared in the same
534 // scope. If a class or enumeration name and an object, function,
535 // or enumerator are declared in the same scope (in any order)
536 // with the same name, the class or enumeration name is hidden
537 // wherever the object, function, or enumerator name is visible.
538 if (HideTags && isa<TagDecl>(D)) {
539 bool Hidden = false;
540 for (auto *OtherDecl : Decls) {
541 if (canHideTag(OtherDecl) && !OtherDecl->isInvalidDecl() &&
542 getContextForScopeMatching(OtherDecl)->Equals(
543 getContextForScopeMatching(Decls[I]))) {
544 RemovedDecls.set(I);
545 Hidden = true;
546 break;
549 if (Hidden)
550 continue;
553 std::optional<unsigned> ExistingI;
555 // Redeclarations of types via typedef can occur both within a scope
556 // and, through using declarations and directives, across scopes. There is
557 // no ambiguity if they all refer to the same type, so unique based on the
558 // canonical type.
559 if (const auto *TD = dyn_cast<TypeDecl>(D)) {
560 QualType T = getSema().Context.getTypeDeclType(TD);
561 auto UniqueResult = UniqueTypes.insert(
562 std::make_pair(getSema().Context.getCanonicalType(T), I));
563 if (!UniqueResult.second) {
564 // The type is not unique.
565 ExistingI = UniqueResult.first->second;
569 // For non-type declarations, check for a prior lookup result naming this
570 // canonical declaration.
571 if (!D->isPlaceholderVar(getSema().getLangOpts()) && !ExistingI) {
572 auto UniqueResult = Unique.insert(std::make_pair(D, I));
573 if (!UniqueResult.second) {
574 // We've seen this entity before.
575 ExistingI = UniqueResult.first->second;
579 if (ExistingI) {
580 // This is not a unique lookup result. Pick one of the results and
581 // discard the other.
582 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
583 Decls[*ExistingI]))
584 Decls[*ExistingI] = Decls[I];
585 RemovedDecls.set(I);
586 continue;
589 // Otherwise, do some decl type analysis and then continue.
591 if (isa<UnresolvedUsingValueDecl>(D)) {
592 HasUnresolved = true;
593 } else if (isa<TagDecl>(D)) {
594 if (HasTag)
595 Ambiguous = true;
596 HasTag = true;
597 } else if (isa<FunctionTemplateDecl>(D)) {
598 HasFunction = true;
599 HasFunctionTemplate = true;
600 } else if (isa<FunctionDecl>(D)) {
601 HasFunction = true;
602 } else {
603 if (HasNonFunction) {
604 // If we're about to create an ambiguity between two declarations that
605 // are equivalent, but one is an internal linkage declaration from one
606 // module and the other is an internal linkage declaration from another
607 // module, just skip it.
608 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
609 D)) {
610 EquivalentNonFunctions.push_back(D);
611 RemovedDecls.set(I);
612 continue;
614 if (D->isPlaceholderVar(getSema().getLangOpts()) &&
615 getContextForScopeMatching(D) ==
616 getContextForScopeMatching(Decls[I])) {
617 ReferenceToPlaceHolderVariable = true;
619 Ambiguous = true;
621 HasNonFunction = D;
625 // FIXME: This diagnostic should really be delayed until we're done with
626 // the lookup result, in case the ambiguity is resolved by the caller.
627 if (!EquivalentNonFunctions.empty() && !Ambiguous)
628 getSema().diagnoseEquivalentInternalLinkageDeclarations(
629 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
631 // Remove decls by replacing them with decls from the end (which
632 // means that we need to iterate from the end) and then truncating
633 // to the new size.
634 for (int I = RemovedDecls.find_last(); I >= 0; I = RemovedDecls.find_prev(I))
635 Decls[I] = Decls[--N];
636 Decls.truncate(N);
638 if ((HasNonFunction && (HasFunction || HasUnresolved)) ||
639 (HideTags && HasTag && (HasFunction || HasNonFunction || HasUnresolved)))
640 Ambiguous = true;
642 if (Ambiguous && ReferenceToPlaceHolderVariable)
643 setAmbiguous(LookupResult::AmbiguousReferenceToPlaceholderVariable);
644 else if (Ambiguous)
645 setAmbiguous(LookupResult::AmbiguousReference);
646 else if (HasUnresolved)
647 ResultKind = LookupResult::FoundUnresolvedValue;
648 else if (N > 1 || HasFunctionTemplate)
649 ResultKind = LookupResult::FoundOverloaded;
650 else
651 ResultKind = LookupResult::Found;
654 void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
655 CXXBasePaths::const_paths_iterator I, E;
656 for (I = P.begin(), E = P.end(); I != E; ++I)
657 for (DeclContext::lookup_iterator DI = I->Decls, DE = DI.end(); DI != DE;
658 ++DI)
659 addDecl(*DI);
662 void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
663 Paths = new CXXBasePaths;
664 Paths->swap(P);
665 addDeclsFromBasePaths(*Paths);
666 resolveKind();
667 setAmbiguous(AmbiguousBaseSubobjects);
670 void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
671 Paths = new CXXBasePaths;
672 Paths->swap(P);
673 addDeclsFromBasePaths(*Paths);
674 resolveKind();
675 setAmbiguous(AmbiguousBaseSubobjectTypes);
678 void LookupResult::print(raw_ostream &Out) {
679 Out << Decls.size() << " result(s)";
680 if (isAmbiguous()) Out << ", ambiguous";
681 if (Paths) Out << ", base paths present";
683 for (iterator I = begin(), E = end(); I != E; ++I) {
684 Out << "\n";
685 (*I)->print(Out, 2);
689 LLVM_DUMP_METHOD void LookupResult::dump() {
690 llvm::errs() << "lookup results for " << getLookupName().getAsString()
691 << ":\n";
692 for (NamedDecl *D : *this)
693 D->dump();
696 /// Diagnose a missing builtin type.
697 static QualType diagOpenCLBuiltinTypeError(Sema &S, llvm::StringRef TypeClass,
698 llvm::StringRef Name) {
699 S.Diag(SourceLocation(), diag::err_opencl_type_not_found)
700 << TypeClass << Name;
701 return S.Context.VoidTy;
704 /// Lookup an OpenCL enum type.
705 static QualType getOpenCLEnumType(Sema &S, llvm::StringRef Name) {
706 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
707 Sema::LookupTagName);
708 S.LookupName(Result, S.TUScope);
709 if (Result.empty())
710 return diagOpenCLBuiltinTypeError(S, "enum", Name);
711 EnumDecl *Decl = Result.getAsSingle<EnumDecl>();
712 if (!Decl)
713 return diagOpenCLBuiltinTypeError(S, "enum", Name);
714 return S.Context.getEnumType(Decl);
717 /// Lookup an OpenCL typedef type.
718 static QualType getOpenCLTypedefType(Sema &S, llvm::StringRef Name) {
719 LookupResult Result(S, &S.Context.Idents.get(Name), SourceLocation(),
720 Sema::LookupOrdinaryName);
721 S.LookupName(Result, S.TUScope);
722 if (Result.empty())
723 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
724 TypedefNameDecl *Decl = Result.getAsSingle<TypedefNameDecl>();
725 if (!Decl)
726 return diagOpenCLBuiltinTypeError(S, "typedef", Name);
727 return S.Context.getTypedefType(Decl);
730 /// Get the QualType instances of the return type and arguments for an OpenCL
731 /// builtin function signature.
732 /// \param S (in) The Sema instance.
733 /// \param OpenCLBuiltin (in) The signature currently handled.
734 /// \param GenTypeMaxCnt (out) Maximum number of types contained in a generic
735 /// type used as return type or as argument.
736 /// Only meaningful for generic types, otherwise equals 1.
737 /// \param RetTypes (out) List of the possible return types.
738 /// \param ArgTypes (out) List of the possible argument types. For each
739 /// argument, ArgTypes contains QualTypes for the Cartesian product
740 /// of (vector sizes) x (types) .
741 static void GetQualTypesForOpenCLBuiltin(
742 Sema &S, const OpenCLBuiltinStruct &OpenCLBuiltin, unsigned &GenTypeMaxCnt,
743 SmallVector<QualType, 1> &RetTypes,
744 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
745 // Get the QualType instances of the return types.
746 unsigned Sig = SignatureTable[OpenCLBuiltin.SigTableIndex];
747 OCL2Qual(S, TypeTable[Sig], RetTypes);
748 GenTypeMaxCnt = RetTypes.size();
750 // Get the QualType instances of the arguments.
751 // First type is the return type, skip it.
752 for (unsigned Index = 1; Index < OpenCLBuiltin.NumTypes; Index++) {
753 SmallVector<QualType, 1> Ty;
754 OCL2Qual(S, TypeTable[SignatureTable[OpenCLBuiltin.SigTableIndex + Index]],
755 Ty);
756 GenTypeMaxCnt = (Ty.size() > GenTypeMaxCnt) ? Ty.size() : GenTypeMaxCnt;
757 ArgTypes.push_back(std::move(Ty));
761 /// Create a list of the candidate function overloads for an OpenCL builtin
762 /// function.
763 /// \param Context (in) The ASTContext instance.
764 /// \param GenTypeMaxCnt (in) Maximum number of types contained in a generic
765 /// type used as return type or as argument.
766 /// Only meaningful for generic types, otherwise equals 1.
767 /// \param FunctionList (out) List of FunctionTypes.
768 /// \param RetTypes (in) List of the possible return types.
769 /// \param ArgTypes (in) List of the possible types for the arguments.
770 static void GetOpenCLBuiltinFctOverloads(
771 ASTContext &Context, unsigned GenTypeMaxCnt,
772 std::vector<QualType> &FunctionList, SmallVector<QualType, 1> &RetTypes,
773 SmallVector<SmallVector<QualType, 1>, 5> &ArgTypes) {
774 FunctionProtoType::ExtProtoInfo PI(
775 Context.getDefaultCallingConvention(false, false, true));
776 PI.Variadic = false;
778 // Do not attempt to create any FunctionTypes if there are no return types,
779 // which happens when a type belongs to a disabled extension.
780 if (RetTypes.size() == 0)
781 return;
783 // Create FunctionTypes for each (gen)type.
784 for (unsigned IGenType = 0; IGenType < GenTypeMaxCnt; IGenType++) {
785 SmallVector<QualType, 5> ArgList;
787 for (unsigned A = 0; A < ArgTypes.size(); A++) {
788 // Bail out if there is an argument that has no available types.
789 if (ArgTypes[A].size() == 0)
790 return;
792 // Builtins such as "max" have an "sgentype" argument that represents
793 // the corresponding scalar type of a gentype. The number of gentypes
794 // must be a multiple of the number of sgentypes.
795 assert(GenTypeMaxCnt % ArgTypes[A].size() == 0 &&
796 "argument type count not compatible with gentype type count");
797 unsigned Idx = IGenType % ArgTypes[A].size();
798 ArgList.push_back(ArgTypes[A][Idx]);
801 FunctionList.push_back(Context.getFunctionType(
802 RetTypes[(RetTypes.size() != 1) ? IGenType : 0], ArgList, PI));
806 /// When trying to resolve a function name, if isOpenCLBuiltin() returns a
807 /// non-null <Index, Len> pair, then the name is referencing an OpenCL
808 /// builtin function. Add all candidate signatures to the LookUpResult.
810 /// \param S (in) The Sema instance.
811 /// \param LR (inout) The LookupResult instance.
812 /// \param II (in) The identifier being resolved.
813 /// \param FctIndex (in) Starting index in the BuiltinTable.
814 /// \param Len (in) The signature list has Len elements.
815 static void InsertOCLBuiltinDeclarationsFromTable(Sema &S, LookupResult &LR,
816 IdentifierInfo *II,
817 const unsigned FctIndex,
818 const unsigned Len) {
819 // The builtin function declaration uses generic types (gentype).
820 bool HasGenType = false;
822 // Maximum number of types contained in a generic type used as return type or
823 // as argument. Only meaningful for generic types, otherwise equals 1.
824 unsigned GenTypeMaxCnt;
826 ASTContext &Context = S.Context;
828 for (unsigned SignatureIndex = 0; SignatureIndex < Len; SignatureIndex++) {
829 const OpenCLBuiltinStruct &OpenCLBuiltin =
830 BuiltinTable[FctIndex + SignatureIndex];
832 // Ignore this builtin function if it is not available in the currently
833 // selected language version.
834 if (!isOpenCLVersionContainedInMask(Context.getLangOpts(),
835 OpenCLBuiltin.Versions))
836 continue;
838 // Ignore this builtin function if it carries an extension macro that is
839 // not defined. This indicates that the extension is not supported by the
840 // target, so the builtin function should not be available.
841 StringRef Extensions = FunctionExtensionTable[OpenCLBuiltin.Extension];
842 if (!Extensions.empty()) {
843 SmallVector<StringRef, 2> ExtVec;
844 Extensions.split(ExtVec, " ");
845 bool AllExtensionsDefined = true;
846 for (StringRef Ext : ExtVec) {
847 if (!S.getPreprocessor().isMacroDefined(Ext)) {
848 AllExtensionsDefined = false;
849 break;
852 if (!AllExtensionsDefined)
853 continue;
856 SmallVector<QualType, 1> RetTypes;
857 SmallVector<SmallVector<QualType, 1>, 5> ArgTypes;
859 // Obtain QualType lists for the function signature.
860 GetQualTypesForOpenCLBuiltin(S, OpenCLBuiltin, GenTypeMaxCnt, RetTypes,
861 ArgTypes);
862 if (GenTypeMaxCnt > 1) {
863 HasGenType = true;
866 // Create function overload for each type combination.
867 std::vector<QualType> FunctionList;
868 GetOpenCLBuiltinFctOverloads(Context, GenTypeMaxCnt, FunctionList, RetTypes,
869 ArgTypes);
871 SourceLocation Loc = LR.getNameLoc();
872 DeclContext *Parent = Context.getTranslationUnitDecl();
873 FunctionDecl *NewOpenCLBuiltin;
875 for (const auto &FTy : FunctionList) {
876 NewOpenCLBuiltin = FunctionDecl::Create(
877 Context, Parent, Loc, Loc, II, FTy, /*TInfo=*/nullptr, SC_Extern,
878 S.getCurFPFeatures().isFPConstrained(), false,
879 FTy->isFunctionProtoType());
880 NewOpenCLBuiltin->setImplicit();
882 // Create Decl objects for each parameter, adding them to the
883 // FunctionDecl.
884 const auto *FP = cast<FunctionProtoType>(FTy);
885 SmallVector<ParmVarDecl *, 4> ParmList;
886 for (unsigned IParm = 0, e = FP->getNumParams(); IParm != e; ++IParm) {
887 ParmVarDecl *Parm = ParmVarDecl::Create(
888 Context, NewOpenCLBuiltin, SourceLocation(), SourceLocation(),
889 nullptr, FP->getParamType(IParm), nullptr, SC_None, nullptr);
890 Parm->setScopeInfo(0, IParm);
891 ParmList.push_back(Parm);
893 NewOpenCLBuiltin->setParams(ParmList);
895 // Add function attributes.
896 if (OpenCLBuiltin.IsPure)
897 NewOpenCLBuiltin->addAttr(PureAttr::CreateImplicit(Context));
898 if (OpenCLBuiltin.IsConst)
899 NewOpenCLBuiltin->addAttr(ConstAttr::CreateImplicit(Context));
900 if (OpenCLBuiltin.IsConv)
901 NewOpenCLBuiltin->addAttr(ConvergentAttr::CreateImplicit(Context));
903 if (!S.getLangOpts().OpenCLCPlusPlus)
904 NewOpenCLBuiltin->addAttr(OverloadableAttr::CreateImplicit(Context));
906 LR.addDecl(NewOpenCLBuiltin);
910 // If we added overloads, need to resolve the lookup result.
911 if (Len > 1 || HasGenType)
912 LR.resolveKind();
915 /// Lookup a builtin function, when name lookup would otherwise
916 /// fail.
917 bool Sema::LookupBuiltin(LookupResult &R) {
918 Sema::LookupNameKind NameKind = R.getLookupKind();
920 // If we didn't find a use of this identifier, and if the identifier
921 // corresponds to a compiler builtin, create the decl object for the builtin
922 // now, injecting it into translation unit scope, and return it.
923 if (NameKind == Sema::LookupOrdinaryName ||
924 NameKind == Sema::LookupRedeclarationWithLinkage) {
925 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
926 if (II) {
927 if (getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
928 if (II == getASTContext().getMakeIntegerSeqName()) {
929 R.addDecl(getASTContext().getMakeIntegerSeqDecl());
930 return true;
931 } else if (II == getASTContext().getTypePackElementName()) {
932 R.addDecl(getASTContext().getTypePackElementDecl());
933 return true;
937 // Check if this is an OpenCL Builtin, and if so, insert its overloads.
938 if (getLangOpts().OpenCL && getLangOpts().DeclareOpenCLBuiltins) {
939 auto Index = isOpenCLBuiltin(II->getName());
940 if (Index.first) {
941 InsertOCLBuiltinDeclarationsFromTable(*this, R, II, Index.first - 1,
942 Index.second);
943 return true;
947 if (DeclareRISCVVBuiltins || DeclareRISCVSiFiveVectorBuiltins) {
948 if (!RVIntrinsicManager)
949 RVIntrinsicManager = CreateRISCVIntrinsicManager(*this);
951 RVIntrinsicManager->InitIntrinsicList();
953 if (RVIntrinsicManager->CreateIntrinsicIfFound(R, II, PP))
954 return true;
957 // If this is a builtin on this (or all) targets, create the decl.
958 if (unsigned BuiltinID = II->getBuiltinID()) {
959 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
960 // library functions like 'malloc'. Instead, we'll just error.
961 if ((getLangOpts().CPlusPlus || getLangOpts().OpenCL) &&
962 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
963 return false;
965 if (NamedDecl *D =
966 LazilyCreateBuiltin(II, BuiltinID, TUScope,
967 R.isForRedeclaration(), R.getNameLoc())) {
968 R.addDecl(D);
969 return true;
975 return false;
978 /// Looks up the declaration of "struct objc_super" and
979 /// saves it for later use in building builtin declaration of
980 /// objc_msgSendSuper and objc_msgSendSuper_stret.
981 static void LookupPredefedObjCSuperType(Sema &Sema, Scope *S) {
982 ASTContext &Context = Sema.Context;
983 LookupResult Result(Sema, &Context.Idents.get("objc_super"), SourceLocation(),
984 Sema::LookupTagName);
985 Sema.LookupName(Result, S);
986 if (Result.getResultKind() == LookupResult::Found)
987 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
988 Context.setObjCSuperType(Context.getTagDeclType(TD));
991 void Sema::LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID) {
992 if (ID == Builtin::BIobjc_msgSendSuper)
993 LookupPredefedObjCSuperType(*this, S);
996 /// Determine whether we can declare a special member function within
997 /// the class at this point.
998 static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
999 // We need to have a definition for the class.
1000 if (!Class->getDefinition() || Class->isDependentContext())
1001 return false;
1003 // We can't be in the middle of defining the class.
1004 return !Class->isBeingDefined();
1007 void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
1008 if (!CanDeclareSpecialMemberFunction(Class))
1009 return;
1011 // If the default constructor has not yet been declared, do so now.
1012 if (Class->needsImplicitDefaultConstructor())
1013 DeclareImplicitDefaultConstructor(Class);
1015 // If the copy constructor has not yet been declared, do so now.
1016 if (Class->needsImplicitCopyConstructor())
1017 DeclareImplicitCopyConstructor(Class);
1019 // If the copy assignment operator has not yet been declared, do so now.
1020 if (Class->needsImplicitCopyAssignment())
1021 DeclareImplicitCopyAssignment(Class);
1023 if (getLangOpts().CPlusPlus11) {
1024 // If the move constructor has not yet been declared, do so now.
1025 if (Class->needsImplicitMoveConstructor())
1026 DeclareImplicitMoveConstructor(Class);
1028 // If the move assignment operator has not yet been declared, do so now.
1029 if (Class->needsImplicitMoveAssignment())
1030 DeclareImplicitMoveAssignment(Class);
1033 // If the destructor has not yet been declared, do so now.
1034 if (Class->needsImplicitDestructor())
1035 DeclareImplicitDestructor(Class);
1038 /// Determine whether this is the name of an implicitly-declared
1039 /// special member function.
1040 static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
1041 switch (Name.getNameKind()) {
1042 case DeclarationName::CXXConstructorName:
1043 case DeclarationName::CXXDestructorName:
1044 return true;
1046 case DeclarationName::CXXOperatorName:
1047 return Name.getCXXOverloadedOperator() == OO_Equal;
1049 default:
1050 break;
1053 return false;
1056 /// If there are any implicit member functions with the given name
1057 /// that need to be declared in the given declaration context, do so.
1058 static void DeclareImplicitMemberFunctionsWithName(Sema &S,
1059 DeclarationName Name,
1060 SourceLocation Loc,
1061 const DeclContext *DC) {
1062 if (!DC)
1063 return;
1065 switch (Name.getNameKind()) {
1066 case DeclarationName::CXXConstructorName:
1067 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1068 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1069 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1070 if (Record->needsImplicitDefaultConstructor())
1071 S.DeclareImplicitDefaultConstructor(Class);
1072 if (Record->needsImplicitCopyConstructor())
1073 S.DeclareImplicitCopyConstructor(Class);
1074 if (S.getLangOpts().CPlusPlus11 &&
1075 Record->needsImplicitMoveConstructor())
1076 S.DeclareImplicitMoveConstructor(Class);
1078 break;
1080 case DeclarationName::CXXDestructorName:
1081 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
1082 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
1083 CanDeclareSpecialMemberFunction(Record))
1084 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
1085 break;
1087 case DeclarationName::CXXOperatorName:
1088 if (Name.getCXXOverloadedOperator() != OO_Equal)
1089 break;
1091 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
1092 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
1093 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
1094 if (Record->needsImplicitCopyAssignment())
1095 S.DeclareImplicitCopyAssignment(Class);
1096 if (S.getLangOpts().CPlusPlus11 &&
1097 Record->needsImplicitMoveAssignment())
1098 S.DeclareImplicitMoveAssignment(Class);
1101 break;
1103 case DeclarationName::CXXDeductionGuideName:
1104 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
1105 break;
1107 default:
1108 break;
1112 // Adds all qualifying matches for a name within a decl context to the
1113 // given lookup result. Returns true if any matches were found.
1114 static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
1115 bool Found = false;
1117 // Lazily declare C++ special member functions.
1118 if (S.getLangOpts().CPlusPlus)
1119 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
1120 DC);
1122 // Perform lookup into this declaration context.
1123 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
1124 for (NamedDecl *D : DR) {
1125 if ((D = R.getAcceptableDecl(D))) {
1126 R.addDecl(D);
1127 Found = true;
1131 if (!Found && DC->isTranslationUnit() && S.LookupBuiltin(R))
1132 return true;
1134 if (R.getLookupName().getNameKind()
1135 != DeclarationName::CXXConversionFunctionName ||
1136 R.getLookupName().getCXXNameType()->isDependentType() ||
1137 !isa<CXXRecordDecl>(DC))
1138 return Found;
1140 // C++ [temp.mem]p6:
1141 // A specialization of a conversion function template is not found by
1142 // name lookup. Instead, any conversion function templates visible in the
1143 // context of the use are considered. [...]
1144 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1145 if (!Record->isCompleteDefinition())
1146 return Found;
1148 // For conversion operators, 'operator auto' should only match
1149 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
1150 // as a candidate for template substitution.
1151 auto *ContainedDeducedType =
1152 R.getLookupName().getCXXNameType()->getContainedDeducedType();
1153 if (R.getLookupName().getNameKind() ==
1154 DeclarationName::CXXConversionFunctionName &&
1155 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
1156 return Found;
1158 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
1159 UEnd = Record->conversion_end(); U != UEnd; ++U) {
1160 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
1161 if (!ConvTemplate)
1162 continue;
1164 // When we're performing lookup for the purposes of redeclaration, just
1165 // add the conversion function template. When we deduce template
1166 // arguments for specializations, we'll end up unifying the return
1167 // type of the new declaration with the type of the function template.
1168 if (R.isForRedeclaration()) {
1169 R.addDecl(ConvTemplate);
1170 Found = true;
1171 continue;
1174 // C++ [temp.mem]p6:
1175 // [...] For each such operator, if argument deduction succeeds
1176 // (14.9.2.3), the resulting specialization is used as if found by
1177 // name lookup.
1179 // When referencing a conversion function for any purpose other than
1180 // a redeclaration (such that we'll be building an expression with the
1181 // result), perform template argument deduction and place the
1182 // specialization into the result set. We do this to avoid forcing all
1183 // callers to perform special deduction for conversion functions.
1184 TemplateDeductionInfo Info(R.getNameLoc());
1185 FunctionDecl *Specialization = nullptr;
1187 const FunctionProtoType *ConvProto
1188 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
1189 assert(ConvProto && "Nonsensical conversion function template type");
1191 // Compute the type of the function that we would expect the conversion
1192 // function to have, if it were to match the name given.
1193 // FIXME: Calling convention!
1194 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
1195 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
1196 EPI.ExceptionSpec = EST_None;
1197 QualType ExpectedType = R.getSema().Context.getFunctionType(
1198 R.getLookupName().getCXXNameType(), std::nullopt, EPI);
1200 // Perform template argument deduction against the type that we would
1201 // expect the function to have.
1202 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
1203 Specialization, Info)
1204 == Sema::TDK_Success) {
1205 R.addDecl(Specialization);
1206 Found = true;
1210 return Found;
1213 // Performs C++ unqualified lookup into the given file context.
1214 static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
1215 const DeclContext *NS,
1216 UnqualUsingDirectiveSet &UDirs) {
1218 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
1220 // Perform direct name lookup into the LookupCtx.
1221 bool Found = LookupDirect(S, R, NS);
1223 // Perform direct name lookup into the namespaces nominated by the
1224 // using directives whose common ancestor is this namespace.
1225 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
1226 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
1227 Found = true;
1229 R.resolveKind();
1231 return Found;
1234 static bool isNamespaceOrTranslationUnitScope(Scope *S) {
1235 if (DeclContext *Ctx = S->getEntity())
1236 return Ctx->isFileContext();
1237 return false;
1240 /// Find the outer declaration context from this scope. This indicates the
1241 /// context that we should search up to (exclusive) before considering the
1242 /// parent of the specified scope.
1243 static DeclContext *findOuterContext(Scope *S) {
1244 for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent())
1245 if (DeclContext *DC = OuterS->getLookupEntity())
1246 return DC;
1247 return nullptr;
1250 namespace {
1251 /// An RAII object to specify that we want to find block scope extern
1252 /// declarations.
1253 struct FindLocalExternScope {
1254 FindLocalExternScope(LookupResult &R)
1255 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1256 Decl::IDNS_LocalExtern) {
1257 R.setFindLocalExtern(R.getIdentifierNamespace() &
1258 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
1260 void restore() {
1261 R.setFindLocalExtern(OldFindLocalExtern);
1263 ~FindLocalExternScope() {
1264 restore();
1266 LookupResult &R;
1267 bool OldFindLocalExtern;
1269 } // end anonymous namespace
1271 bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1272 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup");
1274 DeclarationName Name = R.getLookupName();
1275 Sema::LookupNameKind NameKind = R.getLookupKind();
1277 // If this is the name of an implicitly-declared special member function,
1278 // go through the scope stack to implicitly declare
1279 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1280 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1281 if (DeclContext *DC = PreS->getEntity())
1282 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
1285 // Implicitly declare member functions with the name we're looking for, if in
1286 // fact we are in a scope where it matters.
1288 Scope *Initial = S;
1289 IdentifierResolver::iterator
1290 I = IdResolver.begin(Name),
1291 IEnd = IdResolver.end();
1293 // First we lookup local scope.
1294 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1295 // ...During unqualified name lookup (3.4.1), the names appear as if
1296 // they were declared in the nearest enclosing namespace which contains
1297 // both the using-directive and the nominated namespace.
1298 // [Note: in this context, "contains" means "contains directly or
1299 // indirectly".
1301 // For example:
1302 // namespace A { int i; }
1303 // void foo() {
1304 // int i;
1305 // {
1306 // using namespace A;
1307 // ++i; // finds local 'i', A::i appears at global scope
1308 // }
1309 // }
1311 UnqualUsingDirectiveSet UDirs(*this);
1312 bool VisitedUsingDirectives = false;
1313 bool LeftStartingScope = false;
1315 // When performing a scope lookup, we want to find local extern decls.
1316 FindLocalExternScope FindLocals(R);
1318 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1319 bool SearchNamespaceScope = true;
1320 // Check whether the IdResolver has anything in this scope.
1321 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1322 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1323 if (NameKind == LookupRedeclarationWithLinkage &&
1324 !(*I)->isTemplateParameter()) {
1325 // If it's a template parameter, we still find it, so we can diagnose
1326 // the invalid redeclaration.
1328 // Determine whether this (or a previous) declaration is
1329 // out-of-scope.
1330 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1331 LeftStartingScope = true;
1333 // If we found something outside of our starting scope that
1334 // does not have linkage, skip it.
1335 if (LeftStartingScope && !((*I)->hasLinkage())) {
1336 R.setShadowed();
1337 continue;
1339 } else {
1340 // We found something in this scope, we should not look at the
1341 // namespace scope
1342 SearchNamespaceScope = false;
1344 R.addDecl(ND);
1347 if (!SearchNamespaceScope) {
1348 R.resolveKind();
1349 if (S->isClassScope())
1350 if (auto *Record = dyn_cast_if_present<CXXRecordDecl>(S->getEntity()))
1351 R.setNamingClass(Record);
1352 return true;
1355 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1356 // C++11 [class.friend]p11:
1357 // If a friend declaration appears in a local class and the name
1358 // specified is an unqualified name, a prior declaration is
1359 // looked up without considering scopes that are outside the
1360 // innermost enclosing non-class scope.
1361 return false;
1364 if (DeclContext *Ctx = S->getLookupEntity()) {
1365 DeclContext *OuterCtx = findOuterContext(S);
1366 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1367 // We do not directly look into transparent contexts, since
1368 // those entities will be found in the nearest enclosing
1369 // non-transparent context.
1370 if (Ctx->isTransparentContext())
1371 continue;
1373 // We do not look directly into function or method contexts,
1374 // since all of the local variables and parameters of the
1375 // function/method are present within the Scope.
1376 if (Ctx->isFunctionOrMethod()) {
1377 // If we have an Objective-C instance method, look for ivars
1378 // in the corresponding interface.
1379 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1380 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1381 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1382 ObjCInterfaceDecl *ClassDeclared;
1383 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1384 Name.getAsIdentifierInfo(),
1385 ClassDeclared)) {
1386 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1387 R.addDecl(ND);
1388 R.resolveKind();
1389 return true;
1395 continue;
1398 // If this is a file context, we need to perform unqualified name
1399 // lookup considering using directives.
1400 if (Ctx->isFileContext()) {
1401 // If we haven't handled using directives yet, do so now.
1402 if (!VisitedUsingDirectives) {
1403 // Add using directives from this context up to the top level.
1404 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1405 if (UCtx->isTransparentContext())
1406 continue;
1408 UDirs.visit(UCtx, UCtx);
1411 // Find the innermost file scope, so we can add using directives
1412 // from local scopes.
1413 Scope *InnermostFileScope = S;
1414 while (InnermostFileScope &&
1415 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1416 InnermostFileScope = InnermostFileScope->getParent();
1417 UDirs.visitScopeChain(Initial, InnermostFileScope);
1419 UDirs.done();
1421 VisitedUsingDirectives = true;
1424 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1425 R.resolveKind();
1426 return true;
1429 continue;
1432 // Perform qualified name lookup into this context.
1433 // FIXME: In some cases, we know that every name that could be found by
1434 // this qualified name lookup will also be on the identifier chain. For
1435 // example, inside a class without any base classes, we never need to
1436 // perform qualified lookup because all of the members are on top of the
1437 // identifier chain.
1438 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1439 return true;
1444 // Stop if we ran out of scopes.
1445 // FIXME: This really, really shouldn't be happening.
1446 if (!S) return false;
1448 // If we are looking for members, no need to look into global/namespace scope.
1449 if (NameKind == LookupMemberName)
1450 return false;
1452 // Collect UsingDirectiveDecls in all scopes, and recursively all
1453 // nominated namespaces by those using-directives.
1455 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1456 // don't build it for each lookup!
1457 if (!VisitedUsingDirectives) {
1458 UDirs.visitScopeChain(Initial, S);
1459 UDirs.done();
1462 // If we're not performing redeclaration lookup, do not look for local
1463 // extern declarations outside of a function scope.
1464 if (!R.isForRedeclaration())
1465 FindLocals.restore();
1467 // Lookup namespace scope, and global scope.
1468 // Unqualified name lookup in C++ requires looking into scopes
1469 // that aren't strictly lexical, and therefore we walk through the
1470 // context as well as walking through the scopes.
1471 for (; S; S = S->getParent()) {
1472 // Check whether the IdResolver has anything in this scope.
1473 bool Found = false;
1474 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1475 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1476 // We found something. Look for anything else in our scope
1477 // with this same name and in an acceptable identifier
1478 // namespace, so that we can construct an overload set if we
1479 // need to.
1480 Found = true;
1481 R.addDecl(ND);
1485 if (Found && S->isTemplateParamScope()) {
1486 R.resolveKind();
1487 return true;
1490 DeclContext *Ctx = S->getLookupEntity();
1491 if (Ctx) {
1492 DeclContext *OuterCtx = findOuterContext(S);
1493 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1494 // We do not directly look into transparent contexts, since
1495 // those entities will be found in the nearest enclosing
1496 // non-transparent context.
1497 if (Ctx->isTransparentContext())
1498 continue;
1500 // If we have a context, and it's not a context stashed in the
1501 // template parameter scope for an out-of-line definition, also
1502 // look into that context.
1503 if (!(Found && S->isTemplateParamScope())) {
1504 assert(Ctx->isFileContext() &&
1505 "We should have been looking only at file context here already.");
1507 // Look into context considering using-directives.
1508 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1509 Found = true;
1512 if (Found) {
1513 R.resolveKind();
1514 return true;
1517 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1518 return false;
1522 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1523 return false;
1526 return !R.empty();
1529 void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1530 if (auto *M = getCurrentModule())
1531 Context.mergeDefinitionIntoModule(ND, M);
1532 else
1533 // We're not building a module; just make the definition visible.
1534 ND->setVisibleDespiteOwningModule();
1536 // If ND is a template declaration, make the template parameters
1537 // visible too. They're not (necessarily) within a mergeable DeclContext.
1538 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1539 for (auto *Param : *TD->getTemplateParameters())
1540 makeMergedDefinitionVisible(Param);
1543 /// Find the module in which the given declaration was defined.
1544 static Module *getDefiningModule(Sema &S, Decl *Entity) {
1545 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1546 // If this function was instantiated from a template, the defining module is
1547 // the module containing the pattern.
1548 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1549 Entity = Pattern;
1550 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1551 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1552 Entity = Pattern;
1553 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1554 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1555 Entity = Pattern;
1556 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1557 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1558 Entity = Pattern;
1561 // Walk up to the containing context. That might also have been instantiated
1562 // from a template.
1563 DeclContext *Context = Entity->getLexicalDeclContext();
1564 if (Context->isFileContext())
1565 return S.getOwningModule(Entity);
1566 return getDefiningModule(S, cast<Decl>(Context));
1569 llvm::DenseSet<Module*> &Sema::getLookupModules() {
1570 unsigned N = CodeSynthesisContexts.size();
1571 for (unsigned I = CodeSynthesisContextLookupModules.size();
1572 I != N; ++I) {
1573 Module *M = CodeSynthesisContexts[I].Entity ?
1574 getDefiningModule(*this, CodeSynthesisContexts[I].Entity) :
1575 nullptr;
1576 if (M && !LookupModulesCache.insert(M).second)
1577 M = nullptr;
1578 CodeSynthesisContextLookupModules.push_back(M);
1580 return LookupModulesCache;
1583 /// Determine if we could use all the declarations in the module.
1584 bool Sema::isUsableModule(const Module *M) {
1585 assert(M && "We shouldn't check nullness for module here");
1586 // Return quickly if we cached the result.
1587 if (UsableModuleUnitsCache.count(M))
1588 return true;
1590 // If M is the global module fragment of the current translation unit. So it
1591 // should be usable.
1592 // [module.global.frag]p1:
1593 // The global module fragment can be used to provide declarations that are
1594 // attached to the global module and usable within the module unit.
1595 if (M == TheGlobalModuleFragment || M == TheImplicitGlobalModuleFragment ||
1596 M == TheExportedImplicitGlobalModuleFragment ||
1597 // If M is the module we're parsing, it should be usable. This covers the
1598 // private module fragment. The private module fragment is usable only if
1599 // it is within the current module unit. And it must be the current
1600 // parsing module unit if it is within the current module unit according
1601 // to the grammar of the private module fragment. NOTE: This is covered by
1602 // the following condition. The intention of the check is to avoid string
1603 // comparison as much as possible.
1604 M == getCurrentModule() ||
1605 // The module unit which is in the same module with the current module
1606 // unit is usable.
1608 // FIXME: Here we judge if they are in the same module by comparing the
1609 // string. Is there any better solution?
1610 M->getPrimaryModuleInterfaceName() ==
1611 llvm::StringRef(getLangOpts().CurrentModule).split(':').first) {
1612 UsableModuleUnitsCache.insert(M);
1613 return true;
1616 return false;
1619 bool Sema::hasVisibleMergedDefinition(const NamedDecl *Def) {
1620 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1621 if (isModuleVisible(Merged))
1622 return true;
1623 return false;
1626 bool Sema::hasMergedDefinitionInCurrentModule(const NamedDecl *Def) {
1627 for (const Module *Merged : Context.getModulesWithMergedDefinition(Def))
1628 if (isUsableModule(Merged))
1629 return true;
1630 return false;
1633 template <typename ParmDecl>
1634 static bool
1635 hasAcceptableDefaultArgument(Sema &S, const ParmDecl *D,
1636 llvm::SmallVectorImpl<Module *> *Modules,
1637 Sema::AcceptableKind Kind) {
1638 if (!D->hasDefaultArgument())
1639 return false;
1641 llvm::SmallPtrSet<const ParmDecl *, 4> Visited;
1642 while (D && Visited.insert(D).second) {
1643 auto &DefaultArg = D->getDefaultArgStorage();
1644 if (!DefaultArg.isInherited() && S.isAcceptable(D, Kind))
1645 return true;
1647 if (!DefaultArg.isInherited() && Modules) {
1648 auto *NonConstD = const_cast<ParmDecl*>(D);
1649 Modules->push_back(S.getOwningModule(NonConstD));
1652 // If there was a previous default argument, maybe its parameter is
1653 // acceptable.
1654 D = DefaultArg.getInheritedFrom();
1656 return false;
1659 bool Sema::hasAcceptableDefaultArgument(
1660 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules,
1661 Sema::AcceptableKind Kind) {
1662 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1663 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1665 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1666 return ::hasAcceptableDefaultArgument(*this, P, Modules, Kind);
1668 return ::hasAcceptableDefaultArgument(
1669 *this, cast<TemplateTemplateParmDecl>(D), Modules, Kind);
1672 bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1673 llvm::SmallVectorImpl<Module *> *Modules) {
1674 return hasAcceptableDefaultArgument(D, Modules,
1675 Sema::AcceptableKind::Visible);
1678 bool Sema::hasReachableDefaultArgument(
1679 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1680 return hasAcceptableDefaultArgument(D, Modules,
1681 Sema::AcceptableKind::Reachable);
1684 template <typename Filter>
1685 static bool
1686 hasAcceptableDeclarationImpl(Sema &S, const NamedDecl *D,
1687 llvm::SmallVectorImpl<Module *> *Modules, Filter F,
1688 Sema::AcceptableKind Kind) {
1689 bool HasFilteredRedecls = false;
1691 for (auto *Redecl : D->redecls()) {
1692 auto *R = cast<NamedDecl>(Redecl);
1693 if (!F(R))
1694 continue;
1696 if (S.isAcceptable(R, Kind))
1697 return true;
1699 HasFilteredRedecls = true;
1701 if (Modules)
1702 Modules->push_back(R->getOwningModule());
1705 // Only return false if there is at least one redecl that is not filtered out.
1706 if (HasFilteredRedecls)
1707 return false;
1709 return true;
1712 static bool
1713 hasAcceptableExplicitSpecialization(Sema &S, const NamedDecl *D,
1714 llvm::SmallVectorImpl<Module *> *Modules,
1715 Sema::AcceptableKind Kind) {
1716 return hasAcceptableDeclarationImpl(
1717 S, D, Modules,
1718 [](const NamedDecl *D) {
1719 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1720 return RD->getTemplateSpecializationKind() ==
1721 TSK_ExplicitSpecialization;
1722 if (auto *FD = dyn_cast<FunctionDecl>(D))
1723 return FD->getTemplateSpecializationKind() ==
1724 TSK_ExplicitSpecialization;
1725 if (auto *VD = dyn_cast<VarDecl>(D))
1726 return VD->getTemplateSpecializationKind() ==
1727 TSK_ExplicitSpecialization;
1728 llvm_unreachable("unknown explicit specialization kind");
1730 Kind);
1733 bool Sema::hasVisibleExplicitSpecialization(
1734 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1735 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1736 Sema::AcceptableKind::Visible);
1739 bool Sema::hasReachableExplicitSpecialization(
1740 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1741 return ::hasAcceptableExplicitSpecialization(*this, D, Modules,
1742 Sema::AcceptableKind::Reachable);
1745 static bool
1746 hasAcceptableMemberSpecialization(Sema &S, const NamedDecl *D,
1747 llvm::SmallVectorImpl<Module *> *Modules,
1748 Sema::AcceptableKind Kind) {
1749 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&
1750 "not a member specialization");
1751 return hasAcceptableDeclarationImpl(
1752 S, D, Modules,
1753 [](const NamedDecl *D) {
1754 // If the specialization is declared at namespace scope, then it's a
1755 // member specialization declaration. If it's lexically inside the class
1756 // definition then it was instantiated.
1758 // FIXME: This is a hack. There should be a better way to determine
1759 // this.
1760 // FIXME: What about MS-style explicit specializations declared within a
1761 // class definition?
1762 return D->getLexicalDeclContext()->isFileContext();
1764 Kind);
1767 bool Sema::hasVisibleMemberSpecialization(
1768 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1769 return hasAcceptableMemberSpecialization(*this, D, Modules,
1770 Sema::AcceptableKind::Visible);
1773 bool Sema::hasReachableMemberSpecialization(
1774 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1775 return hasAcceptableMemberSpecialization(*this, D, Modules,
1776 Sema::AcceptableKind::Reachable);
1779 /// Determine whether a declaration is acceptable to name lookup.
1781 /// This routine determines whether the declaration D is acceptable in the
1782 /// current lookup context, taking into account the current template
1783 /// instantiation stack. During template instantiation, a declaration is
1784 /// acceptable if it is acceptable from a module containing any entity on the
1785 /// template instantiation path (by instantiating a template, you allow it to
1786 /// see the declarations that your module can see, including those later on in
1787 /// your module).
1788 bool LookupResult::isAcceptableSlow(Sema &SemaRef, NamedDecl *D,
1789 Sema::AcceptableKind Kind) {
1790 assert(!D->isUnconditionallyVisible() &&
1791 "should not call this: not in slow case");
1793 Module *DeclModule = SemaRef.getOwningModule(D);
1794 assert(DeclModule && "hidden decl has no owning module");
1796 // If the owning module is visible, the decl is acceptable.
1797 if (SemaRef.isModuleVisible(DeclModule,
1798 D->isInvisibleOutsideTheOwningModule()))
1799 return true;
1801 // Determine whether a decl context is a file context for the purpose of
1802 // visibility/reachability. This looks through some (export and linkage spec)
1803 // transparent contexts, but not others (enums).
1804 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1805 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1806 isa<ExportDecl>(DC);
1809 // If this declaration is not at namespace scope
1810 // then it is acceptable if its lexical parent has a acceptable definition.
1811 DeclContext *DC = D->getLexicalDeclContext();
1812 if (DC && !IsEffectivelyFileContext(DC)) {
1813 // For a parameter, check whether our current template declaration's
1814 // lexical context is acceptable, not whether there's some other acceptable
1815 // definition of it, because parameters aren't "within" the definition.
1817 // In C++ we need to check for a acceptable definition due to ODR merging,
1818 // and in C we must not because each declaration of a function gets its own
1819 // set of declarations for tags in prototype scope.
1820 bool AcceptableWithinParent;
1821 if (D->isTemplateParameter()) {
1822 bool SearchDefinitions = true;
1823 if (const auto *DCD = dyn_cast<Decl>(DC)) {
1824 if (const auto *TD = DCD->getDescribedTemplate()) {
1825 TemplateParameterList *TPL = TD->getTemplateParameters();
1826 auto Index = getDepthAndIndex(D).second;
1827 SearchDefinitions = Index >= TPL->size() || TPL->getParam(Index) != D;
1830 if (SearchDefinitions)
1831 AcceptableWithinParent =
1832 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1833 else
1834 AcceptableWithinParent =
1835 isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1836 } else if (isa<ParmVarDecl>(D) ||
1837 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1838 AcceptableWithinParent = isAcceptable(SemaRef, cast<NamedDecl>(DC), Kind);
1839 else if (D->isModulePrivate()) {
1840 // A module-private declaration is only acceptable if an enclosing lexical
1841 // parent was merged with another definition in the current module.
1842 AcceptableWithinParent = false;
1843 do {
1844 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1845 AcceptableWithinParent = true;
1846 break;
1848 DC = DC->getLexicalParent();
1849 } while (!IsEffectivelyFileContext(DC));
1850 } else {
1851 AcceptableWithinParent =
1852 SemaRef.hasAcceptableDefinition(cast<NamedDecl>(DC), Kind);
1855 if (AcceptableWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1856 Kind == Sema::AcceptableKind::Visible &&
1857 // FIXME: Do something better in this case.
1858 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1859 // Cache the fact that this declaration is implicitly visible because
1860 // its parent has a visible definition.
1861 D->setVisibleDespiteOwningModule();
1863 return AcceptableWithinParent;
1866 if (Kind == Sema::AcceptableKind::Visible)
1867 return false;
1869 assert(Kind == Sema::AcceptableKind::Reachable &&
1870 "Additional Sema::AcceptableKind?");
1871 return isReachableSlow(SemaRef, D);
1874 bool Sema::isModuleVisible(const Module *M, bool ModulePrivate) {
1875 // The module might be ordinarily visible. For a module-private query, that
1876 // means it is part of the current module.
1877 if (ModulePrivate && isUsableModule(M))
1878 return true;
1880 // For a query which is not module-private, that means it is in our visible
1881 // module set.
1882 if (!ModulePrivate && VisibleModules.isVisible(M))
1883 return true;
1885 // Otherwise, it might be visible by virtue of the query being within a
1886 // template instantiation or similar that is permitted to look inside M.
1888 // Find the extra places where we need to look.
1889 const auto &LookupModules = getLookupModules();
1890 if (LookupModules.empty())
1891 return false;
1893 // If our lookup set contains the module, it's visible.
1894 if (LookupModules.count(M))
1895 return true;
1897 // The global module fragments are visible to its corresponding module unit.
1898 // So the global module fragment should be visible if the its corresponding
1899 // module unit is visible.
1900 if (M->isGlobalModule() && LookupModules.count(M->getTopLevelModule()))
1901 return true;
1903 // For a module-private query, that's everywhere we get to look.
1904 if (ModulePrivate)
1905 return false;
1907 // Check whether M is transitively exported to an import of the lookup set.
1908 return llvm::any_of(LookupModules, [&](const Module *LookupM) {
1909 return LookupM->isModuleVisible(M);
1913 // FIXME: Return false directly if we don't have an interface dependency on the
1914 // translation unit containing D.
1915 bool LookupResult::isReachableSlow(Sema &SemaRef, NamedDecl *D) {
1916 assert(!isVisible(SemaRef, D) && "Shouldn't call the slow case.\n");
1918 Module *DeclModule = SemaRef.getOwningModule(D);
1919 assert(DeclModule && "hidden decl has no owning module");
1921 // Entities in header like modules are reachable only if they're visible.
1922 if (DeclModule->isHeaderLikeModule())
1923 return false;
1925 if (!D->isInAnotherModuleUnit())
1926 return true;
1928 // [module.reach]/p3:
1929 // A declaration D is reachable from a point P if:
1930 // ...
1931 // - D is not discarded ([module.global.frag]), appears in a translation unit
1932 // that is reachable from P, and does not appear within a private module
1933 // fragment.
1935 // A declaration that's discarded in the GMF should be module-private.
1936 if (D->isModulePrivate())
1937 return false;
1939 // [module.reach]/p1
1940 // A translation unit U is necessarily reachable from a point P if U is a
1941 // module interface unit on which the translation unit containing P has an
1942 // interface dependency, or the translation unit containing P imports U, in
1943 // either case prior to P ([module.import]).
1945 // [module.import]/p10
1946 // A translation unit has an interface dependency on a translation unit U if
1947 // it contains a declaration (possibly a module-declaration) that imports U
1948 // or if it has an interface dependency on a translation unit that has an
1949 // interface dependency on U.
1951 // So we could conclude the module unit U is necessarily reachable if:
1952 // (1) The module unit U is module interface unit.
1953 // (2) The current unit has an interface dependency on the module unit U.
1955 // Here we only check for the first condition. Since we couldn't see
1956 // DeclModule if it isn't (transitively) imported.
1957 if (DeclModule->getTopLevelModule()->isModuleInterfaceUnit())
1958 return true;
1960 // [module.reach]/p2
1961 // Additional translation units on
1962 // which the point within the program has an interface dependency may be
1963 // considered reachable, but it is unspecified which are and under what
1964 // circumstances.
1966 // The decision here is to treat all additional tranditional units as
1967 // unreachable.
1968 return false;
1971 bool Sema::isAcceptableSlow(const NamedDecl *D, Sema::AcceptableKind Kind) {
1972 return LookupResult::isAcceptable(*this, const_cast<NamedDecl *>(D), Kind);
1975 bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1976 // FIXME: If there are both visible and hidden declarations, we need to take
1977 // into account whether redeclaration is possible. Example:
1979 // Non-imported module:
1980 // int f(T); // #1
1981 // Some TU:
1982 // static int f(U); // #2, not a redeclaration of #1
1983 // int f(T); // #3, finds both, should link with #1 if T != U, but
1984 // // with #2 if T == U; neither should be ambiguous.
1985 for (auto *D : R) {
1986 if (isVisible(D))
1987 return true;
1988 assert(D->isExternallyDeclarable() &&
1989 "should not have hidden, non-externally-declarable result here");
1992 // This function is called once "New" is essentially complete, but before a
1993 // previous declaration is attached. We can't query the linkage of "New" in
1994 // general, because attaching the previous declaration can change the
1995 // linkage of New to match the previous declaration.
1997 // However, because we've just determined that there is no *visible* prior
1998 // declaration, we can compute the linkage here. There are two possibilities:
2000 // * This is not a redeclaration; it's safe to compute the linkage now.
2002 // * This is a redeclaration of a prior declaration that is externally
2003 // redeclarable. In that case, the linkage of the declaration is not
2004 // changed by attaching the prior declaration, because both are externally
2005 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
2007 // FIXME: This is subtle and fragile.
2008 return New->isExternallyDeclarable();
2011 /// Retrieve the visible declaration corresponding to D, if any.
2013 /// This routine determines whether the declaration D is visible in the current
2014 /// module, with the current imports. If not, it checks whether any
2015 /// redeclaration of D is visible, and if so, returns that declaration.
2017 /// \returns D, or a visible previous declaration of D, whichever is more recent
2018 /// and visible. If no declaration of D is visible, returns null.
2019 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D,
2020 unsigned IDNS) {
2021 assert(!LookupResult::isAvailableForLookup(SemaRef, D) && "not in slow case");
2023 for (auto *RD : D->redecls()) {
2024 // Don't bother with extra checks if we already know this one isn't visible.
2025 if (RD == D)
2026 continue;
2028 auto ND = cast<NamedDecl>(RD);
2029 // FIXME: This is wrong in the case where the previous declaration is not
2030 // visible in the same scope as D. This needs to be done much more
2031 // carefully.
2032 if (ND->isInIdentifierNamespace(IDNS) &&
2033 LookupResult::isAvailableForLookup(SemaRef, ND))
2034 return ND;
2037 return nullptr;
2040 bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
2041 llvm::SmallVectorImpl<Module *> *Modules) {
2042 assert(!isVisible(D) && "not in slow case");
2043 return hasAcceptableDeclarationImpl(
2044 *this, D, Modules, [](const NamedDecl *) { return true; },
2045 Sema::AcceptableKind::Visible);
2048 bool Sema::hasReachableDeclarationSlow(
2049 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
2050 assert(!isReachable(D) && "not in slow case");
2051 return hasAcceptableDeclarationImpl(
2052 *this, D, Modules, [](const NamedDecl *) { return true; },
2053 Sema::AcceptableKind::Reachable);
2056 NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
2057 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
2058 // Namespaces are a bit of a special case: we expect there to be a lot of
2059 // redeclarations of some namespaces, all declarations of a namespace are
2060 // essentially interchangeable, all declarations are found by name lookup
2061 // if any is, and namespaces are never looked up during template
2062 // instantiation. So we benefit from caching the check in this case, and
2063 // it is correct to do so.
2064 auto *Key = ND->getCanonicalDecl();
2065 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
2066 return Acceptable;
2067 auto *Acceptable = isVisible(getSema(), Key)
2068 ? Key
2069 : findAcceptableDecl(getSema(), Key, IDNS);
2070 if (Acceptable)
2071 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
2072 return Acceptable;
2075 return findAcceptableDecl(getSema(), D, IDNS);
2078 bool LookupResult::isVisible(Sema &SemaRef, NamedDecl *D) {
2079 // If this declaration is already visible, return it directly.
2080 if (D->isUnconditionallyVisible())
2081 return true;
2083 // During template instantiation, we can refer to hidden declarations, if
2084 // they were visible in any module along the path of instantiation.
2085 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Visible);
2088 bool LookupResult::isReachable(Sema &SemaRef, NamedDecl *D) {
2089 if (D->isUnconditionallyVisible())
2090 return true;
2092 return isAcceptableSlow(SemaRef, D, Sema::AcceptableKind::Reachable);
2095 bool LookupResult::isAvailableForLookup(Sema &SemaRef, NamedDecl *ND) {
2096 // We should check the visibility at the callsite already.
2097 if (isVisible(SemaRef, ND))
2098 return true;
2100 // Deduction guide lives in namespace scope generally, but it is just a
2101 // hint to the compilers. What we actually lookup for is the generated member
2102 // of the corresponding template. So it is sufficient to check the
2103 // reachability of the template decl.
2104 if (auto *DeductionGuide = ND->getDeclName().getCXXDeductionGuideTemplate())
2105 return SemaRef.hasReachableDefinition(DeductionGuide);
2107 // FIXME: The lookup for allocation function is a standalone process.
2108 // (We can find the logics in Sema::FindAllocationFunctions)
2110 // Such structure makes it a problem when we instantiate a template
2111 // declaration using placement allocation function if the placement
2112 // allocation function is invisible.
2113 // (See https://github.com/llvm/llvm-project/issues/59601)
2115 // Here we workaround it by making the placement allocation functions
2116 // always acceptable. The downside is that we can't diagnose the direct
2117 // use of the invisible placement allocation functions. (Although such uses
2118 // should be rare).
2119 if (auto *FD = dyn_cast<FunctionDecl>(ND);
2120 FD && FD->isReservedGlobalPlacementOperator())
2121 return true;
2123 auto *DC = ND->getDeclContext();
2124 // If ND is not visible and it is at namespace scope, it shouldn't be found
2125 // by name lookup.
2126 if (DC->isFileContext())
2127 return false;
2129 // [module.interface]p7
2130 // Class and enumeration member names can be found by name lookup in any
2131 // context in which a definition of the type is reachable.
2133 // FIXME: The current implementation didn't consider about scope. For example,
2134 // ```
2135 // // m.cppm
2136 // export module m;
2137 // enum E1 { e1 };
2138 // // Use.cpp
2139 // import m;
2140 // void test() {
2141 // auto a = E1::e1; // Error as expected.
2142 // auto b = e1; // Should be error. namespace-scope name e1 is not visible
2143 // }
2144 // ```
2145 // For the above example, the current implementation would emit error for `a`
2146 // correctly. However, the implementation wouldn't diagnose about `b` now.
2147 // Since we only check the reachability for the parent only.
2148 // See clang/test/CXX/module/module.interface/p7.cpp for example.
2149 if (auto *TD = dyn_cast<TagDecl>(DC))
2150 return SemaRef.hasReachableDefinition(TD);
2152 return false;
2155 /// Perform unqualified name lookup starting from a given
2156 /// scope.
2158 /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
2159 /// used to find names within the current scope. For example, 'x' in
2160 /// @code
2161 /// int x;
2162 /// int f() {
2163 /// return x; // unqualified name look finds 'x' in the global scope
2164 /// }
2165 /// @endcode
2167 /// Different lookup criteria can find different names. For example, a
2168 /// particular scope can have both a struct and a function of the same
2169 /// name, and each can be found by certain lookup criteria. For more
2170 /// information about lookup criteria, see the documentation for the
2171 /// class LookupCriteria.
2173 /// @param S The scope from which unqualified name lookup will
2174 /// begin. If the lookup criteria permits, name lookup may also search
2175 /// in the parent scopes.
2177 /// @param [in,out] R Specifies the lookup to perform (e.g., the name to
2178 /// look up and the lookup kind), and is updated with the results of lookup
2179 /// including zero or more declarations and possibly additional information
2180 /// used to diagnose ambiguities.
2182 /// @returns \c true if lookup succeeded and false otherwise.
2183 bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation,
2184 bool ForceNoCPlusPlus) {
2185 DeclarationName Name = R.getLookupName();
2186 if (!Name) return false;
2188 LookupNameKind NameKind = R.getLookupKind();
2190 if (!getLangOpts().CPlusPlus || ForceNoCPlusPlus) {
2191 // Unqualified name lookup in C/Objective-C is purely lexical, so
2192 // search in the declarations attached to the name.
2193 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
2194 // Find the nearest non-transparent declaration scope.
2195 while (!(S->getFlags() & Scope::DeclScope) ||
2196 (S->getEntity() && S->getEntity()->isTransparentContext()))
2197 S = S->getParent();
2200 // When performing a scope lookup, we want to find local extern decls.
2201 FindLocalExternScope FindLocals(R);
2203 // Scan up the scope chain looking for a decl that matches this
2204 // identifier that is in the appropriate namespace. This search
2205 // should not take long, as shadowing of names is uncommon, and
2206 // deep shadowing is extremely uncommon.
2207 bool LeftStartingScope = false;
2209 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2210 IEnd = IdResolver.end();
2211 I != IEnd; ++I)
2212 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
2213 if (NameKind == LookupRedeclarationWithLinkage) {
2214 // Determine whether this (or a previous) declaration is
2215 // out-of-scope.
2216 if (!LeftStartingScope && !S->isDeclScope(*I))
2217 LeftStartingScope = true;
2219 // If we found something outside of our starting scope that
2220 // does not have linkage, skip it.
2221 if (LeftStartingScope && !((*I)->hasLinkage())) {
2222 R.setShadowed();
2223 continue;
2226 else if (NameKind == LookupObjCImplicitSelfParam &&
2227 !isa<ImplicitParamDecl>(*I))
2228 continue;
2230 R.addDecl(D);
2232 // Check whether there are any other declarations with the same name
2233 // and in the same scope.
2234 if (I != IEnd) {
2235 // Find the scope in which this declaration was declared (if it
2236 // actually exists in a Scope).
2237 while (S && !S->isDeclScope(D))
2238 S = S->getParent();
2240 // If the scope containing the declaration is the translation unit,
2241 // then we'll need to perform our checks based on the matching
2242 // DeclContexts rather than matching scopes.
2243 if (S && isNamespaceOrTranslationUnitScope(S))
2244 S = nullptr;
2246 // Compute the DeclContext, if we need it.
2247 DeclContext *DC = nullptr;
2248 if (!S)
2249 DC = (*I)->getDeclContext()->getRedeclContext();
2251 IdentifierResolver::iterator LastI = I;
2252 for (++LastI; LastI != IEnd; ++LastI) {
2253 if (S) {
2254 // Match based on scope.
2255 if (!S->isDeclScope(*LastI))
2256 break;
2257 } else {
2258 // Match based on DeclContext.
2259 DeclContext *LastDC
2260 = (*LastI)->getDeclContext()->getRedeclContext();
2261 if (!LastDC->Equals(DC))
2262 break;
2265 // If the declaration is in the right namespace and visible, add it.
2266 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
2267 R.addDecl(LastD);
2270 R.resolveKind();
2273 return true;
2275 } else {
2276 // Perform C++ unqualified name lookup.
2277 if (CppLookupName(R, S))
2278 return true;
2281 // If we didn't find a use of this identifier, and if the identifier
2282 // corresponds to a compiler builtin, create the decl object for the builtin
2283 // now, injecting it into translation unit scope, and return it.
2284 if (AllowBuiltinCreation && LookupBuiltin(R))
2285 return true;
2287 // If we didn't find a use of this identifier, the ExternalSource
2288 // may be able to handle the situation.
2289 // Note: some lookup failures are expected!
2290 // See e.g. R.isForRedeclaration().
2291 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
2294 /// Perform qualified name lookup in the namespaces nominated by
2295 /// using directives by the given context.
2297 /// C++98 [namespace.qual]p2:
2298 /// Given X::m (where X is a user-declared namespace), or given \::m
2299 /// (where X is the global namespace), let S be the set of all
2300 /// declarations of m in X and in the transitive closure of all
2301 /// namespaces nominated by using-directives in X and its used
2302 /// namespaces, except that using-directives are ignored in any
2303 /// namespace, including X, directly containing one or more
2304 /// declarations of m. No namespace is searched more than once in
2305 /// the lookup of a name. If S is the empty set, the program is
2306 /// ill-formed. Otherwise, if S has exactly one member, or if the
2307 /// context of the reference is a using-declaration
2308 /// (namespace.udecl), S is the required set of declarations of
2309 /// m. Otherwise if the use of m is not one that allows a unique
2310 /// declaration to be chosen from S, the program is ill-formed.
2312 /// C++98 [namespace.qual]p5:
2313 /// During the lookup of a qualified namespace member name, if the
2314 /// lookup finds more than one declaration of the member, and if one
2315 /// declaration introduces a class name or enumeration name and the
2316 /// other declarations either introduce the same object, the same
2317 /// enumerator or a set of functions, the non-type name hides the
2318 /// class or enumeration name if and only if the declarations are
2319 /// from the same namespace; otherwise (the declarations are from
2320 /// different namespaces), the program is ill-formed.
2321 static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
2322 DeclContext *StartDC) {
2323 assert(StartDC->isFileContext() && "start context is not a file context");
2325 // We have not yet looked into these namespaces, much less added
2326 // their "using-children" to the queue.
2327 SmallVector<NamespaceDecl*, 8> Queue;
2329 // We have at least added all these contexts to the queue.
2330 llvm::SmallPtrSet<DeclContext*, 8> Visited;
2331 Visited.insert(StartDC);
2333 // We have already looked into the initial namespace; seed the queue
2334 // with its using-children.
2335 for (auto *I : StartDC->using_directives()) {
2336 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
2337 if (S.isVisible(I) && Visited.insert(ND).second)
2338 Queue.push_back(ND);
2341 // The easiest way to implement the restriction in [namespace.qual]p5
2342 // is to check whether any of the individual results found a tag
2343 // and, if so, to declare an ambiguity if the final result is not
2344 // a tag.
2345 bool FoundTag = false;
2346 bool FoundNonTag = false;
2348 LookupResult LocalR(LookupResult::Temporary, R);
2350 bool Found = false;
2351 while (!Queue.empty()) {
2352 NamespaceDecl *ND = Queue.pop_back_val();
2354 // We go through some convolutions here to avoid copying results
2355 // between LookupResults.
2356 bool UseLocal = !R.empty();
2357 LookupResult &DirectR = UseLocal ? LocalR : R;
2358 bool FoundDirect = LookupDirect(S, DirectR, ND);
2360 if (FoundDirect) {
2361 // First do any local hiding.
2362 DirectR.resolveKind();
2364 // If the local result is a tag, remember that.
2365 if (DirectR.isSingleTagDecl())
2366 FoundTag = true;
2367 else
2368 FoundNonTag = true;
2370 // Append the local results to the total results if necessary.
2371 if (UseLocal) {
2372 R.addAllDecls(LocalR);
2373 LocalR.clear();
2377 // If we find names in this namespace, ignore its using directives.
2378 if (FoundDirect) {
2379 Found = true;
2380 continue;
2383 for (auto *I : ND->using_directives()) {
2384 NamespaceDecl *Nom = I->getNominatedNamespace();
2385 if (S.isVisible(I) && Visited.insert(Nom).second)
2386 Queue.push_back(Nom);
2390 if (Found) {
2391 if (FoundTag && FoundNonTag)
2392 R.setAmbiguousQualifiedTagHiding();
2393 else
2394 R.resolveKind();
2397 return Found;
2400 /// Perform qualified name lookup into a given context.
2402 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2403 /// names when the context of those names is explicit specified, e.g.,
2404 /// "std::vector" or "x->member", or as part of unqualified name lookup.
2406 /// Different lookup criteria can find different names. For example, a
2407 /// particular scope can have both a struct and a function of the same
2408 /// name, and each can be found by certain lookup criteria. For more
2409 /// information about lookup criteria, see the documentation for the
2410 /// class LookupCriteria.
2412 /// \param R captures both the lookup criteria and any lookup results found.
2414 /// \param LookupCtx The context in which qualified name lookup will
2415 /// search. If the lookup criteria permits, name lookup may also search
2416 /// in the parent contexts or (for C++ classes) base classes.
2418 /// \param InUnqualifiedLookup true if this is qualified name lookup that
2419 /// occurs as part of unqualified name lookup.
2421 /// \returns true if lookup succeeded, false if it failed.
2422 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2423 bool InUnqualifiedLookup) {
2424 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2426 if (!R.getLookupName())
2427 return false;
2429 // Make sure that the declaration context is complete.
2430 assert((!isa<TagDecl>(LookupCtx) ||
2431 LookupCtx->isDependentContext() ||
2432 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2433 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2434 "Declaration context must already be complete!");
2436 struct QualifiedLookupInScope {
2437 bool oldVal;
2438 DeclContext *Context;
2439 // Set flag in DeclContext informing debugger that we're looking for qualified name
2440 QualifiedLookupInScope(DeclContext *ctx)
2441 : oldVal(ctx->shouldUseQualifiedLookup()), Context(ctx) {
2442 ctx->setUseQualifiedLookup();
2444 ~QualifiedLookupInScope() {
2445 Context->setUseQualifiedLookup(oldVal);
2447 } QL(LookupCtx);
2449 if (LookupDirect(*this, R, LookupCtx)) {
2450 R.resolveKind();
2451 if (isa<CXXRecordDecl>(LookupCtx))
2452 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2453 return true;
2456 // Don't descend into implied contexts for redeclarations.
2457 // C++98 [namespace.qual]p6:
2458 // In a declaration for a namespace member in which the
2459 // declarator-id is a qualified-id, given that the qualified-id
2460 // for the namespace member has the form
2461 // nested-name-specifier unqualified-id
2462 // the unqualified-id shall name a member of the namespace
2463 // designated by the nested-name-specifier.
2464 // See also [class.mfct]p5 and [class.static.data]p2.
2465 if (R.isForRedeclaration())
2466 return false;
2468 // If this is a namespace, look it up in the implied namespaces.
2469 if (LookupCtx->isFileContext())
2470 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2472 // If this isn't a C++ class, we aren't allowed to look into base
2473 // classes, we're done.
2474 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2475 if (!LookupRec || !LookupRec->getDefinition())
2476 return false;
2478 // We're done for lookups that can never succeed for C++ classes.
2479 if (R.getLookupKind() == LookupOperatorName ||
2480 R.getLookupKind() == LookupNamespaceName ||
2481 R.getLookupKind() == LookupObjCProtocolName ||
2482 R.getLookupKind() == LookupLabel)
2483 return false;
2485 // If we're performing qualified name lookup into a dependent class,
2486 // then we are actually looking into a current instantiation. If we have any
2487 // dependent base classes, then we either have to delay lookup until
2488 // template instantiation time (at which point all bases will be available)
2489 // or we have to fail.
2490 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2491 LookupRec->hasAnyDependentBases()) {
2492 R.setNotFoundInCurrentInstantiation();
2493 return false;
2496 // Perform lookup into our base classes.
2498 DeclarationName Name = R.getLookupName();
2499 unsigned IDNS = R.getIdentifierNamespace();
2501 // Look for this member in our base classes.
2502 auto BaseCallback = [Name, IDNS](const CXXBaseSpecifier *Specifier,
2503 CXXBasePath &Path) -> bool {
2504 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
2505 // Drop leading non-matching lookup results from the declaration list so
2506 // we don't need to consider them again below.
2507 for (Path.Decls = BaseRecord->lookup(Name).begin();
2508 Path.Decls != Path.Decls.end(); ++Path.Decls) {
2509 if ((*Path.Decls)->isInIdentifierNamespace(IDNS))
2510 return true;
2512 return false;
2515 CXXBasePaths Paths;
2516 Paths.setOrigin(LookupRec);
2517 if (!LookupRec->lookupInBases(BaseCallback, Paths))
2518 return false;
2520 R.setNamingClass(LookupRec);
2522 // C++ [class.member.lookup]p2:
2523 // [...] If the resulting set of declarations are not all from
2524 // sub-objects of the same type, or the set has a nonstatic member
2525 // and includes members from distinct sub-objects, there is an
2526 // ambiguity and the program is ill-formed. Otherwise that set is
2527 // the result of the lookup.
2528 QualType SubobjectType;
2529 int SubobjectNumber = 0;
2530 AccessSpecifier SubobjectAccess = AS_none;
2532 // Check whether the given lookup result contains only static members.
2533 auto HasOnlyStaticMembers = [&](DeclContext::lookup_iterator Result) {
2534 for (DeclContext::lookup_iterator I = Result, E = I.end(); I != E; ++I)
2535 if ((*I)->isInIdentifierNamespace(IDNS) && (*I)->isCXXInstanceMember())
2536 return false;
2537 return true;
2540 bool TemplateNameLookup = R.isTemplateNameLookup();
2542 // Determine whether two sets of members contain the same members, as
2543 // required by C++ [class.member.lookup]p6.
2544 auto HasSameDeclarations = [&](DeclContext::lookup_iterator A,
2545 DeclContext::lookup_iterator B) {
2546 using Iterator = DeclContextLookupResult::iterator;
2547 using Result = const void *;
2549 auto Next = [&](Iterator &It, Iterator End) -> Result {
2550 while (It != End) {
2551 NamedDecl *ND = *It++;
2552 if (!ND->isInIdentifierNamespace(IDNS))
2553 continue;
2555 // C++ [temp.local]p3:
2556 // A lookup that finds an injected-class-name (10.2) can result in
2557 // an ambiguity in certain cases (for example, if it is found in
2558 // more than one base class). If all of the injected-class-names
2559 // that are found refer to specializations of the same class
2560 // template, and if the name is used as a template-name, the
2561 // reference refers to the class template itself and not a
2562 // specialization thereof, and is not ambiguous.
2563 if (TemplateNameLookup)
2564 if (auto *TD = getAsTemplateNameDecl(ND))
2565 ND = TD;
2567 // C++ [class.member.lookup]p3:
2568 // type declarations (including injected-class-names) are replaced by
2569 // the types they designate
2570 if (const TypeDecl *TD = dyn_cast<TypeDecl>(ND->getUnderlyingDecl())) {
2571 QualType T = Context.getTypeDeclType(TD);
2572 return T.getCanonicalType().getAsOpaquePtr();
2575 return ND->getUnderlyingDecl()->getCanonicalDecl();
2577 return nullptr;
2580 // We'll often find the declarations are in the same order. Handle this
2581 // case (and the special case of only one declaration) efficiently.
2582 Iterator AIt = A, BIt = B, AEnd, BEnd;
2583 while (true) {
2584 Result AResult = Next(AIt, AEnd);
2585 Result BResult = Next(BIt, BEnd);
2586 if (!AResult && !BResult)
2587 return true;
2588 if (!AResult || !BResult)
2589 return false;
2590 if (AResult != BResult) {
2591 // Found a mismatch; carefully check both lists, accounting for the
2592 // possibility of declarations appearing more than once.
2593 llvm::SmallDenseMap<Result, bool, 32> AResults;
2594 for (; AResult; AResult = Next(AIt, AEnd))
2595 AResults.insert({AResult, /*FoundInB*/false});
2596 unsigned Found = 0;
2597 for (; BResult; BResult = Next(BIt, BEnd)) {
2598 auto It = AResults.find(BResult);
2599 if (It == AResults.end())
2600 return false;
2601 if (!It->second) {
2602 It->second = true;
2603 ++Found;
2606 return AResults.size() == Found;
2611 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2612 Path != PathEnd; ++Path) {
2613 const CXXBasePathElement &PathElement = Path->back();
2615 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2616 // across all paths.
2617 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2619 // Determine whether we're looking at a distinct sub-object or not.
2620 if (SubobjectType.isNull()) {
2621 // This is the first subobject we've looked at. Record its type.
2622 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2623 SubobjectNumber = PathElement.SubobjectNumber;
2624 continue;
2627 if (SubobjectType !=
2628 Context.getCanonicalType(PathElement.Base->getType())) {
2629 // We found members of the given name in two subobjects of
2630 // different types. If the declaration sets aren't the same, this
2631 // lookup is ambiguous.
2633 // FIXME: The language rule says that this applies irrespective of
2634 // whether the sets contain only static members.
2635 if (HasOnlyStaticMembers(Path->Decls) &&
2636 HasSameDeclarations(Paths.begin()->Decls, Path->Decls))
2637 continue;
2639 R.setAmbiguousBaseSubobjectTypes(Paths);
2640 return true;
2643 // FIXME: This language rule no longer exists. Checking for ambiguous base
2644 // subobjects should be done as part of formation of a class member access
2645 // expression (when converting the object parameter to the member's type).
2646 if (SubobjectNumber != PathElement.SubobjectNumber) {
2647 // We have a different subobject of the same type.
2649 // C++ [class.member.lookup]p5:
2650 // A static member, a nested type or an enumerator defined in
2651 // a base class T can unambiguously be found even if an object
2652 // has more than one base class subobject of type T.
2653 if (HasOnlyStaticMembers(Path->Decls))
2654 continue;
2656 // We have found a nonstatic member name in multiple, distinct
2657 // subobjects. Name lookup is ambiguous.
2658 R.setAmbiguousBaseSubobjects(Paths);
2659 return true;
2663 // Lookup in a base class succeeded; return these results.
2665 for (DeclContext::lookup_iterator I = Paths.front().Decls, E = I.end();
2666 I != E; ++I) {
2667 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2668 (*I)->getAccess());
2669 if (NamedDecl *ND = R.getAcceptableDecl(*I))
2670 R.addDecl(ND, AS);
2672 R.resolveKind();
2673 return true;
2676 /// Performs qualified name lookup or special type of lookup for
2677 /// "__super::" scope specifier.
2679 /// This routine is a convenience overload meant to be called from contexts
2680 /// that need to perform a qualified name lookup with an optional C++ scope
2681 /// specifier that might require special kind of lookup.
2683 /// \param R captures both the lookup criteria and any lookup results found.
2685 /// \param LookupCtx The context in which qualified name lookup will
2686 /// search.
2688 /// \param SS An optional C++ scope-specifier.
2690 /// \returns true if lookup succeeded, false if it failed.
2691 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2692 CXXScopeSpec &SS) {
2693 auto *NNS = SS.getScopeRep();
2694 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2695 return LookupInSuper(R, NNS->getAsRecordDecl());
2696 else
2698 return LookupQualifiedName(R, LookupCtx);
2701 /// Performs name lookup for a name that was parsed in the
2702 /// source code, and may contain a C++ scope specifier.
2704 /// This routine is a convenience routine meant to be called from
2705 /// contexts that receive a name and an optional C++ scope specifier
2706 /// (e.g., "N::M::x"). It will then perform either qualified or
2707 /// unqualified name lookup (with LookupQualifiedName or LookupName,
2708 /// respectively) on the given name and return those results. It will
2709 /// perform a special type of lookup for "__super::" scope specifier.
2711 /// @param S The scope from which unqualified name lookup will
2712 /// begin.
2714 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2716 /// @param EnteringContext Indicates whether we are going to enter the
2717 /// context of the scope-specifier SS (if present).
2719 /// @returns True if any decls were found (but possibly ambiguous)
2720 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2721 bool AllowBuiltinCreation, bool EnteringContext) {
2722 if (SS && SS->isInvalid()) {
2723 // When the scope specifier is invalid, don't even look for
2724 // anything.
2725 return false;
2728 if (SS && SS->isSet()) {
2729 NestedNameSpecifier *NNS = SS->getScopeRep();
2730 if (NNS->getKind() == NestedNameSpecifier::Super)
2731 return LookupInSuper(R, NNS->getAsRecordDecl());
2733 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2734 // We have resolved the scope specifier to a particular declaration
2735 // contex, and will perform name lookup in that context.
2736 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2737 return false;
2739 R.setContextRange(SS->getRange());
2740 return LookupQualifiedName(R, DC);
2743 // We could not resolve the scope specified to a specific declaration
2744 // context, which means that SS refers to an unknown specialization.
2745 // Name lookup can't find anything in this case.
2746 R.setNotFoundInCurrentInstantiation();
2747 R.setContextRange(SS->getRange());
2748 return false;
2751 // Perform unqualified name lookup starting in the given scope.
2752 return LookupName(R, S, AllowBuiltinCreation);
2755 /// Perform qualified name lookup into all base classes of the given
2756 /// class.
2758 /// \param R captures both the lookup criteria and any lookup results found.
2760 /// \param Class The context in which qualified name lookup will
2761 /// search. Name lookup will search in all base classes merging the results.
2763 /// @returns True if any decls were found (but possibly ambiguous)
2764 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2765 // The access-control rules we use here are essentially the rules for
2766 // doing a lookup in Class that just magically skipped the direct
2767 // members of Class itself. That is, the naming class is Class, and the
2768 // access includes the access of the base.
2769 for (const auto &BaseSpec : Class->bases()) {
2770 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2771 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2772 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2773 Result.setBaseObjectType(Context.getRecordType(Class));
2774 LookupQualifiedName(Result, RD);
2776 // Copy the lookup results into the target, merging the base's access into
2777 // the path access.
2778 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2779 R.addDecl(I.getDecl(),
2780 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2781 I.getAccess()));
2784 Result.suppressDiagnostics();
2787 R.resolveKind();
2788 R.setNamingClass(Class);
2790 return !R.empty();
2793 /// Produce a diagnostic describing the ambiguity that resulted
2794 /// from name lookup.
2796 /// \param Result The result of the ambiguous lookup to be diagnosed.
2797 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2798 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2800 DeclarationName Name = Result.getLookupName();
2801 SourceLocation NameLoc = Result.getNameLoc();
2802 SourceRange LookupRange = Result.getContextRange();
2804 switch (Result.getAmbiguityKind()) {
2805 case LookupResult::AmbiguousBaseSubobjects: {
2806 CXXBasePaths *Paths = Result.getBasePaths();
2807 QualType SubobjectType = Paths->front().back().Base->getType();
2808 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2809 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2810 << LookupRange;
2812 DeclContext::lookup_iterator Found = Paths->front().Decls;
2813 while (isa<CXXMethodDecl>(*Found) &&
2814 cast<CXXMethodDecl>(*Found)->isStatic())
2815 ++Found;
2817 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2818 break;
2821 case LookupResult::AmbiguousBaseSubobjectTypes: {
2822 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2823 << Name << LookupRange;
2825 CXXBasePaths *Paths = Result.getBasePaths();
2826 std::set<const NamedDecl *> DeclsPrinted;
2827 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2828 PathEnd = Paths->end();
2829 Path != PathEnd; ++Path) {
2830 const NamedDecl *D = *Path->Decls;
2831 if (!D->isInIdentifierNamespace(Result.getIdentifierNamespace()))
2832 continue;
2833 if (DeclsPrinted.insert(D).second) {
2834 if (const auto *TD = dyn_cast<TypedefNameDecl>(D->getUnderlyingDecl()))
2835 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2836 << TD->getUnderlyingType();
2837 else if (const auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
2838 Diag(D->getLocation(), diag::note_ambiguous_member_type_found)
2839 << Context.getTypeDeclType(TD);
2840 else
2841 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2844 break;
2847 case LookupResult::AmbiguousTagHiding: {
2848 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2850 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2852 for (auto *D : Result)
2853 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2854 TagDecls.insert(TD);
2855 Diag(TD->getLocation(), diag::note_hidden_tag);
2858 for (auto *D : Result)
2859 if (!isa<TagDecl>(D))
2860 Diag(D->getLocation(), diag::note_hiding_object);
2862 // For recovery purposes, go ahead and implement the hiding.
2863 LookupResult::Filter F = Result.makeFilter();
2864 while (F.hasNext()) {
2865 if (TagDecls.count(F.next()))
2866 F.erase();
2868 F.done();
2869 break;
2872 case LookupResult::AmbiguousReferenceToPlaceholderVariable: {
2873 Diag(NameLoc, diag::err_using_placeholder_variable) << Name << LookupRange;
2874 DeclContext *DC = nullptr;
2875 for (auto *D : Result) {
2876 Diag(D->getLocation(), diag::note_reference_placeholder) << D;
2877 if (DC != nullptr && DC != D->getDeclContext())
2878 break;
2879 DC = D->getDeclContext();
2881 break;
2884 case LookupResult::AmbiguousReference: {
2885 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2887 for (auto *D : Result)
2888 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2889 break;
2894 namespace {
2895 struct AssociatedLookup {
2896 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2897 Sema::AssociatedNamespaceSet &Namespaces,
2898 Sema::AssociatedClassSet &Classes)
2899 : S(S), Namespaces(Namespaces), Classes(Classes),
2900 InstantiationLoc(InstantiationLoc) {
2903 bool addClassTransitive(CXXRecordDecl *RD) {
2904 Classes.insert(RD);
2905 return ClassesTransitive.insert(RD);
2908 Sema &S;
2909 Sema::AssociatedNamespaceSet &Namespaces;
2910 Sema::AssociatedClassSet &Classes;
2911 SourceLocation InstantiationLoc;
2913 private:
2914 Sema::AssociatedClassSet ClassesTransitive;
2916 } // end anonymous namespace
2918 static void
2919 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2921 // Given the declaration context \param Ctx of a class, class template or
2922 // enumeration, add the associated namespaces to \param Namespaces as described
2923 // in [basic.lookup.argdep]p2.
2924 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2925 DeclContext *Ctx) {
2926 // The exact wording has been changed in C++14 as a result of
2927 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2928 // to all language versions since it is possible to return a local type
2929 // from a lambda in C++11.
2931 // C++14 [basic.lookup.argdep]p2:
2932 // If T is a class type [...]. Its associated namespaces are the innermost
2933 // enclosing namespaces of its associated classes. [...]
2935 // If T is an enumeration type, its associated namespace is the innermost
2936 // enclosing namespace of its declaration. [...]
2938 // We additionally skip inline namespaces. The innermost non-inline namespace
2939 // contains all names of all its nested inline namespaces anyway, so we can
2940 // replace the entire inline namespace tree with its root.
2941 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2942 Ctx = Ctx->getParent();
2944 Namespaces.insert(Ctx->getPrimaryContext());
2947 // Add the associated classes and namespaces for argument-dependent
2948 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2949 static void
2950 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2951 const TemplateArgument &Arg) {
2952 // C++ [basic.lookup.argdep]p2, last bullet:
2953 // -- [...] ;
2954 switch (Arg.getKind()) {
2955 case TemplateArgument::Null:
2956 break;
2958 case TemplateArgument::Type:
2959 // [...] the namespaces and classes associated with the types of the
2960 // template arguments provided for template type parameters (excluding
2961 // template template parameters)
2962 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2963 break;
2965 case TemplateArgument::Template:
2966 case TemplateArgument::TemplateExpansion: {
2967 // [...] the namespaces in which any template template arguments are
2968 // defined; and the classes in which any member templates used as
2969 // template template arguments are defined.
2970 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2971 if (ClassTemplateDecl *ClassTemplate
2972 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2973 DeclContext *Ctx = ClassTemplate->getDeclContext();
2974 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2975 Result.Classes.insert(EnclosingClass);
2976 // Add the associated namespace for this class.
2977 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2979 break;
2982 case TemplateArgument::Declaration:
2983 case TemplateArgument::Integral:
2984 case TemplateArgument::Expression:
2985 case TemplateArgument::NullPtr:
2986 // [Note: non-type template arguments do not contribute to the set of
2987 // associated namespaces. ]
2988 break;
2990 case TemplateArgument::Pack:
2991 for (const auto &P : Arg.pack_elements())
2992 addAssociatedClassesAndNamespaces(Result, P);
2993 break;
2997 // Add the associated classes and namespaces for argument-dependent lookup
2998 // with an argument of class type (C++ [basic.lookup.argdep]p2).
2999 static void
3000 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
3001 CXXRecordDecl *Class) {
3003 // Just silently ignore anything whose name is __va_list_tag.
3004 if (Class->getDeclName() == Result.S.VAListTagName)
3005 return;
3007 // C++ [basic.lookup.argdep]p2:
3008 // [...]
3009 // -- If T is a class type (including unions), its associated
3010 // classes are: the class itself; the class of which it is a
3011 // member, if any; and its direct and indirect base classes.
3012 // Its associated namespaces are the innermost enclosing
3013 // namespaces of its associated classes.
3015 // Add the class of which it is a member, if any.
3016 DeclContext *Ctx = Class->getDeclContext();
3017 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3018 Result.Classes.insert(EnclosingClass);
3020 // Add the associated namespace for this class.
3021 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3023 // -- If T is a template-id, its associated namespaces and classes are
3024 // the namespace in which the template is defined; for member
3025 // templates, the member template's class; the namespaces and classes
3026 // associated with the types of the template arguments provided for
3027 // template type parameters (excluding template template parameters); the
3028 // namespaces in which any template template arguments are defined; and
3029 // the classes in which any member templates used as template template
3030 // arguments are defined. [Note: non-type template arguments do not
3031 // contribute to the set of associated namespaces. ]
3032 if (ClassTemplateSpecializationDecl *Spec
3033 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
3034 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
3035 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3036 Result.Classes.insert(EnclosingClass);
3037 // Add the associated namespace for this class.
3038 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3040 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
3041 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
3042 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
3045 // Add the class itself. If we've already transitively visited this class,
3046 // we don't need to visit base classes.
3047 if (!Result.addClassTransitive(Class))
3048 return;
3050 // Only recurse into base classes for complete types.
3051 if (!Result.S.isCompleteType(Result.InstantiationLoc,
3052 Result.S.Context.getRecordType(Class)))
3053 return;
3055 // Add direct and indirect base classes along with their associated
3056 // namespaces.
3057 SmallVector<CXXRecordDecl *, 32> Bases;
3058 Bases.push_back(Class);
3059 while (!Bases.empty()) {
3060 // Pop this class off the stack.
3061 Class = Bases.pop_back_val();
3063 // Visit the base classes.
3064 for (const auto &Base : Class->bases()) {
3065 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
3066 // In dependent contexts, we do ADL twice, and the first time around,
3067 // the base type might be a dependent TemplateSpecializationType, or a
3068 // TemplateTypeParmType. If that happens, simply ignore it.
3069 // FIXME: If we want to support export, we probably need to add the
3070 // namespace of the template in a TemplateSpecializationType, or even
3071 // the classes and namespaces of known non-dependent arguments.
3072 if (!BaseType)
3073 continue;
3074 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
3075 if (Result.addClassTransitive(BaseDecl)) {
3076 // Find the associated namespace for this base class.
3077 DeclContext *BaseCtx = BaseDecl->getDeclContext();
3078 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
3080 // Make sure we visit the bases of this base class.
3081 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
3082 Bases.push_back(BaseDecl);
3088 // Add the associated classes and namespaces for
3089 // argument-dependent lookup with an argument of type T
3090 // (C++ [basic.lookup.koenig]p2).
3091 static void
3092 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
3093 // C++ [basic.lookup.koenig]p2:
3095 // For each argument type T in the function call, there is a set
3096 // of zero or more associated namespaces and a set of zero or more
3097 // associated classes to be considered. The sets of namespaces and
3098 // classes is determined entirely by the types of the function
3099 // arguments (and the namespace of any template template
3100 // argument). Typedef names and using-declarations used to specify
3101 // the types do not contribute to this set. The sets of namespaces
3102 // and classes are determined in the following way:
3104 SmallVector<const Type *, 16> Queue;
3105 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
3107 while (true) {
3108 switch (T->getTypeClass()) {
3110 #define TYPE(Class, Base)
3111 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3112 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
3113 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
3114 #define ABSTRACT_TYPE(Class, Base)
3115 #include "clang/AST/TypeNodes.inc"
3116 // T is canonical. We can also ignore dependent types because
3117 // we don't need to do ADL at the definition point, but if we
3118 // wanted to implement template export (or if we find some other
3119 // use for associated classes and namespaces...) this would be
3120 // wrong.
3121 break;
3123 // -- If T is a pointer to U or an array of U, its associated
3124 // namespaces and classes are those associated with U.
3125 case Type::Pointer:
3126 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
3127 continue;
3128 case Type::ConstantArray:
3129 case Type::IncompleteArray:
3130 case Type::VariableArray:
3131 T = cast<ArrayType>(T)->getElementType().getTypePtr();
3132 continue;
3134 // -- If T is a fundamental type, its associated sets of
3135 // namespaces and classes are both empty.
3136 case Type::Builtin:
3137 break;
3139 // -- If T is a class type (including unions), its associated
3140 // classes are: the class itself; the class of which it is
3141 // a member, if any; and its direct and indirect base classes.
3142 // Its associated namespaces are the innermost enclosing
3143 // namespaces of its associated classes.
3144 case Type::Record: {
3145 CXXRecordDecl *Class =
3146 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
3147 addAssociatedClassesAndNamespaces(Result, Class);
3148 break;
3151 // -- If T is an enumeration type, its associated namespace
3152 // is the innermost enclosing namespace of its declaration.
3153 // If it is a class member, its associated class is the
3154 // member’s class; else it has no associated class.
3155 case Type::Enum: {
3156 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
3158 DeclContext *Ctx = Enum->getDeclContext();
3159 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
3160 Result.Classes.insert(EnclosingClass);
3162 // Add the associated namespace for this enumeration.
3163 CollectEnclosingNamespace(Result.Namespaces, Ctx);
3165 break;
3168 // -- If T is a function type, its associated namespaces and
3169 // classes are those associated with the function parameter
3170 // types and those associated with the return type.
3171 case Type::FunctionProto: {
3172 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
3173 for (const auto &Arg : Proto->param_types())
3174 Queue.push_back(Arg.getTypePtr());
3175 // fallthrough
3176 [[fallthrough]];
3178 case Type::FunctionNoProto: {
3179 const FunctionType *FnType = cast<FunctionType>(T);
3180 T = FnType->getReturnType().getTypePtr();
3181 continue;
3184 // -- If T is a pointer to a member function of a class X, its
3185 // associated namespaces and classes are those associated
3186 // with the function parameter types and return type,
3187 // together with those associated with X.
3189 // -- If T is a pointer to a data member of class X, its
3190 // associated namespaces and classes are those associated
3191 // with the member type together with those associated with
3192 // X.
3193 case Type::MemberPointer: {
3194 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
3196 // Queue up the class type into which this points.
3197 Queue.push_back(MemberPtr->getClass());
3199 // And directly continue with the pointee type.
3200 T = MemberPtr->getPointeeType().getTypePtr();
3201 continue;
3204 // As an extension, treat this like a normal pointer.
3205 case Type::BlockPointer:
3206 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
3207 continue;
3209 // References aren't covered by the standard, but that's such an
3210 // obvious defect that we cover them anyway.
3211 case Type::LValueReference:
3212 case Type::RValueReference:
3213 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
3214 continue;
3216 // These are fundamental types.
3217 case Type::Vector:
3218 case Type::ExtVector:
3219 case Type::ConstantMatrix:
3220 case Type::Complex:
3221 case Type::BitInt:
3222 break;
3224 // Non-deduced auto types only get here for error cases.
3225 case Type::Auto:
3226 case Type::DeducedTemplateSpecialization:
3227 break;
3229 // If T is an Objective-C object or interface type, or a pointer to an
3230 // object or interface type, the associated namespace is the global
3231 // namespace.
3232 case Type::ObjCObject:
3233 case Type::ObjCInterface:
3234 case Type::ObjCObjectPointer:
3235 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
3236 break;
3238 // Atomic types are just wrappers; use the associations of the
3239 // contained type.
3240 case Type::Atomic:
3241 T = cast<AtomicType>(T)->getValueType().getTypePtr();
3242 continue;
3243 case Type::Pipe:
3244 T = cast<PipeType>(T)->getElementType().getTypePtr();
3245 continue;
3248 if (Queue.empty())
3249 break;
3250 T = Queue.pop_back_val();
3254 /// Find the associated classes and namespaces for
3255 /// argument-dependent lookup for a call with the given set of
3256 /// arguments.
3258 /// This routine computes the sets of associated classes and associated
3259 /// namespaces searched by argument-dependent lookup
3260 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
3261 void Sema::FindAssociatedClassesAndNamespaces(
3262 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
3263 AssociatedNamespaceSet &AssociatedNamespaces,
3264 AssociatedClassSet &AssociatedClasses) {
3265 AssociatedNamespaces.clear();
3266 AssociatedClasses.clear();
3268 AssociatedLookup Result(*this, InstantiationLoc,
3269 AssociatedNamespaces, AssociatedClasses);
3271 // C++ [basic.lookup.koenig]p2:
3272 // For each argument type T in the function call, there is a set
3273 // of zero or more associated namespaces and a set of zero or more
3274 // associated classes to be considered. The sets of namespaces and
3275 // classes is determined entirely by the types of the function
3276 // arguments (and the namespace of any template template
3277 // argument).
3278 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
3279 Expr *Arg = Args[ArgIdx];
3281 if (Arg->getType() != Context.OverloadTy) {
3282 addAssociatedClassesAndNamespaces(Result, Arg->getType());
3283 continue;
3286 // [...] In addition, if the argument is the name or address of a
3287 // set of overloaded functions and/or function templates, its
3288 // associated classes and namespaces are the union of those
3289 // associated with each of the members of the set: the namespace
3290 // in which the function or function template is defined and the
3291 // classes and namespaces associated with its (non-dependent)
3292 // parameter types and return type.
3293 OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
3295 for (const NamedDecl *D : OE->decls()) {
3296 // Look through any using declarations to find the underlying function.
3297 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
3299 // Add the classes and namespaces associated with the parameter
3300 // types and return type of this function.
3301 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
3306 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
3307 SourceLocation Loc,
3308 LookupNameKind NameKind,
3309 RedeclarationKind Redecl) {
3310 LookupResult R(*this, Name, Loc, NameKind, Redecl);
3311 LookupName(R, S);
3312 return R.getAsSingle<NamedDecl>();
3315 /// Find the protocol with the given name, if any.
3316 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
3317 SourceLocation IdLoc,
3318 RedeclarationKind Redecl) {
3319 Decl *D = LookupSingleName(TUScope, II, IdLoc,
3320 LookupObjCProtocolName, Redecl);
3321 return cast_or_null<ObjCProtocolDecl>(D);
3324 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3325 UnresolvedSetImpl &Functions) {
3326 // C++ [over.match.oper]p3:
3327 // -- The set of non-member candidates is the result of the
3328 // unqualified lookup of operator@ in the context of the
3329 // expression according to the usual rules for name lookup in
3330 // unqualified function calls (3.4.2) except that all member
3331 // functions are ignored.
3332 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3333 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3334 LookupName(Operators, S);
3336 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3337 Functions.append(Operators.begin(), Operators.end());
3340 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
3341 CXXSpecialMember SM,
3342 bool ConstArg,
3343 bool VolatileArg,
3344 bool RValueThis,
3345 bool ConstThis,
3346 bool VolatileThis) {
3347 assert(CanDeclareSpecialMemberFunction(RD) &&
3348 "doing special member lookup into record that isn't fully complete");
3349 RD = RD->getDefinition();
3350 if (RValueThis || ConstThis || VolatileThis)
3351 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
3352 "constructors and destructors always have unqualified lvalue this");
3353 if (ConstArg || VolatileArg)
3354 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
3355 "parameter-less special members can't have qualified arguments");
3357 // FIXME: Get the caller to pass in a location for the lookup.
3358 SourceLocation LookupLoc = RD->getLocation();
3360 llvm::FoldingSetNodeID ID;
3361 ID.AddPointer(RD);
3362 ID.AddInteger(SM);
3363 ID.AddInteger(ConstArg);
3364 ID.AddInteger(VolatileArg);
3365 ID.AddInteger(RValueThis);
3366 ID.AddInteger(ConstThis);
3367 ID.AddInteger(VolatileThis);
3369 void *InsertPoint;
3370 SpecialMemberOverloadResultEntry *Result =
3371 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3373 // This was already cached
3374 if (Result)
3375 return *Result;
3377 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
3378 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
3379 SpecialMemberCache.InsertNode(Result, InsertPoint);
3381 if (SM == CXXDestructor) {
3382 if (RD->needsImplicitDestructor()) {
3383 runWithSufficientStackSpace(RD->getLocation(), [&] {
3384 DeclareImplicitDestructor(RD);
3387 CXXDestructorDecl *DD = RD->getDestructor();
3388 Result->setMethod(DD);
3389 Result->setKind(DD && !DD->isDeleted()
3390 ? SpecialMemberOverloadResult::Success
3391 : SpecialMemberOverloadResult::NoMemberOrDeleted);
3392 return *Result;
3395 // Prepare for overload resolution. Here we construct a synthetic argument
3396 // if necessary and make sure that implicit functions are declared.
3397 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
3398 DeclarationName Name;
3399 Expr *Arg = nullptr;
3400 unsigned NumArgs;
3402 QualType ArgType = CanTy;
3403 ExprValueKind VK = VK_LValue;
3405 if (SM == CXXDefaultConstructor) {
3406 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3407 NumArgs = 0;
3408 if (RD->needsImplicitDefaultConstructor()) {
3409 runWithSufficientStackSpace(RD->getLocation(), [&] {
3410 DeclareImplicitDefaultConstructor(RD);
3413 } else {
3414 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
3415 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3416 if (RD->needsImplicitCopyConstructor()) {
3417 runWithSufficientStackSpace(RD->getLocation(), [&] {
3418 DeclareImplicitCopyConstructor(RD);
3421 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
3422 runWithSufficientStackSpace(RD->getLocation(), [&] {
3423 DeclareImplicitMoveConstructor(RD);
3426 } else {
3427 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3428 if (RD->needsImplicitCopyAssignment()) {
3429 runWithSufficientStackSpace(RD->getLocation(), [&] {
3430 DeclareImplicitCopyAssignment(RD);
3433 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
3434 runWithSufficientStackSpace(RD->getLocation(), [&] {
3435 DeclareImplicitMoveAssignment(RD);
3440 if (ConstArg)
3441 ArgType.addConst();
3442 if (VolatileArg)
3443 ArgType.addVolatile();
3445 // This isn't /really/ specified by the standard, but it's implied
3446 // we should be working from a PRValue in the case of move to ensure
3447 // that we prefer to bind to rvalue references, and an LValue in the
3448 // case of copy to ensure we don't bind to rvalue references.
3449 // Possibly an XValue is actually correct in the case of move, but
3450 // there is no semantic difference for class types in this restricted
3451 // case.
3452 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
3453 VK = VK_LValue;
3454 else
3455 VK = VK_PRValue;
3458 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3460 if (SM != CXXDefaultConstructor) {
3461 NumArgs = 1;
3462 Arg = &FakeArg;
3465 // Create the object argument
3466 QualType ThisTy = CanTy;
3467 if (ConstThis)
3468 ThisTy.addConst();
3469 if (VolatileThis)
3470 ThisTy.addVolatile();
3471 Expr::Classification Classification =
3472 OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_PRValue : VK_LValue)
3473 .Classify(Context);
3475 // Now we perform lookup on the name we computed earlier and do overload
3476 // resolution. Lookup is only performed directly into the class since there
3477 // will always be a (possibly implicit) declaration to shadow any others.
3478 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
3479 DeclContext::lookup_result R = RD->lookup(Name);
3481 if (R.empty()) {
3482 // We might have no default constructor because we have a lambda's closure
3483 // type, rather than because there's some other declared constructor.
3484 // Every class has a copy/move constructor, copy/move assignment, and
3485 // destructor.
3486 assert(SM == CXXDefaultConstructor &&
3487 "lookup for a constructor or assignment operator was empty");
3488 Result->setMethod(nullptr);
3489 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3490 return *Result;
3493 // Copy the candidates as our processing of them may load new declarations
3494 // from an external source and invalidate lookup_result.
3495 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3497 for (NamedDecl *CandDecl : Candidates) {
3498 if (CandDecl->isInvalidDecl())
3499 continue;
3501 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3502 auto CtorInfo = getConstructorInfo(Cand);
3503 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3504 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3505 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3506 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3507 else if (CtorInfo)
3508 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3509 llvm::ArrayRef(&Arg, NumArgs), OCS,
3510 /*SuppressUserConversions*/ true);
3511 else
3512 AddOverloadCandidate(M, Cand, llvm::ArrayRef(&Arg, NumArgs), OCS,
3513 /*SuppressUserConversions*/ true);
3514 } else if (FunctionTemplateDecl *Tmpl =
3515 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3516 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3517 AddMethodTemplateCandidate(Tmpl, Cand, RD, nullptr, ThisTy,
3518 Classification,
3519 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3520 else if (CtorInfo)
3521 AddTemplateOverloadCandidate(CtorInfo.ConstructorTmpl,
3522 CtorInfo.FoundDecl, nullptr,
3523 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3524 else
3525 AddTemplateOverloadCandidate(Tmpl, Cand, nullptr,
3526 llvm::ArrayRef(&Arg, NumArgs), OCS, true);
3527 } else {
3528 assert(isa<UsingDecl>(Cand.getDecl()) &&
3529 "illegal Kind of operator = Decl");
3533 OverloadCandidateSet::iterator Best;
3534 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3535 case OR_Success:
3536 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3537 Result->setKind(SpecialMemberOverloadResult::Success);
3538 break;
3540 case OR_Deleted:
3541 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3542 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3543 break;
3545 case OR_Ambiguous:
3546 Result->setMethod(nullptr);
3547 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3548 break;
3550 case OR_No_Viable_Function:
3551 Result->setMethod(nullptr);
3552 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3553 break;
3556 return *Result;
3559 /// Look up the default constructor for the given class.
3560 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3561 SpecialMemberOverloadResult Result =
3562 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3563 false, false);
3565 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3568 /// Look up the copying constructor for the given class.
3569 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3570 unsigned Quals) {
3571 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3572 "non-const, non-volatile qualifiers for copy ctor arg");
3573 SpecialMemberOverloadResult Result =
3574 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3575 Quals & Qualifiers::Volatile, false, false, false);
3577 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3580 /// Look up the moving constructor for the given class.
3581 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3582 unsigned Quals) {
3583 SpecialMemberOverloadResult Result =
3584 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3585 Quals & Qualifiers::Volatile, false, false, false);
3587 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3590 /// Look up the constructors for the given class.
3591 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3592 // If the implicit constructors have not yet been declared, do so now.
3593 if (CanDeclareSpecialMemberFunction(Class)) {
3594 runWithSufficientStackSpace(Class->getLocation(), [&] {
3595 if (Class->needsImplicitDefaultConstructor())
3596 DeclareImplicitDefaultConstructor(Class);
3597 if (Class->needsImplicitCopyConstructor())
3598 DeclareImplicitCopyConstructor(Class);
3599 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3600 DeclareImplicitMoveConstructor(Class);
3604 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3605 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3606 return Class->lookup(Name);
3609 /// Look up the copying assignment operator for the given class.
3610 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3611 unsigned Quals, bool RValueThis,
3612 unsigned ThisQuals) {
3613 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3614 "non-const, non-volatile qualifiers for copy assignment arg");
3615 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3616 "non-const, non-volatile qualifiers for copy assignment this");
3617 SpecialMemberOverloadResult Result =
3618 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3619 Quals & Qualifiers::Volatile, RValueThis,
3620 ThisQuals & Qualifiers::Const,
3621 ThisQuals & Qualifiers::Volatile);
3623 return Result.getMethod();
3626 /// Look up the moving assignment operator for the given class.
3627 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3628 unsigned Quals,
3629 bool RValueThis,
3630 unsigned ThisQuals) {
3631 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3632 "non-const, non-volatile qualifiers for copy assignment this");
3633 SpecialMemberOverloadResult Result =
3634 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3635 Quals & Qualifiers::Volatile, RValueThis,
3636 ThisQuals & Qualifiers::Const,
3637 ThisQuals & Qualifiers::Volatile);
3639 return Result.getMethod();
3642 /// Look for the destructor of the given class.
3644 /// During semantic analysis, this routine should be used in lieu of
3645 /// CXXRecordDecl::getDestructor().
3647 /// \returns The destructor for this class.
3648 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3649 return cast_or_null<CXXDestructorDecl>(
3650 LookupSpecialMember(Class, CXXDestructor, false, false, false, false,
3651 false)
3652 .getMethod());
3655 /// LookupLiteralOperator - Determine which literal operator should be used for
3656 /// a user-defined literal, per C++11 [lex.ext].
3658 /// Normal overload resolution is not used to select which literal operator to
3659 /// call for a user-defined literal. Look up the provided literal operator name,
3660 /// and filter the results to the appropriate set for the given argument types.
3661 Sema::LiteralOperatorLookupResult
3662 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3663 ArrayRef<QualType> ArgTys, bool AllowRaw,
3664 bool AllowTemplate, bool AllowStringTemplatePack,
3665 bool DiagnoseMissing, StringLiteral *StringLit) {
3666 LookupName(R, S);
3667 assert(R.getResultKind() != LookupResult::Ambiguous &&
3668 "literal operator lookup can't be ambiguous");
3670 // Filter the lookup results appropriately.
3671 LookupResult::Filter F = R.makeFilter();
3673 bool AllowCooked = true;
3674 bool FoundRaw = false;
3675 bool FoundTemplate = false;
3676 bool FoundStringTemplatePack = false;
3677 bool FoundCooked = false;
3679 while (F.hasNext()) {
3680 Decl *D = F.next();
3681 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3682 D = USD->getTargetDecl();
3684 // If the declaration we found is invalid, skip it.
3685 if (D->isInvalidDecl()) {
3686 F.erase();
3687 continue;
3690 bool IsRaw = false;
3691 bool IsTemplate = false;
3692 bool IsStringTemplatePack = false;
3693 bool IsCooked = false;
3695 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3696 if (FD->getNumParams() == 1 &&
3697 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3698 IsRaw = true;
3699 else if (FD->getNumParams() == ArgTys.size()) {
3700 IsCooked = true;
3701 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3702 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3703 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3704 IsCooked = false;
3705 break;
3710 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3711 TemplateParameterList *Params = FD->getTemplateParameters();
3712 if (Params->size() == 1) {
3713 IsTemplate = true;
3714 if (!Params->getParam(0)->isTemplateParameterPack() && !StringLit) {
3715 // Implied but not stated: user-defined integer and floating literals
3716 // only ever use numeric literal operator templates, not templates
3717 // taking a parameter of class type.
3718 F.erase();
3719 continue;
3722 // A string literal template is only considered if the string literal
3723 // is a well-formed template argument for the template parameter.
3724 if (StringLit) {
3725 SFINAETrap Trap(*this);
3726 SmallVector<TemplateArgument, 1> SugaredChecked, CanonicalChecked;
3727 TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3728 if (CheckTemplateArgument(
3729 Params->getParam(0), Arg, FD, R.getNameLoc(), R.getNameLoc(),
3730 0, SugaredChecked, CanonicalChecked, CTAK_Specified) ||
3731 Trap.hasErrorOccurred())
3732 IsTemplate = false;
3734 } else {
3735 IsStringTemplatePack = true;
3739 if (AllowTemplate && StringLit && IsTemplate) {
3740 FoundTemplate = true;
3741 AllowRaw = false;
3742 AllowCooked = false;
3743 AllowStringTemplatePack = false;
3744 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3745 F.restart();
3746 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3748 } else if (AllowCooked && IsCooked) {
3749 FoundCooked = true;
3750 AllowRaw = false;
3751 AllowTemplate = StringLit;
3752 AllowStringTemplatePack = false;
3753 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3754 // Go through again and remove the raw and template decls we've
3755 // already found.
3756 F.restart();
3757 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3759 } else if (AllowRaw && IsRaw) {
3760 FoundRaw = true;
3761 } else if (AllowTemplate && IsTemplate) {
3762 FoundTemplate = true;
3763 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3764 FoundStringTemplatePack = true;
3765 } else {
3766 F.erase();
3770 F.done();
3772 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3773 // form for string literal operator templates.
3774 if (StringLit && FoundTemplate)
3775 return LOLR_Template;
3777 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3778 // parameter type, that is used in preference to a raw literal operator
3779 // or literal operator template.
3780 if (FoundCooked)
3781 return LOLR_Cooked;
3783 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3784 // operator template, but not both.
3785 if (FoundRaw && FoundTemplate) {
3786 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3787 for (const NamedDecl *D : R)
3788 NoteOverloadCandidate(D, D->getUnderlyingDecl()->getAsFunction());
3789 return LOLR_Error;
3792 if (FoundRaw)
3793 return LOLR_Raw;
3795 if (FoundTemplate)
3796 return LOLR_Template;
3798 if (FoundStringTemplatePack)
3799 return LOLR_StringTemplatePack;
3801 // Didn't find anything we could use.
3802 if (DiagnoseMissing) {
3803 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3804 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3805 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3806 << (AllowTemplate || AllowStringTemplatePack);
3807 return LOLR_Error;
3810 return LOLR_ErrorNoDiagnostic;
3813 void ADLResult::insert(NamedDecl *New) {
3814 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3816 // If we haven't yet seen a decl for this key, or the last decl
3817 // was exactly this one, we're done.
3818 if (Old == nullptr || Old == New) {
3819 Old = New;
3820 return;
3823 // Otherwise, decide which is a more recent redeclaration.
3824 FunctionDecl *OldFD = Old->getAsFunction();
3825 FunctionDecl *NewFD = New->getAsFunction();
3827 FunctionDecl *Cursor = NewFD;
3828 while (true) {
3829 Cursor = Cursor->getPreviousDecl();
3831 // If we got to the end without finding OldFD, OldFD is the newer
3832 // declaration; leave things as they are.
3833 if (!Cursor) return;
3835 // If we do find OldFD, then NewFD is newer.
3836 if (Cursor == OldFD) break;
3838 // Otherwise, keep looking.
3841 Old = New;
3844 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3845 ArrayRef<Expr *> Args, ADLResult &Result) {
3846 // Find all of the associated namespaces and classes based on the
3847 // arguments we have.
3848 AssociatedNamespaceSet AssociatedNamespaces;
3849 AssociatedClassSet AssociatedClasses;
3850 FindAssociatedClassesAndNamespaces(Loc, Args,
3851 AssociatedNamespaces,
3852 AssociatedClasses);
3854 // C++ [basic.lookup.argdep]p3:
3855 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3856 // and let Y be the lookup set produced by argument dependent
3857 // lookup (defined as follows). If X contains [...] then Y is
3858 // empty. Otherwise Y is the set of declarations found in the
3859 // namespaces associated with the argument types as described
3860 // below. The set of declarations found by the lookup of the name
3861 // is the union of X and Y.
3863 // Here, we compute Y and add its members to the overloaded
3864 // candidate set.
3865 for (auto *NS : AssociatedNamespaces) {
3866 // When considering an associated namespace, the lookup is the
3867 // same as the lookup performed when the associated namespace is
3868 // used as a qualifier (3.4.3.2) except that:
3870 // -- Any using-directives in the associated namespace are
3871 // ignored.
3873 // -- Any namespace-scope friend functions declared in
3874 // associated classes are visible within their respective
3875 // namespaces even if they are not visible during an ordinary
3876 // lookup (11.4).
3878 // C++20 [basic.lookup.argdep] p4.3
3879 // -- are exported, are attached to a named module M, do not appear
3880 // in the translation unit containing the point of the lookup, and
3881 // have the same innermost enclosing non-inline namespace scope as
3882 // a declaration of an associated entity attached to M.
3883 DeclContext::lookup_result R = NS->lookup(Name);
3884 for (auto *D : R) {
3885 auto *Underlying = D;
3886 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3887 Underlying = USD->getTargetDecl();
3889 if (!isa<FunctionDecl>(Underlying) &&
3890 !isa<FunctionTemplateDecl>(Underlying))
3891 continue;
3893 // The declaration is visible to argument-dependent lookup if either
3894 // it's ordinarily visible or declared as a friend in an associated
3895 // class.
3896 bool Visible = false;
3897 for (D = D->getMostRecentDecl(); D;
3898 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3899 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3900 if (isVisible(D)) {
3901 Visible = true;
3902 break;
3905 if (!getLangOpts().CPlusPlusModules)
3906 continue;
3908 if (D->isInExportDeclContext()) {
3909 Module *FM = D->getOwningModule();
3910 // C++20 [basic.lookup.argdep] p4.3 .. are exported ...
3911 // exports are only valid in module purview and outside of any
3912 // PMF (although a PMF should not even be present in a module
3913 // with an import).
3914 assert(FM && FM->isModulePurview() && !FM->isPrivateModule() &&
3915 "bad export context");
3916 // .. are attached to a named module M, do not appear in the
3917 // translation unit containing the point of the lookup..
3918 if (D->isInAnotherModuleUnit() &&
3919 llvm::any_of(AssociatedClasses, [&](auto *E) {
3920 // ... and have the same innermost enclosing non-inline
3921 // namespace scope as a declaration of an associated entity
3922 // attached to M
3923 if (E->getOwningModule() != FM)
3924 return false;
3925 // TODO: maybe this could be cached when generating the
3926 // associated namespaces / entities.
3927 DeclContext *Ctx = E->getDeclContext();
3928 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
3929 Ctx = Ctx->getParent();
3930 return Ctx == NS;
3931 })) {
3932 Visible = true;
3933 break;
3936 } else if (D->getFriendObjectKind()) {
3937 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3938 // [basic.lookup.argdep]p4:
3939 // Argument-dependent lookup finds all declarations of functions and
3940 // function templates that
3941 // - ...
3942 // - are declared as a friend ([class.friend]) of any class with a
3943 // reachable definition in the set of associated entities,
3945 // FIXME: If there's a merged definition of D that is reachable, then
3946 // the friend declaration should be considered.
3947 if (AssociatedClasses.count(RD) && isReachable(D)) {
3948 Visible = true;
3949 break;
3954 // FIXME: Preserve D as the FoundDecl.
3955 if (Visible)
3956 Result.insert(Underlying);
3961 //----------------------------------------------------------------------------
3962 // Search for all visible declarations.
3963 //----------------------------------------------------------------------------
3964 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3966 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3968 namespace {
3970 class ShadowContextRAII;
3972 class VisibleDeclsRecord {
3973 public:
3974 /// An entry in the shadow map, which is optimized to store a
3975 /// single declaration (the common case) but can also store a list
3976 /// of declarations.
3977 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3979 private:
3980 /// A mapping from declaration names to the declarations that have
3981 /// this name within a particular scope.
3982 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3984 /// A list of shadow maps, which is used to model name hiding.
3985 std::list<ShadowMap> ShadowMaps;
3987 /// The declaration contexts we have already visited.
3988 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3990 friend class ShadowContextRAII;
3992 public:
3993 /// Determine whether we have already visited this context
3994 /// (and, if not, note that we are going to visit that context now).
3995 bool visitedContext(DeclContext *Ctx) {
3996 return !VisitedContexts.insert(Ctx).second;
3999 bool alreadyVisitedContext(DeclContext *Ctx) {
4000 return VisitedContexts.count(Ctx);
4003 /// Determine whether the given declaration is hidden in the
4004 /// current scope.
4006 /// \returns the declaration that hides the given declaration, or
4007 /// NULL if no such declaration exists.
4008 NamedDecl *checkHidden(NamedDecl *ND);
4010 /// Add a declaration to the current shadow map.
4011 void add(NamedDecl *ND) {
4012 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
4016 /// RAII object that records when we've entered a shadow context.
4017 class ShadowContextRAII {
4018 VisibleDeclsRecord &Visible;
4020 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
4022 public:
4023 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
4024 Visible.ShadowMaps.emplace_back();
4027 ~ShadowContextRAII() {
4028 Visible.ShadowMaps.pop_back();
4032 } // end anonymous namespace
4034 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
4035 unsigned IDNS = ND->getIdentifierNamespace();
4036 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
4037 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
4038 SM != SMEnd; ++SM) {
4039 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
4040 if (Pos == SM->end())
4041 continue;
4043 for (auto *D : Pos->second) {
4044 // A tag declaration does not hide a non-tag declaration.
4045 if (D->hasTagIdentifierNamespace() &&
4046 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
4047 Decl::IDNS_ObjCProtocol)))
4048 continue;
4050 // Protocols are in distinct namespaces from everything else.
4051 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
4052 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
4053 D->getIdentifierNamespace() != IDNS)
4054 continue;
4056 // Functions and function templates in the same scope overload
4057 // rather than hide. FIXME: Look for hiding based on function
4058 // signatures!
4059 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4060 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
4061 SM == ShadowMaps.rbegin())
4062 continue;
4064 // A shadow declaration that's created by a resolved using declaration
4065 // is not hidden by the same using declaration.
4066 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
4067 cast<UsingShadowDecl>(ND)->getIntroducer() == D)
4068 continue;
4070 // We've found a declaration that hides this one.
4071 return D;
4075 return nullptr;
4078 namespace {
4079 class LookupVisibleHelper {
4080 public:
4081 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
4082 bool LoadExternal)
4083 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
4084 LoadExternal(LoadExternal) {}
4086 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
4087 bool IncludeGlobalScope) {
4088 // Determine the set of using directives available during
4089 // unqualified name lookup.
4090 Scope *Initial = S;
4091 UnqualUsingDirectiveSet UDirs(SemaRef);
4092 if (SemaRef.getLangOpts().CPlusPlus) {
4093 // Find the first namespace or translation-unit scope.
4094 while (S && !isNamespaceOrTranslationUnitScope(S))
4095 S = S->getParent();
4097 UDirs.visitScopeChain(Initial, S);
4099 UDirs.done();
4101 // Look for visible declarations.
4102 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4103 Result.setAllowHidden(Consumer.includeHiddenDecls());
4104 if (!IncludeGlobalScope)
4105 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4106 ShadowContextRAII Shadow(Visited);
4107 lookupInScope(Initial, Result, UDirs);
4110 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
4111 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
4112 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
4113 Result.setAllowHidden(Consumer.includeHiddenDecls());
4114 if (!IncludeGlobalScope)
4115 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
4117 ShadowContextRAII Shadow(Visited);
4118 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
4119 /*InBaseClass=*/false);
4122 private:
4123 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
4124 bool QualifiedNameLookup, bool InBaseClass) {
4125 if (!Ctx)
4126 return;
4128 // Make sure we don't visit the same context twice.
4129 if (Visited.visitedContext(Ctx->getPrimaryContext()))
4130 return;
4132 Consumer.EnteredContext(Ctx);
4134 // Outside C++, lookup results for the TU live on identifiers.
4135 if (isa<TranslationUnitDecl>(Ctx) &&
4136 !Result.getSema().getLangOpts().CPlusPlus) {
4137 auto &S = Result.getSema();
4138 auto &Idents = S.Context.Idents;
4140 // Ensure all external identifiers are in the identifier table.
4141 if (LoadExternal)
4142 if (IdentifierInfoLookup *External =
4143 Idents.getExternalIdentifierLookup()) {
4144 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4145 for (StringRef Name = Iter->Next(); !Name.empty();
4146 Name = Iter->Next())
4147 Idents.get(Name);
4150 // Walk all lookup results in the TU for each identifier.
4151 for (const auto &Ident : Idents) {
4152 for (auto I = S.IdResolver.begin(Ident.getValue()),
4153 E = S.IdResolver.end();
4154 I != E; ++I) {
4155 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
4156 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
4157 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4158 Visited.add(ND);
4164 return;
4167 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
4168 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
4170 llvm::SmallVector<NamedDecl *, 4> DeclsToVisit;
4171 // We sometimes skip loading namespace-level results (they tend to be huge).
4172 bool Load = LoadExternal ||
4173 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
4174 // Enumerate all of the results in this context.
4175 for (DeclContextLookupResult R :
4176 Load ? Ctx->lookups()
4177 : Ctx->noload_lookups(/*PreserveInternalState=*/false))
4178 for (auto *D : R)
4179 // Rather than visit immediately, we put ND into a vector and visit
4180 // all decls, in order, outside of this loop. The reason is that
4181 // Consumer.FoundDecl() and LookupResult::getAcceptableDecl(D)
4182 // may invalidate the iterators used in the two
4183 // loops above.
4184 DeclsToVisit.push_back(D);
4186 for (auto *D : DeclsToVisit)
4187 if (auto *ND = Result.getAcceptableDecl(D)) {
4188 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
4189 Visited.add(ND);
4192 DeclsToVisit.clear();
4194 // Traverse using directives for qualified name lookup.
4195 if (QualifiedNameLookup) {
4196 ShadowContextRAII Shadow(Visited);
4197 for (auto *I : Ctx->using_directives()) {
4198 if (!Result.getSema().isVisible(I))
4199 continue;
4200 lookupInDeclContext(I->getNominatedNamespace(), Result,
4201 QualifiedNameLookup, InBaseClass);
4205 // Traverse the contexts of inherited C++ classes.
4206 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
4207 if (!Record->hasDefinition())
4208 return;
4210 for (const auto &B : Record->bases()) {
4211 QualType BaseType = B.getType();
4213 RecordDecl *RD;
4214 if (BaseType->isDependentType()) {
4215 if (!IncludeDependentBases) {
4216 // Don't look into dependent bases, because name lookup can't look
4217 // there anyway.
4218 continue;
4220 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
4221 if (!TST)
4222 continue;
4223 TemplateName TN = TST->getTemplateName();
4224 const auto *TD =
4225 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
4226 if (!TD)
4227 continue;
4228 RD = TD->getTemplatedDecl();
4229 } else {
4230 const auto *Record = BaseType->getAs<RecordType>();
4231 if (!Record)
4232 continue;
4233 RD = Record->getDecl();
4236 // FIXME: It would be nice to be able to determine whether referencing
4237 // a particular member would be ambiguous. For example, given
4239 // struct A { int member; };
4240 // struct B { int member; };
4241 // struct C : A, B { };
4243 // void f(C *c) { c->### }
4245 // accessing 'member' would result in an ambiguity. However, we
4246 // could be smart enough to qualify the member with the base
4247 // class, e.g.,
4249 // c->B::member
4251 // or
4253 // c->A::member
4255 // Find results in this base class (and its bases).
4256 ShadowContextRAII Shadow(Visited);
4257 lookupInDeclContext(RD, Result, QualifiedNameLookup,
4258 /*InBaseClass=*/true);
4262 // Traverse the contexts of Objective-C classes.
4263 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
4264 // Traverse categories.
4265 for (auto *Cat : IFace->visible_categories()) {
4266 ShadowContextRAII Shadow(Visited);
4267 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
4268 /*InBaseClass=*/false);
4271 // Traverse protocols.
4272 for (auto *I : IFace->all_referenced_protocols()) {
4273 ShadowContextRAII Shadow(Visited);
4274 lookupInDeclContext(I, Result, QualifiedNameLookup,
4275 /*InBaseClass=*/false);
4278 // Traverse the superclass.
4279 if (IFace->getSuperClass()) {
4280 ShadowContextRAII Shadow(Visited);
4281 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
4282 /*InBaseClass=*/true);
4285 // If there is an implementation, traverse it. We do this to find
4286 // synthesized ivars.
4287 if (IFace->getImplementation()) {
4288 ShadowContextRAII Shadow(Visited);
4289 lookupInDeclContext(IFace->getImplementation(), Result,
4290 QualifiedNameLookup, InBaseClass);
4292 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
4293 for (auto *I : Protocol->protocols()) {
4294 ShadowContextRAII Shadow(Visited);
4295 lookupInDeclContext(I, Result, QualifiedNameLookup,
4296 /*InBaseClass=*/false);
4298 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
4299 for (auto *I : Category->protocols()) {
4300 ShadowContextRAII Shadow(Visited);
4301 lookupInDeclContext(I, Result, QualifiedNameLookup,
4302 /*InBaseClass=*/false);
4305 // If there is an implementation, traverse it.
4306 if (Category->getImplementation()) {
4307 ShadowContextRAII Shadow(Visited);
4308 lookupInDeclContext(Category->getImplementation(), Result,
4309 QualifiedNameLookup, /*InBaseClass=*/true);
4314 void lookupInScope(Scope *S, LookupResult &Result,
4315 UnqualUsingDirectiveSet &UDirs) {
4316 // No clients run in this mode and it's not supported. Please add tests and
4317 // remove the assertion if you start relying on it.
4318 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
4320 if (!S)
4321 return;
4323 if (!S->getEntity() ||
4324 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
4325 (S->getEntity())->isFunctionOrMethod()) {
4326 FindLocalExternScope FindLocals(Result);
4327 // Walk through the declarations in this Scope. The consumer might add new
4328 // decls to the scope as part of deserialization, so make a copy first.
4329 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
4330 for (Decl *D : ScopeDecls) {
4331 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
4332 if ((ND = Result.getAcceptableDecl(ND))) {
4333 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
4334 Visited.add(ND);
4339 DeclContext *Entity = S->getLookupEntity();
4340 if (Entity) {
4341 // Look into this scope's declaration context, along with any of its
4342 // parent lookup contexts (e.g., enclosing classes), up to the point
4343 // where we hit the context stored in the next outer scope.
4344 DeclContext *OuterCtx = findOuterContext(S);
4346 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
4347 Ctx = Ctx->getLookupParent()) {
4348 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
4349 if (Method->isInstanceMethod()) {
4350 // For instance methods, look for ivars in the method's interface.
4351 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
4352 Result.getNameLoc(),
4353 Sema::LookupMemberName);
4354 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
4355 lookupInDeclContext(IFace, IvarResult,
4356 /*QualifiedNameLookup=*/false,
4357 /*InBaseClass=*/false);
4361 // We've already performed all of the name lookup that we need
4362 // to for Objective-C methods; the next context will be the
4363 // outer scope.
4364 break;
4367 if (Ctx->isFunctionOrMethod())
4368 continue;
4370 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
4371 /*InBaseClass=*/false);
4373 } else if (!S->getParent()) {
4374 // Look into the translation unit scope. We walk through the translation
4375 // unit's declaration context, because the Scope itself won't have all of
4376 // the declarations if we loaded a precompiled header.
4377 // FIXME: We would like the translation unit's Scope object to point to
4378 // the translation unit, so we don't need this special "if" branch.
4379 // However, doing so would force the normal C++ name-lookup code to look
4380 // into the translation unit decl when the IdentifierInfo chains would
4381 // suffice. Once we fix that problem (which is part of a more general
4382 // "don't look in DeclContexts unless we have to" optimization), we can
4383 // eliminate this.
4384 Entity = Result.getSema().Context.getTranslationUnitDecl();
4385 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
4386 /*InBaseClass=*/false);
4389 if (Entity) {
4390 // Lookup visible declarations in any namespaces found by using
4391 // directives.
4392 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4393 lookupInDeclContext(
4394 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4395 /*QualifiedNameLookup=*/false,
4396 /*InBaseClass=*/false);
4399 // Lookup names in the parent scope.
4400 ShadowContextRAII Shadow(Visited);
4401 lookupInScope(S->getParent(), Result, UDirs);
4404 private:
4405 VisibleDeclsRecord Visited;
4406 VisibleDeclConsumer &Consumer;
4407 bool IncludeDependentBases;
4408 bool LoadExternal;
4410 } // namespace
4412 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4413 VisibleDeclConsumer &Consumer,
4414 bool IncludeGlobalScope, bool LoadExternal) {
4415 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4416 LoadExternal);
4417 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4420 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4421 VisibleDeclConsumer &Consumer,
4422 bool IncludeGlobalScope,
4423 bool IncludeDependentBases, bool LoadExternal) {
4424 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4425 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4428 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
4429 /// If GnuLabelLoc is a valid source location, then this is a definition
4430 /// of an __label__ label name, otherwise it is a normal label definition
4431 /// or use.
4432 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
4433 SourceLocation GnuLabelLoc) {
4434 // Do a lookup to see if we have a label with this name already.
4435 NamedDecl *Res = nullptr;
4437 if (GnuLabelLoc.isValid()) {
4438 // Local label definitions always shadow existing labels.
4439 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4440 Scope *S = CurScope;
4441 PushOnScopeChains(Res, S, true);
4442 return cast<LabelDecl>(Res);
4445 // Not a GNU local label.
4446 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
4447 // If we found a label, check to see if it is in the same context as us.
4448 // When in a Block, we don't want to reuse a label in an enclosing function.
4449 if (Res && Res->getDeclContext() != CurContext)
4450 Res = nullptr;
4451 if (!Res) {
4452 // If not forward referenced or defined already, create the backing decl.
4453 Res = LabelDecl::Create(Context, CurContext, Loc, II);
4454 Scope *S = CurScope->getFnParent();
4455 assert(S && "Not in a function?");
4456 PushOnScopeChains(Res, S, true);
4458 return cast<LabelDecl>(Res);
4461 //===----------------------------------------------------------------------===//
4462 // Typo correction
4463 //===----------------------------------------------------------------------===//
4465 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
4466 TypoCorrection &Candidate) {
4467 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4468 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4471 static void LookupPotentialTypoResult(Sema &SemaRef,
4472 LookupResult &Res,
4473 IdentifierInfo *Name,
4474 Scope *S, CXXScopeSpec *SS,
4475 DeclContext *MemberContext,
4476 bool EnteringContext,
4477 bool isObjCIvarLookup,
4478 bool FindHidden);
4480 /// Check whether the declarations found for a typo correction are
4481 /// visible. Set the correction's RequiresImport flag to true if none of the
4482 /// declarations are visible, false otherwise.
4483 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4484 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4486 for (/**/; DI != DE; ++DI)
4487 if (!LookupResult::isVisible(SemaRef, *DI))
4488 break;
4489 // No filtering needed if all decls are visible.
4490 if (DI == DE) {
4491 TC.setRequiresImport(false);
4492 return;
4495 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4496 bool AnyVisibleDecls = !NewDecls.empty();
4498 for (/**/; DI != DE; ++DI) {
4499 if (LookupResult::isVisible(SemaRef, *DI)) {
4500 if (!AnyVisibleDecls) {
4501 // Found a visible decl, discard all hidden ones.
4502 AnyVisibleDecls = true;
4503 NewDecls.clear();
4505 NewDecls.push_back(*DI);
4506 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4507 NewDecls.push_back(*DI);
4510 if (NewDecls.empty())
4511 TC = TypoCorrection();
4512 else {
4513 TC.setCorrectionDecls(NewDecls);
4514 TC.setRequiresImport(!AnyVisibleDecls);
4518 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4519 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4520 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
4521 static void getNestedNameSpecifierIdentifiers(
4522 NestedNameSpecifier *NNS,
4523 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4524 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4525 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4526 else
4527 Identifiers.clear();
4529 const IdentifierInfo *II = nullptr;
4531 switch (NNS->getKind()) {
4532 case NestedNameSpecifier::Identifier:
4533 II = NNS->getAsIdentifier();
4534 break;
4536 case NestedNameSpecifier::Namespace:
4537 if (NNS->getAsNamespace()->isAnonymousNamespace())
4538 return;
4539 II = NNS->getAsNamespace()->getIdentifier();
4540 break;
4542 case NestedNameSpecifier::NamespaceAlias:
4543 II = NNS->getAsNamespaceAlias()->getIdentifier();
4544 break;
4546 case NestedNameSpecifier::TypeSpecWithTemplate:
4547 case NestedNameSpecifier::TypeSpec:
4548 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4549 break;
4551 case NestedNameSpecifier::Global:
4552 case NestedNameSpecifier::Super:
4553 return;
4556 if (II)
4557 Identifiers.push_back(II);
4560 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4561 DeclContext *Ctx, bool InBaseClass) {
4562 // Don't consider hidden names for typo correction.
4563 if (Hiding)
4564 return;
4566 // Only consider entities with identifiers for names, ignoring
4567 // special names (constructors, overloaded operators, selectors,
4568 // etc.).
4569 IdentifierInfo *Name = ND->getIdentifier();
4570 if (!Name)
4571 return;
4573 // Only consider visible declarations and declarations from modules with
4574 // names that exactly match.
4575 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4576 return;
4578 FoundName(Name->getName());
4581 void TypoCorrectionConsumer::FoundName(StringRef Name) {
4582 // Compute the edit distance between the typo and the name of this
4583 // entity, and add the identifier to the list of results.
4584 addName(Name, nullptr);
4587 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4588 // Compute the edit distance between the typo and this keyword,
4589 // and add the keyword to the list of results.
4590 addName(Keyword, nullptr, nullptr, true);
4593 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4594 NestedNameSpecifier *NNS, bool isKeyword) {
4595 // Use a simple length-based heuristic to determine the minimum possible
4596 // edit distance. If the minimum isn't good enough, bail out early.
4597 StringRef TypoStr = Typo->getName();
4598 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4599 if (MinED && TypoStr.size() / MinED < 3)
4600 return;
4602 // Compute an upper bound on the allowable edit distance, so that the
4603 // edit-distance algorithm can short-circuit.
4604 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4605 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4606 if (ED > UpperBound) return;
4608 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4609 if (isKeyword) TC.makeKeyword();
4610 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4611 addCorrection(TC);
4614 static const unsigned MaxTypoDistanceResultSets = 5;
4616 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4617 StringRef TypoStr = Typo->getName();
4618 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4620 // For very short typos, ignore potential corrections that have a different
4621 // base identifier from the typo or which have a normalized edit distance
4622 // longer than the typo itself.
4623 if (TypoStr.size() < 3 &&
4624 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4625 return;
4627 // If the correction is resolved but is not viable, ignore it.
4628 if (Correction.isResolved()) {
4629 checkCorrectionVisibility(SemaRef, Correction);
4630 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4631 return;
4634 TypoResultList &CList =
4635 CorrectionResults[Correction.getEditDistance(false)][Name];
4637 if (!CList.empty() && !CList.back().isResolved())
4638 CList.pop_back();
4639 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4640 auto RI = llvm::find_if(CList, [NewND](const TypoCorrection &TypoCorr) {
4641 return TypoCorr.getCorrectionDecl() == NewND;
4643 if (RI != CList.end()) {
4644 // The Correction refers to a decl already in the list. No insertion is
4645 // necessary and all further cases will return.
4647 auto IsDeprecated = [](Decl *D) {
4648 while (D) {
4649 if (D->isDeprecated())
4650 return true;
4651 D = llvm::dyn_cast_or_null<NamespaceDecl>(D->getDeclContext());
4653 return false;
4656 // Prefer non deprecated Corrections over deprecated and only then
4657 // sort using an alphabetical order.
4658 std::pair<bool, std::string> NewKey = {
4659 IsDeprecated(Correction.getFoundDecl()),
4660 Correction.getAsString(SemaRef.getLangOpts())};
4662 std::pair<bool, std::string> PrevKey = {
4663 IsDeprecated(RI->getFoundDecl()),
4664 RI->getAsString(SemaRef.getLangOpts())};
4666 if (NewKey < PrevKey)
4667 *RI = Correction;
4668 return;
4671 if (CList.empty() || Correction.isResolved())
4672 CList.push_back(Correction);
4674 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4675 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4678 void TypoCorrectionConsumer::addNamespaces(
4679 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4680 SearchNamespaces = true;
4682 for (auto KNPair : KnownNamespaces)
4683 Namespaces.addNameSpecifier(KNPair.first);
4685 bool SSIsTemplate = false;
4686 if (NestedNameSpecifier *NNS =
4687 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4688 if (const Type *T = NNS->getAsType())
4689 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4691 // Do not transform this into an iterator-based loop. The loop body can
4692 // trigger the creation of further types (through lazy deserialization) and
4693 // invalid iterators into this list.
4694 auto &Types = SemaRef.getASTContext().getTypes();
4695 for (unsigned I = 0; I != Types.size(); ++I) {
4696 const auto *TI = Types[I];
4697 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4698 CD = CD->getCanonicalDecl();
4699 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4700 !CD->isUnion() && CD->getIdentifier() &&
4701 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4702 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4703 Namespaces.addNameSpecifier(CD);
4708 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4709 if (++CurrentTCIndex < ValidatedCorrections.size())
4710 return ValidatedCorrections[CurrentTCIndex];
4712 CurrentTCIndex = ValidatedCorrections.size();
4713 while (!CorrectionResults.empty()) {
4714 auto DI = CorrectionResults.begin();
4715 if (DI->second.empty()) {
4716 CorrectionResults.erase(DI);
4717 continue;
4720 auto RI = DI->second.begin();
4721 if (RI->second.empty()) {
4722 DI->second.erase(RI);
4723 performQualifiedLookups();
4724 continue;
4727 TypoCorrection TC = RI->second.pop_back_val();
4728 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4729 ValidatedCorrections.push_back(TC);
4730 return ValidatedCorrections[CurrentTCIndex];
4733 return ValidatedCorrections[0]; // The empty correction.
4736 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4737 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4738 DeclContext *TempMemberContext = MemberContext;
4739 CXXScopeSpec *TempSS = SS.get();
4740 retry_lookup:
4741 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4742 EnteringContext,
4743 CorrectionValidator->IsObjCIvarLookup,
4744 Name == Typo && !Candidate.WillReplaceSpecifier());
4745 switch (Result.getResultKind()) {
4746 case LookupResult::NotFound:
4747 case LookupResult::NotFoundInCurrentInstantiation:
4748 case LookupResult::FoundUnresolvedValue:
4749 if (TempSS) {
4750 // Immediately retry the lookup without the given CXXScopeSpec
4751 TempSS = nullptr;
4752 Candidate.WillReplaceSpecifier(true);
4753 goto retry_lookup;
4755 if (TempMemberContext) {
4756 if (SS && !TempSS)
4757 TempSS = SS.get();
4758 TempMemberContext = nullptr;
4759 goto retry_lookup;
4761 if (SearchNamespaces)
4762 QualifiedResults.push_back(Candidate);
4763 break;
4765 case LookupResult::Ambiguous:
4766 // We don't deal with ambiguities.
4767 break;
4769 case LookupResult::Found:
4770 case LookupResult::FoundOverloaded:
4771 // Store all of the Decls for overloaded symbols
4772 for (auto *TRD : Result)
4773 Candidate.addCorrectionDecl(TRD);
4774 checkCorrectionVisibility(SemaRef, Candidate);
4775 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4776 if (SearchNamespaces)
4777 QualifiedResults.push_back(Candidate);
4778 break;
4780 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4781 return true;
4783 return false;
4786 void TypoCorrectionConsumer::performQualifiedLookups() {
4787 unsigned TypoLen = Typo->getName().size();
4788 for (const TypoCorrection &QR : QualifiedResults) {
4789 for (const auto &NSI : Namespaces) {
4790 DeclContext *Ctx = NSI.DeclCtx;
4791 const Type *NSType = NSI.NameSpecifier->getAsType();
4793 // If the current NestedNameSpecifier refers to a class and the
4794 // current correction candidate is the name of that class, then skip
4795 // it as it is unlikely a qualified version of the class' constructor
4796 // is an appropriate correction.
4797 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4798 nullptr) {
4799 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4800 continue;
4803 TypoCorrection TC(QR);
4804 TC.ClearCorrectionDecls();
4805 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4806 TC.setQualifierDistance(NSI.EditDistance);
4807 TC.setCallbackDistance(0); // Reset the callback distance
4809 // If the current correction candidate and namespace combination are
4810 // too far away from the original typo based on the normalized edit
4811 // distance, then skip performing a qualified name lookup.
4812 unsigned TmpED = TC.getEditDistance(true);
4813 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4814 TypoLen / TmpED < 3)
4815 continue;
4817 Result.clear();
4818 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4819 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4820 continue;
4822 // Any corrections added below will be validated in subsequent
4823 // iterations of the main while() loop over the Consumer's contents.
4824 switch (Result.getResultKind()) {
4825 case LookupResult::Found:
4826 case LookupResult::FoundOverloaded: {
4827 if (SS && SS->isValid()) {
4828 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4829 std::string OldQualified;
4830 llvm::raw_string_ostream OldOStream(OldQualified);
4831 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4832 OldOStream << Typo->getName();
4833 // If correction candidate would be an identical written qualified
4834 // identifier, then the existing CXXScopeSpec probably included a
4835 // typedef that didn't get accounted for properly.
4836 if (OldOStream.str() == NewQualified)
4837 break;
4839 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4840 TRD != TRDEnd; ++TRD) {
4841 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4842 NSType ? NSType->getAsCXXRecordDecl()
4843 : nullptr,
4844 TRD.getPair()) == Sema::AR_accessible)
4845 TC.addCorrectionDecl(*TRD);
4847 if (TC.isResolved()) {
4848 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4849 addCorrection(TC);
4851 break;
4853 case LookupResult::NotFound:
4854 case LookupResult::NotFoundInCurrentInstantiation:
4855 case LookupResult::Ambiguous:
4856 case LookupResult::FoundUnresolvedValue:
4857 break;
4861 QualifiedResults.clear();
4864 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4865 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4866 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4867 if (NestedNameSpecifier *NNS =
4868 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4869 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4870 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4872 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4874 // Build the list of identifiers that would be used for an absolute
4875 // (from the global context) NestedNameSpecifier referring to the current
4876 // context.
4877 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4878 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4879 CurContextIdentifiers.push_back(ND->getIdentifier());
4882 // Add the global context as a NestedNameSpecifier
4883 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4884 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4885 DistanceMap[1].push_back(SI);
4888 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4889 DeclContext *Start) -> DeclContextList {
4890 assert(Start && "Building a context chain from a null context");
4891 DeclContextList Chain;
4892 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4893 DC = DC->getLookupParent()) {
4894 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4895 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4896 !(ND && ND->isAnonymousNamespace()))
4897 Chain.push_back(DC->getPrimaryContext());
4899 return Chain;
4902 unsigned
4903 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4904 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4905 unsigned NumSpecifiers = 0;
4906 for (DeclContext *C : llvm::reverse(DeclChain)) {
4907 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4908 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4909 ++NumSpecifiers;
4910 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4911 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4912 RD->getTypeForDecl());
4913 ++NumSpecifiers;
4916 return NumSpecifiers;
4919 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4920 DeclContext *Ctx) {
4921 NestedNameSpecifier *NNS = nullptr;
4922 unsigned NumSpecifiers = 0;
4923 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4924 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4926 // Eliminate common elements from the two DeclContext chains.
4927 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4928 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4929 break;
4930 NamespaceDeclChain.pop_back();
4933 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4934 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4936 // Add an explicit leading '::' specifier if needed.
4937 if (NamespaceDeclChain.empty()) {
4938 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4939 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4940 NumSpecifiers =
4941 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4942 } else if (NamedDecl *ND =
4943 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4944 IdentifierInfo *Name = ND->getIdentifier();
4945 bool SameNameSpecifier = false;
4946 if (llvm::is_contained(CurNameSpecifierIdentifiers, Name)) {
4947 std::string NewNameSpecifier;
4948 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4949 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4950 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4951 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4952 SpecifierOStream.flush();
4953 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4955 if (SameNameSpecifier || llvm::is_contained(CurContextIdentifiers, Name)) {
4956 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4957 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4958 NumSpecifiers =
4959 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4963 // If the built NestedNameSpecifier would be replacing an existing
4964 // NestedNameSpecifier, use the number of component identifiers that
4965 // would need to be changed as the edit distance instead of the number
4966 // of components in the built NestedNameSpecifier.
4967 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4968 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4969 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4970 NumSpecifiers =
4971 llvm::ComputeEditDistance(llvm::ArrayRef(CurNameSpecifierIdentifiers),
4972 llvm::ArrayRef(NewNameSpecifierIdentifiers));
4975 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4976 DistanceMap[NumSpecifiers].push_back(SI);
4979 /// Perform name lookup for a possible result for typo correction.
4980 static void LookupPotentialTypoResult(Sema &SemaRef,
4981 LookupResult &Res,
4982 IdentifierInfo *Name,
4983 Scope *S, CXXScopeSpec *SS,
4984 DeclContext *MemberContext,
4985 bool EnteringContext,
4986 bool isObjCIvarLookup,
4987 bool FindHidden) {
4988 Res.suppressDiagnostics();
4989 Res.clear();
4990 Res.setLookupName(Name);
4991 Res.setAllowHidden(FindHidden);
4992 if (MemberContext) {
4993 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4994 if (isObjCIvarLookup) {
4995 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4996 Res.addDecl(Ivar);
4997 Res.resolveKind();
4998 return;
5002 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
5003 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
5004 Res.addDecl(Prop);
5005 Res.resolveKind();
5006 return;
5010 SemaRef.LookupQualifiedName(Res, MemberContext);
5011 return;
5014 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
5015 EnteringContext);
5017 // Fake ivar lookup; this should really be part of
5018 // LookupParsedName.
5019 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
5020 if (Method->isInstanceMethod() && Method->getClassInterface() &&
5021 (Res.empty() ||
5022 (Res.isSingleResult() &&
5023 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
5024 if (ObjCIvarDecl *IV
5025 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
5026 Res.addDecl(IV);
5027 Res.resolveKind();
5033 /// Add keywords to the consumer as possible typo corrections.
5034 static void AddKeywordsToConsumer(Sema &SemaRef,
5035 TypoCorrectionConsumer &Consumer,
5036 Scope *S, CorrectionCandidateCallback &CCC,
5037 bool AfterNestedNameSpecifier) {
5038 if (AfterNestedNameSpecifier) {
5039 // For 'X::', we know exactly which keywords can appear next.
5040 Consumer.addKeywordResult("template");
5041 if (CCC.WantExpressionKeywords)
5042 Consumer.addKeywordResult("operator");
5043 return;
5046 if (CCC.WantObjCSuper)
5047 Consumer.addKeywordResult("super");
5049 if (CCC.WantTypeSpecifiers) {
5050 // Add type-specifier keywords to the set of results.
5051 static const char *const CTypeSpecs[] = {
5052 "char", "const", "double", "enum", "float", "int", "long", "short",
5053 "signed", "struct", "union", "unsigned", "void", "volatile",
5054 "_Complex", "_Imaginary",
5055 // storage-specifiers as well
5056 "extern", "inline", "static", "typedef"
5059 for (const auto *CTS : CTypeSpecs)
5060 Consumer.addKeywordResult(CTS);
5062 if (SemaRef.getLangOpts().C99)
5063 Consumer.addKeywordResult("restrict");
5064 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
5065 Consumer.addKeywordResult("bool");
5066 else if (SemaRef.getLangOpts().C99)
5067 Consumer.addKeywordResult("_Bool");
5069 if (SemaRef.getLangOpts().CPlusPlus) {
5070 Consumer.addKeywordResult("class");
5071 Consumer.addKeywordResult("typename");
5072 Consumer.addKeywordResult("wchar_t");
5074 if (SemaRef.getLangOpts().CPlusPlus11) {
5075 Consumer.addKeywordResult("char16_t");
5076 Consumer.addKeywordResult("char32_t");
5077 Consumer.addKeywordResult("constexpr");
5078 Consumer.addKeywordResult("decltype");
5079 Consumer.addKeywordResult("thread_local");
5083 if (SemaRef.getLangOpts().GNUKeywords)
5084 Consumer.addKeywordResult("typeof");
5085 } else if (CCC.WantFunctionLikeCasts) {
5086 static const char *const CastableTypeSpecs[] = {
5087 "char", "double", "float", "int", "long", "short",
5088 "signed", "unsigned", "void"
5090 for (auto *kw : CastableTypeSpecs)
5091 Consumer.addKeywordResult(kw);
5094 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
5095 Consumer.addKeywordResult("const_cast");
5096 Consumer.addKeywordResult("dynamic_cast");
5097 Consumer.addKeywordResult("reinterpret_cast");
5098 Consumer.addKeywordResult("static_cast");
5101 if (CCC.WantExpressionKeywords) {
5102 Consumer.addKeywordResult("sizeof");
5103 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
5104 Consumer.addKeywordResult("false");
5105 Consumer.addKeywordResult("true");
5108 if (SemaRef.getLangOpts().CPlusPlus) {
5109 static const char *const CXXExprs[] = {
5110 "delete", "new", "operator", "throw", "typeid"
5112 for (const auto *CE : CXXExprs)
5113 Consumer.addKeywordResult(CE);
5115 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
5116 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
5117 Consumer.addKeywordResult("this");
5119 if (SemaRef.getLangOpts().CPlusPlus11) {
5120 Consumer.addKeywordResult("alignof");
5121 Consumer.addKeywordResult("nullptr");
5125 if (SemaRef.getLangOpts().C11) {
5126 // FIXME: We should not suggest _Alignof if the alignof macro
5127 // is present.
5128 Consumer.addKeywordResult("_Alignof");
5132 if (CCC.WantRemainingKeywords) {
5133 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
5134 // Statements.
5135 static const char *const CStmts[] = {
5136 "do", "else", "for", "goto", "if", "return", "switch", "while" };
5137 for (const auto *CS : CStmts)
5138 Consumer.addKeywordResult(CS);
5140 if (SemaRef.getLangOpts().CPlusPlus) {
5141 Consumer.addKeywordResult("catch");
5142 Consumer.addKeywordResult("try");
5145 if (S && S->getBreakParent())
5146 Consumer.addKeywordResult("break");
5148 if (S && S->getContinueParent())
5149 Consumer.addKeywordResult("continue");
5151 if (SemaRef.getCurFunction() &&
5152 !SemaRef.getCurFunction()->SwitchStack.empty()) {
5153 Consumer.addKeywordResult("case");
5154 Consumer.addKeywordResult("default");
5156 } else {
5157 if (SemaRef.getLangOpts().CPlusPlus) {
5158 Consumer.addKeywordResult("namespace");
5159 Consumer.addKeywordResult("template");
5162 if (S && S->isClassScope()) {
5163 Consumer.addKeywordResult("explicit");
5164 Consumer.addKeywordResult("friend");
5165 Consumer.addKeywordResult("mutable");
5166 Consumer.addKeywordResult("private");
5167 Consumer.addKeywordResult("protected");
5168 Consumer.addKeywordResult("public");
5169 Consumer.addKeywordResult("virtual");
5173 if (SemaRef.getLangOpts().CPlusPlus) {
5174 Consumer.addKeywordResult("using");
5176 if (SemaRef.getLangOpts().CPlusPlus11)
5177 Consumer.addKeywordResult("static_assert");
5182 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
5183 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5184 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5185 DeclContext *MemberContext, bool EnteringContext,
5186 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
5188 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
5189 DisableTypoCorrection)
5190 return nullptr;
5192 // In Microsoft mode, don't perform typo correction in a template member
5193 // function dependent context because it interferes with the "lookup into
5194 // dependent bases of class templates" feature.
5195 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
5196 isa<CXXMethodDecl>(CurContext))
5197 return nullptr;
5199 // We only attempt to correct typos for identifiers.
5200 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5201 if (!Typo)
5202 return nullptr;
5204 // If the scope specifier itself was invalid, don't try to correct
5205 // typos.
5206 if (SS && SS->isInvalid())
5207 return nullptr;
5209 // Never try to correct typos during any kind of code synthesis.
5210 if (!CodeSynthesisContexts.empty())
5211 return nullptr;
5213 // Don't try to correct 'super'.
5214 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
5215 return nullptr;
5217 // Abort if typo correction already failed for this specific typo.
5218 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
5219 if (locs != TypoCorrectionFailures.end() &&
5220 locs->second.count(TypoName.getLoc()))
5221 return nullptr;
5223 // Don't try to correct the identifier "vector" when in AltiVec mode.
5224 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
5225 // remove this workaround.
5226 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
5227 return nullptr;
5229 // Provide a stop gap for files that are just seriously broken. Trying
5230 // to correct all typos can turn into a HUGE performance penalty, causing
5231 // some files to take minutes to get rejected by the parser.
5232 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
5233 if (Limit && TyposCorrected >= Limit)
5234 return nullptr;
5235 ++TyposCorrected;
5237 // If we're handling a missing symbol error, using modules, and the
5238 // special search all modules option is used, look for a missing import.
5239 if (ErrorRecovery && getLangOpts().Modules &&
5240 getLangOpts().ModulesSearchAll) {
5241 // The following has the side effect of loading the missing module.
5242 getModuleLoader().lookupMissingImports(Typo->getName(),
5243 TypoName.getBeginLoc());
5246 // Extend the lifetime of the callback. We delayed this until here
5247 // to avoid allocations in the hot path (which is where no typo correction
5248 // occurs). Note that CorrectionCandidateCallback is polymorphic and
5249 // initially stack-allocated.
5250 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
5251 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
5252 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
5253 EnteringContext);
5255 // Perform name lookup to find visible, similarly-named entities.
5256 bool IsUnqualifiedLookup = false;
5257 DeclContext *QualifiedDC = MemberContext;
5258 if (MemberContext) {
5259 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
5261 // Look in qualified interfaces.
5262 if (OPT) {
5263 for (auto *I : OPT->quals())
5264 LookupVisibleDecls(I, LookupKind, *Consumer);
5266 } else if (SS && SS->isSet()) {
5267 QualifiedDC = computeDeclContext(*SS, EnteringContext);
5268 if (!QualifiedDC)
5269 return nullptr;
5271 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
5272 } else {
5273 IsUnqualifiedLookup = true;
5276 // Determine whether we are going to search in the various namespaces for
5277 // corrections.
5278 bool SearchNamespaces
5279 = getLangOpts().CPlusPlus &&
5280 (IsUnqualifiedLookup || (SS && SS->isSet()));
5282 if (IsUnqualifiedLookup || SearchNamespaces) {
5283 // For unqualified lookup, look through all of the names that we have
5284 // seen in this translation unit.
5285 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5286 for (const auto &I : Context.Idents)
5287 Consumer->FoundName(I.getKey());
5289 // Walk through identifiers in external identifier sources.
5290 // FIXME: Re-add the ability to skip very unlikely potential corrections.
5291 if (IdentifierInfoLookup *External
5292 = Context.Idents.getExternalIdentifierLookup()) {
5293 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
5294 do {
5295 StringRef Name = Iter->Next();
5296 if (Name.empty())
5297 break;
5299 Consumer->FoundName(Name);
5300 } while (true);
5304 AddKeywordsToConsumer(*this, *Consumer, S,
5305 *Consumer->getCorrectionValidator(),
5306 SS && SS->isNotEmpty());
5308 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
5309 // to search those namespaces.
5310 if (SearchNamespaces) {
5311 // Load any externally-known namespaces.
5312 if (ExternalSource && !LoadedExternalKnownNamespaces) {
5313 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
5314 LoadedExternalKnownNamespaces = true;
5315 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
5316 for (auto *N : ExternalKnownNamespaces)
5317 KnownNamespaces[N] = true;
5320 Consumer->addNamespaces(KnownNamespaces);
5323 return Consumer;
5326 /// Try to "correct" a typo in the source code by finding
5327 /// visible declarations whose names are similar to the name that was
5328 /// present in the source code.
5330 /// \param TypoName the \c DeclarationNameInfo structure that contains
5331 /// the name that was present in the source code along with its location.
5333 /// \param LookupKind the name-lookup criteria used to search for the name.
5335 /// \param S the scope in which name lookup occurs.
5337 /// \param SS the nested-name-specifier that precedes the name we're
5338 /// looking for, if present.
5340 /// \param CCC A CorrectionCandidateCallback object that provides further
5341 /// validation of typo correction candidates. It also provides flags for
5342 /// determining the set of keywords permitted.
5344 /// \param MemberContext if non-NULL, the context in which to look for
5345 /// a member access expression.
5347 /// \param EnteringContext whether we're entering the context described by
5348 /// the nested-name-specifier SS.
5350 /// \param OPT when non-NULL, the search for visible declarations will
5351 /// also walk the protocols in the qualified interfaces of \p OPT.
5353 /// \returns a \c TypoCorrection containing the corrected name if the typo
5354 /// along with information such as the \c NamedDecl where the corrected name
5355 /// was declared, and any additional \c NestedNameSpecifier needed to access
5356 /// it (C++ only). The \c TypoCorrection is empty if there is no correction.
5357 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
5358 Sema::LookupNameKind LookupKind,
5359 Scope *S, CXXScopeSpec *SS,
5360 CorrectionCandidateCallback &CCC,
5361 CorrectTypoKind Mode,
5362 DeclContext *MemberContext,
5363 bool EnteringContext,
5364 const ObjCObjectPointerType *OPT,
5365 bool RecordFailure) {
5366 // Always let the ExternalSource have the first chance at correction, even
5367 // if we would otherwise have given up.
5368 if (ExternalSource) {
5369 if (TypoCorrection Correction =
5370 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
5371 MemberContext, EnteringContext, OPT))
5372 return Correction;
5375 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
5376 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
5377 // some instances of CTC_Unknown, while WantRemainingKeywords is true
5378 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
5379 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
5381 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5382 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5383 MemberContext, EnteringContext,
5384 OPT, Mode == CTK_ErrorRecovery);
5386 if (!Consumer)
5387 return TypoCorrection();
5389 // If we haven't found anything, we're done.
5390 if (Consumer->empty())
5391 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5393 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5394 // is not more that about a third of the length of the typo's identifier.
5395 unsigned ED = Consumer->getBestEditDistance(true);
5396 unsigned TypoLen = Typo->getName().size();
5397 if (ED > 0 && TypoLen / ED < 3)
5398 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5400 TypoCorrection BestTC = Consumer->getNextCorrection();
5401 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5402 if (!BestTC)
5403 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5405 ED = BestTC.getEditDistance();
5407 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5408 // If this was an unqualified lookup and we believe the callback
5409 // object wouldn't have filtered out possible corrections, note
5410 // that no correction was found.
5411 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5414 // If only a single name remains, return that result.
5415 if (!SecondBestTC ||
5416 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5417 const TypoCorrection &Result = BestTC;
5419 // Don't correct to a keyword that's the same as the typo; the keyword
5420 // wasn't actually in scope.
5421 if (ED == 0 && Result.isKeyword())
5422 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5424 TypoCorrection TC = Result;
5425 TC.setCorrectionRange(SS, TypoName);
5426 checkCorrectionVisibility(*this, TC);
5427 return TC;
5428 } else if (SecondBestTC && ObjCMessageReceiver) {
5429 // Prefer 'super' when we're completing in a message-receiver
5430 // context.
5432 if (BestTC.getCorrection().getAsString() != "super") {
5433 if (SecondBestTC.getCorrection().getAsString() == "super")
5434 BestTC = SecondBestTC;
5435 else if ((*Consumer)["super"].front().isKeyword())
5436 BestTC = (*Consumer)["super"].front();
5438 // Don't correct to a keyword that's the same as the typo; the keyword
5439 // wasn't actually in scope.
5440 if (BestTC.getEditDistance() == 0 ||
5441 BestTC.getCorrection().getAsString() != "super")
5442 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5444 BestTC.setCorrectionRange(SS, TypoName);
5445 return BestTC;
5448 // Record the failure's location if needed and return an empty correction. If
5449 // this was an unqualified lookup and we believe the callback object did not
5450 // filter out possible corrections, also cache the failure for the typo.
5451 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5454 /// Try to "correct" a typo in the source code by finding
5455 /// visible declarations whose names are similar to the name that was
5456 /// present in the source code.
5458 /// \param TypoName the \c DeclarationNameInfo structure that contains
5459 /// the name that was present in the source code along with its location.
5461 /// \param LookupKind the name-lookup criteria used to search for the name.
5463 /// \param S the scope in which name lookup occurs.
5465 /// \param SS the nested-name-specifier that precedes the name we're
5466 /// looking for, if present.
5468 /// \param CCC A CorrectionCandidateCallback object that provides further
5469 /// validation of typo correction candidates. It also provides flags for
5470 /// determining the set of keywords permitted.
5472 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
5473 /// diagnostics when the actual typo correction is attempted.
5475 /// \param TRC A TypoRecoveryCallback functor that will be used to build an
5476 /// Expr from a typo correction candidate.
5478 /// \param MemberContext if non-NULL, the context in which to look for
5479 /// a member access expression.
5481 /// \param EnteringContext whether we're entering the context described by
5482 /// the nested-name-specifier SS.
5484 /// \param OPT when non-NULL, the search for visible declarations will
5485 /// also walk the protocols in the qualified interfaces of \p OPT.
5487 /// \returns a new \c TypoExpr that will later be replaced in the AST with an
5488 /// Expr representing the result of performing typo correction, or nullptr if
5489 /// typo correction is not possible. If nullptr is returned, no diagnostics will
5490 /// be emitted and it is the responsibility of the caller to emit any that are
5491 /// needed.
5492 TypoExpr *Sema::CorrectTypoDelayed(
5493 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5494 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5495 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
5496 DeclContext *MemberContext, bool EnteringContext,
5497 const ObjCObjectPointerType *OPT) {
5498 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5499 MemberContext, EnteringContext,
5500 OPT, Mode == CTK_ErrorRecovery);
5502 // Give the external sema source a chance to correct the typo.
5503 TypoCorrection ExternalTypo;
5504 if (ExternalSource && Consumer) {
5505 ExternalTypo = ExternalSource->CorrectTypo(
5506 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5507 MemberContext, EnteringContext, OPT);
5508 if (ExternalTypo)
5509 Consumer->addCorrection(ExternalTypo);
5512 if (!Consumer || Consumer->empty())
5513 return nullptr;
5515 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5516 // is not more that about a third of the length of the typo's identifier.
5517 unsigned ED = Consumer->getBestEditDistance(true);
5518 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5519 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5520 return nullptr;
5521 ExprEvalContexts.back().NumTypos++;
5522 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5523 TypoName.getLoc());
5526 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5527 if (!CDecl) return;
5529 if (isKeyword())
5530 CorrectionDecls.clear();
5532 CorrectionDecls.push_back(CDecl);
5534 if (!CorrectionName)
5535 CorrectionName = CDecl->getDeclName();
5538 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5539 if (CorrectionNameSpec) {
5540 std::string tmpBuffer;
5541 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5542 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5543 PrefixOStream << CorrectionName;
5544 return PrefixOStream.str();
5547 return CorrectionName.getAsString();
5550 bool CorrectionCandidateCallback::ValidateCandidate(
5551 const TypoCorrection &candidate) {
5552 if (!candidate.isResolved())
5553 return true;
5555 if (candidate.isKeyword())
5556 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5557 WantRemainingKeywords || WantObjCSuper;
5559 bool HasNonType = false;
5560 bool HasStaticMethod = false;
5561 bool HasNonStaticMethod = false;
5562 for (Decl *D : candidate) {
5563 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5564 D = FTD->getTemplatedDecl();
5565 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5566 if (Method->isStatic())
5567 HasStaticMethod = true;
5568 else
5569 HasNonStaticMethod = true;
5571 if (!isa<TypeDecl>(D))
5572 HasNonType = true;
5575 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5576 !candidate.getCorrectionSpecifier())
5577 return false;
5579 return WantTypeSpecifiers || HasNonType;
5582 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5583 bool HasExplicitTemplateArgs,
5584 MemberExpr *ME)
5585 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5586 CurContext(SemaRef.CurContext), MemberFn(ME) {
5587 WantTypeSpecifiers = false;
5588 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5589 !HasExplicitTemplateArgs && NumArgs == 1;
5590 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5591 WantRemainingKeywords = false;
5594 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5595 if (!candidate.getCorrectionDecl())
5596 return candidate.isKeyword();
5598 for (auto *C : candidate) {
5599 FunctionDecl *FD = nullptr;
5600 NamedDecl *ND = C->getUnderlyingDecl();
5601 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5602 FD = FTD->getTemplatedDecl();
5603 if (!HasExplicitTemplateArgs && !FD) {
5604 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5605 // If the Decl is neither a function nor a template function,
5606 // determine if it is a pointer or reference to a function. If so,
5607 // check against the number of arguments expected for the pointee.
5608 QualType ValType = cast<ValueDecl>(ND)->getType();
5609 if (ValType.isNull())
5610 continue;
5611 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5612 ValType = ValType->getPointeeType();
5613 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5614 if (FPT->getNumParams() == NumArgs)
5615 return true;
5619 // A typo for a function-style cast can look like a function call in C++.
5620 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5621 : isa<TypeDecl>(ND)) &&
5622 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5623 // Only a class or class template can take two or more arguments.
5624 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5626 // Skip the current candidate if it is not a FunctionDecl or does not accept
5627 // the current number of arguments.
5628 if (!FD || !(FD->getNumParams() >= NumArgs &&
5629 FD->getMinRequiredArguments() <= NumArgs))
5630 continue;
5632 // If the current candidate is a non-static C++ method, skip the candidate
5633 // unless the method being corrected--or the current DeclContext, if the
5634 // function being corrected is not a method--is a method in the same class
5635 // or a descendent class of the candidate's parent class.
5636 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
5637 if (MemberFn || !MD->isStatic()) {
5638 const auto *CurMD =
5639 MemberFn
5640 ? dyn_cast_if_present<CXXMethodDecl>(MemberFn->getMemberDecl())
5641 : dyn_cast_if_present<CXXMethodDecl>(CurContext);
5642 const CXXRecordDecl *CurRD =
5643 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5644 const CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5645 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5646 continue;
5649 return true;
5651 return false;
5654 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5655 const PartialDiagnostic &TypoDiag,
5656 bool ErrorRecovery) {
5657 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5658 ErrorRecovery);
5661 /// Find which declaration we should import to provide the definition of
5662 /// the given declaration.
5663 static const NamedDecl *getDefinitionToImport(const NamedDecl *D) {
5664 if (const auto *VD = dyn_cast<VarDecl>(D))
5665 return VD->getDefinition();
5666 if (const auto *FD = dyn_cast<FunctionDecl>(D))
5667 return FD->getDefinition();
5668 if (const auto *TD = dyn_cast<TagDecl>(D))
5669 return TD->getDefinition();
5670 if (const auto *ID = dyn_cast<ObjCInterfaceDecl>(D))
5671 return ID->getDefinition();
5672 if (const auto *PD = dyn_cast<ObjCProtocolDecl>(D))
5673 return PD->getDefinition();
5674 if (const auto *TD = dyn_cast<TemplateDecl>(D))
5675 if (const NamedDecl *TTD = TD->getTemplatedDecl())
5676 return getDefinitionToImport(TTD);
5677 return nullptr;
5680 void Sema::diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
5681 MissingImportKind MIK, bool Recover) {
5682 // Suggest importing a module providing the definition of this entity, if
5683 // possible.
5684 const NamedDecl *Def = getDefinitionToImport(Decl);
5685 if (!Def)
5686 Def = Decl;
5688 Module *Owner = getOwningModule(Def);
5689 assert(Owner && "definition of hidden declaration is not in a module");
5691 llvm::SmallVector<Module*, 8> OwningModules;
5692 OwningModules.push_back(Owner);
5693 auto Merged = Context.getModulesWithMergedDefinition(Def);
5694 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5696 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5697 Recover);
5700 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5701 /// suggesting the addition of a #include of the specified file.
5702 static std::string getHeaderNameForHeader(Preprocessor &PP, FileEntryRef E,
5703 llvm::StringRef IncludingFile) {
5704 bool IsAngled = false;
5705 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5706 E, IncludingFile, &IsAngled);
5707 return (IsAngled ? '<' : '"') + Path + (IsAngled ? '>' : '"');
5710 void Sema::diagnoseMissingImport(SourceLocation UseLoc, const NamedDecl *Decl,
5711 SourceLocation DeclLoc,
5712 ArrayRef<Module *> Modules,
5713 MissingImportKind MIK, bool Recover) {
5714 assert(!Modules.empty());
5716 auto NotePrevious = [&] {
5717 // FIXME: Suppress the note backtrace even under
5718 // -fdiagnostics-show-note-include-stack. We don't care how this
5719 // declaration was previously reached.
5720 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5723 // Weed out duplicates from module list.
5724 llvm::SmallVector<Module*, 8> UniqueModules;
5725 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5726 for (auto *M : Modules) {
5727 if (M->isGlobalModule() || M->isPrivateModule())
5728 continue;
5729 if (UniqueModuleSet.insert(M).second)
5730 UniqueModules.push_back(M);
5733 // Try to find a suitable header-name to #include.
5734 std::string HeaderName;
5735 if (OptionalFileEntryRef Header =
5736 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5737 if (const FileEntry *FE =
5738 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5739 HeaderName =
5740 getHeaderNameForHeader(PP, *Header, FE->tryGetRealPathName());
5743 // If we have a #include we should suggest, or if all definition locations
5744 // were in global module fragments, don't suggest an import.
5745 if (!HeaderName.empty() || UniqueModules.empty()) {
5746 // FIXME: Find a smart place to suggest inserting a #include, and add
5747 // a FixItHint there.
5748 Diag(UseLoc, diag::err_module_unimported_use_header)
5749 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5750 // Produce a note showing where the entity was declared.
5751 NotePrevious();
5752 if (Recover)
5753 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5754 return;
5757 Modules = UniqueModules;
5759 if (Modules.size() > 1) {
5760 std::string ModuleList;
5761 unsigned N = 0;
5762 for (const auto *M : Modules) {
5763 ModuleList += "\n ";
5764 if (++N == 5 && N != Modules.size()) {
5765 ModuleList += "[...]";
5766 break;
5768 ModuleList += M->getFullModuleName();
5771 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5772 << (int)MIK << Decl << ModuleList;
5773 } else {
5774 // FIXME: Add a FixItHint that imports the corresponding module.
5775 Diag(UseLoc, diag::err_module_unimported_use)
5776 << (int)MIK << Decl << Modules[0]->getFullModuleName();
5779 NotePrevious();
5781 // Try to recover by implicitly importing this module.
5782 if (Recover)
5783 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5786 /// Diagnose a successfully-corrected typo. Separated from the correction
5787 /// itself to allow external validation of the result, etc.
5789 /// \param Correction The result of performing typo correction.
5790 /// \param TypoDiag The diagnostic to produce. This will have the corrected
5791 /// string added to it (and usually also a fixit).
5792 /// \param PrevNote A note to use when indicating the location of the entity to
5793 /// which we are correcting. Will have the correction string added to it.
5794 /// \param ErrorRecovery If \c true (the default), the caller is going to
5795 /// recover from the typo as if the corrected string had been typed.
5796 /// In this case, \c PDiag must be an error, and we will attach a fixit
5797 /// to it.
5798 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5799 const PartialDiagnostic &TypoDiag,
5800 const PartialDiagnostic &PrevNote,
5801 bool ErrorRecovery) {
5802 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5803 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5804 FixItHint FixTypo = FixItHint::CreateReplacement(
5805 Correction.getCorrectionRange(), CorrectedStr);
5807 // Maybe we're just missing a module import.
5808 if (Correction.requiresImport()) {
5809 NamedDecl *Decl = Correction.getFoundDecl();
5810 assert(Decl && "import required but no declaration to import");
5812 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5813 MissingImportKind::Declaration, ErrorRecovery);
5814 return;
5817 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5818 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5820 NamedDecl *ChosenDecl =
5821 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5822 if (PrevNote.getDiagID() && ChosenDecl)
5823 Diag(ChosenDecl->getLocation(), PrevNote)
5824 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5826 // Add any extra diagnostics.
5827 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5828 Diag(Correction.getCorrectionRange().getBegin(), PD);
5831 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5832 TypoDiagnosticGenerator TDG,
5833 TypoRecoveryCallback TRC,
5834 SourceLocation TypoLoc) {
5835 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5836 auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
5837 auto &State = DelayedTypos[TE];
5838 State.Consumer = std::move(TCC);
5839 State.DiagHandler = std::move(TDG);
5840 State.RecoveryHandler = std::move(TRC);
5841 if (TE)
5842 TypoExprs.push_back(TE);
5843 return TE;
5846 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5847 auto Entry = DelayedTypos.find(TE);
5848 assert(Entry != DelayedTypos.end() &&
5849 "Failed to get the state for a TypoExpr!");
5850 return Entry->second;
5853 void Sema::clearDelayedTypo(TypoExpr *TE) {
5854 DelayedTypos.erase(TE);
5857 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5858 DeclarationNameInfo Name(II, IILoc);
5859 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5860 R.suppressDiagnostics();
5861 R.setHideTags(false);
5862 LookupName(R, S);
5863 R.dump();
5866 void Sema::ActOnPragmaDump(Expr *E) {
5867 E->dump();